@vagarylabs/plugin-sdk 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +1224 -0
  2. package/dist/bundlers.d.ts +57 -0
  3. package/dist/bundlers.d.ts.map +1 -0
  4. package/dist/bundlers.js +106 -0
  5. package/dist/bundlers.js.map +1 -0
  6. package/dist/define-plugin.d.ts +266 -0
  7. package/dist/define-plugin.d.ts.map +1 -0
  8. package/dist/define-plugin.js +85 -0
  9. package/dist/define-plugin.js.map +1 -0
  10. package/dist/dev-cli.d.ts +3 -0
  11. package/dist/dev-cli.d.ts.map +1 -0
  12. package/dist/dev-cli.js +49 -0
  13. package/dist/dev-cli.js.map +1 -0
  14. package/dist/dev-server.d.ts +34 -0
  15. package/dist/dev-server.d.ts.map +1 -0
  16. package/dist/dev-server.js +194 -0
  17. package/dist/dev-server.js.map +1 -0
  18. package/dist/host-client-factory.d.ts +312 -0
  19. package/dist/host-client-factory.d.ts.map +1 -0
  20. package/dist/host-client-factory.js +623 -0
  21. package/dist/host-client-factory.js.map +1 -0
  22. package/dist/index.d.ts +84 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +84 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/protocol.d.ts +1556 -0
  27. package/dist/protocol.d.ts.map +1 -0
  28. package/dist/protocol.js +369 -0
  29. package/dist/protocol.js.map +1 -0
  30. package/dist/testing.d.ts +183 -0
  31. package/dist/testing.d.ts.map +1 -0
  32. package/dist/testing.js +2265 -0
  33. package/dist/testing.js.map +1 -0
  34. package/dist/types.d.ts +1621 -0
  35. package/dist/types.d.ts.map +1 -0
  36. package/dist/types.js +12 -0
  37. package/dist/types.js.map +1 -0
  38. package/dist/ui/components.d.ts +517 -0
  39. package/dist/ui/components.d.ts.map +1 -0
  40. package/dist/ui/components.js +135 -0
  41. package/dist/ui/components.js.map +1 -0
  42. package/dist/ui/hooks.d.ts +155 -0
  43. package/dist/ui/hooks.d.ts.map +1 -0
  44. package/dist/ui/hooks.js +195 -0
  45. package/dist/ui/hooks.js.map +1 -0
  46. package/dist/ui/index.d.ts +54 -0
  47. package/dist/ui/index.d.ts.map +1 -0
  48. package/dist/ui/index.js +51 -0
  49. package/dist/ui/index.js.map +1 -0
  50. package/dist/ui/runtime.d.ts +3 -0
  51. package/dist/ui/runtime.d.ts.map +1 -0
  52. package/dist/ui/runtime.js +30 -0
  53. package/dist/ui/runtime.js.map +1 -0
  54. package/dist/ui/types.d.ts +400 -0
  55. package/dist/ui/types.d.ts.map +1 -0
  56. package/dist/ui/types.js +17 -0
  57. package/dist/ui/types.js.map +1 -0
  58. package/dist/worker-rpc-host.d.ts +128 -0
  59. package/dist/worker-rpc-host.d.ts.map +1 -0
  60. package/dist/worker-rpc-host.js +1510 -0
  61. package/dist/worker-rpc-host.js.map +1 -0
  62. package/package.json +128 -0
