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