-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathremote-plugin-bridge.ts
More file actions
653 lines (612 loc) · 20.4 KB
/
remote-plugin-bridge.ts
File metadata and controls
653 lines (612 loc) · 20.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
/**
* RemotePluginBridge — host-side wiring for a remote-mode plugin.
*
* Sits between a `RemotePluginHost`-managed worker (or any
* `BridgeChannel`-shaped transport) and an `IAgentRuntime`. On
* `worker-announce-plugin` it walks the descriptor, synthesises stub
* Plugin contributions (actions, providers, events, models) whose
* handlers proxy back to the worker over `worker-rpc`, and registers
* the resulting Plugin with `runtime.registerPlugin(...)`.
*
* Inbound `host-rpc` messages from the worker are dispatched to the
* real runtime (`getService`, `useModel`, `getMemory`, `emitEvent`,
* `composeState`, etc.) and the result is shipped back as
* `host-rpc-result`.
*
* P1 wires: actions, providers, events, models, evaluators.
* Deferred: services, routes, views (P2), action callbacks (P1 step 4
* follow-up), streaming model tokens (P2).
*/
import type {
Action,
IAgentRuntime,
Memory,
Plugin,
Provider,
ProviderResult,
State,
Validator,
} from "@elizaos/core";
import type {
HostRpcMessage,
HostRpcResultMessage,
JsonObject,
JsonValue,
RemoteFunctionRef,
RemotePluginWorkerMessage,
WorkerAnnouncePluginMessage,
WorkerRpcMessage,
WorkerRpcResultMessage,
} from "@elizaos/plugin-remote-manifest";
import { fromWireError, toWireError } from "@elizaos/plugin-worker-runtime";
/** Transport contract the bridge talks to. */
export interface BridgeChannel {
send(message: RemotePluginWorkerMessage): void;
onMessage(handler: (message: RemotePluginWorkerMessage) => void): () => void;
close(): void;
}
export interface RemotePluginBridgeOptions {
channel: BridgeChannel;
runtime: IAgentRuntime;
/** Soft timeout per outbound worker-rpc, in ms. Defaults to 60s. */
rpcTimeoutMs?: number;
}
interface PendingRequest {
resolve: (value: JsonValue) => void;
reject: (error: Error) => void;
timer: ReturnType<typeof setTimeout> | undefined;
}
/** rpc-id → live handler function on the worker side. */
type RpcId = string;
/** What the bridge tracks per attached worker. */
interface AttachedState {
pluginName: string | null;
pending: Map<number, PendingRequest>;
nextRequestId: () => number;
unsubscribe: (() => void) | undefined;
}
export class RemotePluginBridge {
private readonly channel: BridgeChannel;
private readonly runtime: IAgentRuntime;
private readonly rpcTimeoutMs: number;
private readonly state: AttachedState;
constructor(options: RemotePluginBridgeOptions) {
this.channel = options.channel;
this.runtime = options.runtime;
this.rpcTimeoutMs = options.rpcTimeoutMs ?? 60_000;
this.state = {
pluginName: null,
pending: new Map(),
nextRequestId: (() => {
let n = 0;
return () => {
n = (n + 1) >>> 0;
return n;
};
})(),
unsubscribe: undefined,
};
}
/** Begin listening for announce + host-rpc messages from the worker. */
attach(): void {
if (this.state.unsubscribe) return;
this.state.unsubscribe = this.channel.onMessage((message) => {
void this.onMessage(message);
});
}
/** Tear down. Unloads the plugin from the runtime if registered. */
async detach(): Promise<void> {
this.state.unsubscribe?.();
this.state.unsubscribe = undefined;
const rejection = new Error("RemotePluginBridge detached.");
for (const [, slot] of this.state.pending) {
if (slot.timer) clearTimeout(slot.timer);
slot.reject(rejection);
}
this.state.pending.clear();
if (this.state.pluginName) {
await this.runtime.unloadPlugin(this.state.pluginName).catch(() => {
// ignore unload failures during tear-down
});
this.state.pluginName = null;
}
}
private async onMessage(message: RemotePluginWorkerMessage): Promise<void> {
switch (message.type) {
case "worker-announce-plugin":
await this.handleAnnounce(message as WorkerAnnouncePluginMessage);
return;
case "worker-rpc-result":
this.handleRpcResult(message as WorkerRpcResultMessage);
return;
case "host-rpc":
await this.handleHostRpc(message as HostRpcMessage);
return;
default:
// init-complete, stream-chunk, stream-end, ready, event, etc.
// not handled in P1; the broader RemotePluginHost owns these.
return;
}
}
private async handleAnnounce(
message: WorkerAnnouncePluginMessage,
): Promise<void> {
const plugin = this.materialisePlugin(message.descriptor);
this.state.pluginName = plugin.name;
await this.runtime.registerPlugin(plugin);
}
private materialisePlugin(descriptor: JsonObject): Plugin {
const name = String(descriptor.name ?? "");
if (!name)
throw new Error("worker-announce-plugin descriptor missing name");
const plugin: Plugin = {
name,
description: String(descriptor.description ?? ""),
mode: "remote",
};
if (descriptor.priority !== undefined) {
plugin.priority = Number(descriptor.priority);
}
if (descriptor.dependencies) {
plugin.dependencies = (descriptor.dependencies as string[]) ?? [];
}
this.attachFunctionContributions(plugin, descriptor);
this.attachServiceContributions(plugin, descriptor);
this.attachRouteContributions(plugin, descriptor);
this.attachViewContributions(plugin, descriptor);
return plugin;
}
private attachFunctionContributions(
plugin: Plugin,
descriptor: JsonObject,
): void {
const actions = descriptor.actions as
| Array<JsonObject & { name: string; handler: RemoteFunctionRef }>
| undefined;
if (actions?.length) {
plugin.actions = actions.map((action) => this.makeActionStub(action));
}
const providers = descriptor.providers as
| Array<JsonObject & { name: string; get: RemoteFunctionRef }>
| undefined;
if (providers?.length) {
plugin.providers = providers.map((provider) =>
this.makeProviderStub(provider),
);
}
const events = descriptor.events as unknown as
| Record<string, RemoteFunctionRef[]>
| undefined;
if (events) {
const eventMap: NonNullable<Plugin["events"]> = {};
for (const [eventName, refs] of Object.entries(events)) {
const handlers = refs.map((ref) => this.makeEventHandlerStub(ref));
(eventMap as Record<string, unknown[]>)[eventName] = handlers;
}
plugin.events = eventMap;
}
const models = descriptor.models as unknown as
| Record<string, RemoteFunctionRef>
| undefined;
if (models) {
const modelMap: NonNullable<Plugin["models"]> = {} as NonNullable<
Plugin["models"]
>;
for (const [modelType, ref] of Object.entries(models)) {
(modelMap as Record<string, unknown>)[modelType] =
this.makeModelHandlerStub(ref);
}
plugin.models = modelMap;
}
}
private attachServiceContributions(
plugin: Plugin,
descriptor: JsonObject,
): void {
// Services: opt-in via `static rpcMethods`. The descriptor carries
// one entry per service with the methods list and per-method rpc
// ids; we synthesise a ServiceClass with dynamic methods.
const services = descriptor.services as unknown as
| Array<
JsonObject & {
serviceType: string;
rpcMethods: string[];
capabilityDescription?: string;
}
>
| undefined;
if (services?.length) {
plugin.services = services.map((svc) =>
this.makeServiceClassStub(svc),
) as Plugin["services"];
}
}
private attachRouteContributions(
plugin: Plugin,
descriptor: JsonObject,
): void {
// Routes: the agent's existing plugin-route lifecycle will pick
// these up. Each routeHandler is wrapped to forward
// RouteHandlerContext via worker-rpc and return RouteHandlerResult.
const routes = descriptor.routes as unknown as
| Array<JsonObject & { path: string; routeHandler?: RemoteFunctionRef }>
| undefined;
if (routes?.length) {
plugin.routes = routes
.map((r) => this.makeRouteStub(r))
.filter((r): r is NonNullable<Plugin["routes"]>[number] => r !== null);
}
}
private attachViewContributions(
plugin: Plugin,
descriptor: JsonObject,
): void {
// Views/widgets/componentTypes are pure JSON metadata; pass them
// through unchanged so the existing view registry serves the
// remote plugin's bundle the same way it does direct plugins'.
if (descriptor.views)
plugin.views = descriptor.views as unknown as Plugin["views"];
if (descriptor.widgets)
plugin.widgets = descriptor.widgets as unknown as Plugin["widgets"];
if (descriptor.componentTypes) {
plugin.componentTypes =
descriptor.componentTypes as unknown as Plugin["componentTypes"];
}
}
private makeActionStub(
descriptor: JsonObject & { name: string; handler: RemoteFunctionRef },
): Action {
const name = descriptor.name;
const similes = (descriptor.similes as string[] | undefined) ?? [];
const description = String(descriptor.description ?? "");
const examples =
(descriptor.examples as unknown as Action["examples"]) ?? [];
const validateRef = descriptor.validate as unknown as
| RemoteFunctionRef
| undefined;
const handler: Action["handler"] = async (
_runtime,
message,
state,
options,
_callback,
responses,
) => {
// P1: callback is stubbed on the worker side; pass undefined
// through. Action handlers that need callback() to surface text
// already typically rely on the orchestrator's progress channel
// anyway. Real callback marshalling lands in P1 step 4.
const result = await this.workerRpc<JsonValue>(
"action",
descriptor.handler.id,
{
message: this.normalize(message),
state: this.normalize(state),
options: this.normalize(options ?? null),
responses: this.normalize(responses ?? null),
},
);
return result as unknown as ReturnType<Action["handler"]>;
};
const validate: Validator = validateRef
? async (_runtime, message, state) => {
const result = await this.workerRpc<boolean>(
"action",
validateRef.id,
{
message: this.normalize(message),
state: this.normalize(state ?? null),
},
);
return Boolean(result);
}
: async () => true;
const action: Action = {
name,
similes,
description,
examples,
handler,
validate,
};
return action;
}
private makeProviderStub(
descriptor: JsonObject & { name: string; get: RemoteFunctionRef },
): Provider {
const name = descriptor.name;
const description = String(descriptor.description ?? "");
const dynamic = descriptor.dynamic === true;
const priv = descriptor.private === true;
const position =
typeof descriptor.position === "number" ? descriptor.position : undefined;
const get: Provider["get"] = async (
_runtime: IAgentRuntime,
message: Memory,
state: State,
): Promise<ProviderResult> => {
const result = await this.workerRpc<JsonValue>(
"provider",
descriptor.get.id,
{
message: this.normalize(message),
state: this.normalize(state),
},
);
if (result && typeof result === "object" && !Array.isArray(result)) {
return result as ProviderResult;
}
return { values: {}, data: {}, text: "" } as ProviderResult;
};
const provider: Provider = {
name,
description,
get,
};
if (dynamic) provider.dynamic = true;
if (priv) provider.private = true;
if (position !== undefined) provider.position = position;
return provider;
}
/**
* Build a {@link ServiceClass} stub from a service descriptor. The
* returned class has the announced serviceType and a static `start`
* factory that constructs an instance whose declared rpcMethods
* worker-rpc into the worker's service trampoline.
*
* Methods not in rpcMethods are absent — there is no way to reach
* private worker methods from the host, which is the whole point of
* the opt-in.
*/
private makeServiceClassStub(descriptor: {
serviceType: string;
rpcMethods: string[];
capabilityDescription?: string;
[rpcKey: string]: unknown;
}): unknown {
const bridge = this;
const serviceType = descriptor.serviceType;
const description = descriptor.capabilityDescription ?? "";
const methodIdMap = new Map<string, RpcId>();
for (const method of descriptor.rpcMethods) {
const ref = descriptor[`rpc:${method}`] as RemoteFunctionRef | undefined;
if (ref?.rpc) methodIdMap.set(method, ref.id);
}
// Build the proxy class on the fly. The Service base class isn't
// imported here to avoid pulling all of @elizaos/core into this
// module; the runtime only needs the static fields it checks.
class RemoteServiceProxy {
static readonly serviceType = serviceType;
static readonly capabilityDescription = description;
readonly capabilityDescription = description;
static async start(): Promise<RemoteServiceProxy> {
const instance = new RemoteServiceProxy();
return instance;
}
constructor() {
for (const method of descriptor.rpcMethods) {
const id = methodIdMap.get(method);
if (!id) continue;
(this as unknown as Record<string, unknown>)[method] = async (
...callArgs: unknown[]
) =>
bridge.workerRpc("service", id, {
args: callArgs.map((a) => bridge.normalize(a)),
});
}
}
async stop(): Promise<void> {
// Stopping the proxy doesn't tear down the worker; the
// RemotePluginHost owns the worker lifecycle.
}
}
return RemoteServiceProxy;
}
/**
* Build a route stub. The agent's plugin-route registration code
* picks up `plugin.routes[i]` exactly as for direct plugins; the
* `routeHandler` here forwards via worker-rpc.
*/
private makeRouteStub(descriptor: {
path: string;
routeHandler?: RemoteFunctionRef;
type?: unknown;
name?: unknown;
public?: unknown;
isMultipart?: unknown;
}): NonNullable<Plugin["routes"]>[number] | null {
if (!descriptor.routeHandler) return null;
const ref = descriptor.routeHandler;
const routeHandler = async (ctx: unknown) =>
this.workerRpc("route", ref.id, { ctx: this.normalize(ctx) });
const route = {
path: descriptor.path,
...(descriptor.type ? { type: descriptor.type as string } : {}),
...(descriptor.name ? { name: descriptor.name as string } : {}),
...(descriptor.public !== undefined
? { public: Boolean(descriptor.public) }
: {}),
...(descriptor.isMultipart !== undefined
? { isMultipart: Boolean(descriptor.isMultipart) }
: {}),
routeHandler,
} as unknown as NonNullable<Plugin["routes"]>[number];
return route;
}
private makeEventHandlerStub(ref: RemoteFunctionRef) {
return async (payload: unknown): Promise<void> => {
await this.workerRpc<JsonValue>(
"event",
ref.id,
this.normalize(payload as JsonValue),
);
};
}
private makeModelHandlerStub(ref: RemoteFunctionRef) {
return async (
_runtime: IAgentRuntime,
params: JsonValue,
): Promise<JsonValue> => {
return this.workerRpc<JsonValue>("model", ref.id, {
params: this.normalize(params),
});
};
}
private workerRpc<T extends JsonValue>(
surface: WorkerRpcMessage["surface"],
target: RpcId,
args: JsonValue,
): Promise<T> {
const requestId = this.state.nextRequestId();
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
if (this.state.pending.delete(requestId)) {
reject(
new Error(
`worker-rpc ${surface}:${target} timed out after ${this.rpcTimeoutMs}ms`,
),
);
}
}, this.rpcTimeoutMs);
this.state.pending.set(requestId, {
resolve: (v) => resolve(v as T),
reject,
timer,
});
const envelope: WorkerRpcMessage = {
type: "worker-rpc",
requestId,
surface,
target,
args,
};
this.channel.send(envelope);
});
}
private handleRpcResult(message: WorkerRpcResultMessage): void {
const slot = this.state.pending.get(message.requestId);
if (!slot) return;
this.state.pending.delete(message.requestId);
if (slot.timer) clearTimeout(slot.timer);
if (message.ok) {
slot.resolve((message.payload ?? null) as JsonValue);
} else {
slot.reject(
fromWireError(
message.error ?? {
name: "Error",
message: "Unknown worker-rpc failure",
},
"remote worker",
),
);
}
}
private async handleHostRpc(message: HostRpcMessage): Promise<void> {
const reply = (result: HostRpcResultMessage): void => {
this.channel.send(result);
};
try {
const payload = await this.dispatchRuntimeMethod(message);
reply({
type: "host-rpc-result",
requestId: message.requestId,
ok: true,
payload,
});
} catch (error) {
reply({
type: "host-rpc-result",
requestId: message.requestId,
ok: false,
error: toWireError(error),
});
}
}
private async dispatchRuntimeMethod(
message: HostRpcMessage,
): Promise<JsonValue> {
const args = (message.args ?? {}) as Record<string, JsonValue>;
switch (message.method) {
case "getService": {
const serviceType = String(args.serviceType);
const service = this.runtime.getService(serviceType);
return service ? { available: true } : null;
}
case "useModel": {
const modelType = String(args.modelType);
const params = args.params as JsonValue;
const result = await this.runtime.useModel(
modelType as Parameters<IAgentRuntime["useModel"]>[0],
params as Parameters<IAgentRuntime["useModel"]>[1],
);
return (result ?? null) as JsonValue;
}
case "getMemory": {
const memoryId = String(args.memoryId);
const memory = await this.runtime.getMemoryById(
memoryId as Parameters<IAgentRuntime["getMemoryById"]>[0],
);
return (memory ?? null) as unknown as JsonValue;
}
case "createMemory": {
const memory = args.memory as JsonValue;
const tableName =
typeof args.tableName === "string" ? args.tableName : undefined;
const created = await this.runtime.createMemory(
memory as unknown as Memory,
tableName ?? "messages",
);
return String(created);
}
case "updateMemory": {
await this.runtime.updateMemory(
args.memory as unknown as Parameters<
IAgentRuntime["updateMemory"]
>[0],
);
return null;
}
case "emitEvent": {
const eventName = String(args.name);
const payload = args.payload as JsonValue;
await this.runtime.emitEvent(
eventName as Parameters<IAgentRuntime["emitEvent"]>[0],
payload as unknown as Parameters<IAgentRuntime["emitEvent"]>[1],
);
return null;
}
case "getSetting": {
const key = String(args.key);
const value = this.runtime.getSetting(key);
return (value ?? null) as JsonValue;
}
case "setSetting": {
const key = String(args.key);
const value = args.value;
this.runtime.setSetting(
key,
value as Parameters<IAgentRuntime["setSetting"]>[1],
);
return null;
}
case "composeState": {
const memory = args.message as unknown as Memory;
const result = await this.runtime.composeState(memory);
return (result ?? null) as unknown as JsonValue;
}
default:
throw new Error(
`Unsupported host-rpc method: ${message.method}. P1 supports getService, useModel, getMemory, createMemory, updateMemory, emitEvent, getSetting, setSetting, composeState.`,
);
}
}
private normalize(value: unknown): JsonValue {
if (value === undefined) return null;
try {
return JSON.parse(JSON.stringify(value)) as JsonValue;
} catch {
return null;
}
}
}