@open-conduit/sdk 7.0.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/actions.d.ts +145 -0
  2. package/dist/actions.js +281 -0
  3. package/dist/actiontest.d.ts +80 -0
  4. package/dist/actiontest.js +190 -0
  5. package/dist/artifactstore.d.ts +133 -0
  6. package/dist/artifactstore.js +364 -0
  7. package/dist/backup.d.ts +99 -0
  8. package/dist/backup.js +178 -0
  9. package/dist/containertest.d.ts +71 -0
  10. package/dist/containertest.js +294 -0
  11. package/dist/errors.d.ts +28 -0
  12. package/dist/errors.js +37 -0
  13. package/dist/executor.d.ts +374 -0
  14. package/dist/executor.js +556 -0
  15. package/dist/executortest.d.ts +183 -0
  16. package/dist/executortest.js +534 -0
  17. package/dist/extension.d.ts +496 -1
  18. package/dist/extension.js +1152 -4
  19. package/dist/feed.d.ts +20 -0
  20. package/dist/feed.js +88 -0
  21. package/dist/forward.d.ts +38 -0
  22. package/dist/forward.js +163 -0
  23. package/dist/forwardca.d.ts +21 -0
  24. package/dist/forwardca.js +144 -0
  25. package/dist/hooks.d.ts +108 -0
  26. package/dist/hooks.js +13 -0
  27. package/dist/host.d.ts +166 -2
  28. package/dist/host.js +235 -2
  29. package/dist/index.d.ts +27 -3
  30. package/dist/index.js +14 -2
  31. package/dist/probe.d.ts +61 -0
  32. package/dist/probe.js +92 -0
  33. package/dist/providertest.d.ts +59 -0
  34. package/dist/providertest.js +168 -0
  35. package/dist/resources.d.ts +208 -0
  36. package/dist/resources.js +303 -0
  37. package/dist/sandbox.d.ts +84 -0
  38. package/dist/sandbox.js +85 -0
  39. package/dist/setup.d.ts +145 -0
  40. package/dist/setup.js +179 -0
  41. package/dist/setuptest.d.ts +90 -0
  42. package/dist/setuptest.js +319 -0
  43. package/dist/storetest.d.ts +64 -0
  44. package/dist/storetest.js +740 -0
  45. package/dist/telemetry.d.ts +86 -0
  46. package/dist/telemetry.js +46 -0
  47. package/dist/testing.d.ts +591 -2
  48. package/dist/testing.js +1460 -6
  49. package/dist/toolbelt.d.ts +91 -0
  50. package/dist/toolbelt.js +216 -0
  51. package/dist/tunnel.d.ts +62 -0
  52. package/dist/tunnel.js +93 -0
  53. package/dist/wire.d.ts +4060 -348
  54. package/dist/wire.js +1583 -0
  55. package/package.json +1 -1