@@ -0,0 +1,1510 @@
1
+ /**
2
+ * Worker-side RPC host — runs inside the child process spawned by the host.
3
+ *
4
+ * This module is the worker-side counterpart to the server's
5
+ * `PluginWorkerManager`. It:
6
+ *
7
+ * 1. Reads newline-delimited JSON-RPC 2.0 requests from **stdin**
8
+ * 2. Dispatches them to the appropriate plugin handler (events, jobs, tools, …)
9
+ * 3. Writes JSON-RPC 2.0 responses back on **stdout**
10
+ * 4. Provides a concrete `PluginContext` whose SDK client methods (e.g.
11
+ * `ctx.state.get()`, `ctx.events.emit()`) send JSON-RPC requests to the
12
+ * host on stdout and await responses on stdin.
13
+ *
14
+ * ## Message flow
15
+ *
16
+ * ```
17
+ * Host (parent) Worker (this module)
18
+ * | |
19
+ * |--- request(initialize) -------------> | → calls plugin.setup(ctx)
20
+ * |<-- response(ok:true) ---------------- |
21
+ * | |
22
+ * |--- notification(onEvent) -----------> | → dispatches to registered handler
23
+ * | |
24
+ * |<-- request(state.get) --------------- | ← SDK client call from plugin code
25
+ * |--- response(result) ----------------> |
26
+ * | |
27
+ * |--- request(shutdown) ---------------> | → calls plugin.onShutdown()
28
+ * |<-- response(void) ------------------ |
29
+ * | (process exits)
30
+ * ```
31
+ *
32
+ * @see PLUGIN_SPEC.md §12 — Process Model
33
+ * @see PLUGIN_SPEC.md §13 — Host-Worker Protocol
34
+ * @see PLUGIN_SPEC.md §14 — SDK Surface
35
+ */
36
+ import fs from "node:fs";
37
+ import { AsyncLocalStorage } from "node:async_hooks";
38
+ import path from "node:path";
39
+ import { createInterface } from "node:readline";
40
+ import { fileURLToPath } from "node:url";
41
+ import { JSONRPC_ERROR_CODES, PLUGIN_RPC_ERROR_CODES, createRequest, createSuccessResponse, createErrorResponse, createNotification, parseMessage, serializeMessage, isJsonRpcRequest, isJsonRpcResponse, isJsonRpcNotification, isJsonRpcSuccessResponse, isJsonRpcErrorResponse, JsonRpcParseError, JsonRpcCallError, } from "./protocol.js";
42
+ // ---------------------------------------------------------------------------
43
+ // Constants
44
+ // ---------------------------------------------------------------------------
45
+ /** Default timeout for worker→host RPC calls. */
46
+ const DEFAULT_RPC_TIMEOUT_MS = 30_000;
47
+ function realpathOrResolvedPath(filePath) {
48
+ const resolvedPath = path.resolve(filePath);
49
+ try {
50
+ return fs.realpathSync.native(resolvedPath);
51
+ }
52
+ catch {
53
+ return resolvedPath;
54
+ }
55
+ }
56
+ export function isWorkerEntrypoint(entry, moduleUrl) {
57
+ const thisFile = realpathOrResolvedPath(fileURLToPath(moduleUrl));
58
+ const entryPath = realpathOrResolvedPath(entry);
59
+ return thisFile === entryPath;
60
+ }
61
+ /**
62
+ * Start the worker when this module is the process entrypoint.
63
+ *
64
+ * Call this at the bottom of your worker file so that when the host runs
65
+ * `node dist/worker.js`, the RPC host starts and the process stays alive.
66
+ * When the module is imported (e.g. for re-exports or tests), nothing runs.
67
+ *
68
+ * When `options.stdin` and `options.stdout` are provided (e.g. in tests),
69
+ * the main-module check is skipped and the host is started with those streams.
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * const plugin = definePlugin({ ... });
74
+ * export default plugin;
75
+ * runWorker(plugin, import.meta.url);
76
+ * ```
77
+ */
78
+ export function runWorker(plugin, moduleUrl, options) {
79
+ if (options?.stdin != null &&
80
+ options?.stdout != null) {
81
+ return startWorkerRpcHost({
82
+ plugin,
83
+ stdin: options.stdin,
84
+ stdout: options.stdout,
85
+ });
86
+ }
87
+ const entry = process.argv[1];
88
+ if (typeof entry !== "string")
89
+ return;
90
+ if (isWorkerEntrypoint(entry, moduleUrl)) {
91
+ startWorkerRpcHost({ plugin });
92
+ }
93
+ }
94
+ /**
95
+ * Start the worker-side RPC host.
96
+ *
97
+ * This function is typically called from a thin bootstrap script that is the
98
+ * actual entrypoint of the child process:
99
+ *
100
+ * ```ts
101
+ * // worker-bootstrap.ts
102
+ * import plugin from "./worker.js";
103
+ * import { startWorkerRpcHost } from "@vagris/plugin-sdk";
104
+ *
105
+ * startWorkerRpcHost({ plugin });
106
+ * ```
107
+ *
108
+ * The host begins listening on stdin immediately. It does NOT call
109
+ * `plugin.definition.setup()` yet — that happens when the host sends the
110
+ * `initialize` RPC.
111
+ *
112
+ * @returns A handle for inspecting or stopping the RPC host
113
+ */
114
+ export function startWorkerRpcHost(options) {
115
+ const { plugin } = options;
116
+ const stdinStream = options.stdin ?? process.stdin;
117
+ const stdoutStream = options.stdout ?? process.stdout;
118
+ const rpcTimeoutMs = options.rpcTimeoutMs ?? DEFAULT_RPC_TIMEOUT_MS;
119
+ // -----------------------------------------------------------------------
120
+ // State
121
+ // -----------------------------------------------------------------------
122
+ let running = true;
123
+ let initialized = false;
124
+ let manifest = null;
125
+ let currentConfig = {};
126
+ let databaseNamespace = null;
127
+ /**
128
+ * Per-method field lists the HOST advertised at `initialize`. `null` means the host never sent
129
+ * one — an older host — which is treated as "unknown, assume supported", never as "supports
130
+ * nothing". See {@link warnUnsupportedRequestFields}.
131
+ */
132
+ let hostSupportedRequestFields = null;
133
+ /** Signatures already warned about, so a plugin creating 1000 issues logs once, not 1000 times. */
134
+ const warnedFieldSkews = new Set();
135
+ const invocationContextStorage = new AsyncLocalStorage();
136
+ // Plugin handler registrations (populated during setup())
137
+ const eventHandlers = [];
138
+ const jobHandlers = new Map();
139
+ const launcherRegistrations = new Map();
140
+ const dataHandlers = new Map();
141
+ const actionHandlers = new Map();
142
+ const toolHandlers = new Map();
143
+ // Agent session event callbacks (populated by sendMessage, cleared by close)
144
+ const sessionEventCallbacks = new Map();
145
+ // Pending outbound (worker→host) requests
146
+ const pendingRequests = new Map();
147
+ let nextOutboundId = 1;
148
+ const MAX_OUTBOUND_ID = Number.MAX_SAFE_INTEGER - 1;
149
+ // -----------------------------------------------------------------------
150
+ // Outbound messaging (worker → host)
151
+ // -----------------------------------------------------------------------
152
+ function sendMessage(message) {
153
+ if (!running)
154
+ return;
155
+ const serialized = serializeMessage(message);
156
+ stdoutStream.write(serialized);
157
+ }
158
+ /**
159
+ * Warn when this plugin emits a field the host did not advertise support for.
160
+ *
161
+ * THE DEFECT: a worker enumerates the fields it forwards (see `issues.create` below — enumerated
162
+ * deliberately, so an omission drops the field). A plugin built against a NEWER SDK therefore
163
+ * sends fields an older host does not destructure; the host drops them in silence, and the only
164
+ * symptom is a row missing a column nobody notices. `apiVersion` cannot see this — it is one
165
+ * integer for the whole protocol, unchanged by a field addition.
166
+ *
167
+ * Lives in `callHost`, the single outbound choke point, rather than in `issues.create`: covering
168
+ * another method is then one entry in `HOST_SUPPORTED_REQUEST_FIELDS` and no new call-site code.
169
+ *
170
+ * SILENT BY DEFAULT in both unknown cases — no advertisement at all (older host) and no entry for
171
+ * this method (unchecked method) — because a warning a plugin author cannot act on is noise, and
172
+ * all in-tree plugins run against a host of their own version.
173
+ */
174
+ function warnUnsupportedRequestFields(method, params) {
175
+ const supported = hostSupportedRequestFields?.[method];
176
+ if (!supported || params === null || typeof params !== "object")
177
+ return;
178
+ const unsupported = Object.entries(params)
179
+ // An `undefined` value is a field the caller did not set; the enumeration emits every key
180
+ // regardless, so counting them would warn about fields nobody sent.
181
+ .filter(([, value]) => value !== undefined)
182
+ .map(([key]) => key)
183
+ .filter((key) => !supported.includes(key));
184
+ if (unsupported.length === 0)
185
+ return;
186
+ const signature = `${method}:${unsupported.join(",")}`;
187
+ if (warnedFieldSkews.has(signature))
188
+ return;
189
+ warnedFieldSkews.add(signature);
190
+ notifyHost("log", {
191
+ level: "warn",
192
+ message: `Host does not support field(s) on "${method}": ${unsupported.join(", ")}. ` +
193
+ `They will be SILENTLY DROPPED — this plugin's SDK is newer than the host.`,
194
+ meta: { method, unsupportedFields: unsupported },
195
+ });
196
+ }
197
+ /**
198
+ * Send a typed JSON-RPC request to the host and await the response.
199
+ */
200
+ function callHost(method, params, timeoutMs) {
201
+ warnUnsupportedRequestFields(method, params);
202
+ return new Promise((resolve, reject) => {
203
+ if (!running) {
204
+ reject(new Error(`Cannot call "${method}" — worker RPC host is not running`));
205
+ return;
206
+ }
207
+ if (nextOutboundId >= MAX_OUTBOUND_ID) {
208
+ nextOutboundId = 1;
209
+ }
210
+ const id = nextOutboundId++;
211
+ const timeout = timeoutMs ?? rpcTimeoutMs;
212
+ let settled = false;
213
+ const settle = (fn, value) => {
214
+ if (settled)
215
+ return;
216
+ settled = true;
217
+ clearTimeout(timer);
218
+ pendingRequests.delete(id);
219
+ fn(value);
220
+ };
221
+ const timer = setTimeout(() => {
222
+ settle(reject, new JsonRpcCallError({
223
+ code: PLUGIN_RPC_ERROR_CODES.TIMEOUT,
224
+ message: `Worker→host call "${method}" timed out after ${timeout}ms`,
225
+ }));
226
+ }, timeout);
227
+ pendingRequests.set(id, {
228
+ resolve: (response) => {
229
+ if (isJsonRpcSuccessResponse(response)) {
230
+ settle(resolve, response.result);
231
+ }
232
+ else if (isJsonRpcErrorResponse(response)) {
233
+ settle(reject, new JsonRpcCallError(response.error));
234
+ }
235
+ else {
236
+ settle(reject, new Error(`Unexpected response format for "${method}"`));
237
+ }
238
+ },
239
+ timer,
240
+ });
241
+ try {
242
+ const activeInvocation = invocationContextStorage.getStore();
243
+ const request = {
244
+ ...createRequest(method, params, id),
245
+ ...(activeInvocation ? { paperclipInvocationId: activeInvocation.id } : {}),
246
+ };
247
+ sendMessage(request);
248
+ }
249
+ catch (err) {
250
+ settle(reject, err instanceof Error ? err : new Error(String(err)));
251
+ }
252
+ });
253
+ }
254
+ /**
255
+ * Send a JSON-RPC notification to the host (fire-and-forget).
256
+ */
257
+ function notifyHost(method, params) {
258
+ try {
259
+ const activeInvocation = invocationContextStorage.getStore();
260
+ sendMessage({
261
+ ...createNotification(method, params),
262
+ ...(activeInvocation ? { paperclipInvocationId: activeInvocation.id } : {}),
263
+ });
264
+ }
265
+ catch {
266
+ // Swallow — the host may have closed stdin
267
+ }
268
+ }
269
+ // -----------------------------------------------------------------------
270
+ // Build the PluginContext (SDK surface for plugin code)
271
+ // -----------------------------------------------------------------------
272
+ function buildContext() {
273
+ return {
274
+ get manifest() {
275
+ if (!manifest)
276
+ throw new Error("Plugin context accessed before initialization");
277
+ return manifest;
278
+ },
279
+ /**
280
+ * ARCH-5 — the host's advertisement, READ BY THE PLUGIN.
281
+ *
282
+ * The skew check inside `callHost` reports to the HOST (a `log` notification), which is the
283
+ * wrong party: the host is the one that already knows. A published SDK means the plugin author
284
+ * is the one who can act — by not sending the field, by degrading, or by refusing to start —
285
+ * and until this client existed the advertisement lived in a module-local `let` nothing outside
286
+ * this file could read. This is the pull half of the same fact, on the surface a plugin
287
+ * actually receives (`setup(ctx)`), so it needs no host cooperation and no new RPC.
288
+ *
289
+ * Does NOT throw before initialization: an accessor whose failure mode is a crash during setup
290
+ * would be worse than the silence it replaces. Un-initialized reads as UNKNOWN, like an older
291
+ * host, because that is exactly what it is — no advertisement has arrived.
292
+ */
293
+ host: {
294
+ supportedRequestFields() {
295
+ return hostSupportedRequestFields;
296
+ },
297
+ supportsRequestField(method, field) {
298
+ const supported = hostSupportedRequestFields?.[method];
299
+ if (!supported)
300
+ return null;
301
+ return supported.includes(field);
302
+ },
303
+ unsupportedRequestFields(method, fields) {
304
+ const supported = hostSupportedRequestFields?.[method];
305
+ if (!supported)
306
+ return [];
307
+ return fields.filter((f) => !supported.includes(f));
308
+ },
309
+ },
310
+ config: {
311
+ async get() {
312
+ return callHost("config.get", {});
313
+ },
314
+ },
315
+ localFolders: {
316
+ declarations() {
317
+ if (!manifest)
318
+ throw new Error("Plugin context accessed before initialization");
319
+ return manifest.localFolders ?? [];
320
+ },
321
+ async configure(input) {
322
+ return callHost("localFolders.configure", {
323
+ companyId: input.companyId,
324
+ folderKey: input.folderKey,
325
+ path: input.path,
326
+ access: input.access,
327
+ requiredDirectories: input.requiredDirectories,
328
+ requiredFiles: input.requiredFiles,
329
+ });
330
+ },
331
+ async status(companyId, folderKey) {
332
+ return callHost("localFolders.status", { companyId, folderKey });
333
+ },
334
+ async list(companyId, folderKey, options = {}) {
335
+ return callHost("localFolders.list", {
336
+ companyId,
337
+ folderKey,
338
+ relativePath: options.relativePath,
339
+ recursive: options.recursive,
340
+ maxEntries: options.maxEntries,
341
+ });
342
+ },
343
+ async readText(companyId, folderKey, relativePath) {
344
+ return callHost("localFolders.readText", { companyId, folderKey, relativePath });
345
+ },
346
+ async writeTextAtomic(companyId, folderKey, relativePath, contents) {
347
+ return callHost("localFolders.writeTextAtomic", {
348
+ companyId,
349
+ folderKey,
350
+ relativePath,
351
+ contents,
352
+ });
353
+ },
354
+ async deleteFile(companyId, folderKey, relativePath) {
355
+ return callHost("localFolders.deleteFile", { companyId, folderKey, relativePath });
356
+ },
357
+ },
358
+ events: {
359
+ on(name, filterOrFn, maybeFn) {
360
+ let registration;
361
+ if (typeof filterOrFn === "function") {
362
+ registration = { name, fn: filterOrFn };
363
+ }
364
+ else {
365
+ if (!maybeFn)
366
+ throw new Error("Event handler function is required");
367
+ registration = { name, filter: filterOrFn, fn: maybeFn };
368
+ }
369
+ eventHandlers.push(registration);
370
+ // Register subscription on the host so events are forwarded to this worker
371
+ void callHost("events.subscribe", { eventPattern: name, filter: registration.filter ?? null }).catch((err) => {
372
+ notifyHost("log", {
373
+ level: "warn",
374
+ message: `Failed to subscribe to event "${name}" on host: ${err instanceof Error ? err.message : String(err)}`,
375
+ });
376
+ });
377
+ return () => {
378
+ const idx = eventHandlers.indexOf(registration);
379
+ if (idx !== -1)
380
+ eventHandlers.splice(idx, 1);
381
+ };
382
+ },
383
+ async emit(name, companyId, payload) {
384
+ await callHost("events.emit", { name, companyId, payload });
385
+ },
386
+ },
387
+ jobs: {
388
+ register(key, fn) {
389
+ jobHandlers.set(key, fn);
390
+ },
391
+ },
392
+ launchers: {
393
+ register(launcher) {
394
+ launcherRegistrations.set(launcher.id, launcher);
395
+ },
396
+ },
397
+ db: {
398
+ get namespace() {
399
+ return databaseNamespace ?? "";
400
+ },
401
+ async query(sql, params) {
402
+ return callHost("db.query", { sql, params });
403
+ },
404
+ async execute(sql, params) {
405
+ return callHost("db.execute", { sql, params });
406
+ },
407
+ },
408
+ http: {
409
+ async fetch(url, init) {
410
+ const serializedInit = {};
411
+ if (init) {
412
+ if (init.method)
413
+ serializedInit.method = init.method;
414
+ if (init.headers) {
415
+ // Normalize headers to a plain object
416
+ if (init.headers instanceof Headers) {
417
+ const obj = {};
418
+ init.headers.forEach((v, k) => { obj[k] = v; });
419
+ serializedInit.headers = obj;
420
+ }
421
+ else if (Array.isArray(init.headers)) {
422
+ const obj = {};
423
+ for (const [k, v] of init.headers)
424
+ obj[k] = v;
425
+ serializedInit.headers = obj;
426
+ }
427
+ else {
428
+ serializedInit.headers = init.headers;
429
+ }
430
+ }
431
+ if (init.body !== undefined && init.body !== null) {
432
+ serializedInit.body = typeof init.body === "string"
433
+ ? init.body
434
+ : String(init.body);
435
+ }
436
+ }
437
+ const result = await callHost("http.fetch", {
438
+ url,
439
+ init: Object.keys(serializedInit).length > 0 ? serializedInit : undefined,
440
+ });
441
+ // Reconstruct a Response-like object from the serialized result
442
+ return new Response(result.body, {
443
+ status: result.status,
444
+ statusText: result.statusText,
445
+ headers: result.headers,
446
+ });
447
+ },
448
+ },
449
+ secrets: {
450
+ async resolve(secretRef) {
451
+ return callHost("secrets.resolve", { secretRef });
452
+ },
453
+ },
454
+ activity: {
455
+ async log(entry) {
456
+ await callHost("activity.log", {
457
+ companyId: entry.companyId,
458
+ message: entry.message,
459
+ entityType: entry.entityType,
460
+ entityId: entry.entityId,
461
+ metadata: entry.metadata,
462
+ });
463
+ },
464
+ },
465
+ state: {
466
+ async get(input) {
467
+ return callHost("state.get", {
468
+ scopeKind: input.scopeKind,
469
+ scopeId: input.scopeId,
470
+ namespace: input.namespace,
471
+ stateKey: input.stateKey,
472
+ });
473
+ },
474
+ async set(input, value) {
475
+ await callHost("state.set", {
476
+ scopeKind: input.scopeKind,
477
+ scopeId: input.scopeId,
478
+ namespace: input.namespace,
479
+ stateKey: input.stateKey,
480
+ value,
481
+ });
482
+ },
483
+ async delete(input) {
484
+ await callHost("state.delete", {
485
+ scopeKind: input.scopeKind,
486
+ scopeId: input.scopeId,
487
+ namespace: input.namespace,
488
+ stateKey: input.stateKey,
489
+ });
490
+ },
491
+ },
492
+ entities: {
493
+ async upsert(input) {
494
+ return callHost("entities.upsert", {
495
+ entityType: input.entityType,
496
+ scopeKind: input.scopeKind,
497
+ scopeId: input.scopeId,
498
+ externalId: input.externalId,
499
+ title: input.title,
500
+ status: input.status,
501
+ data: input.data,
502
+ });
503
+ },
504
+ async list(query) {
505
+ return callHost("entities.list", {
506
+ entityType: query.entityType,
507
+ scopeKind: query.scopeKind,
508
+ scopeId: query.scopeId,
509
+ externalId: query.externalId,
510
+ limit: query.limit,
511
+ offset: query.offset,
512
+ });
513
+ },
514
+ },
515
+ projects: {
516
+ async list(input) {
517
+ return callHost("projects.list", {
518
+ companyId: input.companyId,
519
+ limit: input.limit,
520
+ offset: input.offset,
521
+ });
522
+ },
523
+ async get(projectId, companyId) {
524
+ return callHost("projects.get", { projectId, companyId });
525
+ },
526
+ async listWorkspaces(projectId, companyId) {
527
+ return callHost("projects.listWorkspaces", { projectId, companyId });
528
+ },
529
+ async getPrimaryWorkspace(projectId, companyId) {
530
+ return callHost("projects.getPrimaryWorkspace", { projectId, companyId });
531
+ },
532
+ async getWorkspaceForIssue(issueId, companyId) {
533
+ return callHost("projects.getWorkspaceForIssue", { issueId, companyId });
534
+ },
535
+ managed: {
536
+ async get(projectKey, companyId) {
537
+ return callHost("projects.managed.get", { projectKey, companyId });
538
+ },
539
+ async reconcile(projectKey, companyId) {
540
+ return callHost("projects.managed.reconcile", { projectKey, companyId });
541
+ },
542
+ async reset(projectKey, companyId) {
543
+ return callHost("projects.managed.reset", { projectKey, companyId });
544
+ },
545
+ },
546
+ },
547
+ executionWorkspaces: {
548
+ async get(workspaceId, companyId) {
549
+ return callHost("executionWorkspaces.get", { workspaceId, companyId });
550
+ },
551
+ },
552
+ routines: {
553
+ managed: {
554
+ async get(routineKey, companyId) {
555
+ return callHost("routines.managed.get", { routineKey, companyId });
556
+ },
557
+ async reconcile(routineKey, companyId, overrides) {
558
+ return callHost("routines.managed.reconcile", { routineKey, companyId, ...overrides });
559
+ },
560
+ async reset(routineKey, companyId, overrides) {
561
+ return callHost("routines.managed.reset", { routineKey, companyId, ...overrides });
562
+ },
563
+ async update(routineKey, companyId, patch) {
564
+ return callHost("routines.managed.update", { routineKey, companyId, ...patch });
565
+ },
566
+ async run(routineKey, companyId, overrides) {
567
+ return callHost("routines.managed.run", { routineKey, companyId, ...overrides });
568
+ },
569
+ },
570
+ },
571
+ skills: {
572
+ managed: {
573
+ async get(skillKey, companyId) {
574
+ return callHost("skills.managed.get", { skillKey, companyId });
575
+ },
576
+ async reconcile(skillKey, companyId) {
577
+ return callHost("skills.managed.reconcile", { skillKey, companyId });
578
+ },
579
+ async reset(skillKey, companyId) {
580
+ return callHost("skills.managed.reset", { skillKey, companyId });
581
+ },
582
+ },
583
+ },
584
+ companies: {
585
+ async list(input) {
586
+ return callHost("companies.list", {
587
+ limit: input?.limit,
588
+ offset: input?.offset,
589
+ });
590
+ },
591
+ async get(companyId) {
592
+ return callHost("companies.get", { companyId });
593
+ },
594
+ },
595
+ issues: {
596
+ async list(input) {
597
+ return callHost("issues.list", {
598
+ companyId: input.companyId,
599
+ projectId: input.projectId,
600
+ assigneeAgentId: input.assigneeAgentId,
601
+ originKind: input.originKind,
602
+ originKindPrefix: input.originKindPrefix,
603
+ originId: input.originId,
604
+ status: input.status,
605
+ includePluginOperations: input.includePluginOperations,
606
+ limit: input.limit,
607
+ offset: input.offset,
608
+ });
609
+ },
610
+ async get(issueId, companyId) {
611
+ return callHost("issues.get", { issueId, companyId });
612
+ },
613
+ async create(input) {
614
+ return callHost("issues.create", {
615
+ companyId: input.companyId,
616
+ projectId: input.projectId,
617
+ goalId: input.goalId,
618
+ parentId: input.parentId,
619
+ inheritExecutionWorkspaceFromIssueId: input.inheritExecutionWorkspaceFromIssueId,
620
+ title: input.title,
621
+ description: input.description,
622
+ status: input.status,
623
+ priority: input.priority,
624
+ assigneeAgentId: input.assigneeAgentId,
625
+ assigneeUserId: input.assigneeUserId,
626
+ requestDepth: input.requestDepth,
627
+ billingCode: input.billingCode,
628
+ assigneeAdapterOverrides: input.assigneeAdapterOverrides,
629
+ surfaceVisibility: input.surfaceVisibility,
630
+ originKind: input.originKind,
631
+ originId: input.originId,
632
+ originRunId: input.originRunId,
633
+ // Enumerated, not spread — a field missing from this list is SILENTLY DROPPED.
634
+ originFingerprint: input.originFingerprint,
635
+ blockedByIssueIds: input.blockedByIssueIds,
636
+ labelIds: input.labelIds,
637
+ executionWorkspaceId: input.executionWorkspaceId,
638
+ executionWorkspacePreference: input.executionWorkspacePreference,
639
+ executionWorkspaceSettings: input.executionWorkspaceSettings,
640
+ actorAgentId: input.actor?.actorAgentId,
641
+ actorUserId: input.actor?.actorUserId,
642
+ actorRunId: input.actor?.actorRunId,
643
+ });
644
+ },
645
+ async update(issueId, patch, companyId, actor) {
646
+ return callHost("issues.update", {
647
+ issueId,
648
+ patch: {
649
+ ...patch,
650
+ actorAgentId: actor?.actorAgentId,
651
+ actorUserId: actor?.actorUserId,
652
+ actorRunId: actor?.actorRunId,
653
+ },
654
+ companyId,
655
+ });
656
+ },
657
+ async assertCheckoutOwner(input) {
658
+ return callHost("issues.assertCheckoutOwner", input);
659
+ },
660
+ async getSubtree(issueId, companyId, options) {
661
+ return callHost("issues.getSubtree", {
662
+ issueId,
663
+ companyId,
664
+ includeRoot: options?.includeRoot,
665
+ includeRelations: options?.includeRelations,
666
+ includeDocuments: options?.includeDocuments,
667
+ includeActiveRuns: options?.includeActiveRuns,
668
+ includeAssignees: options?.includeAssignees,
669
+ });
670
+ },
671
+ async requestWakeup(issueId, companyId, options) {
672
+ return callHost("issues.requestWakeup", {
673
+ issueId,
674
+ companyId,
675
+ reason: options?.reason,
676
+ contextSource: options?.contextSource,
677
+ idempotencyKey: options?.idempotencyKey,
678
+ actorAgentId: options?.actorAgentId,
679
+ actorUserId: options?.actorUserId,
680
+ actorRunId: options?.actorRunId,
681
+ });
682
+ },
683
+ async requestWakeups(issueIds, companyId, options) {
684
+ return callHost("issues.requestWakeups", {
685
+ issueIds,
686
+ companyId,
687
+ reason: options?.reason,
688
+ contextSource: options?.contextSource,
689
+ idempotencyKeyPrefix: options?.idempotencyKeyPrefix,
690
+ actorAgentId: options?.actorAgentId,
691
+ actorUserId: options?.actorUserId,
692
+ actorRunId: options?.actorRunId,
693
+ });
694
+ },
695
+ async listComments(issueId, companyId) {
696
+ return callHost("issues.listComments", { issueId, companyId });
697
+ },
698
+ async createComment(issueId, body, companyId, options) {
699
+ return callHost("issues.createComment", { issueId, body, companyId, authorAgentId: options?.authorAgentId });
700
+ },
701
+ async createInteraction(issueId, interaction, companyId, options) {
702
+ return callHost("issues.createInteraction", {
703
+ issueId,
704
+ companyId,
705
+ interaction,
706
+ authorAgentId: options?.authorAgentId,
707
+ });
708
+ },
709
+ async suggestTasks(issueId, interaction, companyId, options) {
710
+ return callHost("issues.createInteraction", {
711
+ issueId,
712
+ companyId,
713
+ interaction: {
714
+ ...interaction,
715
+ kind: "suggest_tasks",
716
+ },
717
+ authorAgentId: options?.authorAgentId,
718
+ });
719
+ },
720
+ async askUserQuestions(issueId, interaction, companyId, options) {
721
+ return callHost("issues.createInteraction", {
722
+ issueId,
723
+ companyId,
724
+ interaction: {
725
+ ...interaction,
726
+ kind: "ask_user_questions",
727
+ },
728
+ authorAgentId: options?.authorAgentId,
729
+ });
730
+ },
731
+ async requestConfirmation(issueId, interaction, companyId, options) {
732
+ return callHost("issues.createInteraction", {
733
+ issueId,
734
+ companyId,
735
+ interaction: {
736
+ ...interaction,
737
+ kind: "request_confirmation",
738
+ },
739
+ authorAgentId: options?.authorAgentId,
740
+ });
741
+ },
742
+ documents: {
743
+ async list(issueId, companyId) {
744
+ return callHost("issues.documents.list", { issueId, companyId });
745
+ },
746
+ async get(issueId, key, companyId) {
747
+ return callHost("issues.documents.get", { issueId, key, companyId });
748
+ },
749
+ async upsert(input) {
750
+ return callHost("issues.documents.upsert", {
751
+ issueId: input.issueId,
752
+ key: input.key,
753
+ body: input.body,
754
+ companyId: input.companyId,
755
+ title: input.title,
756
+ format: input.format,
757
+ changeSummary: input.changeSummary,
758
+ });
759
+ },
760
+ async delete(issueId, key, companyId) {
761
+ return callHost("issues.documents.delete", { issueId, key, companyId });
762
+ },
763
+ },
764
+ relations: {
765
+ async get(issueId, companyId) {
766
+ return callHost("issues.relations.get", { issueId, companyId });
767
+ },
768
+ async setBlockedBy(issueId, blockedByIssueIds, companyId, actor) {
769
+ return callHost("issues.relations.setBlockedBy", {
770
+ issueId,
771
+ companyId,
772
+ blockedByIssueIds,
773
+ actorAgentId: actor?.actorAgentId,
774
+ actorUserId: actor?.actorUserId,
775
+ actorRunId: actor?.actorRunId,
776
+ });
777
+ },
778
+ async addBlockers(issueId, blockerIssueIds, companyId, actor) {
779
+ return callHost("issues.relations.addBlockers", {
780
+ issueId,
781
+ companyId,
782
+ blockerIssueIds,
783
+ actorAgentId: actor?.actorAgentId,
784
+ actorUserId: actor?.actorUserId,
785
+ actorRunId: actor?.actorRunId,
786
+ });
787
+ },
788
+ async removeBlockers(issueId, blockerIssueIds, companyId, actor) {
789
+ return callHost("issues.relations.removeBlockers", {
790
+ issueId,
791
+ companyId,
792
+ blockerIssueIds,
793
+ actorAgentId: actor?.actorAgentId,
794
+ actorUserId: actor?.actorUserId,
795
+ actorRunId: actor?.actorRunId,
796
+ });
797
+ },
798
+ },
799
+ summaries: {
800
+ async getOrchestration(input) {
801
+ return callHost("issues.summaries.getOrchestration", input);
802
+ },
803
+ },
804
+ },
805
+ agents: {
806
+ async list(input) {
807
+ return callHost("agents.list", {
808
+ companyId: input.companyId,
809
+ status: input.status,
810
+ limit: input.limit,
811
+ offset: input.offset,
812
+ });
813
+ },
814
+ async get(agentId, companyId) {
815
+ return callHost("agents.get", { agentId, companyId });
816
+ },
817
+ async pause(agentId, companyId) {
818
+ return callHost("agents.pause", { agentId, companyId });
819
+ },
820
+ async resume(agentId, companyId) {
821
+ return callHost("agents.resume", { agentId, companyId });
822
+ },
823
+ async invoke(agentId, companyId, opts) {
824
+ return callHost("agents.invoke", { agentId, companyId, prompt: opts.prompt, reason: opts.reason });
825
+ },
826
+ managed: {
827
+ async get(agentKey, companyId) {
828
+ return callHost("agents.managed.get", { agentKey, companyId });
829
+ },
830
+ async reconcile(agentKey, companyId) {
831
+ return callHost("agents.managed.reconcile", { agentKey, companyId });
832
+ },
833
+ async reset(agentKey, companyId) {
834
+ return callHost("agents.managed.reset", { agentKey, companyId });
835
+ },
836
+ },
837
+ sessions: {
838
+ async create(agentId, companyId, opts) {
839
+ return callHost("agents.sessions.create", {
840
+ agentId,
841
+ companyId,
842
+ taskKey: opts?.taskKey,
843
+ reason: opts?.reason,
844
+ });
845
+ },
846
+ async list(agentId, companyId) {
847
+ return callHost("agents.sessions.list", { agentId, companyId });
848
+ },
849
+ async sendMessage(sessionId, companyId, opts) {
850
+ if (opts.onEvent) {
851
+ sessionEventCallbacks.set(sessionId, opts.onEvent);
852
+ }
853
+ try {
854
+ return await callHost("agents.sessions.sendMessage", {
855
+ sessionId,
856
+ companyId,
857
+ prompt: opts.prompt,
858
+ reason: opts.reason,
859
+ });
860
+ }
861
+ catch (err) {
862
+ sessionEventCallbacks.delete(sessionId);
863
+ throw err;
864
+ }
865
+ },
866
+ async close(sessionId, companyId) {
867
+ sessionEventCallbacks.delete(sessionId);
868
+ await callHost("agents.sessions.close", { sessionId, companyId });
869
+ },
870
+ },
871
+ },
872
+ goals: {
873
+ async list(input) {
874
+ return callHost("goals.list", {
875
+ companyId: input.companyId,
876
+ level: input.level,
877
+ status: input.status,
878
+ limit: input.limit,
879
+ offset: input.offset,
880
+ });
881
+ },
882
+ async get(goalId, companyId) {
883
+ return callHost("goals.get", { goalId, companyId });
884
+ },
885
+ async create(input) {
886
+ return callHost("goals.create", {
887
+ companyId: input.companyId,
888
+ title: input.title,
889
+ description: input.description,
890
+ level: input.level,
891
+ status: input.status,
892
+ parentId: input.parentId,
893
+ ownerAgentId: input.ownerAgentId,
894
+ });
895
+ },
896
+ async update(goalId, patch, companyId) {
897
+ return callHost("goals.update", {
898
+ goalId,
899
+ patch: patch,
900
+ companyId,
901
+ });
902
+ },
903
+ },
904
+ access: {
905
+ members: {
906
+ async list(input) {
907
+ return callHost("access.members.list", {
908
+ companyId: input.companyId,
909
+ includeArchived: input.includeArchived,
910
+ });
911
+ },
912
+ async get(memberId, companyId) {
913
+ return callHost("access.members.get", { memberId, companyId });
914
+ },
915
+ async update(memberId, patch, companyId) {
916
+ return callHost("access.members.update", { memberId, patch, companyId });
917
+ },
918
+ },
919
+ invites: {
920
+ async list(input) {
921
+ return callHost("access.invites.list", {
922
+ companyId: input.companyId,
923
+ state: input.state,
924
+ limit: input.limit,
925
+ offset: input.offset,
926
+ });
927
+ },
928
+ async create(input) {
929
+ return callHost("access.invites.create", {
930
+ companyId: input.companyId,
931
+ allowedJoinTypes: input.allowedJoinTypes,
932
+ humanRole: input.humanRole,
933
+ defaultsPayload: input.defaultsPayload,
934
+ agentMessage: input.agentMessage,
935
+ });
936
+ },
937
+ async revoke(inviteId, companyId) {
938
+ return callHost("access.invites.revoke", { inviteId, companyId });
939
+ },
940
+ },
941
+ },
942
+ authorization: {
943
+ grants: {
944
+ async list(input) {
945
+ return callHost("authorization.grants.list", input);
946
+ },
947
+ async set(input) {
948
+ return callHost("authorization.grants.set", input);
949
+ },
950
+ },
951
+ policies: {
952
+ async summary(companyId) {
953
+ return callHost("authorization.policies.summary", { companyId });
954
+ },
955
+ async get(input) {
956
+ return callHost("authorization.policies.get", input);
957
+ },
958
+ async update(input) {
959
+ return callHost("authorization.policies.update", input);
960
+ },
961
+ async previewAssignment(input) {
962
+ return callHost("authorization.policies.previewAssignment", input);
963
+ },
964
+ async explainAssignment(input) {
965
+ return callHost("authorization.policies.explainAssignment", input);
966
+ },
967
+ },
968
+ audit: {
969
+ async search(input) {
970
+ return callHost("authorization.audit.search", input);
971
+ },
972
+ },
973
+ },
974
+ data: {
975
+ register(key, handler) {
976
+ dataHandlers.set(key, handler);
977
+ },
978
+ },
979
+ actions: {
980
+ register(key, handler) {
981
+ actionHandlers.set(key, handler);
982
+ },
983
+ },
984
+ streams: (() => {
985
+ // Track channel → companyId so emit/close don't require companyId
986
+ const channelCompanyMap = new Map();
987
+ return {
988
+ open(channel, companyId) {
989
+ channelCompanyMap.set(channel, companyId);
990
+ notifyHost("streams.open", { channel, companyId });
991
+ },
992
+ emit(channel, event) {
993
+ const companyId = channelCompanyMap.get(channel) ?? "";
994
+ notifyHost("streams.emit", { channel, companyId, event });
995
+ },
996
+ close(channel) {
997
+ const companyId = channelCompanyMap.get(channel) ?? "";
998
+ channelCompanyMap.delete(channel);
999
+ notifyHost("streams.close", { channel, companyId });
1000
+ },
1001
+ };
1002
+ })(),
1003
+ tools: {
1004
+ register(name, declaration, fn) {
1005
+ toolHandlers.set(name, { declaration, fn });
1006
+ },
1007
+ },
1008
+ metrics: {
1009
+ async write(name, value, tags) {
1010
+ await callHost("metrics.write", { name, value, tags });
1011
+ },
1012
+ },
1013
+ telemetry: {
1014
+ async track(eventName, dimensions) {
1015
+ await callHost("telemetry.track", { eventName, dimensions });
1016
+ },
1017
+ },
1018
+ logger: {
1019
+ info(message, meta) {
1020
+ notifyHost("log", { level: "info", message, meta });
1021
+ },
1022
+ warn(message, meta) {
1023
+ notifyHost("log", { level: "warn", message, meta });
1024
+ },
1025
+ error(message, meta) {
1026
+ notifyHost("log", { level: "error", message, meta });
1027
+ },
1028
+ debug(message, meta) {
1029
+ notifyHost("log", { level: "debug", message, meta });
1030
+ },
1031
+ },
1032
+ };
1033
+ }
1034
+ const ctx = buildContext();
1035
+ // -----------------------------------------------------------------------
1036
+ // Inbound message handling (host → worker)
1037
+ // -----------------------------------------------------------------------
1038
+ /**
1039
+ * Handle an incoming JSON-RPC request from the host.
1040
+ *
1041
+ * Dispatches to the correct handler based on the method name.
1042
+ */
1043
+ async function handleHostRequest(request) {
1044
+ const { id, method, params } = request;
1045
+ try {
1046
+ const invoke = () => dispatchMethod(method, params);
1047
+ const result = request.paperclipInvocation
1048
+ ? await invocationContextStorage.run(request.paperclipInvocation, invoke)
1049
+ : await invoke();
1050
+ sendMessage(createSuccessResponse(id, result ?? null));
1051
+ }
1052
+ catch (err) {
1053
+ const errorMessage = err instanceof Error ? err.message : String(err);
1054
+ // Propagate specific error codes from handler errors (e.g.
1055
+ // METHOD_NOT_FOUND, METHOD_NOT_IMPLEMENTED) — fall back to
1056
+ // WORKER_ERROR for untyped exceptions.
1057
+ const errorCode = typeof err?.code === "number"
1058
+ ? err.code
1059
+ : PLUGIN_RPC_ERROR_CODES.WORKER_ERROR;
1060
+ sendMessage(createErrorResponse(id, errorCode, errorMessage));
1061
+ }
1062
+ }
1063
+ /**
1064
+ * Dispatch a host→worker method call to the appropriate handler.
1065
+ */
1066
+ async function dispatchMethod(method, params) {
1067
+ switch (method) {
1068
+ case "initialize":
1069
+ return handleInitialize(params);
1070
+ case "health":
1071
+ return handleHealth();
1072
+ case "shutdown":
1073
+ return handleShutdown();
1074
+ case "validateConfig":
1075
+ return handleValidateConfig(params);
1076
+ case "configChanged":
1077
+ return handleConfigChanged(params);
1078
+ case "onEvent":
1079
+ return handleOnEvent(params);
1080
+ case "runJob":
1081
+ return handleRunJob(params);
1082
+ case "handleWebhook":
1083
+ return handleWebhook(params);
1084
+ case "handleApiRequest":
1085
+ return handleApiRequest(params);
1086
+ case "getData":
1087
+ return handleGetData(params);
1088
+ case "performAction":
1089
+ return handlePerformAction(params);
1090
+ case "executeTool":
1091
+ return handleExecuteTool(params);
1092
+ case "environmentValidateConfig":
1093
+ return handleEnvironmentValidateConfig(params);
1094
+ case "environmentProbe":
1095
+ return handleEnvironmentProbe(params);
1096
+ case "environmentAcquireLease":
1097
+ return handleEnvironmentAcquireLease(params);
1098
+ case "environmentResumeLease":
1099
+ return handleEnvironmentResumeLease(params);
1100
+ case "environmentReleaseLease":
1101
+ return handleEnvironmentReleaseLease(params);
1102
+ case "environmentDestroyLease":
1103
+ return handleEnvironmentDestroyLease(params);
1104
+ case "environmentRealizeWorkspace":
1105
+ return handleEnvironmentRealizeWorkspace(params);
1106
+ case "environmentExecute":
1107
+ return handleEnvironmentExecute(params);
1108
+ default:
1109
+ throw Object.assign(new Error(`Unknown method: ${method}`), { code: JSONRPC_ERROR_CODES.METHOD_NOT_FOUND });
1110
+ }
1111
+ }
1112
+ // -----------------------------------------------------------------------
1113
+ // Host→Worker method handlers
1114
+ // -----------------------------------------------------------------------
1115
+ async function handleInitialize(params) {
1116
+ if (initialized) {
1117
+ throw new Error("Worker already initialized");
1118
+ }
1119
+ manifest = params.manifest;
1120
+ currentConfig = params.config;
1121
+ databaseNamespace = params.databaseNamespace ?? null;
1122
+ hostSupportedRequestFields = params.supportedRequestFields ?? null;
1123
+ // Call the plugin's setup function
1124
+ await plugin.definition.setup(ctx);
1125
+ initialized = true;
1126
+ // Report which optional methods this plugin implements
1127
+ const supportedMethods = [];
1128
+ if (plugin.definition.onValidateConfig)
1129
+ supportedMethods.push("validateConfig");
1130
+ if (plugin.definition.onConfigChanged)
1131
+ supportedMethods.push("configChanged");
1132
+ if (plugin.definition.onHealth)
1133
+ supportedMethods.push("health");
1134
+ if (plugin.definition.onShutdown)
1135
+ supportedMethods.push("shutdown");
1136
+ if (plugin.definition.onApiRequest)
1137
+ supportedMethods.push("handleApiRequest");
1138
+ if (plugin.definition.onEnvironmentValidateConfig)
1139
+ supportedMethods.push("environmentValidateConfig");
1140
+ if (plugin.definition.onEnvironmentProbe)
1141
+ supportedMethods.push("environmentProbe");
1142
+ if (plugin.definition.onEnvironmentAcquireLease)
1143
+ supportedMethods.push("environmentAcquireLease");
1144
+ if (plugin.definition.onEnvironmentResumeLease)
1145
+ supportedMethods.push("environmentResumeLease");
1146
+ if (plugin.definition.onEnvironmentReleaseLease)
1147
+ supportedMethods.push("environmentReleaseLease");
1148
+ if (plugin.definition.onEnvironmentDestroyLease)
1149
+ supportedMethods.push("environmentDestroyLease");
1150
+ if (plugin.definition.onEnvironmentRealizeWorkspace)
1151
+ supportedMethods.push("environmentRealizeWorkspace");
1152
+ if (plugin.definition.onEnvironmentExecute)
1153
+ supportedMethods.push("environmentExecute");
1154
+ return { ok: true, supportedMethods };
1155
+ }
1156
+ async function handleHealth() {
1157
+ if (plugin.definition.onHealth) {
1158
+ return plugin.definition.onHealth();
1159
+ }
1160
+ // Default: report OK if the worker is alive
1161
+ return { status: "ok" };
1162
+ }
1163
+ async function handleShutdown() {
1164
+ if (plugin.definition.onShutdown) {
1165
+ await plugin.definition.onShutdown();
1166
+ }
1167
+ // Schedule cleanup after we send the response.
1168
+ // Use setImmediate to let the response flush before exiting.
1169
+ // Only call process.exit() when running with real process streams.
1170
+ // When custom streams are provided (tests), just clean up.
1171
+ setImmediate(() => {
1172
+ cleanup();
1173
+ if (!options.stdin && !options.stdout) {
1174
+ process.exit(0);
1175
+ }
1176
+ });
1177
+ }
1178
+ async function handleValidateConfig(params) {
1179
+ if (!plugin.definition.onValidateConfig) {
1180
+ throw Object.assign(new Error("validateConfig is not implemented by this plugin"), { code: PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED });
1181
+ }
1182
+ return plugin.definition.onValidateConfig(params.config);
1183
+ }
1184
+ async function handleConfigChanged(params) {
1185
+ currentConfig = params.config;
1186
+ if (plugin.definition.onConfigChanged) {
1187
+ await plugin.definition.onConfigChanged(params.config);
1188
+ }
1189
+ }
1190
+ async function handleOnEvent(params) {
1191
+ const event = params.event;
1192
+ for (const registration of eventHandlers) {
1193
+ // Check event type match
1194
+ const exactMatch = registration.name === event.eventType;
1195
+ const wildcardPluginAll = registration.name === "plugin.*" &&
1196
+ event.eventType.startsWith("plugin.");
1197
+ const wildcardPluginOne = registration.name.endsWith(".*") &&
1198
+ event.eventType.startsWith(registration.name.slice(0, -1));
1199
+ if (!exactMatch && !wildcardPluginAll && !wildcardPluginOne)
1200
+ continue;
1201
+ // Check filter
1202
+ if (registration.filter && !allowsEvent(registration.filter, event))
1203
+ continue;
1204
+ try {
1205
+ await registration.fn(event);
1206
+ }
1207
+ catch (err) {
1208
+ // Log error but continue processing other handlers so one failing
1209
+ // handler doesn't prevent the rest from running.
1210
+ notifyHost("log", {
1211
+ level: "error",
1212
+ message: `Event handler for "${registration.name}" failed: ${err instanceof Error ? err.message : String(err)}`,
1213
+ meta: { eventType: event.eventType, stack: err instanceof Error ? err.stack : undefined },
1214
+ });
1215
+ }
1216
+ }
1217
+ }
1218
+ async function handleRunJob(params) {
1219
+ const handler = jobHandlers.get(params.job.jobKey);
1220
+ if (!handler) {
1221
+ throw new Error(`No handler registered for job "${params.job.jobKey}"`);
1222
+ }
1223
+ await handler(params.job);
1224
+ }
1225
+ async function handleWebhook(params) {
1226
+ if (!plugin.definition.onWebhook) {
1227
+ throw Object.assign(new Error("handleWebhook is not implemented by this plugin"), { code: PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED });
1228
+ }
1229
+ await plugin.definition.onWebhook(params);
1230
+ }
1231
+ async function handleApiRequest(params) {
1232
+ if (!plugin.definition.onApiRequest) {
1233
+ throw Object.assign(new Error("handleApiRequest is not implemented by this plugin"), { code: PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED });
1234
+ }
1235
+ return plugin.definition.onApiRequest(params);
1236
+ }
1237
+ async function handleGetData(params) {
1238
+ const handler = dataHandlers.get(params.key);
1239
+ if (!handler) {
1240
+ throw new Error(`No data handler registered for key "${params.key}"`);
1241
+ }
1242
+ return handler({
1243
+ ...params.params,
1244
+ ...(params.companyId === undefined ? {} : { companyId: params.companyId }),
1245
+ ...(params.renderEnvironment === undefined ? {} : { renderEnvironment: params.renderEnvironment }),
1246
+ });
1247
+ }
1248
+ function stringOrNull(value) {
1249
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
1250
+ }
1251
+ function actorTypeOrSystem(value) {
1252
+ return value === "user" || value === "agent" || value === "system" ? value : "system";
1253
+ }
1254
+ function actionContextFromParams(params) {
1255
+ const rawActor = params.actorContext && typeof params.actorContext === "object"
1256
+ ? params.actorContext
1257
+ : null;
1258
+ const actor = Object.freeze({
1259
+ type: actorTypeOrSystem(rawActor?.type),
1260
+ userId: stringOrNull(rawActor?.userId),
1261
+ agentId: stringOrNull(rawActor?.agentId),
1262
+ runId: stringOrNull(rawActor?.runId),
1263
+ companyId: stringOrNull(rawActor?.companyId),
1264
+ });
1265
+ return Object.freeze({
1266
+ actor,
1267
+ companyId: actor.companyId,
1268
+ });
1269
+ }
1270
+ async function handlePerformAction(params) {
1271
+ const handler = actionHandlers.get(params.key);
1272
+ if (!handler) {
1273
+ throw new Error(`No action handler registered for key "${params.key}"`);
1274
+ }
1275
+ return handler({
1276
+ ...params.params,
1277
+ ...(params.companyId === undefined ? {} : { companyId: params.companyId }),
1278
+ ...(params.renderEnvironment === undefined ? {} : { renderEnvironment: params.renderEnvironment }),
1279
+ }, actionContextFromParams(params));
1280
+ }
1281
+ async function handleExecuteTool(params) {
1282
+ const entry = toolHandlers.get(params.toolName);
1283
+ if (!entry) {
1284
+ throw new Error(`No tool handler registered for "${params.toolName}"`);
1285
+ }
1286
+ return entry.fn(params.parameters, params.runContext);
1287
+ }
1288
+ function methodNotImplemented(method) {
1289
+ return Object.assign(new Error(`${method} is not implemented by this plugin`), { code: PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED });
1290
+ }
1291
+ async function handleEnvironmentValidateConfig(params) {
1292
+ if (!plugin.definition.onEnvironmentValidateConfig) {
1293
+ throw methodNotImplemented("environmentValidateConfig");
1294
+ }
1295
+ return plugin.definition.onEnvironmentValidateConfig(params);
1296
+ }
1297
+ async function handleEnvironmentProbe(params) {
1298
+ if (!plugin.definition.onEnvironmentProbe) {
1299
+ throw methodNotImplemented("environmentProbe");
1300
+ }
1301
+ return plugin.definition.onEnvironmentProbe(params);
1302
+ }
1303
+ async function handleEnvironmentAcquireLease(params) {
1304
+ if (!plugin.definition.onEnvironmentAcquireLease) {
1305
+ throw methodNotImplemented("environmentAcquireLease");
1306
+ }
1307
+ return plugin.definition.onEnvironmentAcquireLease(params);
1308
+ }
1309
+ async function handleEnvironmentResumeLease(params) {
1310
+ if (!plugin.definition.onEnvironmentResumeLease) {
1311
+ throw methodNotImplemented("environmentResumeLease");
1312
+ }
1313
+ return plugin.definition.onEnvironmentResumeLease(params);
1314
+ }
1315
+ async function handleEnvironmentReleaseLease(params) {
1316
+ if (!plugin.definition.onEnvironmentReleaseLease) {
1317
+ throw methodNotImplemented("environmentReleaseLease");
1318
+ }
1319
+ return plugin.definition.onEnvironmentReleaseLease(params);
1320
+ }
1321
+ async function handleEnvironmentDestroyLease(params) {
1322
+ if (!plugin.definition.onEnvironmentDestroyLease) {
1323
+ throw methodNotImplemented("environmentDestroyLease");
1324
+ }
1325
+ return plugin.definition.onEnvironmentDestroyLease(params);
1326
+ }
1327
+ async function handleEnvironmentRealizeWorkspace(params) {
1328
+ if (!plugin.definition.onEnvironmentRealizeWorkspace) {
1329
+ throw methodNotImplemented("environmentRealizeWorkspace");
1330
+ }
1331
+ return plugin.definition.onEnvironmentRealizeWorkspace(params);
1332
+ }
1333
+ async function handleEnvironmentExecute(params) {
1334
+ if (!plugin.definition.onEnvironmentExecute) {
1335
+ throw methodNotImplemented("environmentExecute");
1336
+ }
1337
+ return plugin.definition.onEnvironmentExecute(params);
1338
+ }
1339
+ // -----------------------------------------------------------------------
1340
+ // Event filter helper
1341
+ // -----------------------------------------------------------------------
1342
+ function allowsEvent(filter, event) {
1343
+ const payload = event.payload;
1344
+ if (filter.companyId !== undefined) {
1345
+ const companyId = event.companyId ?? String(payload?.companyId ?? "");
1346
+ if (companyId !== filter.companyId)
1347
+ return false;
1348
+ }
1349
+ if (filter.projectId !== undefined) {
1350
+ const projectId = event.entityType === "project"
1351
+ ? event.entityId
1352
+ : String(payload?.projectId ?? "");
1353
+ if (projectId !== filter.projectId)
1354
+ return false;
1355
+ }
1356
+ if (filter.agentId !== undefined) {
1357
+ const agentId = event.entityType === "agent"
1358
+ ? event.entityId
1359
+ : String(payload?.agentId ?? "");
1360
+ if (agentId !== filter.agentId)
1361
+ return false;
1362
+ }
1363
+ return true;
1364
+ }
1365
+ // -----------------------------------------------------------------------
1366
+ // Inbound response handling (host → worker, response to our outbound call)
1367
+ // -----------------------------------------------------------------------
1368
+ function handleHostResponse(response) {
1369
+ const id = response.id;
1370
+ if (id === null || id === undefined)
1371
+ return;
1372
+ const pending = pendingRequests.get(id);
1373
+ if (!pending)
1374
+ return;
1375
+ clearTimeout(pending.timer);
1376
+ pendingRequests.delete(id);
1377
+ pending.resolve(response);
1378
+ }
1379
+ // -----------------------------------------------------------------------
1380
+ // Incoming line handler
1381
+ // -----------------------------------------------------------------------
1382
+ function handleLine(line) {
1383
+ if (!line.trim())
1384
+ return;
1385
+ let message;
1386
+ try {
1387
+ message = parseMessage(line);
1388
+ }
1389
+ catch (err) {
1390
+ if (err instanceof JsonRpcParseError) {
1391
+ // Send parse error response
1392
+ sendMessage(createErrorResponse(null, JSONRPC_ERROR_CODES.PARSE_ERROR, `Parse error: ${err.message}`));
1393
+ }
1394
+ return;
1395
+ }
1396
+ if (isJsonRpcResponse(message)) {
1397
+ // This is a response to one of our outbound worker→host calls
1398
+ handleHostResponse(message);
1399
+ }
1400
+ else if (isJsonRpcRequest(message)) {
1401
+ // This is a host→worker RPC call — dispatch it
1402
+ handleHostRequest(message).catch((err) => {
1403
+ // Unhandled error in the async handler — send error response
1404
+ const errorMessage = err instanceof Error ? err.message : String(err);
1405
+ const errorCode = err?.code ?? PLUGIN_RPC_ERROR_CODES.WORKER_ERROR;
1406
+ try {
1407
+ sendMessage(createErrorResponse(message.id, typeof errorCode === "number" ? errorCode : PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, errorMessage));
1408
+ }
1409
+ catch {
1410
+ // Cannot send response, stdout may be closed
1411
+ }
1412
+ });
1413
+ }
1414
+ else if (isJsonRpcNotification(message)) {
1415
+ // Dispatch host→worker push notifications
1416
+ const notif = message;
1417
+ const runNotification = (fn) => {
1418
+ if (notif.paperclipInvocation) {
1419
+ return invocationContextStorage.run(notif.paperclipInvocation, fn);
1420
+ }
1421
+ return fn();
1422
+ };
1423
+ if (notif.method === "agents.sessions.event" && notif.params) {
1424
+ const event = notif.params;
1425
+ const cb = sessionEventCallbacks.get(event.sessionId);
1426
+ if (cb)
1427
+ cb(event);
1428
+ }
1429
+ else if (notif.method === "onEvent" && notif.params) {
1430
+ // Plugin event bus notifications — dispatch to registered event handlers
1431
+ Promise.resolve(runNotification(() => handleOnEvent(notif.params))).catch((err) => {
1432
+ notifyHost("log", {
1433
+ level: "error",
1434
+ message: `Failed to handle event notification: ${err instanceof Error ? err.message : String(err)}`,
1435
+ });
1436
+ });
1437
+ }
1438
+ }
1439
+ }
1440
+ // -----------------------------------------------------------------------
1441
+ // Cleanup
1442
+ // -----------------------------------------------------------------------
1443
+ function cleanup() {
1444
+ running = false;
1445
+ // Close readline
1446
+ if (readline) {
1447
+ readline.close();
1448
+ readline = null;
1449
+ }
1450
+ // Reject all pending outbound calls
1451
+ for (const [id, pending] of pendingRequests) {
1452
+ clearTimeout(pending.timer);
1453
+ pending.resolve(createErrorResponse(id, PLUGIN_RPC_ERROR_CODES.WORKER_UNAVAILABLE, "Worker RPC host is shutting down"));
1454
+ }
1455
+ pendingRequests.clear();
1456
+ sessionEventCallbacks.clear();
1457
+ }
1458
+ // -----------------------------------------------------------------------
1459
+ // Bootstrap: wire up stdin readline
1460
+ // -----------------------------------------------------------------------
1461
+ let readline = createInterface({
1462
+ input: stdinStream,
1463
+ crlfDelay: Infinity,
1464
+ });
1465
+ readline.on("line", handleLine);
1466
+ // If stdin closes, we should exit gracefully
1467
+ readline.on("close", () => {
1468
+ if (running) {
1469
+ cleanup();
1470
+ if (!options.stdin && !options.stdout) {
1471
+ process.exit(0);
1472
+ }
1473
+ }
1474
+ });
1475
+ // Handle uncaught errors in the worker process.
1476
+ // Only install these when using the real process streams (not in tests
1477
+ // where the caller provides custom streams).
1478
+ if (!options.stdin && !options.stdout) {
1479
+ process.on("uncaughtException", (err) => {
1480
+ notifyHost("log", {
1481
+ level: "error",
1482
+ message: `Uncaught exception: ${err.message}`,
1483
+ meta: { stack: err.stack },
1484
+ });
1485
+ // Give the notification a moment to flush, then exit
1486
+ setTimeout(() => process.exit(1), 100);
1487
+ });
1488
+ process.on("unhandledRejection", (reason) => {
1489
+ const message = reason instanceof Error ? reason.message : String(reason);
1490
+ const stack = reason instanceof Error ? reason.stack : undefined;
1491
+ notifyHost("log", {
1492
+ level: "error",
1493
+ message: `Unhandled rejection: ${message}`,
1494
+ meta: { stack },
1495
+ });
1496
+ });
1497
+ }
1498
+ // -----------------------------------------------------------------------
1499
+ // Return the handle
1500
+ // -----------------------------------------------------------------------
1501
+ return {
1502
+ get running() {
1503
+ return running;
1504
+ },
1505
+ stop() {
1506
+ cleanup();
1507
+ },
1508
+ };
1509
+ }
1510
+ //# sourceMappingURL=worker-rpc-host.js.map