@tickernelz/paperclip-pro-plugin-sdk 2026.925.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.
- package/LICENSE +22 -0
- package/README.md +1307 -0
- package/dist/.paperclip-build-complete +1 -0
- package/dist/bundlers.d.ts +57 -0
- package/dist/bundlers.d.ts.map +1 -0
- package/dist/bundlers.js +106 -0
- package/dist/bundlers.js.map +1 -0
- package/dist/define-plugin.d.ts +396 -0
- package/dist/define-plugin.d.ts.map +1 -0
- package/dist/define-plugin.js +87 -0
- package/dist/define-plugin.js.map +1 -0
- package/dist/dev-cli.d.ts +3 -0
- package/dist/dev-cli.d.ts.map +1 -0
- package/dist/dev-cli.js +49 -0
- package/dist/dev-cli.js.map +1 -0
- package/dist/dev-server.d.ts +34 -0
- package/dist/dev-server.d.ts.map +1 -0
- package/dist/dev-server.js +194 -0
- package/dist/dev-server.js.map +1 -0
- package/dist/host-client-factory.d.ts +326 -0
- package/dist/host-client-factory.d.ts.map +1 -0
- package/dist/host-client-factory.js +688 -0
- package/dist/host-client-factory.js.map +1 -0
- package/dist/index.d.ts +85 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +86 -0
- package/dist/index.js.map +1 -0
- package/dist/protocol.d.ts +2333 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.duplex-channel.test.d.ts +2 -0
- package/dist/protocol.duplex-channel.test.d.ts.map +1 -0
- package/dist/protocol.duplex-channel.test.js +229 -0
- package/dist/protocol.duplex-channel.test.js.map +1 -0
- package/dist/protocol.js +364 -0
- package/dist/protocol.js.map +1 -0
- package/dist/testing.d.ts +203 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +2475 -0
- package/dist/testing.js.map +1 -0
- package/dist/types.d.ts +1837 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +23 -0
- package/dist/types.js.map +1 -0
- package/dist/ui/clipboard.d.ts +8 -0
- package/dist/ui/clipboard.d.ts.map +1 -0
- package/dist/ui/clipboard.js +12 -0
- package/dist/ui/clipboard.js.map +1 -0
- package/dist/ui/components.d.ts +518 -0
- package/dist/ui/components.d.ts.map +1 -0
- package/dist/ui/components.js +135 -0
- package/dist/ui/components.js.map +1 -0
- package/dist/ui/hooks.d.ts +155 -0
- package/dist/ui/hooks.d.ts.map +1 -0
- package/dist/ui/hooks.js +195 -0
- package/dist/ui/hooks.js.map +1 -0
- package/dist/ui/index.d.ts +55 -0
- package/dist/ui/index.d.ts.map +1 -0
- package/dist/ui/index.js +52 -0
- package/dist/ui/index.js.map +1 -0
- package/dist/ui/runtime.d.ts +3 -0
- package/dist/ui/runtime.d.ts.map +1 -0
- package/dist/ui/runtime.js +30 -0
- package/dist/ui/runtime.js.map +1 -0
- package/dist/ui/types.d.ts +423 -0
- package/dist/ui/types.d.ts.map +1 -0
- package/dist/ui/types.js +17 -0
- package/dist/ui/types.js.map +1 -0
- package/dist/worker-rpc-host.d.ts +128 -0
- package/dist/worker-rpc-host.d.ts.map +1 -0
- package/dist/worker-rpc-host.js +1877 -0
- package/dist/worker-rpc-host.js.map +1 -0
- package/package.json +92 -0
|
@@ -0,0 +1,1877 @@
|
|
|
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 { LOGIN_PTY_OUTPUT_NOTIFICATION, LOGIN_PTY_EXIT_NOTIFICATION, DUPLEX_CHANNEL_DATA_NOTIFICATION, DUPLEX_CHANNEL_EXIT_NOTIFICATION, JSONRPC_ERROR_CODES, PLUGIN_RPC_ERROR_CODES, createRequest, createSuccessResponse, createErrorResponse, createNotification, parseMessage, serializeMessage, isJsonRpcRequest, isJsonRpcResponse, isJsonRpcNotification, isJsonRpcSuccessResponse, isJsonRpcErrorResponse, JsonRpcParseError, JsonRpcCallError, encodeChannelBytes, } 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
|
+
/**
|
|
57
|
+
* Order-independent structural equality for two plugin config objects.
|
|
58
|
+
*
|
|
59
|
+
* Config arrives as parsed JSON, so plain `JSON.stringify` comparison is
|
|
60
|
+
* sensitive to key ordering across independent saves. Canonicalizing with
|
|
61
|
+
* recursively sorted object keys makes an idempotent replay of the same config
|
|
62
|
+
* compare equal regardless of serialization order.
|
|
63
|
+
*/
|
|
64
|
+
function configsEqual(a, b) {
|
|
65
|
+
return canonicalize(a) === canonicalize(b);
|
|
66
|
+
}
|
|
67
|
+
function canonicalize(value) {
|
|
68
|
+
if (value === null || typeof value !== "object") {
|
|
69
|
+
return JSON.stringify(value) ?? "null";
|
|
70
|
+
}
|
|
71
|
+
if (Array.isArray(value)) {
|
|
72
|
+
return `[${value.map(canonicalize).join(",")}]`;
|
|
73
|
+
}
|
|
74
|
+
const entries = Object.entries(value)
|
|
75
|
+
.filter(([, v]) => v !== undefined)
|
|
76
|
+
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
77
|
+
.map(([key, v]) => `${JSON.stringify(key)}:${canonicalize(v)}`);
|
|
78
|
+
return `{${entries.join(",")}}`;
|
|
79
|
+
}
|
|
80
|
+
export function isWorkerEntrypoint(entry, moduleUrl) {
|
|
81
|
+
const thisFile = realpathOrResolvedPath(fileURLToPath(moduleUrl));
|
|
82
|
+
const entryPath = realpathOrResolvedPath(entry);
|
|
83
|
+
return thisFile === entryPath;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Start the worker when this module is the process entrypoint.
|
|
87
|
+
*
|
|
88
|
+
* Call this at the bottom of your worker file so that when the host runs
|
|
89
|
+
* `node dist/worker.js`, the RPC host starts and the process stays alive.
|
|
90
|
+
* When the module is imported (e.g. for re-exports or tests), nothing runs.
|
|
91
|
+
*
|
|
92
|
+
* When `options.stdin` and `options.stdout` are provided (e.g. in tests),
|
|
93
|
+
* the main-module check is skipped and the host is started with those streams.
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* ```ts
|
|
97
|
+
* const plugin = definePlugin({ ... });
|
|
98
|
+
* export default plugin;
|
|
99
|
+
* runWorker(plugin, import.meta.url);
|
|
100
|
+
* ```
|
|
101
|
+
*/
|
|
102
|
+
export function runWorker(plugin, moduleUrl, options) {
|
|
103
|
+
if (options?.stdin != null &&
|
|
104
|
+
options?.stdout != null) {
|
|
105
|
+
return startWorkerRpcHost({
|
|
106
|
+
plugin,
|
|
107
|
+
stdin: options.stdin,
|
|
108
|
+
stdout: options.stdout,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
const entry = process.argv[1];
|
|
112
|
+
if (typeof entry !== "string")
|
|
113
|
+
return;
|
|
114
|
+
if (isWorkerEntrypoint(entry, moduleUrl)) {
|
|
115
|
+
startWorkerRpcHost({ plugin });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Start the worker-side RPC host.
|
|
120
|
+
*
|
|
121
|
+
* This function is typically called from a thin bootstrap script that is the
|
|
122
|
+
* actual entrypoint of the child process:
|
|
123
|
+
*
|
|
124
|
+
* ```ts
|
|
125
|
+
* // worker-bootstrap.ts
|
|
126
|
+
* import plugin from "./worker.js";
|
|
127
|
+
* import { startWorkerRpcHost } from "@tickernelz/paperclip-pro-plugin-sdk";
|
|
128
|
+
*
|
|
129
|
+
* startWorkerRpcHost({ plugin });
|
|
130
|
+
* ```
|
|
131
|
+
*
|
|
132
|
+
* The host begins listening on stdin immediately. It does NOT call
|
|
133
|
+
* `plugin.definition.setup()` yet — that happens when the host sends the
|
|
134
|
+
* `initialize` RPC.
|
|
135
|
+
*
|
|
136
|
+
* @returns A handle for inspecting or stopping the RPC host
|
|
137
|
+
*/
|
|
138
|
+
export function startWorkerRpcHost(options) {
|
|
139
|
+
const { plugin } = options;
|
|
140
|
+
const stdinStream = options.stdin ?? process.stdin;
|
|
141
|
+
const stdoutStream = options.stdout ?? process.stdout;
|
|
142
|
+
const rpcTimeoutMs = options.rpcTimeoutMs ?? DEFAULT_RPC_TIMEOUT_MS;
|
|
143
|
+
// -----------------------------------------------------------------------
|
|
144
|
+
// State
|
|
145
|
+
// -----------------------------------------------------------------------
|
|
146
|
+
let running = true;
|
|
147
|
+
let initialized = false;
|
|
148
|
+
let manifest = null;
|
|
149
|
+
let currentConfig = {};
|
|
150
|
+
// The company whose config was last applied via configChanged. Used to fail
|
|
151
|
+
// closed when a single-tenant plugin would be collapsed onto a second,
|
|
152
|
+
// distinct company's config. `null` until the first company-scoped delivery.
|
|
153
|
+
let configCompanyId = null;
|
|
154
|
+
let databaseNamespace = null;
|
|
155
|
+
const invocationContextStorage = new AsyncLocalStorage();
|
|
156
|
+
// Plugin handler registrations (populated during setup())
|
|
157
|
+
const eventHandlers = [];
|
|
158
|
+
const jobHandlers = new Map();
|
|
159
|
+
const launcherRegistrations = new Map();
|
|
160
|
+
const dataHandlers = new Map();
|
|
161
|
+
const actionHandlers = new Map();
|
|
162
|
+
const toolHandlers = new Map();
|
|
163
|
+
// Agent session event callbacks (populated by sendMessage, cleared by close)
|
|
164
|
+
const sessionEventCallbacks = new Map();
|
|
165
|
+
// Pending outbound (worker→host) requests
|
|
166
|
+
const pendingRequests = new Map();
|
|
167
|
+
let nextOutboundId = 1;
|
|
168
|
+
const MAX_OUTBOUND_ID = Number.MAX_SAFE_INTEGER - 1;
|
|
169
|
+
// -----------------------------------------------------------------------
|
|
170
|
+
// Outbound messaging (worker → host)
|
|
171
|
+
// -----------------------------------------------------------------------
|
|
172
|
+
function sendMessage(message) {
|
|
173
|
+
if (!running)
|
|
174
|
+
return;
|
|
175
|
+
const serialized = serializeMessage(message);
|
|
176
|
+
stdoutStream.write(serialized);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Send a typed JSON-RPC request to the host and await the response.
|
|
180
|
+
*/
|
|
181
|
+
function callHost(method, params, timeoutMs) {
|
|
182
|
+
return new Promise((resolve, reject) => {
|
|
183
|
+
if (!running) {
|
|
184
|
+
reject(new Error(`Cannot call "${method}" — worker RPC host is not running`));
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (nextOutboundId >= MAX_OUTBOUND_ID) {
|
|
188
|
+
nextOutboundId = 1;
|
|
189
|
+
}
|
|
190
|
+
const id = nextOutboundId++;
|
|
191
|
+
const timeout = timeoutMs ?? rpcTimeoutMs;
|
|
192
|
+
let settled = false;
|
|
193
|
+
const settle = (fn, value) => {
|
|
194
|
+
if (settled)
|
|
195
|
+
return;
|
|
196
|
+
settled = true;
|
|
197
|
+
clearTimeout(timer);
|
|
198
|
+
pendingRequests.delete(id);
|
|
199
|
+
fn(value);
|
|
200
|
+
};
|
|
201
|
+
const timer = setTimeout(() => {
|
|
202
|
+
settle(reject, new JsonRpcCallError({
|
|
203
|
+
code: PLUGIN_RPC_ERROR_CODES.TIMEOUT,
|
|
204
|
+
message: `Worker→host call "${method}" timed out after ${timeout}ms`,
|
|
205
|
+
}));
|
|
206
|
+
}, timeout);
|
|
207
|
+
pendingRequests.set(id, {
|
|
208
|
+
resolve: (response) => {
|
|
209
|
+
if (isJsonRpcSuccessResponse(response)) {
|
|
210
|
+
settle(resolve, response.result);
|
|
211
|
+
}
|
|
212
|
+
else if (isJsonRpcErrorResponse(response)) {
|
|
213
|
+
settle(reject, new JsonRpcCallError(response.error));
|
|
214
|
+
}
|
|
215
|
+
else {
|
|
216
|
+
settle(reject, new Error(`Unexpected response format for "${method}"`));
|
|
217
|
+
}
|
|
218
|
+
},
|
|
219
|
+
timer,
|
|
220
|
+
});
|
|
221
|
+
try {
|
|
222
|
+
const activeInvocation = invocationContextStorage.getStore();
|
|
223
|
+
const request = {
|
|
224
|
+
...createRequest(method, params, id),
|
|
225
|
+
...(activeInvocation ? { paperclipInvocationId: activeInvocation.id } : {}),
|
|
226
|
+
};
|
|
227
|
+
sendMessage(request);
|
|
228
|
+
}
|
|
229
|
+
catch (err) {
|
|
230
|
+
settle(reject, err instanceof Error ? err : new Error(String(err)));
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Send a JSON-RPC notification to the host (fire-and-forget).
|
|
236
|
+
*/
|
|
237
|
+
function notifyHost(method, params) {
|
|
238
|
+
try {
|
|
239
|
+
const activeInvocation = invocationContextStorage.getStore();
|
|
240
|
+
sendMessage({
|
|
241
|
+
...createNotification(method, params),
|
|
242
|
+
...(activeInvocation ? { paperclipInvocationId: activeInvocation.id } : {}),
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
// Swallow — the host may have closed stdin
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
// -----------------------------------------------------------------------
|
|
250
|
+
// Build the PluginContext (SDK surface for plugin code)
|
|
251
|
+
// -----------------------------------------------------------------------
|
|
252
|
+
function buildContext() {
|
|
253
|
+
return {
|
|
254
|
+
get manifest() {
|
|
255
|
+
if (!manifest)
|
|
256
|
+
throw new Error("Plugin context accessed before initialization");
|
|
257
|
+
return manifest;
|
|
258
|
+
},
|
|
259
|
+
config: {
|
|
260
|
+
async get(companyId) {
|
|
261
|
+
return callHost("config.get", companyId ? { companyId } : {});
|
|
262
|
+
},
|
|
263
|
+
},
|
|
264
|
+
localFolders: {
|
|
265
|
+
declarations() {
|
|
266
|
+
if (!manifest)
|
|
267
|
+
throw new Error("Plugin context accessed before initialization");
|
|
268
|
+
return manifest.localFolders ?? [];
|
|
269
|
+
},
|
|
270
|
+
async configure(input) {
|
|
271
|
+
return callHost("localFolders.configure", {
|
|
272
|
+
companyId: input.companyId,
|
|
273
|
+
folderKey: input.folderKey,
|
|
274
|
+
path: input.path,
|
|
275
|
+
access: input.access,
|
|
276
|
+
requiredDirectories: input.requiredDirectories,
|
|
277
|
+
requiredFiles: input.requiredFiles,
|
|
278
|
+
});
|
|
279
|
+
},
|
|
280
|
+
async status(companyId, folderKey) {
|
|
281
|
+
return callHost("localFolders.status", { companyId, folderKey });
|
|
282
|
+
},
|
|
283
|
+
async list(companyId, folderKey, options = {}) {
|
|
284
|
+
return callHost("localFolders.list", {
|
|
285
|
+
companyId,
|
|
286
|
+
folderKey,
|
|
287
|
+
relativePath: options.relativePath,
|
|
288
|
+
recursive: options.recursive,
|
|
289
|
+
maxEntries: options.maxEntries,
|
|
290
|
+
});
|
|
291
|
+
},
|
|
292
|
+
async readText(companyId, folderKey, relativePath) {
|
|
293
|
+
return callHost("localFolders.readText", { companyId, folderKey, relativePath });
|
|
294
|
+
},
|
|
295
|
+
async writeTextAtomic(companyId, folderKey, relativePath, contents) {
|
|
296
|
+
return callHost("localFolders.writeTextAtomic", {
|
|
297
|
+
companyId,
|
|
298
|
+
folderKey,
|
|
299
|
+
relativePath,
|
|
300
|
+
contents,
|
|
301
|
+
});
|
|
302
|
+
},
|
|
303
|
+
async deleteFile(companyId, folderKey, relativePath) {
|
|
304
|
+
return callHost("localFolders.deleteFile", { companyId, folderKey, relativePath });
|
|
305
|
+
},
|
|
306
|
+
},
|
|
307
|
+
events: {
|
|
308
|
+
on(name, filterOrFn, maybeFn) {
|
|
309
|
+
let registration;
|
|
310
|
+
if (typeof filterOrFn === "function") {
|
|
311
|
+
registration = { name, fn: filterOrFn };
|
|
312
|
+
}
|
|
313
|
+
else {
|
|
314
|
+
if (!maybeFn)
|
|
315
|
+
throw new Error("Event handler function is required");
|
|
316
|
+
registration = { name, filter: filterOrFn, fn: maybeFn };
|
|
317
|
+
}
|
|
318
|
+
eventHandlers.push(registration);
|
|
319
|
+
// Register subscription on the host so events are forwarded to this worker
|
|
320
|
+
void callHost("events.subscribe", { eventPattern: name, filter: registration.filter ?? null }).catch((err) => {
|
|
321
|
+
notifyHost("log", {
|
|
322
|
+
level: "warn",
|
|
323
|
+
message: `Failed to subscribe to event "${name}" on host: ${err instanceof Error ? err.message : String(err)}`,
|
|
324
|
+
});
|
|
325
|
+
});
|
|
326
|
+
return () => {
|
|
327
|
+
const idx = eventHandlers.indexOf(registration);
|
|
328
|
+
if (idx !== -1)
|
|
329
|
+
eventHandlers.splice(idx, 1);
|
|
330
|
+
};
|
|
331
|
+
},
|
|
332
|
+
async emit(name, companyId, payload) {
|
|
333
|
+
await callHost("events.emit", { name, companyId, payload });
|
|
334
|
+
},
|
|
335
|
+
},
|
|
336
|
+
jobs: {
|
|
337
|
+
register(key, fn) {
|
|
338
|
+
jobHandlers.set(key, fn);
|
|
339
|
+
},
|
|
340
|
+
},
|
|
341
|
+
launchers: {
|
|
342
|
+
register(launcher) {
|
|
343
|
+
launcherRegistrations.set(launcher.id, launcher);
|
|
344
|
+
},
|
|
345
|
+
},
|
|
346
|
+
db: {
|
|
347
|
+
get namespace() {
|
|
348
|
+
return databaseNamespace ?? "";
|
|
349
|
+
},
|
|
350
|
+
async query(sql, params) {
|
|
351
|
+
return callHost("db.query", { sql, params });
|
|
352
|
+
},
|
|
353
|
+
async execute(sql, params) {
|
|
354
|
+
return callHost("db.execute", { sql, params });
|
|
355
|
+
},
|
|
356
|
+
},
|
|
357
|
+
http: {
|
|
358
|
+
async fetch(url, init) {
|
|
359
|
+
const serializedInit = {};
|
|
360
|
+
if (init) {
|
|
361
|
+
if (init.method)
|
|
362
|
+
serializedInit.method = init.method;
|
|
363
|
+
if (init.headers) {
|
|
364
|
+
// Normalize headers to a plain object
|
|
365
|
+
if (init.headers instanceof Headers) {
|
|
366
|
+
const obj = {};
|
|
367
|
+
init.headers.forEach((v, k) => { obj[k] = v; });
|
|
368
|
+
serializedInit.headers = obj;
|
|
369
|
+
}
|
|
370
|
+
else if (Array.isArray(init.headers)) {
|
|
371
|
+
const obj = {};
|
|
372
|
+
for (const [k, v] of init.headers)
|
|
373
|
+
obj[k] = v;
|
|
374
|
+
serializedInit.headers = obj;
|
|
375
|
+
}
|
|
376
|
+
else {
|
|
377
|
+
serializedInit.headers = init.headers;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if (init.body !== undefined && init.body !== null) {
|
|
381
|
+
serializedInit.body = typeof init.body === "string"
|
|
382
|
+
? init.body
|
|
383
|
+
: String(init.body);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
const result = await callHost("http.fetch", {
|
|
387
|
+
url,
|
|
388
|
+
init: Object.keys(serializedInit).length > 0 ? serializedInit : undefined,
|
|
389
|
+
});
|
|
390
|
+
// Reconstruct a Response-like object from the serialized result
|
|
391
|
+
return new Response(result.body, {
|
|
392
|
+
status: result.status,
|
|
393
|
+
statusText: result.statusText,
|
|
394
|
+
headers: result.headers,
|
|
395
|
+
});
|
|
396
|
+
},
|
|
397
|
+
},
|
|
398
|
+
secrets: {
|
|
399
|
+
async resolve(secretRef, options = {}) {
|
|
400
|
+
return callHost("secrets.resolve", {
|
|
401
|
+
secretRef,
|
|
402
|
+
companyId: options.companyId,
|
|
403
|
+
configPath: options.configPath,
|
|
404
|
+
});
|
|
405
|
+
},
|
|
406
|
+
},
|
|
407
|
+
activity: {
|
|
408
|
+
async log(entry) {
|
|
409
|
+
await callHost("activity.log", {
|
|
410
|
+
companyId: entry.companyId,
|
|
411
|
+
message: entry.message,
|
|
412
|
+
entityType: entry.entityType,
|
|
413
|
+
entityId: entry.entityId,
|
|
414
|
+
metadata: entry.metadata,
|
|
415
|
+
});
|
|
416
|
+
},
|
|
417
|
+
},
|
|
418
|
+
state: {
|
|
419
|
+
async get(input) {
|
|
420
|
+
return callHost("state.get", {
|
|
421
|
+
scopeKind: input.scopeKind,
|
|
422
|
+
scopeId: input.scopeId,
|
|
423
|
+
namespace: input.namespace,
|
|
424
|
+
stateKey: input.stateKey,
|
|
425
|
+
});
|
|
426
|
+
},
|
|
427
|
+
async set(input, value) {
|
|
428
|
+
await callHost("state.set", {
|
|
429
|
+
scopeKind: input.scopeKind,
|
|
430
|
+
scopeId: input.scopeId,
|
|
431
|
+
namespace: input.namespace,
|
|
432
|
+
stateKey: input.stateKey,
|
|
433
|
+
value,
|
|
434
|
+
});
|
|
435
|
+
},
|
|
436
|
+
async delete(input) {
|
|
437
|
+
await callHost("state.delete", {
|
|
438
|
+
scopeKind: input.scopeKind,
|
|
439
|
+
scopeId: input.scopeId,
|
|
440
|
+
namespace: input.namespace,
|
|
441
|
+
stateKey: input.stateKey,
|
|
442
|
+
});
|
|
443
|
+
},
|
|
444
|
+
},
|
|
445
|
+
entities: {
|
|
446
|
+
async upsert(input) {
|
|
447
|
+
return callHost("entities.upsert", {
|
|
448
|
+
entityType: input.entityType,
|
|
449
|
+
scopeKind: input.scopeKind,
|
|
450
|
+
scopeId: input.scopeId,
|
|
451
|
+
externalId: input.externalId,
|
|
452
|
+
title: input.title,
|
|
453
|
+
status: input.status,
|
|
454
|
+
data: input.data,
|
|
455
|
+
});
|
|
456
|
+
},
|
|
457
|
+
async list(query) {
|
|
458
|
+
return callHost("entities.list", {
|
|
459
|
+
entityType: query.entityType,
|
|
460
|
+
scopeKind: query.scopeKind,
|
|
461
|
+
scopeId: query.scopeId,
|
|
462
|
+
externalId: query.externalId,
|
|
463
|
+
limit: query.limit,
|
|
464
|
+
offset: query.offset,
|
|
465
|
+
});
|
|
466
|
+
},
|
|
467
|
+
},
|
|
468
|
+
projects: {
|
|
469
|
+
async list(input) {
|
|
470
|
+
return callHost("projects.list", {
|
|
471
|
+
companyId: input.companyId,
|
|
472
|
+
limit: input.limit,
|
|
473
|
+
offset: input.offset,
|
|
474
|
+
});
|
|
475
|
+
},
|
|
476
|
+
async get(projectId, companyId) {
|
|
477
|
+
return callHost("projects.get", { projectId, companyId });
|
|
478
|
+
},
|
|
479
|
+
async listWorkspaces(projectId, companyId) {
|
|
480
|
+
return callHost("projects.listWorkspaces", { projectId, companyId });
|
|
481
|
+
},
|
|
482
|
+
async getPrimaryWorkspace(projectId, companyId) {
|
|
483
|
+
return callHost("projects.getPrimaryWorkspace", { projectId, companyId });
|
|
484
|
+
},
|
|
485
|
+
async getWorkspaceForIssue(issueId, companyId) {
|
|
486
|
+
return callHost("projects.getWorkspaceForIssue", { issueId, companyId });
|
|
487
|
+
},
|
|
488
|
+
managed: {
|
|
489
|
+
async get(projectKey, companyId) {
|
|
490
|
+
return callHost("projects.managed.get", { projectKey, companyId });
|
|
491
|
+
},
|
|
492
|
+
async reconcile(projectKey, companyId) {
|
|
493
|
+
return callHost("projects.managed.reconcile", { projectKey, companyId });
|
|
494
|
+
},
|
|
495
|
+
async reset(projectKey, companyId) {
|
|
496
|
+
return callHost("projects.managed.reset", { projectKey, companyId });
|
|
497
|
+
},
|
|
498
|
+
},
|
|
499
|
+
},
|
|
500
|
+
executionWorkspaces: {
|
|
501
|
+
async get(workspaceId, companyId) {
|
|
502
|
+
return callHost("executionWorkspaces.get", { workspaceId, companyId });
|
|
503
|
+
},
|
|
504
|
+
},
|
|
505
|
+
routines: {
|
|
506
|
+
managed: {
|
|
507
|
+
async get(routineKey, companyId) {
|
|
508
|
+
return callHost("routines.managed.get", { routineKey, companyId });
|
|
509
|
+
},
|
|
510
|
+
async reconcile(routineKey, companyId, overrides) {
|
|
511
|
+
return callHost("routines.managed.reconcile", { routineKey, companyId, ...overrides });
|
|
512
|
+
},
|
|
513
|
+
async reset(routineKey, companyId, overrides) {
|
|
514
|
+
return callHost("routines.managed.reset", { routineKey, companyId, ...overrides });
|
|
515
|
+
},
|
|
516
|
+
async update(routineKey, companyId, patch) {
|
|
517
|
+
return callHost("routines.managed.update", { routineKey, companyId, ...patch });
|
|
518
|
+
},
|
|
519
|
+
async run(routineKey, companyId, overrides) {
|
|
520
|
+
return callHost("routines.managed.run", { routineKey, companyId, ...overrides });
|
|
521
|
+
},
|
|
522
|
+
},
|
|
523
|
+
},
|
|
524
|
+
skills: {
|
|
525
|
+
managed: {
|
|
526
|
+
async get(skillKey, companyId) {
|
|
527
|
+
return callHost("skills.managed.get", { skillKey, companyId });
|
|
528
|
+
},
|
|
529
|
+
async reconcile(skillKey, companyId) {
|
|
530
|
+
return callHost("skills.managed.reconcile", { skillKey, companyId });
|
|
531
|
+
},
|
|
532
|
+
async reset(skillKey, companyId) {
|
|
533
|
+
return callHost("skills.managed.reset", { skillKey, companyId });
|
|
534
|
+
},
|
|
535
|
+
},
|
|
536
|
+
},
|
|
537
|
+
companies: {
|
|
538
|
+
async list(input) {
|
|
539
|
+
return callHost("companies.list", {
|
|
540
|
+
limit: input?.limit,
|
|
541
|
+
offset: input?.offset,
|
|
542
|
+
});
|
|
543
|
+
},
|
|
544
|
+
async get(companyId) {
|
|
545
|
+
return callHost("companies.get", { companyId });
|
|
546
|
+
},
|
|
547
|
+
},
|
|
548
|
+
issues: {
|
|
549
|
+
async list(input) {
|
|
550
|
+
return callHost("issues.list", {
|
|
551
|
+
companyId: input.companyId,
|
|
552
|
+
projectId: input.projectId,
|
|
553
|
+
assigneeAgentId: input.assigneeAgentId,
|
|
554
|
+
originKind: input.originKind,
|
|
555
|
+
originKindPrefix: input.originKindPrefix,
|
|
556
|
+
originId: input.originId,
|
|
557
|
+
status: input.status,
|
|
558
|
+
includePluginOperations: input.includePluginOperations,
|
|
559
|
+
limit: input.limit,
|
|
560
|
+
offset: input.offset,
|
|
561
|
+
});
|
|
562
|
+
},
|
|
563
|
+
async get(issueId, companyId) {
|
|
564
|
+
return callHost("issues.get", { issueId, companyId });
|
|
565
|
+
},
|
|
566
|
+
async create(input) {
|
|
567
|
+
return callHost("issues.create", {
|
|
568
|
+
companyId: input.companyId,
|
|
569
|
+
projectId: input.projectId,
|
|
570
|
+
goalId: input.goalId,
|
|
571
|
+
parentId: input.parentId,
|
|
572
|
+
inheritExecutionWorkspaceFromIssueId: input.inheritExecutionWorkspaceFromIssueId,
|
|
573
|
+
title: input.title,
|
|
574
|
+
description: input.description,
|
|
575
|
+
status: input.status,
|
|
576
|
+
priority: input.priority,
|
|
577
|
+
assigneeAgentId: input.assigneeAgentId,
|
|
578
|
+
assigneeUserId: input.assigneeUserId,
|
|
579
|
+
requestDepth: input.requestDepth,
|
|
580
|
+
billingCode: input.billingCode,
|
|
581
|
+
assigneeAdapterOverrides: input.assigneeAdapterOverrides,
|
|
582
|
+
surfaceVisibility: input.surfaceVisibility,
|
|
583
|
+
originKind: input.originKind,
|
|
584
|
+
originId: input.originId,
|
|
585
|
+
originRunId: input.originRunId,
|
|
586
|
+
blockedByIssueIds: input.blockedByIssueIds,
|
|
587
|
+
labelIds: input.labelIds,
|
|
588
|
+
executionWorkspaceId: input.executionWorkspaceId,
|
|
589
|
+
executionWorkspacePreference: input.executionWorkspacePreference,
|
|
590
|
+
executionWorkspaceSettings: input.executionWorkspaceSettings,
|
|
591
|
+
actorAgentId: input.actor?.actorAgentId,
|
|
592
|
+
actorUserId: input.actor?.actorUserId,
|
|
593
|
+
actorRunId: input.actor?.actorRunId,
|
|
594
|
+
});
|
|
595
|
+
},
|
|
596
|
+
async update(issueId, patch, companyId, actor) {
|
|
597
|
+
return callHost("issues.update", {
|
|
598
|
+
issueId,
|
|
599
|
+
patch: {
|
|
600
|
+
...patch,
|
|
601
|
+
actorAgentId: actor?.actorAgentId,
|
|
602
|
+
actorUserId: actor?.actorUserId,
|
|
603
|
+
actorRunId: actor?.actorRunId,
|
|
604
|
+
},
|
|
605
|
+
companyId,
|
|
606
|
+
});
|
|
607
|
+
},
|
|
608
|
+
async assertCheckoutOwner(input) {
|
|
609
|
+
return callHost("issues.assertCheckoutOwner", input);
|
|
610
|
+
},
|
|
611
|
+
async getSubtree(issueId, companyId, options) {
|
|
612
|
+
return callHost("issues.getSubtree", {
|
|
613
|
+
issueId,
|
|
614
|
+
companyId,
|
|
615
|
+
includeRoot: options?.includeRoot,
|
|
616
|
+
includeRelations: options?.includeRelations,
|
|
617
|
+
includeDocuments: options?.includeDocuments,
|
|
618
|
+
includeActiveRuns: options?.includeActiveRuns,
|
|
619
|
+
includeAssignees: options?.includeAssignees,
|
|
620
|
+
});
|
|
621
|
+
},
|
|
622
|
+
async requestWakeup(issueId, companyId, options) {
|
|
623
|
+
return callHost("issues.requestWakeup", {
|
|
624
|
+
issueId,
|
|
625
|
+
companyId,
|
|
626
|
+
reason: options?.reason,
|
|
627
|
+
contextSource: options?.contextSource,
|
|
628
|
+
idempotencyKey: options?.idempotencyKey,
|
|
629
|
+
actorAgentId: options?.actorAgentId,
|
|
630
|
+
actorUserId: options?.actorUserId,
|
|
631
|
+
actorRunId: options?.actorRunId,
|
|
632
|
+
});
|
|
633
|
+
},
|
|
634
|
+
async requestWakeups(issueIds, companyId, options) {
|
|
635
|
+
return callHost("issues.requestWakeups", {
|
|
636
|
+
issueIds,
|
|
637
|
+
companyId,
|
|
638
|
+
reason: options?.reason,
|
|
639
|
+
contextSource: options?.contextSource,
|
|
640
|
+
idempotencyKeyPrefix: options?.idempotencyKeyPrefix,
|
|
641
|
+
actorAgentId: options?.actorAgentId,
|
|
642
|
+
actorUserId: options?.actorUserId,
|
|
643
|
+
actorRunId: options?.actorRunId,
|
|
644
|
+
});
|
|
645
|
+
},
|
|
646
|
+
async listComments(issueId, companyId) {
|
|
647
|
+
return callHost("issues.listComments", { issueId, companyId });
|
|
648
|
+
},
|
|
649
|
+
async createComment(issueId, body, companyId, options) {
|
|
650
|
+
return callHost("issues.createComment", {
|
|
651
|
+
issueId,
|
|
652
|
+
body,
|
|
653
|
+
companyId,
|
|
654
|
+
authorAgentId: options?.authorAgentId,
|
|
655
|
+
actorUserId: options?.actorUserId,
|
|
656
|
+
});
|
|
657
|
+
},
|
|
658
|
+
async createInteraction(issueId, interaction, companyId, options) {
|
|
659
|
+
return callHost("issues.createInteraction", {
|
|
660
|
+
issueId,
|
|
661
|
+
companyId,
|
|
662
|
+
interaction,
|
|
663
|
+
authorAgentId: options?.authorAgentId,
|
|
664
|
+
});
|
|
665
|
+
},
|
|
666
|
+
async suggestTasks(issueId, interaction, companyId, options) {
|
|
667
|
+
return callHost("issues.createInteraction", {
|
|
668
|
+
issueId,
|
|
669
|
+
companyId,
|
|
670
|
+
interaction: {
|
|
671
|
+
...interaction,
|
|
672
|
+
kind: "suggest_tasks",
|
|
673
|
+
},
|
|
674
|
+
authorAgentId: options?.authorAgentId,
|
|
675
|
+
});
|
|
676
|
+
},
|
|
677
|
+
async askUserQuestions(issueId, interaction, companyId, options) {
|
|
678
|
+
return callHost("issues.createInteraction", {
|
|
679
|
+
issueId,
|
|
680
|
+
companyId,
|
|
681
|
+
interaction: {
|
|
682
|
+
...interaction,
|
|
683
|
+
kind: "ask_user_questions",
|
|
684
|
+
},
|
|
685
|
+
authorAgentId: options?.authorAgentId,
|
|
686
|
+
});
|
|
687
|
+
},
|
|
688
|
+
async requestConfirmation(issueId, interaction, companyId, options) {
|
|
689
|
+
return callHost("issues.createInteraction", {
|
|
690
|
+
issueId,
|
|
691
|
+
companyId,
|
|
692
|
+
interaction: {
|
|
693
|
+
...interaction,
|
|
694
|
+
kind: "request_confirmation",
|
|
695
|
+
},
|
|
696
|
+
authorAgentId: options?.authorAgentId,
|
|
697
|
+
});
|
|
698
|
+
},
|
|
699
|
+
async requestCheckboxConfirmation(issueId, interaction, companyId, options) {
|
|
700
|
+
return callHost("issues.createInteraction", {
|
|
701
|
+
issueId,
|
|
702
|
+
companyId,
|
|
703
|
+
interaction: {
|
|
704
|
+
...interaction,
|
|
705
|
+
kind: "request_checkbox_confirmation",
|
|
706
|
+
},
|
|
707
|
+
authorAgentId: options?.authorAgentId,
|
|
708
|
+
});
|
|
709
|
+
},
|
|
710
|
+
async listInteractions(issueId, companyId) {
|
|
711
|
+
return callHost("issues.listInteractions", { issueId, companyId });
|
|
712
|
+
},
|
|
713
|
+
async respondInteraction(issueId, interactionId, input, companyId) {
|
|
714
|
+
return callHost("issues.respondInteraction", {
|
|
715
|
+
issueId,
|
|
716
|
+
interactionId,
|
|
717
|
+
companyId,
|
|
718
|
+
action: input.action,
|
|
719
|
+
actorUserId: input.actorUserId,
|
|
720
|
+
reason: input.reason,
|
|
721
|
+
});
|
|
722
|
+
},
|
|
723
|
+
async listAttachments(issueId, companyId) {
|
|
724
|
+
return callHost("issues.listAttachments", { issueId, companyId });
|
|
725
|
+
},
|
|
726
|
+
async getAttachmentContent(attachmentId, companyId, options) {
|
|
727
|
+
return callHost("issues.getAttachmentContent", {
|
|
728
|
+
attachmentId,
|
|
729
|
+
companyId,
|
|
730
|
+
maxBytes: options?.maxBytes ?? null,
|
|
731
|
+
});
|
|
732
|
+
},
|
|
733
|
+
documents: {
|
|
734
|
+
async list(issueId, companyId) {
|
|
735
|
+
return callHost("issues.documents.list", { issueId, companyId });
|
|
736
|
+
},
|
|
737
|
+
async get(issueId, key, companyId) {
|
|
738
|
+
return callHost("issues.documents.get", { issueId, key, companyId });
|
|
739
|
+
},
|
|
740
|
+
async upsert(input) {
|
|
741
|
+
return callHost("issues.documents.upsert", {
|
|
742
|
+
issueId: input.issueId,
|
|
743
|
+
key: input.key,
|
|
744
|
+
body: input.body,
|
|
745
|
+
companyId: input.companyId,
|
|
746
|
+
title: input.title,
|
|
747
|
+
format: input.format,
|
|
748
|
+
changeSummary: input.changeSummary,
|
|
749
|
+
});
|
|
750
|
+
},
|
|
751
|
+
async delete(issueId, key, companyId) {
|
|
752
|
+
return callHost("issues.documents.delete", { issueId, key, companyId });
|
|
753
|
+
},
|
|
754
|
+
},
|
|
755
|
+
relations: {
|
|
756
|
+
async get(issueId, companyId) {
|
|
757
|
+
return callHost("issues.relations.get", { issueId, companyId });
|
|
758
|
+
},
|
|
759
|
+
async setBlockedBy(issueId, blockedByIssueIds, companyId, actor) {
|
|
760
|
+
return callHost("issues.relations.setBlockedBy", {
|
|
761
|
+
issueId,
|
|
762
|
+
companyId,
|
|
763
|
+
blockedByIssueIds,
|
|
764
|
+
actorAgentId: actor?.actorAgentId,
|
|
765
|
+
actorUserId: actor?.actorUserId,
|
|
766
|
+
actorRunId: actor?.actorRunId,
|
|
767
|
+
});
|
|
768
|
+
},
|
|
769
|
+
async addBlockers(issueId, blockerIssueIds, companyId, actor) {
|
|
770
|
+
return callHost("issues.relations.addBlockers", {
|
|
771
|
+
issueId,
|
|
772
|
+
companyId,
|
|
773
|
+
blockerIssueIds,
|
|
774
|
+
actorAgentId: actor?.actorAgentId,
|
|
775
|
+
actorUserId: actor?.actorUserId,
|
|
776
|
+
actorRunId: actor?.actorRunId,
|
|
777
|
+
});
|
|
778
|
+
},
|
|
779
|
+
async removeBlockers(issueId, blockerIssueIds, companyId, actor) {
|
|
780
|
+
return callHost("issues.relations.removeBlockers", {
|
|
781
|
+
issueId,
|
|
782
|
+
companyId,
|
|
783
|
+
blockerIssueIds,
|
|
784
|
+
actorAgentId: actor?.actorAgentId,
|
|
785
|
+
actorUserId: actor?.actorUserId,
|
|
786
|
+
actorRunId: actor?.actorRunId,
|
|
787
|
+
});
|
|
788
|
+
},
|
|
789
|
+
},
|
|
790
|
+
summaries: {
|
|
791
|
+
async getOrchestration(input) {
|
|
792
|
+
return callHost("issues.summaries.getOrchestration", input);
|
|
793
|
+
},
|
|
794
|
+
},
|
|
795
|
+
},
|
|
796
|
+
approvals: {
|
|
797
|
+
async list(input) {
|
|
798
|
+
return callHost("approvals.list", {
|
|
799
|
+
companyId: input.companyId,
|
|
800
|
+
status: input.status,
|
|
801
|
+
});
|
|
802
|
+
},
|
|
803
|
+
async get(approvalId, companyId) {
|
|
804
|
+
return callHost("approvals.get", { approvalId, companyId });
|
|
805
|
+
},
|
|
806
|
+
async decide(approvalId, input, companyId) {
|
|
807
|
+
return callHost("approvals.decide", {
|
|
808
|
+
approvalId,
|
|
809
|
+
companyId,
|
|
810
|
+
action: input.action,
|
|
811
|
+
actorUserId: input.actorUserId,
|
|
812
|
+
decisionNote: input.decisionNote,
|
|
813
|
+
});
|
|
814
|
+
},
|
|
815
|
+
},
|
|
816
|
+
agents: {
|
|
817
|
+
async list(input) {
|
|
818
|
+
return callHost("agents.list", {
|
|
819
|
+
companyId: input.companyId,
|
|
820
|
+
status: input.status,
|
|
821
|
+
limit: input.limit,
|
|
822
|
+
offset: input.offset,
|
|
823
|
+
});
|
|
824
|
+
},
|
|
825
|
+
async get(agentId, companyId) {
|
|
826
|
+
return callHost("agents.get", { agentId, companyId });
|
|
827
|
+
},
|
|
828
|
+
async pause(agentId, companyId) {
|
|
829
|
+
return callHost("agents.pause", { agentId, companyId });
|
|
830
|
+
},
|
|
831
|
+
async resume(agentId, companyId) {
|
|
832
|
+
return callHost("agents.resume", { agentId, companyId });
|
|
833
|
+
},
|
|
834
|
+
async invoke(agentId, companyId, opts) {
|
|
835
|
+
return callHost("agents.invoke", { agentId, companyId, prompt: opts.prompt, reason: opts.reason });
|
|
836
|
+
},
|
|
837
|
+
managed: {
|
|
838
|
+
async get(agentKey, companyId) {
|
|
839
|
+
return callHost("agents.managed.get", { agentKey, companyId });
|
|
840
|
+
},
|
|
841
|
+
async reconcile(agentKey, companyId) {
|
|
842
|
+
return callHost("agents.managed.reconcile", { agentKey, companyId });
|
|
843
|
+
},
|
|
844
|
+
async reset(agentKey, companyId) {
|
|
845
|
+
return callHost("agents.managed.reset", { agentKey, companyId });
|
|
846
|
+
},
|
|
847
|
+
},
|
|
848
|
+
sessions: {
|
|
849
|
+
async create(agentId, companyId, opts) {
|
|
850
|
+
return callHost("agents.sessions.create", {
|
|
851
|
+
agentId,
|
|
852
|
+
companyId,
|
|
853
|
+
taskKey: opts?.taskKey,
|
|
854
|
+
reason: opts?.reason,
|
|
855
|
+
});
|
|
856
|
+
},
|
|
857
|
+
async list(agentId, companyId) {
|
|
858
|
+
return callHost("agents.sessions.list", { agentId, companyId });
|
|
859
|
+
},
|
|
860
|
+
async sendMessage(sessionId, companyId, opts) {
|
|
861
|
+
if (opts.onEvent) {
|
|
862
|
+
sessionEventCallbacks.set(sessionId, opts.onEvent);
|
|
863
|
+
}
|
|
864
|
+
try {
|
|
865
|
+
return await callHost("agents.sessions.sendMessage", {
|
|
866
|
+
sessionId,
|
|
867
|
+
companyId,
|
|
868
|
+
prompt: opts.prompt,
|
|
869
|
+
reason: opts.reason,
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
catch (err) {
|
|
873
|
+
sessionEventCallbacks.delete(sessionId);
|
|
874
|
+
throw err;
|
|
875
|
+
}
|
|
876
|
+
},
|
|
877
|
+
async close(sessionId, companyId) {
|
|
878
|
+
sessionEventCallbacks.delete(sessionId);
|
|
879
|
+
await callHost("agents.sessions.close", { sessionId, companyId });
|
|
880
|
+
},
|
|
881
|
+
},
|
|
882
|
+
},
|
|
883
|
+
goals: {
|
|
884
|
+
async list(input) {
|
|
885
|
+
return callHost("goals.list", {
|
|
886
|
+
companyId: input.companyId,
|
|
887
|
+
level: input.level,
|
|
888
|
+
status: input.status,
|
|
889
|
+
limit: input.limit,
|
|
890
|
+
offset: input.offset,
|
|
891
|
+
});
|
|
892
|
+
},
|
|
893
|
+
async get(goalId, companyId) {
|
|
894
|
+
return callHost("goals.get", { goalId, companyId });
|
|
895
|
+
},
|
|
896
|
+
async create(input) {
|
|
897
|
+
return callHost("goals.create", {
|
|
898
|
+
companyId: input.companyId,
|
|
899
|
+
title: input.title,
|
|
900
|
+
description: input.description,
|
|
901
|
+
level: input.level,
|
|
902
|
+
status: input.status,
|
|
903
|
+
parentId: input.parentId,
|
|
904
|
+
ownerAgentId: input.ownerAgentId,
|
|
905
|
+
});
|
|
906
|
+
},
|
|
907
|
+
async update(goalId, patch, companyId) {
|
|
908
|
+
return callHost("goals.update", {
|
|
909
|
+
goalId,
|
|
910
|
+
patch: patch,
|
|
911
|
+
companyId,
|
|
912
|
+
});
|
|
913
|
+
},
|
|
914
|
+
},
|
|
915
|
+
access: {
|
|
916
|
+
members: {
|
|
917
|
+
async list(input) {
|
|
918
|
+
return callHost("access.members.list", {
|
|
919
|
+
companyId: input.companyId,
|
|
920
|
+
includeArchived: input.includeArchived,
|
|
921
|
+
});
|
|
922
|
+
},
|
|
923
|
+
async get(memberId, companyId) {
|
|
924
|
+
return callHost("access.members.get", { memberId, companyId });
|
|
925
|
+
},
|
|
926
|
+
async update(memberId, patch, companyId) {
|
|
927
|
+
return callHost("access.members.update", { memberId, patch, companyId });
|
|
928
|
+
},
|
|
929
|
+
},
|
|
930
|
+
invites: {
|
|
931
|
+
async list(input) {
|
|
932
|
+
return callHost("access.invites.list", {
|
|
933
|
+
companyId: input.companyId,
|
|
934
|
+
state: input.state,
|
|
935
|
+
limit: input.limit,
|
|
936
|
+
offset: input.offset,
|
|
937
|
+
});
|
|
938
|
+
},
|
|
939
|
+
async create(input) {
|
|
940
|
+
return callHost("access.invites.create", {
|
|
941
|
+
companyId: input.companyId,
|
|
942
|
+
allowedJoinTypes: input.allowedJoinTypes,
|
|
943
|
+
humanRole: input.humanRole,
|
|
944
|
+
defaultsPayload: input.defaultsPayload,
|
|
945
|
+
agentMessage: input.agentMessage,
|
|
946
|
+
});
|
|
947
|
+
},
|
|
948
|
+
async revoke(inviteId, companyId) {
|
|
949
|
+
return callHost("access.invites.revoke", { inviteId, companyId });
|
|
950
|
+
},
|
|
951
|
+
},
|
|
952
|
+
},
|
|
953
|
+
authorization: {
|
|
954
|
+
grants: {
|
|
955
|
+
async list(input) {
|
|
956
|
+
return callHost("authorization.grants.list", input);
|
|
957
|
+
},
|
|
958
|
+
async set(input) {
|
|
959
|
+
return callHost("authorization.grants.set", input);
|
|
960
|
+
},
|
|
961
|
+
},
|
|
962
|
+
policies: {
|
|
963
|
+
async summary(companyId) {
|
|
964
|
+
return callHost("authorization.policies.summary", { companyId });
|
|
965
|
+
},
|
|
966
|
+
async get(input) {
|
|
967
|
+
return callHost("authorization.policies.get", input);
|
|
968
|
+
},
|
|
969
|
+
async update(input) {
|
|
970
|
+
return callHost("authorization.policies.update", input);
|
|
971
|
+
},
|
|
972
|
+
async previewAssignment(input) {
|
|
973
|
+
return callHost("authorization.policies.previewAssignment", input);
|
|
974
|
+
},
|
|
975
|
+
async explainAssignment(input) {
|
|
976
|
+
return callHost("authorization.policies.explainAssignment", input);
|
|
977
|
+
},
|
|
978
|
+
},
|
|
979
|
+
audit: {
|
|
980
|
+
async search(input) {
|
|
981
|
+
return callHost("authorization.audit.search", input);
|
|
982
|
+
},
|
|
983
|
+
},
|
|
984
|
+
},
|
|
985
|
+
data: {
|
|
986
|
+
register(key, handler) {
|
|
987
|
+
dataHandlers.set(key, handler);
|
|
988
|
+
},
|
|
989
|
+
},
|
|
990
|
+
actions: {
|
|
991
|
+
register(key, handler) {
|
|
992
|
+
actionHandlers.set(key, handler);
|
|
993
|
+
},
|
|
994
|
+
},
|
|
995
|
+
streams: (() => {
|
|
996
|
+
// Track channel → companyId so emit/close don't require companyId
|
|
997
|
+
const channelCompanyMap = new Map();
|
|
998
|
+
return {
|
|
999
|
+
open(channel, companyId) {
|
|
1000
|
+
channelCompanyMap.set(channel, companyId);
|
|
1001
|
+
notifyHost("streams.open", { channel, companyId });
|
|
1002
|
+
},
|
|
1003
|
+
emit(channel, event) {
|
|
1004
|
+
const companyId = channelCompanyMap.get(channel) ?? "";
|
|
1005
|
+
notifyHost("streams.emit", { channel, companyId, event });
|
|
1006
|
+
},
|
|
1007
|
+
close(channel) {
|
|
1008
|
+
const companyId = channelCompanyMap.get(channel) ?? "";
|
|
1009
|
+
channelCompanyMap.delete(channel);
|
|
1010
|
+
notifyHost("streams.close", { channel, companyId });
|
|
1011
|
+
},
|
|
1012
|
+
};
|
|
1013
|
+
})(),
|
|
1014
|
+
execution: {
|
|
1015
|
+
log(stream, chunk) {
|
|
1016
|
+
// Emit one incremental output chunk of the active execute call.
|
|
1017
|
+
// `notifyHost` stamps the active invocation id from the invocation
|
|
1018
|
+
// context, so the host correlates the chunk to the host-owned execute
|
|
1019
|
+
// route for that call. The notification carries no company id; the
|
|
1020
|
+
// host binds the company from its own execute route. A chunk sent with
|
|
1021
|
+
// no active invocation carries no id and the host drops it.
|
|
1022
|
+
if (typeof chunk !== "string" || chunk.length === 0)
|
|
1023
|
+
return;
|
|
1024
|
+
notifyHost("execute.log", { stream, chunk });
|
|
1025
|
+
},
|
|
1026
|
+
},
|
|
1027
|
+
loginPty: {
|
|
1028
|
+
output(hostRouteId, workerSessionId, chunk) {
|
|
1029
|
+
// Forward one raw output chunk of a live login pseudo-terminal. The
|
|
1030
|
+
// notification echoes the host route identifier and the worker session
|
|
1031
|
+
// identifier, so the host can hold more than one concurrent login
|
|
1032
|
+
// pseudo-terminal per worker and binds the chunk to its own route
|
|
1033
|
+
// while that route is open. The host drops an unknown, a stale, or a
|
|
1034
|
+
// mismatched identifier and never logs the raw bytes. This
|
|
1035
|
+
// notification carries no invocation id, because it fires after the
|
|
1036
|
+
// open reply returns.
|
|
1037
|
+
if (typeof hostRouteId !== "string" || hostRouteId.length === 0)
|
|
1038
|
+
return;
|
|
1039
|
+
if (typeof workerSessionId !== "string" || workerSessionId.length === 0)
|
|
1040
|
+
return;
|
|
1041
|
+
if (typeof chunk !== "string" || chunk.length === 0)
|
|
1042
|
+
return;
|
|
1043
|
+
notifyHost(LOGIN_PTY_OUTPUT_NOTIFICATION, { hostRouteId, workerSessionId, chunk });
|
|
1044
|
+
},
|
|
1045
|
+
exit(hostRouteId, workerSessionId, exitCode) {
|
|
1046
|
+
// Forward the child exit of a live login pseudo-terminal. The host
|
|
1047
|
+
// resolves its own route's wait promise by the host route identifier
|
|
1048
|
+
// and the bound worker session identifier while that route is open.
|
|
1049
|
+
if (typeof hostRouteId !== "string" || hostRouteId.length === 0)
|
|
1050
|
+
return;
|
|
1051
|
+
if (typeof workerSessionId !== "string" || workerSessionId.length === 0)
|
|
1052
|
+
return;
|
|
1053
|
+
notifyHost(LOGIN_PTY_EXIT_NOTIFICATION, {
|
|
1054
|
+
hostRouteId,
|
|
1055
|
+
workerSessionId,
|
|
1056
|
+
exitCode: typeof exitCode === "number" ? exitCode : null,
|
|
1057
|
+
});
|
|
1058
|
+
},
|
|
1059
|
+
},
|
|
1060
|
+
duplexChannel: {
|
|
1061
|
+
data(hostRouteId, workerSessionId, chunk) {
|
|
1062
|
+
// Forward one raw data chunk of a persistent duplex channel. The
|
|
1063
|
+
// notification echoes the host route identifier and the worker session
|
|
1064
|
+
// identifier, so the host routes the chunk to the exact live pair while
|
|
1065
|
+
// the route is open. The host drops an unknown or a mismatched pair and
|
|
1066
|
+
// never logs the raw bytes. This notification carries no invocation id,
|
|
1067
|
+
// because it fires after the open reply returns.
|
|
1068
|
+
//
|
|
1069
|
+
// JSON-RPC travels as JSON text, which carries no binary type, so this
|
|
1070
|
+
// is the one point where the chunk crosses from `Uint8Array` to the
|
|
1071
|
+
// wire-safe base64 form. See `ChannelBytesWireValue` in protocol.ts.
|
|
1072
|
+
if (typeof hostRouteId !== "string" || hostRouteId.length === 0)
|
|
1073
|
+
return;
|
|
1074
|
+
if (typeof workerSessionId !== "string" || workerSessionId.length === 0)
|
|
1075
|
+
return;
|
|
1076
|
+
if (!(chunk instanceof Uint8Array) || chunk.byteLength === 0)
|
|
1077
|
+
return;
|
|
1078
|
+
notifyHost(DUPLEX_CHANNEL_DATA_NOTIFICATION, {
|
|
1079
|
+
hostRouteId,
|
|
1080
|
+
workerSessionId,
|
|
1081
|
+
chunk: encodeChannelBytes(chunk),
|
|
1082
|
+
});
|
|
1083
|
+
},
|
|
1084
|
+
exit(hostRouteId, workerSessionId, exitCode, transportClosed) {
|
|
1085
|
+
// Forward the child exit of a persistent duplex channel. The host
|
|
1086
|
+
// resolves the open route's wait promise by the exact live pair while
|
|
1087
|
+
// the route is open. `transportClosed` carries the exit discriminator, so
|
|
1088
|
+
// the host tells a real process exit from a reason-less transport close.
|
|
1089
|
+
if (typeof hostRouteId !== "string" || hostRouteId.length === 0)
|
|
1090
|
+
return;
|
|
1091
|
+
if (typeof workerSessionId !== "string" || workerSessionId.length === 0)
|
|
1092
|
+
return;
|
|
1093
|
+
notifyHost(DUPLEX_CHANNEL_EXIT_NOTIFICATION, {
|
|
1094
|
+
hostRouteId,
|
|
1095
|
+
workerSessionId,
|
|
1096
|
+
exitCode: typeof exitCode === "number" ? exitCode : null,
|
|
1097
|
+
transportClosed: transportClosed === true,
|
|
1098
|
+
});
|
|
1099
|
+
},
|
|
1100
|
+
},
|
|
1101
|
+
tools: {
|
|
1102
|
+
register(name, declaration, fn) {
|
|
1103
|
+
toolHandlers.set(name, { declaration, fn });
|
|
1104
|
+
},
|
|
1105
|
+
},
|
|
1106
|
+
metrics: {
|
|
1107
|
+
async write(name, value, tags) {
|
|
1108
|
+
await callHost("metrics.write", { name, value, tags });
|
|
1109
|
+
},
|
|
1110
|
+
},
|
|
1111
|
+
telemetry: {
|
|
1112
|
+
async track(eventName, dimensions) {
|
|
1113
|
+
await callHost("telemetry.track", { eventName, dimensions });
|
|
1114
|
+
},
|
|
1115
|
+
},
|
|
1116
|
+
logger: {
|
|
1117
|
+
info(message, meta) {
|
|
1118
|
+
notifyHost("log", { level: "info", message, meta });
|
|
1119
|
+
},
|
|
1120
|
+
warn(message, meta) {
|
|
1121
|
+
notifyHost("log", { level: "warn", message, meta });
|
|
1122
|
+
},
|
|
1123
|
+
error(message, meta) {
|
|
1124
|
+
notifyHost("log", { level: "error", message, meta });
|
|
1125
|
+
},
|
|
1126
|
+
debug(message, meta) {
|
|
1127
|
+
notifyHost("log", { level: "debug", message, meta });
|
|
1128
|
+
},
|
|
1129
|
+
},
|
|
1130
|
+
tracer: {
|
|
1131
|
+
startSpan(name, options) {
|
|
1132
|
+
// Read the active host trace context from the per-call invocation
|
|
1133
|
+
// channel. A `traceparent` means a host span is active, so this span
|
|
1134
|
+
// may record. No `traceparent` means tracing is off: the span is a
|
|
1135
|
+
// no-op, so a lifecycle hook can always wrap work in a span.
|
|
1136
|
+
const hasTraceContext = Boolean(invocationContextStorage.getStore()?.traceparent);
|
|
1137
|
+
const attributes = {
|
|
1138
|
+
...(options?.attributes ?? {}),
|
|
1139
|
+
};
|
|
1140
|
+
// Capture the real start time once when the span opens. The host uses
|
|
1141
|
+
// it as the span start time, so the span shows its true native width.
|
|
1142
|
+
const startTimeMs = Date.now();
|
|
1143
|
+
let status;
|
|
1144
|
+
let ended = false;
|
|
1145
|
+
return {
|
|
1146
|
+
setAttribute(key, value) {
|
|
1147
|
+
attributes[key] = value;
|
|
1148
|
+
},
|
|
1149
|
+
setStatus(next) {
|
|
1150
|
+
status = next;
|
|
1151
|
+
},
|
|
1152
|
+
end() {
|
|
1153
|
+
if (ended)
|
|
1154
|
+
return;
|
|
1155
|
+
ended = true;
|
|
1156
|
+
if (!hasTraceContext)
|
|
1157
|
+
return;
|
|
1158
|
+
// Capture the real end time once at the first end call. The host
|
|
1159
|
+
// uses the pair to record the span with its true wall-clock width.
|
|
1160
|
+
const endTimeMs = Date.now();
|
|
1161
|
+
// Send the finished span to the host once. The host re-clamps the
|
|
1162
|
+
// name and the attributes, mints the parentage from its own
|
|
1163
|
+
// invocation record, and records the span through the real tracer.
|
|
1164
|
+
// Fire-and-forget: a span must never block or fail plugin work.
|
|
1165
|
+
void callHost("span.record", {
|
|
1166
|
+
name,
|
|
1167
|
+
attributes,
|
|
1168
|
+
...(status ? { status } : {}),
|
|
1169
|
+
startTimeMs,
|
|
1170
|
+
endTimeMs,
|
|
1171
|
+
}).catch(() => undefined);
|
|
1172
|
+
},
|
|
1173
|
+
};
|
|
1174
|
+
},
|
|
1175
|
+
},
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
const ctx = buildContext();
|
|
1179
|
+
// -----------------------------------------------------------------------
|
|
1180
|
+
// Inbound message handling (host → worker)
|
|
1181
|
+
// -----------------------------------------------------------------------
|
|
1182
|
+
/**
|
|
1183
|
+
* Handle an incoming JSON-RPC request from the host.
|
|
1184
|
+
*
|
|
1185
|
+
* Dispatches to the correct handler based on the method name.
|
|
1186
|
+
*/
|
|
1187
|
+
async function handleHostRequest(request) {
|
|
1188
|
+
const { id, method, params } = request;
|
|
1189
|
+
try {
|
|
1190
|
+
const invoke = () => dispatchMethod(method, params);
|
|
1191
|
+
const result = request.paperclipInvocation
|
|
1192
|
+
? await invocationContextStorage.run(request.paperclipInvocation, invoke)
|
|
1193
|
+
: await invoke();
|
|
1194
|
+
sendMessage(createSuccessResponse(id, result ?? null));
|
|
1195
|
+
}
|
|
1196
|
+
catch (err) {
|
|
1197
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
1198
|
+
// Propagate specific error codes from handler errors (e.g.
|
|
1199
|
+
// METHOD_NOT_FOUND, METHOD_NOT_IMPLEMENTED) — fall back to
|
|
1200
|
+
// WORKER_ERROR for untyped exceptions.
|
|
1201
|
+
const errorCode = typeof err?.code === "number"
|
|
1202
|
+
? err.code
|
|
1203
|
+
: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR;
|
|
1204
|
+
sendMessage(createErrorResponse(id, errorCode, errorMessage));
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* Dispatch a host→worker method call to the appropriate handler.
|
|
1209
|
+
*/
|
|
1210
|
+
async function dispatchMethod(method, params) {
|
|
1211
|
+
switch (method) {
|
|
1212
|
+
case "initialize":
|
|
1213
|
+
return handleInitialize(params);
|
|
1214
|
+
case "health":
|
|
1215
|
+
return handleHealth();
|
|
1216
|
+
case "shutdown":
|
|
1217
|
+
return handleShutdown();
|
|
1218
|
+
case "validateConfig":
|
|
1219
|
+
return handleValidateConfig(params);
|
|
1220
|
+
case "configChanged":
|
|
1221
|
+
return handleConfigChanged(params);
|
|
1222
|
+
case "onEvent":
|
|
1223
|
+
return handleOnEvent(params);
|
|
1224
|
+
case "runJob":
|
|
1225
|
+
return handleRunJob(params);
|
|
1226
|
+
case "handleWebhook":
|
|
1227
|
+
return handleWebhook(params);
|
|
1228
|
+
case "handleApiRequest":
|
|
1229
|
+
return handleApiRequest(params);
|
|
1230
|
+
case "getData":
|
|
1231
|
+
return handleGetData(params);
|
|
1232
|
+
case "performAction":
|
|
1233
|
+
return handlePerformAction(params);
|
|
1234
|
+
case "executeTool":
|
|
1235
|
+
return handleExecuteTool(params);
|
|
1236
|
+
case "detectExternalObjects":
|
|
1237
|
+
return handleDetectExternalObjects(params);
|
|
1238
|
+
case "resolveExternalObject":
|
|
1239
|
+
return handleResolveExternalObject(params);
|
|
1240
|
+
case "refreshExternalObjects":
|
|
1241
|
+
return handleRefreshExternalObjects(params);
|
|
1242
|
+
case "environmentValidateConfig":
|
|
1243
|
+
return handleEnvironmentValidateConfig(params);
|
|
1244
|
+
case "environmentProbe":
|
|
1245
|
+
return handleEnvironmentProbe(params);
|
|
1246
|
+
case "environmentAcquireLease":
|
|
1247
|
+
return handleEnvironmentAcquireLease(params);
|
|
1248
|
+
case "environmentResumeLease":
|
|
1249
|
+
return handleEnvironmentResumeLease(params);
|
|
1250
|
+
case "environmentReleaseLease":
|
|
1251
|
+
return handleEnvironmentReleaseLease(params);
|
|
1252
|
+
case "environmentDestroyLease":
|
|
1253
|
+
return handleEnvironmentDestroyLease(params);
|
|
1254
|
+
case "environmentRealizeWorkspace":
|
|
1255
|
+
return handleEnvironmentRealizeWorkspace(params);
|
|
1256
|
+
case "environmentExecute":
|
|
1257
|
+
return handleEnvironmentExecute(params);
|
|
1258
|
+
case "environmentRunnerIngressEndpoint":
|
|
1259
|
+
return handleEnvironmentRunnerIngressEndpoint(params);
|
|
1260
|
+
case "environmentSyncIn":
|
|
1261
|
+
return handleEnvironmentSyncIn(params);
|
|
1262
|
+
case "environmentSyncOut":
|
|
1263
|
+
return handleEnvironmentSyncOut(params);
|
|
1264
|
+
case "environmentStartInteractiveSetup":
|
|
1265
|
+
return handleEnvironmentStartInteractiveSetup(params);
|
|
1266
|
+
case "environmentGetInteractiveSetup":
|
|
1267
|
+
return handleEnvironmentGetInteractiveSetup(params);
|
|
1268
|
+
case "environmentCaptureTemplate":
|
|
1269
|
+
return handleEnvironmentCaptureTemplate(params);
|
|
1270
|
+
case "environmentCancelInteractiveSetup":
|
|
1271
|
+
return handleEnvironmentCancelInteractiveSetup(params);
|
|
1272
|
+
case "environmentDeleteTemplate":
|
|
1273
|
+
return handleEnvironmentDeleteTemplate(params);
|
|
1274
|
+
case "loginPtyOpen":
|
|
1275
|
+
return handleLoginPtyOpen(params);
|
|
1276
|
+
case "loginPtyInput":
|
|
1277
|
+
return handleLoginPtyInput(params);
|
|
1278
|
+
case "loginPtyStop":
|
|
1279
|
+
return handleLoginPtyStop(params);
|
|
1280
|
+
case "loginPtyClose":
|
|
1281
|
+
return handleLoginPtyClose(params);
|
|
1282
|
+
case "duplexChannelOpen":
|
|
1283
|
+
return handleDuplexChannelOpen(params);
|
|
1284
|
+
case "duplexChannelWrite":
|
|
1285
|
+
return handleDuplexChannelWrite(params);
|
|
1286
|
+
case "duplexChannelStop":
|
|
1287
|
+
return handleDuplexChannelStop(params);
|
|
1288
|
+
case "duplexChannelClose":
|
|
1289
|
+
return handleDuplexChannelClose(params);
|
|
1290
|
+
default:
|
|
1291
|
+
throw Object.assign(new Error(`Unknown method: ${method}`), { code: JSONRPC_ERROR_CODES.METHOD_NOT_FOUND });
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
// -----------------------------------------------------------------------
|
|
1295
|
+
// Host→Worker method handlers
|
|
1296
|
+
// -----------------------------------------------------------------------
|
|
1297
|
+
async function handleInitialize(params) {
|
|
1298
|
+
if (initialized) {
|
|
1299
|
+
throw new Error("Worker already initialized");
|
|
1300
|
+
}
|
|
1301
|
+
manifest = params.manifest;
|
|
1302
|
+
currentConfig = params.config;
|
|
1303
|
+
databaseNamespace = params.databaseNamespace ?? null;
|
|
1304
|
+
// Call the plugin's setup function
|
|
1305
|
+
await plugin.definition.setup(ctx);
|
|
1306
|
+
initialized = true;
|
|
1307
|
+
// Report which optional methods this plugin implements
|
|
1308
|
+
const supportedMethods = [];
|
|
1309
|
+
if (plugin.definition.onValidateConfig)
|
|
1310
|
+
supportedMethods.push("validateConfig");
|
|
1311
|
+
if (plugin.definition.onConfigChanged)
|
|
1312
|
+
supportedMethods.push("configChanged");
|
|
1313
|
+
if (plugin.definition.onHealth)
|
|
1314
|
+
supportedMethods.push("health");
|
|
1315
|
+
if (plugin.definition.onShutdown)
|
|
1316
|
+
supportedMethods.push("shutdown");
|
|
1317
|
+
if (plugin.definition.onApiRequest)
|
|
1318
|
+
supportedMethods.push("handleApiRequest");
|
|
1319
|
+
if (plugin.definition.onDetectExternalObjects)
|
|
1320
|
+
supportedMethods.push("detectExternalObjects");
|
|
1321
|
+
if (plugin.definition.onResolveExternalObject)
|
|
1322
|
+
supportedMethods.push("resolveExternalObject");
|
|
1323
|
+
if (plugin.definition.onRefreshExternalObjects)
|
|
1324
|
+
supportedMethods.push("refreshExternalObjects");
|
|
1325
|
+
if (plugin.definition.onEnvironmentValidateConfig)
|
|
1326
|
+
supportedMethods.push("environmentValidateConfig");
|
|
1327
|
+
if (plugin.definition.onEnvironmentProbe)
|
|
1328
|
+
supportedMethods.push("environmentProbe");
|
|
1329
|
+
if (plugin.definition.onEnvironmentAcquireLease)
|
|
1330
|
+
supportedMethods.push("environmentAcquireLease");
|
|
1331
|
+
if (plugin.definition.onEnvironmentResumeLease)
|
|
1332
|
+
supportedMethods.push("environmentResumeLease");
|
|
1333
|
+
if (plugin.definition.onEnvironmentReleaseLease)
|
|
1334
|
+
supportedMethods.push("environmentReleaseLease");
|
|
1335
|
+
if (plugin.definition.onEnvironmentDestroyLease)
|
|
1336
|
+
supportedMethods.push("environmentDestroyLease");
|
|
1337
|
+
if (plugin.definition.onEnvironmentRealizeWorkspace)
|
|
1338
|
+
supportedMethods.push("environmentRealizeWorkspace");
|
|
1339
|
+
if (plugin.definition.onEnvironmentExecute)
|
|
1340
|
+
supportedMethods.push("environmentExecute");
|
|
1341
|
+
if (plugin.definition.onEnvironmentRunnerIngressEndpoint) {
|
|
1342
|
+
supportedMethods.push("environmentRunnerIngressEndpoint");
|
|
1343
|
+
}
|
|
1344
|
+
if (plugin.definition.onEnvironmentSyncIn)
|
|
1345
|
+
supportedMethods.push("environmentSyncIn");
|
|
1346
|
+
if (plugin.definition.onEnvironmentSyncOut)
|
|
1347
|
+
supportedMethods.push("environmentSyncOut");
|
|
1348
|
+
if (plugin.definition.onEnvironmentStartInteractiveSetup)
|
|
1349
|
+
supportedMethods.push("environmentStartInteractiveSetup");
|
|
1350
|
+
if (plugin.definition.onEnvironmentGetInteractiveSetup)
|
|
1351
|
+
supportedMethods.push("environmentGetInteractiveSetup");
|
|
1352
|
+
if (plugin.definition.onEnvironmentCaptureTemplate)
|
|
1353
|
+
supportedMethods.push("environmentCaptureTemplate");
|
|
1354
|
+
if (plugin.definition.onEnvironmentCancelInteractiveSetup)
|
|
1355
|
+
supportedMethods.push("environmentCancelInteractiveSetup");
|
|
1356
|
+
if (plugin.definition.onEnvironmentDeleteTemplate)
|
|
1357
|
+
supportedMethods.push("environmentDeleteTemplate");
|
|
1358
|
+
if (plugin.definition.onLoginPtyOpen)
|
|
1359
|
+
supportedMethods.push("loginPtyOpen");
|
|
1360
|
+
if (plugin.definition.onLoginPtyInput)
|
|
1361
|
+
supportedMethods.push("loginPtyInput");
|
|
1362
|
+
if (plugin.definition.onLoginPtyStop)
|
|
1363
|
+
supportedMethods.push("loginPtyStop");
|
|
1364
|
+
if (plugin.definition.onLoginPtyClose)
|
|
1365
|
+
supportedMethods.push("loginPtyClose");
|
|
1366
|
+
if (plugin.definition.onDuplexChannelOpen)
|
|
1367
|
+
supportedMethods.push("duplexChannelOpen");
|
|
1368
|
+
if (plugin.definition.onDuplexChannelWrite)
|
|
1369
|
+
supportedMethods.push("duplexChannelWrite");
|
|
1370
|
+
if (plugin.definition.onDuplexChannelStop)
|
|
1371
|
+
supportedMethods.push("duplexChannelStop");
|
|
1372
|
+
if (plugin.definition.onDuplexChannelClose)
|
|
1373
|
+
supportedMethods.push("duplexChannelClose");
|
|
1374
|
+
return { ok: true, supportedMethods };
|
|
1375
|
+
}
|
|
1376
|
+
async function handleHealth() {
|
|
1377
|
+
if (plugin.definition.onHealth) {
|
|
1378
|
+
return plugin.definition.onHealth();
|
|
1379
|
+
}
|
|
1380
|
+
// Default: report OK if the worker is alive
|
|
1381
|
+
return { status: "ok" };
|
|
1382
|
+
}
|
|
1383
|
+
async function handleShutdown() {
|
|
1384
|
+
if (plugin.definition.onShutdown) {
|
|
1385
|
+
await plugin.definition.onShutdown();
|
|
1386
|
+
}
|
|
1387
|
+
// Schedule cleanup after we send the response.
|
|
1388
|
+
// Use setImmediate to let the response flush before exiting.
|
|
1389
|
+
// Only call process.exit() when running with real process streams.
|
|
1390
|
+
// When custom streams are provided (tests), just clean up.
|
|
1391
|
+
setImmediate(() => {
|
|
1392
|
+
cleanup();
|
|
1393
|
+
if (!options.stdin && !options.stdout) {
|
|
1394
|
+
process.exit(0);
|
|
1395
|
+
}
|
|
1396
|
+
});
|
|
1397
|
+
}
|
|
1398
|
+
async function handleValidateConfig(params) {
|
|
1399
|
+
if (!plugin.definition.onValidateConfig) {
|
|
1400
|
+
throw Object.assign(new Error("validateConfig is not implemented by this plugin"), { code: PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED });
|
|
1401
|
+
}
|
|
1402
|
+
return plugin.definition.onValidateConfig(params.config);
|
|
1403
|
+
}
|
|
1404
|
+
async function handleConfigChanged(params) {
|
|
1405
|
+
const incomingCompanyId = params.companyId ?? null;
|
|
1406
|
+
// Fail-closed cross-tenant guard.
|
|
1407
|
+
//
|
|
1408
|
+
// A worker is spawned once per plugin (not per company), so a proactive
|
|
1409
|
+
// plugin that keeps a single worker-global config would silently collapse
|
|
1410
|
+
// onto whichever company's config was delivered last if configChanged is
|
|
1411
|
+
// called for more than one distinct company — for example the startup
|
|
1412
|
+
// config replay fanning out every stored company's config, or two operators
|
|
1413
|
+
// saving configs for different companies. That is a cross-tenant identity /
|
|
1414
|
+
// secret confusion bug (one company's bot token applied to another's work).
|
|
1415
|
+
//
|
|
1416
|
+
// Reject the second, distinct company unless the plugin explicitly declares
|
|
1417
|
+
// it handles multiple companies in one worker (multiCompanyConfig). An
|
|
1418
|
+
// idempotent replay of the *same* config for a different company id is
|
|
1419
|
+
// harmless (single-tenant plugins commonly have duplicate scope rows that
|
|
1420
|
+
// all embed the same config), so it is allowed.
|
|
1421
|
+
if (!plugin.definition.multiCompanyConfig &&
|
|
1422
|
+
incomingCompanyId !== null &&
|
|
1423
|
+
configCompanyId !== null &&
|
|
1424
|
+
configCompanyId !== incomingCompanyId &&
|
|
1425
|
+
!configsEqual(params.config, currentConfig)) {
|
|
1426
|
+
throw Object.assign(new Error(`configChanged: refusing to overwrite configuration for company ` +
|
|
1427
|
+
`"${configCompanyId}" with a different configuration for company ` +
|
|
1428
|
+
`"${incomingCompanyId}". This plugin is single-tenant and cannot ` +
|
|
1429
|
+
`safely serve multiple companies from one worker. If multi-company ` +
|
|
1430
|
+
`support is intended, set multiCompanyConfig: true on the plugin ` +
|
|
1431
|
+
`definition and key per-company state on context.companyId.`), { code: PLUGIN_RPC_ERROR_CODES.CROSS_TENANT_CONFIG });
|
|
1432
|
+
}
|
|
1433
|
+
currentConfig = params.config;
|
|
1434
|
+
if (incomingCompanyId !== null) {
|
|
1435
|
+
configCompanyId = incomingCompanyId;
|
|
1436
|
+
}
|
|
1437
|
+
if (plugin.definition.onConfigChanged) {
|
|
1438
|
+
await plugin.definition.onConfigChanged(params.config, {
|
|
1439
|
+
companyId: incomingCompanyId,
|
|
1440
|
+
});
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
async function handleOnEvent(params) {
|
|
1444
|
+
const event = params.event;
|
|
1445
|
+
for (const registration of eventHandlers) {
|
|
1446
|
+
// Check event type match
|
|
1447
|
+
const exactMatch = registration.name === event.eventType;
|
|
1448
|
+
const wildcardPluginAll = registration.name === "plugin.*" &&
|
|
1449
|
+
event.eventType.startsWith("plugin.");
|
|
1450
|
+
const wildcardPluginOne = registration.name.endsWith(".*") &&
|
|
1451
|
+
event.eventType.startsWith(registration.name.slice(0, -1));
|
|
1452
|
+
if (!exactMatch && !wildcardPluginAll && !wildcardPluginOne)
|
|
1453
|
+
continue;
|
|
1454
|
+
// Check filter
|
|
1455
|
+
if (registration.filter && !allowsEvent(registration.filter, event))
|
|
1456
|
+
continue;
|
|
1457
|
+
try {
|
|
1458
|
+
await registration.fn(event);
|
|
1459
|
+
}
|
|
1460
|
+
catch (err) {
|
|
1461
|
+
// Log error but continue processing other handlers so one failing
|
|
1462
|
+
// handler doesn't prevent the rest from running.
|
|
1463
|
+
notifyHost("log", {
|
|
1464
|
+
level: "error",
|
|
1465
|
+
message: `Event handler for "${registration.name}" failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
1466
|
+
meta: { eventType: event.eventType, stack: err instanceof Error ? err.stack : undefined },
|
|
1467
|
+
});
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
async function handleRunJob(params) {
|
|
1472
|
+
const handler = jobHandlers.get(params.job.jobKey);
|
|
1473
|
+
if (!handler) {
|
|
1474
|
+
throw new Error(`No handler registered for job "${params.job.jobKey}"`);
|
|
1475
|
+
}
|
|
1476
|
+
await handler(params.job);
|
|
1477
|
+
}
|
|
1478
|
+
async function handleWebhook(params) {
|
|
1479
|
+
if (!plugin.definition.onWebhook) {
|
|
1480
|
+
throw Object.assign(new Error("handleWebhook is not implemented by this plugin"), { code: PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED });
|
|
1481
|
+
}
|
|
1482
|
+
await plugin.definition.onWebhook(params);
|
|
1483
|
+
}
|
|
1484
|
+
async function handleApiRequest(params) {
|
|
1485
|
+
if (!plugin.definition.onApiRequest) {
|
|
1486
|
+
throw Object.assign(new Error("handleApiRequest is not implemented by this plugin"), { code: PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED });
|
|
1487
|
+
}
|
|
1488
|
+
return plugin.definition.onApiRequest(params);
|
|
1489
|
+
}
|
|
1490
|
+
async function handleGetData(params) {
|
|
1491
|
+
const handler = dataHandlers.get(params.key);
|
|
1492
|
+
if (!handler) {
|
|
1493
|
+
throw new Error(`No data handler registered for key "${params.key}"`);
|
|
1494
|
+
}
|
|
1495
|
+
return handler({
|
|
1496
|
+
...params.params,
|
|
1497
|
+
...(params.companyId === undefined ? {} : { companyId: params.companyId }),
|
|
1498
|
+
...(params.renderEnvironment === undefined ? {} : { renderEnvironment: params.renderEnvironment }),
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
function stringOrNull(value) {
|
|
1502
|
+
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
|
1503
|
+
}
|
|
1504
|
+
function actorTypeOrSystem(value) {
|
|
1505
|
+
return value === "user" || value === "agent" || value === "system" ? value : "system";
|
|
1506
|
+
}
|
|
1507
|
+
function actionContextFromParams(params) {
|
|
1508
|
+
const rawActor = params.actorContext && typeof params.actorContext === "object"
|
|
1509
|
+
? params.actorContext
|
|
1510
|
+
: null;
|
|
1511
|
+
const actor = Object.freeze({
|
|
1512
|
+
type: actorTypeOrSystem(rawActor?.type),
|
|
1513
|
+
userId: stringOrNull(rawActor?.userId),
|
|
1514
|
+
agentId: stringOrNull(rawActor?.agentId),
|
|
1515
|
+
runId: stringOrNull(rawActor?.runId),
|
|
1516
|
+
companyId: stringOrNull(rawActor?.companyId),
|
|
1517
|
+
});
|
|
1518
|
+
return Object.freeze({
|
|
1519
|
+
actor,
|
|
1520
|
+
companyId: actor.companyId,
|
|
1521
|
+
});
|
|
1522
|
+
}
|
|
1523
|
+
async function handlePerformAction(params) {
|
|
1524
|
+
const handler = actionHandlers.get(params.key);
|
|
1525
|
+
if (!handler) {
|
|
1526
|
+
throw new Error(`No action handler registered for key "${params.key}"`);
|
|
1527
|
+
}
|
|
1528
|
+
return handler({
|
|
1529
|
+
...params.params,
|
|
1530
|
+
...(params.companyId === undefined ? {} : { companyId: params.companyId }),
|
|
1531
|
+
...(params.renderEnvironment === undefined ? {} : { renderEnvironment: params.renderEnvironment }),
|
|
1532
|
+
}, actionContextFromParams(params));
|
|
1533
|
+
}
|
|
1534
|
+
async function handleExecuteTool(params) {
|
|
1535
|
+
const entry = toolHandlers.get(params.toolName);
|
|
1536
|
+
if (!entry) {
|
|
1537
|
+
throw new Error(`No tool handler registered for "${params.toolName}"`);
|
|
1538
|
+
}
|
|
1539
|
+
return entry.fn(params.parameters, params.runContext);
|
|
1540
|
+
}
|
|
1541
|
+
async function handleDetectExternalObjects(params) {
|
|
1542
|
+
if (!plugin.definition.onDetectExternalObjects) {
|
|
1543
|
+
throw methodNotImplemented("detectExternalObjects");
|
|
1544
|
+
}
|
|
1545
|
+
return plugin.definition.onDetectExternalObjects(params);
|
|
1546
|
+
}
|
|
1547
|
+
async function handleResolveExternalObject(params) {
|
|
1548
|
+
if (!plugin.definition.onResolveExternalObject) {
|
|
1549
|
+
throw methodNotImplemented("resolveExternalObject");
|
|
1550
|
+
}
|
|
1551
|
+
return plugin.definition.onResolveExternalObject(params);
|
|
1552
|
+
}
|
|
1553
|
+
async function handleRefreshExternalObjects(params) {
|
|
1554
|
+
if (!plugin.definition.onRefreshExternalObjects) {
|
|
1555
|
+
throw methodNotImplemented("refreshExternalObjects");
|
|
1556
|
+
}
|
|
1557
|
+
return plugin.definition.onRefreshExternalObjects(params);
|
|
1558
|
+
}
|
|
1559
|
+
function methodNotImplemented(method) {
|
|
1560
|
+
return Object.assign(new Error(`${method} is not implemented by this plugin`), { code: PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED });
|
|
1561
|
+
}
|
|
1562
|
+
async function handleEnvironmentValidateConfig(params) {
|
|
1563
|
+
if (!plugin.definition.onEnvironmentValidateConfig) {
|
|
1564
|
+
throw methodNotImplemented("environmentValidateConfig");
|
|
1565
|
+
}
|
|
1566
|
+
return plugin.definition.onEnvironmentValidateConfig(params);
|
|
1567
|
+
}
|
|
1568
|
+
async function handleEnvironmentProbe(params) {
|
|
1569
|
+
if (!plugin.definition.onEnvironmentProbe) {
|
|
1570
|
+
throw methodNotImplemented("environmentProbe");
|
|
1571
|
+
}
|
|
1572
|
+
return plugin.definition.onEnvironmentProbe(params);
|
|
1573
|
+
}
|
|
1574
|
+
async function handleEnvironmentAcquireLease(params) {
|
|
1575
|
+
if (!plugin.definition.onEnvironmentAcquireLease) {
|
|
1576
|
+
throw methodNotImplemented("environmentAcquireLease");
|
|
1577
|
+
}
|
|
1578
|
+
return plugin.definition.onEnvironmentAcquireLease(params);
|
|
1579
|
+
}
|
|
1580
|
+
async function handleEnvironmentResumeLease(params) {
|
|
1581
|
+
if (!plugin.definition.onEnvironmentResumeLease) {
|
|
1582
|
+
throw methodNotImplemented("environmentResumeLease");
|
|
1583
|
+
}
|
|
1584
|
+
return plugin.definition.onEnvironmentResumeLease(params);
|
|
1585
|
+
}
|
|
1586
|
+
async function handleEnvironmentReleaseLease(params) {
|
|
1587
|
+
if (!plugin.definition.onEnvironmentReleaseLease) {
|
|
1588
|
+
throw methodNotImplemented("environmentReleaseLease");
|
|
1589
|
+
}
|
|
1590
|
+
return plugin.definition.onEnvironmentReleaseLease(params);
|
|
1591
|
+
}
|
|
1592
|
+
async function handleEnvironmentDestroyLease(params) {
|
|
1593
|
+
if (!plugin.definition.onEnvironmentDestroyLease) {
|
|
1594
|
+
throw methodNotImplemented("environmentDestroyLease");
|
|
1595
|
+
}
|
|
1596
|
+
return plugin.definition.onEnvironmentDestroyLease(params);
|
|
1597
|
+
}
|
|
1598
|
+
async function handleEnvironmentRealizeWorkspace(params) {
|
|
1599
|
+
if (!plugin.definition.onEnvironmentRealizeWorkspace) {
|
|
1600
|
+
throw methodNotImplemented("environmentRealizeWorkspace");
|
|
1601
|
+
}
|
|
1602
|
+
return plugin.definition.onEnvironmentRealizeWorkspace(params);
|
|
1603
|
+
}
|
|
1604
|
+
async function handleEnvironmentExecute(params) {
|
|
1605
|
+
if (!plugin.definition.onEnvironmentExecute) {
|
|
1606
|
+
throw methodNotImplemented("environmentExecute");
|
|
1607
|
+
}
|
|
1608
|
+
return plugin.definition.onEnvironmentExecute(params);
|
|
1609
|
+
}
|
|
1610
|
+
async function handleEnvironmentRunnerIngressEndpoint(params) {
|
|
1611
|
+
if (!plugin.definition.onEnvironmentRunnerIngressEndpoint) {
|
|
1612
|
+
throw methodNotImplemented("environmentRunnerIngressEndpoint");
|
|
1613
|
+
}
|
|
1614
|
+
return plugin.definition.onEnvironmentRunnerIngressEndpoint(params);
|
|
1615
|
+
}
|
|
1616
|
+
async function handleEnvironmentSyncIn(params) {
|
|
1617
|
+
if (!plugin.definition.onEnvironmentSyncIn) {
|
|
1618
|
+
throw methodNotImplemented("environmentSyncIn");
|
|
1619
|
+
}
|
|
1620
|
+
return plugin.definition.onEnvironmentSyncIn(params);
|
|
1621
|
+
}
|
|
1622
|
+
async function handleEnvironmentSyncOut(params) {
|
|
1623
|
+
if (!plugin.definition.onEnvironmentSyncOut) {
|
|
1624
|
+
throw methodNotImplemented("environmentSyncOut");
|
|
1625
|
+
}
|
|
1626
|
+
return plugin.definition.onEnvironmentSyncOut(params);
|
|
1627
|
+
}
|
|
1628
|
+
async function handleEnvironmentStartInteractiveSetup(params) {
|
|
1629
|
+
if (!plugin.definition.onEnvironmentStartInteractiveSetup) {
|
|
1630
|
+
throw methodNotImplemented("environmentStartInteractiveSetup");
|
|
1631
|
+
}
|
|
1632
|
+
return plugin.definition.onEnvironmentStartInteractiveSetup(params);
|
|
1633
|
+
}
|
|
1634
|
+
async function handleEnvironmentGetInteractiveSetup(params) {
|
|
1635
|
+
if (!plugin.definition.onEnvironmentGetInteractiveSetup) {
|
|
1636
|
+
throw methodNotImplemented("environmentGetInteractiveSetup");
|
|
1637
|
+
}
|
|
1638
|
+
return plugin.definition.onEnvironmentGetInteractiveSetup(params);
|
|
1639
|
+
}
|
|
1640
|
+
async function handleEnvironmentCaptureTemplate(params) {
|
|
1641
|
+
if (!plugin.definition.onEnvironmentCaptureTemplate) {
|
|
1642
|
+
throw methodNotImplemented("environmentCaptureTemplate");
|
|
1643
|
+
}
|
|
1644
|
+
return plugin.definition.onEnvironmentCaptureTemplate(params);
|
|
1645
|
+
}
|
|
1646
|
+
async function handleEnvironmentCancelInteractiveSetup(params) {
|
|
1647
|
+
if (!plugin.definition.onEnvironmentCancelInteractiveSetup) {
|
|
1648
|
+
throw methodNotImplemented("environmentCancelInteractiveSetup");
|
|
1649
|
+
}
|
|
1650
|
+
return plugin.definition.onEnvironmentCancelInteractiveSetup(params);
|
|
1651
|
+
}
|
|
1652
|
+
async function handleEnvironmentDeleteTemplate(params) {
|
|
1653
|
+
if (!plugin.definition.onEnvironmentDeleteTemplate) {
|
|
1654
|
+
throw methodNotImplemented("environmentDeleteTemplate");
|
|
1655
|
+
}
|
|
1656
|
+
return plugin.definition.onEnvironmentDeleteTemplate(params);
|
|
1657
|
+
}
|
|
1658
|
+
async function handleLoginPtyOpen(params) {
|
|
1659
|
+
if (!plugin.definition.onLoginPtyOpen) {
|
|
1660
|
+
throw methodNotImplemented("loginPtyOpen");
|
|
1661
|
+
}
|
|
1662
|
+
return plugin.definition.onLoginPtyOpen(params);
|
|
1663
|
+
}
|
|
1664
|
+
async function handleLoginPtyInput(params) {
|
|
1665
|
+
if (!plugin.definition.onLoginPtyInput) {
|
|
1666
|
+
throw methodNotImplemented("loginPtyInput");
|
|
1667
|
+
}
|
|
1668
|
+
return plugin.definition.onLoginPtyInput(params);
|
|
1669
|
+
}
|
|
1670
|
+
async function handleLoginPtyStop(params) {
|
|
1671
|
+
if (!plugin.definition.onLoginPtyStop) {
|
|
1672
|
+
throw methodNotImplemented("loginPtyStop");
|
|
1673
|
+
}
|
|
1674
|
+
return plugin.definition.onLoginPtyStop(params);
|
|
1675
|
+
}
|
|
1676
|
+
async function handleLoginPtyClose(params) {
|
|
1677
|
+
if (!plugin.definition.onLoginPtyClose) {
|
|
1678
|
+
throw methodNotImplemented("loginPtyClose");
|
|
1679
|
+
}
|
|
1680
|
+
return plugin.definition.onLoginPtyClose(params);
|
|
1681
|
+
}
|
|
1682
|
+
async function handleDuplexChannelOpen(params) {
|
|
1683
|
+
if (!plugin.definition.onDuplexChannelOpen) {
|
|
1684
|
+
throw methodNotImplemented("duplexChannelOpen");
|
|
1685
|
+
}
|
|
1686
|
+
return plugin.definition.onDuplexChannelOpen(params);
|
|
1687
|
+
}
|
|
1688
|
+
async function handleDuplexChannelWrite(params) {
|
|
1689
|
+
if (!plugin.definition.onDuplexChannelWrite) {
|
|
1690
|
+
throw methodNotImplemented("duplexChannelWrite");
|
|
1691
|
+
}
|
|
1692
|
+
return plugin.definition.onDuplexChannelWrite(params);
|
|
1693
|
+
}
|
|
1694
|
+
async function handleDuplexChannelStop(params) {
|
|
1695
|
+
if (!plugin.definition.onDuplexChannelStop) {
|
|
1696
|
+
throw methodNotImplemented("duplexChannelStop");
|
|
1697
|
+
}
|
|
1698
|
+
return plugin.definition.onDuplexChannelStop(params);
|
|
1699
|
+
}
|
|
1700
|
+
async function handleDuplexChannelClose(params) {
|
|
1701
|
+
if (!plugin.definition.onDuplexChannelClose) {
|
|
1702
|
+
throw methodNotImplemented("duplexChannelClose");
|
|
1703
|
+
}
|
|
1704
|
+
return plugin.definition.onDuplexChannelClose(params);
|
|
1705
|
+
}
|
|
1706
|
+
// -----------------------------------------------------------------------
|
|
1707
|
+
// Event filter helper
|
|
1708
|
+
// -----------------------------------------------------------------------
|
|
1709
|
+
function allowsEvent(filter, event) {
|
|
1710
|
+
const payload = event.payload;
|
|
1711
|
+
if (filter.companyId !== undefined) {
|
|
1712
|
+
const companyId = event.companyId ?? String(payload?.companyId ?? "");
|
|
1713
|
+
if (companyId !== filter.companyId)
|
|
1714
|
+
return false;
|
|
1715
|
+
}
|
|
1716
|
+
if (filter.projectId !== undefined) {
|
|
1717
|
+
const projectId = event.entityType === "project"
|
|
1718
|
+
? event.entityId
|
|
1719
|
+
: String(payload?.projectId ?? "");
|
|
1720
|
+
if (projectId !== filter.projectId)
|
|
1721
|
+
return false;
|
|
1722
|
+
}
|
|
1723
|
+
if (filter.agentId !== undefined) {
|
|
1724
|
+
const agentId = event.entityType === "agent"
|
|
1725
|
+
? event.entityId
|
|
1726
|
+
: String(payload?.agentId ?? "");
|
|
1727
|
+
if (agentId !== filter.agentId)
|
|
1728
|
+
return false;
|
|
1729
|
+
}
|
|
1730
|
+
return true;
|
|
1731
|
+
}
|
|
1732
|
+
// -----------------------------------------------------------------------
|
|
1733
|
+
// Inbound response handling (host → worker, response to our outbound call)
|
|
1734
|
+
// -----------------------------------------------------------------------
|
|
1735
|
+
function handleHostResponse(response) {
|
|
1736
|
+
const id = response.id;
|
|
1737
|
+
if (id === null || id === undefined)
|
|
1738
|
+
return;
|
|
1739
|
+
const pending = pendingRequests.get(id);
|
|
1740
|
+
if (!pending)
|
|
1741
|
+
return;
|
|
1742
|
+
clearTimeout(pending.timer);
|
|
1743
|
+
pendingRequests.delete(id);
|
|
1744
|
+
pending.resolve(response);
|
|
1745
|
+
}
|
|
1746
|
+
// -----------------------------------------------------------------------
|
|
1747
|
+
// Incoming line handler
|
|
1748
|
+
// -----------------------------------------------------------------------
|
|
1749
|
+
function handleLine(line) {
|
|
1750
|
+
if (!line.trim())
|
|
1751
|
+
return;
|
|
1752
|
+
let message;
|
|
1753
|
+
try {
|
|
1754
|
+
message = parseMessage(line);
|
|
1755
|
+
}
|
|
1756
|
+
catch (err) {
|
|
1757
|
+
if (err instanceof JsonRpcParseError) {
|
|
1758
|
+
// Send parse error response
|
|
1759
|
+
sendMessage(createErrorResponse(null, JSONRPC_ERROR_CODES.PARSE_ERROR, `Parse error: ${err.message}`));
|
|
1760
|
+
}
|
|
1761
|
+
return;
|
|
1762
|
+
}
|
|
1763
|
+
if (isJsonRpcResponse(message)) {
|
|
1764
|
+
// This is a response to one of our outbound worker→host calls
|
|
1765
|
+
handleHostResponse(message);
|
|
1766
|
+
}
|
|
1767
|
+
else if (isJsonRpcRequest(message)) {
|
|
1768
|
+
// This is a host→worker RPC call — dispatch it
|
|
1769
|
+
handleHostRequest(message).catch((err) => {
|
|
1770
|
+
// Unhandled error in the async handler — send error response
|
|
1771
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
1772
|
+
const errorCode = err?.code ?? PLUGIN_RPC_ERROR_CODES.WORKER_ERROR;
|
|
1773
|
+
try {
|
|
1774
|
+
sendMessage(createErrorResponse(message.id, typeof errorCode === "number" ? errorCode : PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, errorMessage));
|
|
1775
|
+
}
|
|
1776
|
+
catch {
|
|
1777
|
+
// Cannot send response, stdout may be closed
|
|
1778
|
+
}
|
|
1779
|
+
});
|
|
1780
|
+
}
|
|
1781
|
+
else if (isJsonRpcNotification(message)) {
|
|
1782
|
+
// Dispatch host→worker push notifications
|
|
1783
|
+
const notif = message;
|
|
1784
|
+
const runNotification = (fn) => {
|
|
1785
|
+
if (notif.paperclipInvocation) {
|
|
1786
|
+
return invocationContextStorage.run(notif.paperclipInvocation, fn);
|
|
1787
|
+
}
|
|
1788
|
+
return fn();
|
|
1789
|
+
};
|
|
1790
|
+
if (notif.method === "agents.sessions.event" && notif.params) {
|
|
1791
|
+
const event = notif.params;
|
|
1792
|
+
const cb = sessionEventCallbacks.get(event.sessionId);
|
|
1793
|
+
if (cb)
|
|
1794
|
+
cb(event);
|
|
1795
|
+
}
|
|
1796
|
+
else if (notif.method === "onEvent" && notif.params) {
|
|
1797
|
+
// Plugin event bus notifications — dispatch to registered event handlers
|
|
1798
|
+
Promise.resolve(runNotification(() => handleOnEvent(notif.params))).catch((err) => {
|
|
1799
|
+
notifyHost("log", {
|
|
1800
|
+
level: "error",
|
|
1801
|
+
message: `Failed to handle event notification: ${err instanceof Error ? err.message : String(err)}`,
|
|
1802
|
+
});
|
|
1803
|
+
});
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
// -----------------------------------------------------------------------
|
|
1808
|
+
// Cleanup
|
|
1809
|
+
// -----------------------------------------------------------------------
|
|
1810
|
+
function cleanup() {
|
|
1811
|
+
running = false;
|
|
1812
|
+
// Close readline
|
|
1813
|
+
if (readline) {
|
|
1814
|
+
readline.close();
|
|
1815
|
+
readline = null;
|
|
1816
|
+
}
|
|
1817
|
+
// Reject all pending outbound calls
|
|
1818
|
+
for (const [id, pending] of pendingRequests) {
|
|
1819
|
+
clearTimeout(pending.timer);
|
|
1820
|
+
pending.resolve(createErrorResponse(id, PLUGIN_RPC_ERROR_CODES.WORKER_UNAVAILABLE, "Worker RPC host is shutting down"));
|
|
1821
|
+
}
|
|
1822
|
+
pendingRequests.clear();
|
|
1823
|
+
sessionEventCallbacks.clear();
|
|
1824
|
+
}
|
|
1825
|
+
// -----------------------------------------------------------------------
|
|
1826
|
+
// Bootstrap: wire up stdin readline
|
|
1827
|
+
// -----------------------------------------------------------------------
|
|
1828
|
+
let readline = createInterface({
|
|
1829
|
+
input: stdinStream,
|
|
1830
|
+
crlfDelay: Infinity,
|
|
1831
|
+
});
|
|
1832
|
+
readline.on("line", handleLine);
|
|
1833
|
+
// If stdin closes, we should exit gracefully
|
|
1834
|
+
readline.on("close", () => {
|
|
1835
|
+
if (running) {
|
|
1836
|
+
cleanup();
|
|
1837
|
+
if (!options.stdin && !options.stdout) {
|
|
1838
|
+
process.exit(0);
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
});
|
|
1842
|
+
// Handle uncaught errors in the worker process.
|
|
1843
|
+
// Only install these when using the real process streams (not in tests
|
|
1844
|
+
// where the caller provides custom streams).
|
|
1845
|
+
if (!options.stdin && !options.stdout) {
|
|
1846
|
+
process.on("uncaughtException", (err) => {
|
|
1847
|
+
notifyHost("log", {
|
|
1848
|
+
level: "error",
|
|
1849
|
+
message: `Uncaught exception: ${err.message}`,
|
|
1850
|
+
meta: { stack: err.stack },
|
|
1851
|
+
});
|
|
1852
|
+
// Give the notification a moment to flush, then exit
|
|
1853
|
+
setTimeout(() => process.exit(1), 100);
|
|
1854
|
+
});
|
|
1855
|
+
process.on("unhandledRejection", (reason) => {
|
|
1856
|
+
const message = reason instanceof Error ? reason.message : String(reason);
|
|
1857
|
+
const stack = reason instanceof Error ? reason.stack : undefined;
|
|
1858
|
+
notifyHost("log", {
|
|
1859
|
+
level: "error",
|
|
1860
|
+
message: `Unhandled rejection: ${message}`,
|
|
1861
|
+
meta: { stack },
|
|
1862
|
+
});
|
|
1863
|
+
});
|
|
1864
|
+
}
|
|
1865
|
+
// -----------------------------------------------------------------------
|
|
1866
|
+
// Return the handle
|
|
1867
|
+
// -----------------------------------------------------------------------
|
|
1868
|
+
return {
|
|
1869
|
+
get running() {
|
|
1870
|
+
return running;
|
|
1871
|
+
},
|
|
1872
|
+
stop() {
|
|
1873
|
+
cleanup();
|
|
1874
|
+
},
|
|
1875
|
+
};
|
|
1876
|
+
}
|
|
1877
|
+
//# sourceMappingURL=worker-rpc-host.js.map
|