@@ -0,0 +1,556 @@
1
+ // Executors: executor.* as protocol/sdk serves sdk.Extension.Executors
2
+ // (protocol/sdk/sdk.go). An executor is whatever runs an attempt of a
3
+ // Work: a shell command, a job queue, a person, a model. The host starts
4
+ // an attempt with executor.run, adopts one a restarted process or daemon
5
+ // lost with executor.recover, carries a parked one on with
6
+ // executor.resume, and observes each through executor.wait on the handle
7
+ // the start returned. The attempt saves its continuity state through
8
+ // persistRecovery before it is acknowledged, and recover and resume are
9
+ // given that state back. The controls (interrupt, inject, stop, forget,
10
+ // sweep, live, attach, container_attach, interactive_launch) are served as
11
+ // the spec gives them, and the manifest declares exactly those. A run
12
+ // whose binding names a sandbox or container reaches it through the run's
13
+ // brokers (sandbox.plan and sandbox.adopt, container.launch, adopt and
14
+ // reattach), and the validate kinds executor_mode, executor_playbook,
15
+ // executor_probe and executor_folder are answered by the hooks given.
16
+ import { Code, ConfigError, ProtocolError } from "./errors.js";
17
+ import { matches, t } from "./schema.js";
18
+ import { ContainerAttachParams, ContainerExit, ExecutorKnown, ExecutorRunParams, ExecutorSweepParams, ExecutorTargetParams, ExecutorWaitParams, InteractiveLaunchParams, ResourceResult, SandboxPlan, } from "./wire.js";
19
+ /** The most IDs one known call asks about (extension.MaxKnownBatch). */
20
+ export const MaxKnownBatch = 256;
21
+ /** @internal The handles of the attempts a connection started, and the sweeps it serves. */
22
+ export class ExecutorRuns {
23
+ #handles = new Map();
24
+ #next = 0;
25
+ #id;
26
+ constructor(id) {
27
+ this.#id = id;
28
+ }
29
+ add(h) {
30
+ const id = `${this.#id()}-${++this.#next}`;
31
+ this.#handles.set(id, h);
32
+ return id;
33
+ }
34
+ get(id) {
35
+ return this.#handles.get(id);
36
+ }
37
+ delete(id) {
38
+ this.#handles.delete(id);
39
+ }
40
+ }
41
+ const reserved = ["attempts", "turns", "active_seconds"];
42
+ const unitName = /^[a-z][a-z0-9_.-]{0,31}$/;
43
+ const outcomes = new Set(["completed", "failed", "waiting", "handoff"]);
44
+ /**
45
+ * Why a result is invalid (extension.ValidateResult), or "" when it is
46
+ * valid: a known outcome kind, a retry or permanent only on a failure and
47
+ * never both, consumed inputs named once each, a cost with a currency, and
48
+ * usage units and attribution of the allowed names, none of them a unit
49
+ * the host counts itself.
50
+ */
51
+ export function invalidResult(r) {
52
+ if (!outcomes.has(r?.outcome?.kind))
53
+ return "outcome";
54
+ const failed = r.outcome.kind === "failed";
55
+ if (r.retry !== undefined && !failed)
56
+ return "retry hint on a non-failed outcome";
57
+ if (r.permanent && !failed)
58
+ return "permanent on a non-failed outcome";
59
+ if (r.permanent && r.retry !== undefined)
60
+ return "a permanent failure with a retry hint";
61
+ const seen = new Set();
62
+ for (const id of r.consumedInputs ?? []) {
63
+ if (typeof id !== "string" || id === "" || seen.has(id))
64
+ return "consumed inputs";
65
+ seen.add(id);
66
+ }
67
+ const u = r.usage ?? {};
68
+ for (const n of [u.inputTokens, u.outputTokens, u.cachedTokens])
69
+ if (n !== undefined && !(Number.isInteger(n) && n >= 0))
70
+ return "usage tokens";
71
+ if (u.cost !== undefined &&
72
+ (!Number.isFinite(u.cost) || u.cost < 0 || !u.currency))
73
+ return "cost";
74
+ if (reserved.includes((u.currency ?? "").toLowerCase()))
75
+ return "currency names a unit core counts";
76
+ const units = Object.entries(u.units ?? {});
77
+ if (units.length > 16 ||
78
+ units.some(([k, v]) => !unitName.test(k) ||
79
+ reserved.includes(k) ||
80
+ !Number.isFinite(v) ||
81
+ v < 0))
82
+ return "usage units";
83
+ const attribution = Object.entries(u.attribution ?? {});
84
+ if (attribution.length > 8 ||
85
+ attribution.some(([k, v]) => !unitName.test(k) || typeof v !== "string" || v.length > 256))
86
+ return "usage attribution";
87
+ return "";
88
+ }
89
+ /** The result as executor.wait answers it (protocol.FromResult). */
90
+ export function wireResult(r) {
91
+ const u = r.usage ?? {};
92
+ const usage = {};
93
+ if (u.inputTokens !== undefined)
94
+ usage.input_tokens = u.inputTokens;
95
+ if (u.outputTokens !== undefined)
96
+ usage.output_tokens = u.outputTokens;
97
+ if (u.cachedTokens !== undefined)
98
+ usage.cached_tokens = u.cachedTokens;
99
+ if (u.cost !== undefined)
100
+ usage.cost = u.cost;
101
+ if (u.currency)
102
+ usage.currency = u.currency;
103
+ if (u.units && Object.keys(u.units).length > 0)
104
+ usage.units = { ...u.units };
105
+ if (u.attribution && Object.keys(u.attribution).length > 0)
106
+ usage.attribution = { ...u.attribution };
107
+ const out = {
108
+ outcome: {
109
+ kind: r.outcome.kind,
110
+ ...(r.outcome.summary ? { summary: r.outcome.summary } : {}),
111
+ data: r.outcome.data ?? {},
112
+ },
113
+ usage,
114
+ };
115
+ if (r.artifacts?.length)
116
+ out.artifacts = r.artifacts.map((a) => ({ ...a }));
117
+ if (r.retry !== undefined) {
118
+ out.retry_after = true;
119
+ const at = r.retry.resetAt;
120
+ if (at !== undefined)
121
+ out.retry_reset_at = at instanceof Date ? at.toISOString() : at;
122
+ }
123
+ if (r.permanent)
124
+ out.permanent = true;
125
+ if (r.consumedInputs?.length)
126
+ out.consumed_inputs = [...r.consumedInputs];
127
+ if (r.workspace !== undefined)
128
+ out.workspace = r.workspace;
129
+ return out;
130
+ }
131
+ /** The result a wire Result describes (protocol.Result.Extension). */
132
+ export function fromWireResult(r) {
133
+ const u = r.usage ?? {};
134
+ const usage = {};
135
+ if (u.input_tokens !== undefined)
136
+ usage.inputTokens = u.input_tokens;
137
+ if (u.output_tokens !== undefined)
138
+ usage.outputTokens = u.output_tokens;
139
+ if (u.cached_tokens !== undefined)
140
+ usage.cachedTokens = u.cached_tokens;
141
+ if (u.cost !== undefined)
142
+ usage.cost = u.cost;
143
+ if (u.currency)
144
+ usage.currency = u.currency;
145
+ if (u.units)
146
+ usage.units = { ...u.units };
147
+ if (u.attribution)
148
+ usage.attribution = { ...u.attribution };
149
+ const out = {
150
+ outcome: {
151
+ kind: r.outcome.kind,
152
+ ...(r.outcome.summary ? { summary: r.outcome.summary } : {}),
153
+ ...(r.outcome.data?.schema || r.outcome.data?.data !== undefined
154
+ ? { data: r.outcome.data }
155
+ : {}),
156
+ },
157
+ usage,
158
+ };
159
+ if (r.artifacts?.length)
160
+ out.artifacts = r.artifacts;
161
+ if (r.retry_after)
162
+ out.retry = r.retry_reset_at ? { resetAt: r.retry_reset_at } : {};
163
+ if (r.permanent)
164
+ out.permanent = true;
165
+ if (r.consumed_inputs?.length)
166
+ out.consumedInputs = [...r.consumed_inputs];
167
+ if (r.workspace)
168
+ out.workspace = r.workspace;
169
+ return out;
170
+ }
171
+ function params(schema, raw) {
172
+ const p = raw ?? {};
173
+ if (!matches(schema, p))
174
+ throw new ProtocolError(Code.Invalid, "malformed params");
175
+ return p;
176
+ }
177
+ function resource(out) {
178
+ const r = out.resource;
179
+ return {
180
+ kind: r.kind,
181
+ ref: r.ref,
182
+ dir: r.dir ?? "",
183
+ env: { ...(r.env ?? {}) },
184
+ data: r.data,
185
+ summary: r.summary ?? "",
186
+ ...(r.sandbox ? { sandbox: r.sandbox } : {}),
187
+ site: r.site ?? "",
188
+ files: { ...(r.files ?? {}) },
189
+ log: out.log ?? "",
190
+ setupFailed: out.setup_failed === true,
191
+ };
192
+ }
193
+ /** The run's resource broker over resource.acquire and resource.lookup. */
194
+ function broker(host, run) {
195
+ return {
196
+ acquire: async (r = {}, signal) => resource(await host.call("resource.acquire", {
197
+ run_id: run,
198
+ ...(r.mode ? { mode: r.mode } : {}),
199
+ params: r.params ?? {},
200
+ ...(r.files?.length ? { files: r.files } : {}),
201
+ }, ResourceResult, signal)),
202
+ lookup: async (ref, signal) => resource(await host.call("resource.lookup", { run_id: run, ref }, ResourceResult, signal)),
203
+ };
204
+ }
205
+ function launchPlan(p) {
206
+ return {
207
+ argv: [...(p.argv ?? [])],
208
+ env: [...(p.env ?? [])],
209
+ signals: p.signals ?? "",
210
+ summary: p.summary ?? "",
211
+ ...(p.data ? { data: p.data } : {}),
212
+ dir: p.dir ?? "",
213
+ };
214
+ }
215
+ /** The run's sandbox broker over sandbox.plan and sandbox.adopt. */
216
+ function sandboxBroker(host, run) {
217
+ return {
218
+ plan: async (needs, launch, signal) => launchPlan(await host.call("sandbox.plan", { run_id: run, needs, launch }, SandboxPlan, signal)),
219
+ adopt: async (parent, signal) => {
220
+ await host.call("sandbox.adopt", { run_id: run, parent }, anything, signal);
221
+ },
222
+ };
223
+ }
224
+ /** The run's container broker over container.launch, container.adopt and container.reattach. */
225
+ function containerBroker(host, run) {
226
+ return {
227
+ launch: async (needs, launch, signal) => launchPlan(await host.call("container.launch", { run_id: run, needs, launch }, SandboxPlan, signal)),
228
+ adopt: async (alive, signal) => {
229
+ const out = await host.call("container.adopt", { run_id: run, alive }, ContainerExit, signal);
230
+ return {
231
+ exited: out.exited === true,
232
+ exitCode: out.exit_code ?? 0,
233
+ interrupted: out.interrupted === true,
234
+ };
235
+ },
236
+ reattach: async (r, signal) => launchPlan(await host.call("container.reattach", { run_id: run, run: r }, SandboxPlan, signal)),
237
+ };
238
+ }
239
+ const done = (v) => v ?? {};
240
+ // persist_recovery answers an empty object.
241
+ const anything = t.any();
242
+ /** The handler of one declared executor, refusing a spec whose capabilities its handlers don't back. */
243
+ export function executorHandler(name, spec, validateConfig) {
244
+ const c = spec.capabilities;
245
+ if (!["none", "cli", "mcp", "sdk"].includes(c?.toolbelt))
246
+ throw new Error(`sdk: executor ${name} toolbelt must be none, cli, mcp or sdk`);
247
+ for (const cap of ["interrupt", "inject", "resume"])
248
+ if (c[cap] && spec[cap] === undefined)
249
+ throw new Error(`sdk: executor ${name} declares ${cap} but has no ${cap} handler`);
250
+ if (spec.launchNames?.length && spec.interactiveLaunch === undefined)
251
+ throw new Error(`sdk: executor ${name} launch names need an interactiveLaunch handler`);
252
+ const launchNames = spec.launchNames ?? [];
253
+ launchNames.forEach((n, i) => {
254
+ // As the manifest rules check it: an identifier, given once, and not
255
+ // the executor's own name.
256
+ if (!/^[a-z][a-z0-9_-]{0,62}$/.test(n))
257
+ throw new Error(`sdk: executor ${name} launch name ${n} is not a name`);
258
+ if (n === name || launchNames.indexOf(n) !== i)
259
+ throw new Error(`sdk: executor ${name} launch name ${n} repeats a name`);
260
+ });
261
+ const schema = spec.config;
262
+ const decode = (p) => {
263
+ const data = p.data ?? {};
264
+ // A stored binding passed validate; one that no longer matches (a
265
+ // package upgrade changed the schema) runs nothing.
266
+ if (schema !== undefined && !matches(schema, data))
267
+ throw new ProtocolError(Code.Invalid, "the binding's config doesn't match the executor's");
268
+ return data;
269
+ };
270
+ const decl = {
271
+ name,
272
+ capabilities: {
273
+ ...(c.interrupt ? { interrupt: true } : {}),
274
+ ...(c.inject ? { inject: true } : {}),
275
+ ...(c.resume ? { resume: true } : {}),
276
+ ...(c.workspace ? { workspace: true } : {}),
277
+ toolbelt: c.toolbelt,
278
+ ...(c.sandbox ? { sandbox: true } : {}),
279
+ ...(c.container ? { container: true } : {}),
280
+ ...(c.noProcess ? { no_process: true } : {}),
281
+ },
282
+ };
283
+ const controls = {
284
+ ...(spec.stop ? { stop: true } : {}),
285
+ ...(spec.forget ? { forget: true } : {}),
286
+ ...(spec.sweep ? { sweep: true } : {}),
287
+ ...(spec.attach ? { attach: true } : {}),
288
+ ...(spec.containerAttach ? { container_attach: true } : {}),
289
+ ...(spec.live ? { live: true } : {}),
290
+ ...(spec.interactiveLaunch ? { interactive_launch: true } : {}),
291
+ };
292
+ if (Object.keys(controls).length > 0)
293
+ decl.controls = controls;
294
+ if (spec.resourceMode)
295
+ decl.resource_mode = true;
296
+ if (spec.playbook)
297
+ decl.playbook = true;
298
+ if (spec.versionProbe)
299
+ decl.version_probe = true;
300
+ if (spec.folderConfig)
301
+ decl.folder_config = true;
302
+ if (spec.pool)
303
+ decl.pool = spec.pool;
304
+ if (launchNames.length)
305
+ decl.launch_names = [...launchNames];
306
+ if (spec.fields?.length)
307
+ decl.fields = spec.fields;
308
+ const start = async (method, raw, ctx, runs) => {
309
+ const p = params(ExecutorRunParams, raw);
310
+ const req = p.request;
311
+ const run = p.run_id;
312
+ const r = {
313
+ work: req.work,
314
+ execution: req.execution,
315
+ trigger: req.trigger,
316
+ inputs: [...(req.inputs ?? [])],
317
+ config: decode(req.context.config),
318
+ context: req.context,
319
+ // Not the request's signal: an attempt may save newer state after
320
+ // run returned, or re-acknowledge it under a new lease.
321
+ persistRecovery: async (state) => {
322
+ await ctx.host.call("execution.persist_recovery", { run_id: run, state }, anything);
323
+ },
324
+ ...(req.context.resources ? { resources: broker(ctx.host, run) } : {}),
325
+ ...(req.context.sandbox && c.sandbox
326
+ ? { sandbox: sandboxBroker(ctx.host, run) }
327
+ : {}),
328
+ ...(req.context.container && c.container
329
+ ? { container: containerBroker(ctx.host, run) }
330
+ : {}),
331
+ };
332
+ let h;
333
+ if (method === "executor.run")
334
+ h = await spec.run(r, ctx);
335
+ else if (method === "executor.recover") {
336
+ if (p.state === undefined)
337
+ throw new ProtocolError(Code.Invalid, "missing state");
338
+ h = await spec.recover(r, p.state, ctx);
339
+ }
340
+ else {
341
+ if (spec.resume === undefined || !c.resume || p.state === undefined)
342
+ throw new ProtocolError(Code.Unsupported, "resume");
343
+ h = await spec.resume(r, p.state, ctx);
344
+ }
345
+ if (typeof h?.wait !== "function")
346
+ throw new ProtocolError(Code.Invalid, "no handle");
347
+ return { handle: runs.add(h) };
348
+ };
349
+ // The config a hook reads: the schema's when it matches, else nothing
350
+ // (the host's validate refuses such a config anyway).
351
+ const readable = (config) => {
352
+ const data = config ?? {};
353
+ if (schema !== undefined && !matches(schema, data))
354
+ return undefined;
355
+ return data;
356
+ };
357
+ const answer = (p) => {
358
+ switch (p.kind) {
359
+ case "executor_mode": {
360
+ const config = readable(p.config);
361
+ const mode = config === undefined ? "" : (spec.resourceMode?.(config) ?? "");
362
+ return mode ? { mode } : {};
363
+ }
364
+ case "executor_playbook": {
365
+ const config = readable(p.config);
366
+ const playbook = config === undefined ? "" : (spec.playbook?.(config) ?? "");
367
+ return playbook ? { playbook } : {};
368
+ }
369
+ case "executor_probe": {
370
+ const config = readable(p.config);
371
+ const probe = config === undefined ? undefined : spec.versionProbe?.(config);
372
+ if (!probe?.argv.length)
373
+ return {};
374
+ return {
375
+ probe: {
376
+ argv: [...probe.argv],
377
+ ...(probe.env?.length ? { env: [...probe.env] } : {}),
378
+ },
379
+ };
380
+ }
381
+ case "executor_folder": {
382
+ const config = p.config ?? {};
383
+ if (spec.folderConfig === undefined)
384
+ return { config };
385
+ const bad = new ProtocolError(Code.Invalid, "invalid executor config");
386
+ if (typeof config !== "object" ||
387
+ config === null ||
388
+ Array.isArray(config))
389
+ throw bad;
390
+ let out;
391
+ try {
392
+ out = spec.folderConfig(structuredClone(config), p.folder ?? "", p.resource === true);
393
+ }
394
+ catch {
395
+ throw bad;
396
+ }
397
+ if (typeof out !== "object" || out === null || Array.isArray(out))
398
+ throw bad;
399
+ return { config: out };
400
+ }
401
+ }
402
+ return {};
403
+ };
404
+ return {
405
+ decl,
406
+ answer,
407
+ validate: async (config) => {
408
+ if (schema === undefined) {
409
+ try {
410
+ await spec.validate?.((config ?? {}));
411
+ }
412
+ catch (err) {
413
+ if (err instanceof ConfigError)
414
+ throw err;
415
+ throw new ProtocolError(Code.Invalid, "invalid executor config");
416
+ }
417
+ return;
418
+ }
419
+ await validateConfig(schema, config, spec.validate);
420
+ },
421
+ serve: async (method, raw, ctx, runs) => {
422
+ switch (method) {
423
+ case "executor.run":
424
+ case "executor.recover":
425
+ case "executor.resume":
426
+ return start(method, raw, ctx, runs);
427
+ case "executor.wait": {
428
+ const p = params(ExecutorWaitParams, raw);
429
+ const h = runs.get(p.handle);
430
+ if (h === undefined)
431
+ throw new ProtocolError(Code.NotFound, "unknown handle");
432
+ const result = await h.wait(ctx.signal);
433
+ const invalid = invalidResult(result);
434
+ if (invalid !== "")
435
+ throw new ProtocolError(Code.Invalid, `result: ${invalid}`);
436
+ // Kept until it answers, so a wait the host cancelled can be made again.
437
+ runs.delete(p.handle);
438
+ return wireResult(result);
439
+ }
440
+ case "executor.container_attach": {
441
+ const p = params(ContainerAttachParams, raw);
442
+ if (spec.containerAttach === undefined)
443
+ throw new ProtocolError(Code.Unsupported, method);
444
+ const a = await spec.containerAttach({
445
+ work: p.work,
446
+ config: decode(p.config),
447
+ secrets: { ...(p.secrets ?? {}) },
448
+ home: p.home,
449
+ }, ctx);
450
+ const out = {
451
+ needs: { ...a.needs },
452
+ launch: { ...a.launch, argv: [...(a.launch.argv ?? [])] },
453
+ };
454
+ return out;
455
+ }
456
+ case "executor.interactive_launch": {
457
+ const p = params(InteractiveLaunchParams, raw);
458
+ if (spec.interactiveLaunch === undefined)
459
+ throw new ProtocolError(Code.Unsupported, method);
460
+ const l = await spec.interactiveLaunch({
461
+ playbook: p.playbook,
462
+ name: p.name,
463
+ summary: p.summary ?? "",
464
+ allow: [...(p.allow ?? [])],
465
+ dir: p.dir ?? "",
466
+ filesDir: p.files_dir,
467
+ program: p.program ?? "",
468
+ }, ctx);
469
+ const out = {
470
+ argv: [...l.argv],
471
+ ...(l.dir ? { dir: l.dir } : {}),
472
+ ...(l.setEnv && Object.keys(l.setEnv).length > 0
473
+ ? { set_env: { ...l.setEnv } }
474
+ : {}),
475
+ };
476
+ return out;
477
+ }
478
+ case "executor.sweep": {
479
+ const p = params(ExecutorSweepParams, raw);
480
+ if (spec.sweep === undefined)
481
+ throw new ProtocolError(Code.Unsupported, method);
482
+ const known = async (ids) => {
483
+ const out = new Set();
484
+ for (let i = 0; i < ids.length; i += MaxKnownBatch) {
485
+ const batch = ids.slice(i, i + MaxKnownBatch);
486
+ const got = await ctx.host.call("executor.known", { sweep: p.sweep, executions: batch }, ExecutorKnown, ctx.signal);
487
+ for (const id of got.known ?? [])
488
+ if (batch.includes(id))
489
+ out.add(id);
490
+ }
491
+ return out;
492
+ };
493
+ const rep = await spec.sweep(known, ctx);
494
+ const out = {};
495
+ if (rep.removed?.length)
496
+ out.removed = [...rep.removed];
497
+ if (rep.kept?.length)
498
+ out.kept = rep.kept.map((k) => ({
499
+ ...(k.executionId ? { execution_id: k.executionId } : {}),
500
+ ...(k.ref ? { ref: k.ref } : {}),
501
+ kept: k.kept,
502
+ }));
503
+ return out;
504
+ }
505
+ }
506
+ const p = params(ExecutorTargetParams, raw);
507
+ const id = p.execution_id ?? "";
508
+ const unsupported = new ProtocolError(Code.Unsupported, method);
509
+ switch (method) {
510
+ case "executor.interrupt":
511
+ if (!spec.interrupt || !c.interrupt)
512
+ throw unsupported;
513
+ return done(await spec.interrupt(id, ctx));
514
+ case "executor.inject":
515
+ if (!spec.inject || !c.inject || p.event === undefined)
516
+ throw unsupported;
517
+ return done(await spec.inject(id, p.event, ctx));
518
+ case "executor.stop":
519
+ if (!spec.stop)
520
+ throw unsupported;
521
+ return done(await spec.stop(id, p.epoch ?? 0, ctx));
522
+ case "executor.forget":
523
+ if (!spec.forget)
524
+ throw unsupported;
525
+ return done(await spec.forget(id, ctx));
526
+ case "executor.attach": {
527
+ if (!spec.attach)
528
+ throw unsupported;
529
+ const a = await spec.attach(p.work_id ?? "", ctx);
530
+ return { argv: [...a.argv], ...(a.dir ? { dir: a.dir } : {}) };
531
+ }
532
+ case "executor.live": {
533
+ if (!spec.live)
534
+ throw unsupported;
535
+ const outs = await spec.live(id, p.tail ?? 0, ctx);
536
+ const res = { outputs: [] };
537
+ for (const o of outs) {
538
+ const bytes = typeof o.content === "string"
539
+ ? new TextEncoder().encode(o.content)
540
+ : o.content;
541
+ res.outputs.push({
542
+ name: o.name,
543
+ media_type: o.mediaType,
544
+ size: o.size,
545
+ ...(bytes.length > 0
546
+ ? { content: Buffer.from(bytes).toString("base64") }
547
+ : {}),
548
+ });
549
+ }
550
+ return res;
551
+ }
552
+ }
553
+ throw new ProtocolError(Code.MethodNotFound, `no such method ${method}`);
554
+ },
555
+ };
556
+ }