@open-conduit/sdk 0.0.0-stage → 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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/actions.d.ts +145 -0
  4. package/dist/actions.js +281 -0
  5. package/dist/actiontest.d.ts +80 -0
  6. package/dist/actiontest.js +190 -0
  7. package/dist/artifactstore.d.ts +133 -0
  8. package/dist/artifactstore.js +364 -0
  9. package/dist/backup.d.ts +99 -0
  10. package/dist/backup.js +178 -0
  11. package/dist/containertest.d.ts +71 -0
  12. package/dist/containertest.js +294 -0
  13. package/dist/errors.d.ts +127 -0
  14. package/dist/errors.js +180 -0
  15. package/dist/executor.d.ts +374 -0
  16. package/dist/executor.js +556 -0
  17. package/dist/executortest.d.ts +183 -0
  18. package/dist/executortest.js +534 -0
  19. package/dist/extension.d.ts +855 -0
  20. package/dist/extension.js +1822 -0
  21. package/dist/feed.d.ts +20 -0
  22. package/dist/feed.js +88 -0
  23. package/dist/forward.d.ts +38 -0
  24. package/dist/forward.js +163 -0
  25. package/dist/forwardca.d.ts +21 -0
  26. package/dist/forwardca.js +144 -0
  27. package/dist/hooks.d.ts +108 -0
  28. package/dist/hooks.js +13 -0
  29. package/dist/host.d.ts +295 -0
  30. package/dist/host.js +486 -0
  31. package/dist/index.d.ts +34 -0
  32. package/dist/index.js +31 -0
  33. package/dist/jsonrpc.d.ts +39 -0
  34. package/dist/jsonrpc.js +350 -0
  35. package/dist/probe.d.ts +61 -0
  36. package/dist/probe.js +92 -0
  37. package/dist/providertest.d.ts +59 -0
  38. package/dist/providertest.js +168 -0
  39. package/dist/resources.d.ts +208 -0
  40. package/dist/resources.js +303 -0
  41. package/dist/sandbox.d.ts +84 -0
  42. package/dist/sandbox.js +85 -0
  43. package/dist/schema.d.ts +71 -0
  44. package/dist/schema.js +252 -0
  45. package/dist/setup.d.ts +145 -0
  46. package/dist/setup.js +179 -0
  47. package/dist/setuptest.d.ts +90 -0
  48. package/dist/setuptest.js +319 -0
  49. package/dist/storetest.d.ts +64 -0
  50. package/dist/storetest.js +740 -0
  51. package/dist/telemetry.d.ts +86 -0
  52. package/dist/telemetry.js +46 -0
  53. package/dist/testing.d.ts +756 -0
  54. package/dist/testing.js +2165 -0
  55. package/dist/toolbelt.d.ts +91 -0
  56. package/dist/toolbelt.js +216 -0
  57. package/dist/tunnel.d.ts +62 -0
  58. package/dist/tunnel.js +93 -0
  59. package/dist/wire.d.ts +5359 -0
  60. package/dist/wire.js +2211 -0
  61. package/package.json +29 -4
@@ -0,0 +1,2165 @@
1
+ // An in-memory host for unit-testing an extension, as protocol/sdk/sdktest
2
+ // is for Go. testHost serves an Extension over a pair of in-memory streams,
3
+ // as the daemon would, initializes it, and answers the extension-to-host
4
+ // methods from memory: KV with versions and conflicts, event.accept and
5
+ // ingress.deliver, the state.* reads of seeded scopes, Work and Events,
6
+ // secrets from options, artifacts and wait.progress. A test then calls into
7
+ // the extension (configure, operation, route, samples, reconcile, webhook,
8
+ // trigger, task, check, validate, a secret scheme's serve, store and
9
+ // delete, a credential verifier's verify, a container provider's
10
+ // container_provider.* methods, a resource provider's provider.* methods
11
+ // with the provider.owner_status and site.run they call back, a sandbox
12
+ // provider's plan and adopt, a tunnel provider's tunnel.run with the URLs
13
+ // it publishes, an exporter's telemetry.export, telemetry.metrics,
14
+ // telemetry.sink, a run environment's run.environment checked as the host
15
+ // checks it, and call for any other method) and inspects what it wrote
16
+ // (kv, events, artifacts, progress, captured). The
17
+ // container provider checks (checkContainerProvider, checkContainerPlacer,
18
+ // checkContainerForwarder) hold a provider to the contract the Go
19
+ // conformance suite does, the forward's served under a CA of its own, and
20
+ // checkResourceProvider, checkSandboxProvider and checkTunnelProvider to
21
+ // the contract the host's adapters rely on.
22
+ //
23
+ // It is not the host: causal depth and rate limits, timers, Work control and
24
+ // config.* are not served (they answer unsupported). Nothing here reads a
25
+ // real clock, the network or the operator's config: the clock is a
26
+ // TestClock the test moves, fixed at testStart until it does.
27
+ import { createHash, randomBytes } from "node:crypto";
28
+ import { PassThrough } from "node:stream";
29
+ import { Code, CredentialRefusal, OperationError, ProtocolError, SecretRefusal, } from "./errors.js";
30
+ import { ContainerLabel } from "./extension.js";
31
+ import { checkPublicURL } from "./tunnel.js";
32
+ import { appliedEnv, checkRunFiles } from "./telemetry.js";
33
+ import { candidateOf } from "./setup.js";
34
+ import { TestConfigService, TestSetupSession, } from "./setuptest.js";
35
+ import { testExecutor, } from "./executortest.js";
36
+ import { base64, toBytes } from "./host.js";
37
+ import { Conn, MaxChunkBytes } from "./jsonrpc.js";
38
+ import { matches, t } from "./schema.js";
39
+ import { BackupFilesResult, BackupListResult, BackupReadResult, ConfigureResult, ContainerCreated, ContainerForward, ContainerList, ContainerPlan, ContainerState, EmitCommit, EmitPlan, EventAcceptParams, ExecutorKnownParams, PersistRecoveryParams, OwnerStatusParams, ProviderUnsavedResult, ResourceAcquireParams, ResourceReport, ResourceResult, ResourceSweepReport, RunEnvironmentResult, ConfigCandidateResult, SetupRunResult, SandboxPlan, SiteRunParams, TunnelURLParams, ValidateResult, ResourceLookupParams, IngressDeliverParams, KVCommitParams, KVGetParams, KVListParams, OperationResult, Placement, PushResult, RouteDecision, RouteSample, LaunchParams, SandboxAdoptParams, ContainerAdoptParams, ContainerReattachParams, CredentialVerifyResult, SecretDeleteResult, SecretResolveParams, SecretServeResult, SecretStoreResult, SiteResult, Snapshot, StateParams, WaitPlan, WebhookHandleResult, ProbeRunResult, ViewRenderResult, WorkActResult, WorkActionsResult, WorkAnnotateResult, WorkRequestsResult, ActionListParams, ActionSubmitParams, DependencyFilterResult, EventRenderOwnedParams, EventRenderResult, OperationGateResult, RecurrenceNextResult, RequestListParams, ScopeAuthorizeParams, TargetResolveParams, TargetResolveResult, TimerArmParams, TimerCancelParams, WorkAdmitResult, WorkCancelParams, WorkSettleHoldParams, } from "./wire.js";
40
+ /** The test clock's start (sdktest.Start, conformance.NewClock's start). */
41
+ export const testStart = "2026-10-24T12:00:00.000Z";
42
+ /** The host's clock. It moves only when the test moves it. */
43
+ export class TestClock {
44
+ #ms;
45
+ constructor(start = testStart) {
46
+ this.#ms = new Date(start).getTime();
47
+ }
48
+ /** The clock's time, as an RFC 3339 string. */
49
+ now() {
50
+ return new Date(this.#ms).toISOString();
51
+ }
52
+ /** Moves the clock on by ms milliseconds. */
53
+ advance(ms) {
54
+ this.#ms += ms;
55
+ }
56
+ /** Sets the clock to a time. */
57
+ set(at) {
58
+ this.#ms = new Date(at).getTime();
59
+ }
60
+ }
61
+ /** Reads exactly n bytes from it, or fewer at its end. */
62
+ async function readUpTo(it, held, n) {
63
+ const out = new Uint8Array(n);
64
+ let got = 0;
65
+ while (got < n) {
66
+ if (held.rest.length === 0) {
67
+ const r = await it.next();
68
+ if (r.done)
69
+ break;
70
+ held.rest = r.value;
71
+ continue;
72
+ }
73
+ const take = Math.min(n - got, held.rest.length);
74
+ out.set(held.rest.subarray(0, take), got);
75
+ held.rest = held.rest.subarray(take);
76
+ got += take;
77
+ }
78
+ return out.subarray(0, got);
79
+ }
80
+ /** A KV value's version: a digest of its content, as sdktest.Version. */
81
+ export function kvVersion(value) {
82
+ return createHash("sha256").update(value).digest("hex").slice(0, 32);
83
+ }
84
+ function digest(s) {
85
+ return createHash("sha256").update(s).digest("hex").slice(0, 32);
86
+ }
87
+ function unauthorized(message) {
88
+ return new ProtocolError(Code.Unauthorized, message);
89
+ }
90
+ function invalid(message) {
91
+ return new ProtocolError(Code.Invalid, message);
92
+ }
93
+ /** Decodes a request's params, refusing malformed ones as the host does. */
94
+ function params(schema, raw) {
95
+ const p = raw ?? {};
96
+ if (!matches(schema, p))
97
+ throw invalid("malformed params");
98
+ return p;
99
+ }
100
+ /** Decodes an extension's answer, failing the test's call when it is malformed. */
101
+ function result(schema, method, raw) {
102
+ if (!matches(schema, raw))
103
+ throw new ProtocolError(Code.Invalid, `malformed ${method} result: ${JSON.stringify(raw)}`);
104
+ return raw;
105
+ }
106
+ function bytes(b64) {
107
+ return b64 ? new Uint8Array(Buffer.from(b64, "base64")) : new Uint8Array();
108
+ }
109
+ /**
110
+ * Serves ext on an in-memory host and initializes it. Close it when the
111
+ * test ends (in an after hook), so the served connection ends.
112
+ */
113
+ export async function testHost(ext, o = {}) {
114
+ const h = new TestHost(ext, o);
115
+ await h._initialize();
116
+ return h;
117
+ }
118
+ export class TestHost {
119
+ clock;
120
+ stateDir;
121
+ #ext;
122
+ #conn;
123
+ #toExt;
124
+ #o;
125
+ #scopes = new Set();
126
+ #kv = new Map();
127
+ #events = [];
128
+ #causal = new Map();
129
+ #works;
130
+ #sources = new Map();
131
+ #writers = new Map();
132
+ #artifacts = [];
133
+ #progress = new Map();
134
+ #captured = [];
135
+ #config;
136
+ #setups = new Map();
137
+ #timers = new Map();
138
+ /** The Work the extension's start gate holds, by ID: the hold's reason. */
139
+ #holds = new Map();
140
+ #settled = new Map();
141
+ /** The settlements by key, as the runtime dedupes them. */
142
+ #settleKeys = new Map();
143
+ #cancelled = new Map();
144
+ /** The probe runs in progress through a connection, by grant: what secret.resolve may read under it. */
145
+ #probeGrants = new Map();
146
+ /** The webhook paths the last configure registered. */
147
+ #paths = [];
148
+ #kvVersion;
149
+ #calls = 0;
150
+ /** The runs executor.* calls started, by run ID: where their persist_recovery goes. */
151
+ #runs = new Map();
152
+ #sweeps = new Map();
153
+ /** The reconciles and sweeps in progress, by ID: what provider.owner_status quoting it answers. */
154
+ #reconciles = new Map();
155
+ /** The acquisitions in progress at a site, by call ID: where site.run quoting it runs. */
156
+ #siteCalls = new Map();
157
+ /** The tunnel runs the host holds open, by run ID: where tunnel.url quoting it goes. */
158
+ #tunnelRuns = new Map();
159
+ constructor(ext, o) {
160
+ this.#ext = ext;
161
+ this.#o = o;
162
+ this.clock = o.clock ?? new TestClock();
163
+ this.stateDir = o.stateDir ?? "/sdktest/state";
164
+ this.#kvVersion = o.kvVersion ?? 0;
165
+ this.#config = new TestConfigService(o.config);
166
+ this.#works = [...(o.works ?? [])];
167
+ for (const s of o.scopes ?? [])
168
+ this.#scopes.add(s);
169
+ for (const w of this.#works)
170
+ this.#scopes.add(w.scope_id);
171
+ for (const s of Object.keys(o.secrets ?? {}))
172
+ this.#scopes.add(s);
173
+ for (const k of o.kv ?? [])
174
+ this.#put(k.namespace, k.key, toBytes(k.value));
175
+ for (const e of o.events ?? []) {
176
+ this.#scopes.add(e.scopeId);
177
+ this.#accept(e.scopeId, e.event, "");
178
+ }
179
+ this.#toExt = new PassThrough();
180
+ const fromExt = new PassThrough();
181
+ ext.serve(this.#toExt, fromExt);
182
+ this.#conn = new Conn(fromExt, this.#toExt, (method, raw, signal) => this.#handle(method, raw, signal));
183
+ }
184
+ /** @internal */
185
+ async _initialize() {
186
+ await this.#conn.call("initialize", {
187
+ protocol_versions: [1],
188
+ host: { name: "sdktest", version: "0" },
189
+ state_dir: this.stateDir,
190
+ ...(this.#o.configDir ? { config_dir: this.#o.configDir } : {}),
191
+ ...this.#containerInit(),
192
+ ...this.#executorInit(),
193
+ ...this.#resourceInit(),
194
+ });
195
+ }
196
+ #executorInit() {
197
+ const names = (this.#ext.manifest.provides.executors ?? []).map((x) => x.name);
198
+ if (names.length === 0)
199
+ return {};
200
+ return {
201
+ executor_dirs: Object.fromEntries(names.map((n) => [
202
+ n,
203
+ this.#o.executorDirs?.[n] ?? `${this.stateDir}/executors/${n}`,
204
+ ])),
205
+ };
206
+ }
207
+ #resourceInit() {
208
+ const types = (this.#ext.manifest.provides.resources ?? []).map((r) => r.type);
209
+ if (types.length === 0)
210
+ return {};
211
+ return {
212
+ resource_dirs: Object.fromEntries(types.map((typ) => [
213
+ typ,
214
+ this.#o.resourceDirs?.[typ] ?? `${this.stateDir}/resources/${typ}`,
215
+ ])),
216
+ };
217
+ }
218
+ #containerInit() {
219
+ const o = this.#o;
220
+ if (!this.#ext.manifest.provides.containers?.length)
221
+ return {};
222
+ return {
223
+ ...(o.containerDirs ? { container_dirs: o.containerDirs } : {}),
224
+ container_host: this.containerHost,
225
+ ...(o.containerFormerHosts?.length
226
+ ? { container_former_hosts: o.containerFormerHosts }
227
+ : {}),
228
+ };
229
+ }
230
+ /** The host's container label the extension was given. */
231
+ get containerHost() {
232
+ return this.#o.containerHost ?? "sdktest-host";
233
+ }
234
+ /** Ends the served connection. */
235
+ close() {
236
+ this.#toExt.end();
237
+ }
238
+ /** The host clock's time. */
239
+ now() {
240
+ return this.clock.now();
241
+ }
242
+ // Calls into the extension.
243
+ /** Makes any host-to-extension call, for a surface without a helper. */
244
+ call(method, p) {
245
+ return this.#conn.call(method, p);
246
+ }
247
+ /**
248
+ * Applies a configuration generation. Each entry's scope becomes
249
+ * configured, and the sources the result registers can be delivered to,
250
+ * reconciled and sent webhooks.
251
+ */
252
+ async configure(entries, o = {}) {
253
+ const out = result(ConfigureResult, "configure", await this.#conn.call("configure", {
254
+ generation: `sdktest-${++this.#calls}`,
255
+ entries,
256
+ ...(o.disabled ? { disabled: o.disabled } : {}),
257
+ ...(o.publicUrl ? { public_url: o.publicUrl } : {}),
258
+ ...(o.containers?.length ? { containers: o.containers } : {}),
259
+ kv: {
260
+ stored: this.#kvVersion,
261
+ declared: this.#ext.manifest.kv_version ?? 0,
262
+ },
263
+ }));
264
+ for (const e of entries)
265
+ this.#scopes.add(e.scope_id);
266
+ this.#sources.clear();
267
+ for (const s of out.sources ?? [])
268
+ this.#sources.set(s.name, s);
269
+ this.#paths = out.webhook_paths ?? [];
270
+ this.#kvVersion = out.kv_version;
271
+ return out;
272
+ }
273
+ /** Checks a config object as config check does: throws the extension's refusal. */
274
+ async validate(kind, type, config) {
275
+ await this.#conn.call("validate", { kind, type, config });
276
+ }
277
+ /**
278
+ * Calls a declared operation with input as its data, by the kind the
279
+ * manifest declares. Unset authority fields default: the first
280
+ * configured scope, Work "sdktest-work", execution "sdktest-execution",
281
+ * an expiry an hour from now, every declared operation and family. An
282
+ * emission is accepted in the authority's scope, and its commit's
283
+ * records are written to KV, as the toolbelt would.
284
+ */
285
+ async operation(name, input = {}, authority = {}) {
286
+ const decl = this.#ext.manifest.provides.operations?.find((d) => d.name === name);
287
+ if (decl === undefined)
288
+ throw new ProtocolError(Code.Undeclared, `operation ${name} is not declared`);
289
+ const a = this.#authority(authority);
290
+ const p = {
291
+ operation: name,
292
+ authority: a,
293
+ input: { data: input },
294
+ request_id: `sdktest-${++this.#calls}`,
295
+ };
296
+ if (decl.kind === "wait") {
297
+ const plan = result(WaitPlan, "operation.wait", await this.#conn.call("operation.wait", p));
298
+ return { output: plan.output.data, wait: plan };
299
+ }
300
+ if (decl.kind === "emit")
301
+ return this.#emit(a, result(EmitPlan, "operation.emit", await this.#conn.call("operation.emit", p)));
302
+ const out = result(OperationResult, "operation.call", await this.#conn.call("operation.call", p));
303
+ return { output: out.output.data };
304
+ }
305
+ /** Asks a route handler to match one input; route.config is given as its data. */
306
+ async route(handler, input) {
307
+ const event = "event" in input.event
308
+ ? input.event
309
+ : { event: input.event, sequence: 1, routed: false };
310
+ return result(RouteDecision, "route.match", await this.#conn.call("route.match", {
311
+ handler,
312
+ input: { ...input, event },
313
+ }));
314
+ }
315
+ /** The sample Events a route handler offers for a route of a scope, as of the clock's now. */
316
+ async samples(handler, scope, route) {
317
+ const out = result(t.object({ samples: t.array(RouteSample) }, { open: true }), "route.samples", await this.#conn.call("route.samples", {
318
+ handler,
319
+ scope,
320
+ route,
321
+ now: this.now(),
322
+ }));
323
+ return out.samples;
324
+ }
325
+ /** Reads one page of a registered source. */
326
+ async reconcile(source, scan = {}) {
327
+ const decl = this.#source(source);
328
+ return result(Snapshot, "ingress.reconcile", await this.#conn.call("ingress.reconcile", {
329
+ name: source,
330
+ scan: { ...scan, source: decl.source },
331
+ }));
332
+ }
333
+ /** Reads every page of a registered source, from its first. */
334
+ async reconcileAll(source) {
335
+ const pages = [];
336
+ let scan = {};
337
+ for (;;) {
338
+ const page = await this.reconcile(source, scan);
339
+ pages.push(page);
340
+ if (!page.next_cursor)
341
+ return pages;
342
+ if (pages.length > 10_000)
343
+ throw new Error(`sdktest: ${source} never stops paging`);
344
+ scan = { scan_id: page.scan_id, cursor: page.next_cursor };
345
+ }
346
+ }
347
+ /** Pushes a delivery to a registered source and accepts what it observed, as the host's ingress does. */
348
+ async push(source, delivery) {
349
+ return this.#deliver({
350
+ name: source,
351
+ delivery: {
352
+ id: delivery.id,
353
+ received_at: delivery.receivedAt ?? this.now(),
354
+ ...(delivery.contentType ? { content_type: delivery.contentType } : {}),
355
+ body: base64(toBytes(delivery.body)),
356
+ },
357
+ });
358
+ }
359
+ /**
360
+ * Sends one HTTP request on a webhook path, as the host's listener
361
+ * does. A path no registered source took answers 404 here, as the
362
+ * listener answers it, without reaching the extension.
363
+ */
364
+ async webhook(path, req = {}) {
365
+ if (!this.#paths.some((p) => path === p || path.startsWith(`${p}/`)))
366
+ return { status: 404, headers: {}, body: new Uint8Array() };
367
+ const header = {};
368
+ for (const [k, v] of Object.entries(req.headers ?? {}))
369
+ header[k] = Array.isArray(v) ? v : [v];
370
+ const out = result(WebhookHandleResult, "webhook.handle", await this.#conn.call("webhook.handle", {
371
+ path,
372
+ method: req.method ?? "POST",
373
+ ...(req.query ? { query: req.query } : {}),
374
+ ...(Object.keys(header).length ? { header } : {}),
375
+ ...(req.body === undefined ? {} : { body: base64(toBytes(req.body)) }),
376
+ received_at: req.receivedAt ?? this.now(),
377
+ ...(req.forwardId ? { forward_id: req.forwardId } : {}),
378
+ }));
379
+ return {
380
+ status: out.status,
381
+ headers: out.header ?? {},
382
+ body: bytes(out.body),
383
+ };
384
+ }
385
+ /** Asks a Work kind's trigger which of inputs triggers the next execution. */
386
+ async trigger(kind, inputs) {
387
+ const out = result(t.object({ index: t.integer() }, { open: true }), "work_kind.trigger", await this.#conn.call("work_kind.trigger", { kind, inputs }));
388
+ return out.index;
389
+ }
390
+ /** Runs a background task once. */
391
+ async task(name) {
392
+ await this.#conn.call("task.run", { task: name });
393
+ }
394
+ /** Runs a doctor check, with an empty configuration view unless config is given. */
395
+ async check(name, o = {}) {
396
+ return (await this.#conn.call("check.run", {
397
+ check: name,
398
+ ...(o.deep ? { deep: true } : {}),
399
+ config: o.config ?? {},
400
+ }));
401
+ }
402
+ /**
403
+ * Asks the extension's secret scheme for the value reference names
404
+ * (secret.serve), as the host's resolver does: the value, or the code it
405
+ * refused with. An answer with both, or neither, fails the call.
406
+ */
407
+ async serveSecret(scheme, reference) {
408
+ const out = result(SecretServeResult, "secret.serve", await this.#conn.call("secret.serve", { scheme, reference }));
409
+ if (!out.value === !out.code)
410
+ throw invalid("secret.serve answered both a value and a code, or neither");
411
+ return out;
412
+ }
413
+ /**
414
+ * Asks a writable secret scheme to store value under name for owner
415
+ * (secret.store): the reference that reads it back, or the code it
416
+ * refused with. Unless given, owner is "sdktest-store" and there is no
417
+ * config.
418
+ */
419
+ async storeSecret(scheme, name, value, o = {}) {
420
+ const out = result(SecretStoreResult, "secret.store", await this.#conn.call("secret.store", {
421
+ scheme,
422
+ name,
423
+ value,
424
+ ...(o.config === undefined ? {} : { config: o.config }),
425
+ owner: o.owner ?? "sdktest-store",
426
+ }));
427
+ if (!out.reference === !out.code)
428
+ throw invalid("secret.store answered both a reference and a code, or neither");
429
+ return out;
430
+ }
431
+ /** Asks a writable secret scheme to remove what reference names (secret.delete): empty, or the code it refused with. */
432
+ async deleteSecret(scheme, reference, o = {}) {
433
+ return result(SecretDeleteResult, "secret.delete", await this.#conn.call("secret.delete", {
434
+ scheme,
435
+ reference,
436
+ owner: o.owner ?? "sdktest-store",
437
+ }));
438
+ }
439
+ /**
440
+ * The extension's secret scheme as the host reaches it over the wire
441
+ * (sdktest.Host.SecretProvider): each call is one secret.serve,
442
+ * secret.store or secret.delete, a refused one throwing SecretRefusal
443
+ * with its code.
444
+ */
445
+ secretProvider(scheme) {
446
+ const refuse = (code) => {
447
+ if (code)
448
+ throw new SecretRefusal(code);
449
+ };
450
+ return {
451
+ serve: async (reference) => {
452
+ const out = await this.serveSecret(scheme, reference);
453
+ refuse(out.code);
454
+ return out.value;
455
+ },
456
+ store: async (name, value, o = {}) => {
457
+ const out = await this.storeSecret(scheme, name, value, o);
458
+ refuse(out.code);
459
+ return out.reference;
460
+ },
461
+ delete: async (reference, o = {}) => {
462
+ refuse((await this.deleteSecret(scheme, reference, o)).code);
463
+ },
464
+ };
465
+ }
466
+ /**
467
+ * Asks the extension's credential verifier of type about token
468
+ * (credential.verify) under a trusted issuer's config, as the host does
469
+ * (sdktest.Host.Verify): the answer, or the ProtocolError it refused
470
+ * with. Unless given, the issuer's ID is "sdktest-issuer" and its config
471
+ * empty. The answer must name a subject and a valid expires_at.
472
+ */
473
+ async verify(type, token, o = {}) {
474
+ const out = result(CredentialVerifyResult, "credential.verify", await this.#conn.call("credential.verify", {
475
+ type,
476
+ issuer: o.issuer ?? "sdktest-issuer",
477
+ config: {
478
+ schema: "core.auth.issuer.v1",
479
+ data: o.config ?? {},
480
+ },
481
+ token,
482
+ }));
483
+ if (Number.isNaN(Date.parse(out.expires_at)))
484
+ throw invalid("credential.verify answered without a valid expires_at");
485
+ return out;
486
+ }
487
+ /**
488
+ * The extension's credential verifier of type, under one trusted
489
+ * issuer's config, as the host reaches it over the wire: each verify is
490
+ * one credential.verify, a refusal or failure thrown as
491
+ * CredentialRefusal.
492
+ */
493
+ /**
494
+ * The extension's actions, requests and panels as the host reaches them
495
+ * over the wire (extproc's remoteActions): each call one work.actions,
496
+ * work.act, work.requests or view.render, its answer checked as the host
497
+ * reads it. An invocation's refusal throws the OperationError (or
498
+ * ProtocolError) it crossed as. An extension that serves no requests or
499
+ * no panels shows none, as the host treats it.
500
+ */
501
+ actionProvider() {
502
+ const provides = this.#ext.manifest.provides;
503
+ return {
504
+ actions: async (target) => {
505
+ if (!provides.actions)
506
+ return [];
507
+ const out = result(WorkActionsResult, "work.actions", await this.#conn.call("work.actions", { target }));
508
+ const actions = out.actions ?? [];
509
+ if (!provides.secret_actions && actions.some((a) => a.secret))
510
+ throw new ProtocolError("undeclared_secret_action", "an action asks for a secret without secret_actions");
511
+ return actions;
512
+ },
513
+ invoke: async (c) => {
514
+ if (!provides.actions)
515
+ throw invalid("the extension declares no actions");
516
+ const out = result(WorkActResult, "work.act", await this.#conn.call("work.act", {
517
+ target: c.target,
518
+ action: c.action,
519
+ ...(c.input ? { input: c.input } : {}),
520
+ caller: c.caller,
521
+ }));
522
+ const e = out.event;
523
+ if (e.id ||
524
+ e.source ||
525
+ e.delivery_id ||
526
+ e.causation_id ||
527
+ e.execution_id ||
528
+ e.work_id)
529
+ throw invalid("work.act planned an Event with host-assigned fields");
530
+ if (!(provides.families ?? []).some((f) => f.type === e.type))
531
+ throw new ProtocolError(Code.Undeclared, "family not declared");
532
+ return {
533
+ event: {
534
+ type: e.type,
535
+ ...(e.correlation_key
536
+ ? { correlation_key: e.correlation_key }
537
+ : {}),
538
+ ...(e.data === undefined ? {} : { data: e.data }),
539
+ },
540
+ ...(out.message ? { message: out.message } : {}),
541
+ };
542
+ },
543
+ requests: async (target) => {
544
+ if (!provides.actions)
545
+ return [];
546
+ let raw;
547
+ try {
548
+ raw = await this.#conn.call("work.requests", { target });
549
+ }
550
+ catch (err) {
551
+ if (err instanceof ProtocolError && err.code === Code.MethodNotFound)
552
+ return [];
553
+ throw err;
554
+ }
555
+ const out = result(WorkRequestsResult, "work.requests", raw);
556
+ return (out.requests ?? []).map((r) => {
557
+ const { settled_at, ...rest } = r;
558
+ return {
559
+ ...rest,
560
+ state: r.state,
561
+ ...(settled_at ? { settledAt: new Date(settled_at) } : {}),
562
+ };
563
+ });
564
+ },
565
+ panels: async (target) => {
566
+ if (!provides.panels)
567
+ return [];
568
+ const out = result(ViewRenderResult, "view.render", await this.#conn.call("view.render", { target }));
569
+ return (out.panels ?? []).map((p) => ({
570
+ ...p,
571
+ sections: p.sections.map(({ messages, ...s }) => ({
572
+ ...s,
573
+ ...(messages
574
+ ? {
575
+ messages: messages.map((m) => {
576
+ const { at, ...line } = m;
577
+ return {
578
+ ...line,
579
+ from: m.from,
580
+ ...(at ? { at: new Date(at) } : {}),
581
+ };
582
+ }),
583
+ }
584
+ : {}),
585
+ })),
586
+ }));
587
+ },
588
+ };
589
+ }
590
+ /** Asks for the extension's annotations of work (work.annotate), as the host does. */
591
+ async annotate(work) {
592
+ const out = result(WorkAnnotateResult, "work.annotate", await this.#conn.call("work.annotate", { work }));
593
+ return out.annotations ?? [];
594
+ }
595
+ /**
596
+ * Runs one of the extension's probes (probe.serve) as the host's
597
+ * probe.run does: arguments it doesn't declare, or a required one
598
+ * missing, are refused before the probe sees them. With connection, the
599
+ * run goes through that connection in scopeId, and the probe may read
600
+ * its values (default none) until the run ends.
601
+ */
602
+ async probe(name, args = {}, o = {}) {
603
+ const decl = this.#ext.manifest.provides.probes?.find((p) => p.name === name);
604
+ if (decl === undefined)
605
+ throw new ProtocolError(Code.NotFound, "no such probe");
606
+ for (const a of decl.args ?? [])
607
+ if (a.required && !args[a.name])
608
+ throw invalid(`argument ${a.name} is required`);
609
+ for (const k of Object.keys(args))
610
+ if (!(decl.args ?? []).some((a) => a.name === k))
611
+ throw invalid(`the probe takes no argument ${k}`);
612
+ const grant = o.connection === undefined ? "" : randomBytes(8).toString("hex");
613
+ if (o.connection !== undefined)
614
+ this.#probeGrants.set(grant, {
615
+ scopeId: o.scopeId ?? "",
616
+ connection: o.connection.id,
617
+ values: o.values ?? {},
618
+ });
619
+ try {
620
+ return result(ProbeRunResult, "probe.serve", await this.#conn.call("probe.serve", {
621
+ name,
622
+ ...(Object.keys(args).length ? { args } : {}),
623
+ ...(o.scopeId ? { scope_id: o.scopeId } : {}),
624
+ ...(o.connection ? { connection: o.connection, grant } : {}),
625
+ }));
626
+ }
627
+ finally {
628
+ this.#probeGrants.delete(grant);
629
+ }
630
+ }
631
+ credentialVerifier(type, o = {}) {
632
+ return {
633
+ verify: async (token) => {
634
+ let out;
635
+ try {
636
+ out = await this.verify(type, token, o);
637
+ }
638
+ catch (err) {
639
+ if (err instanceof ProtocolError &&
640
+ (err.code === Code.Unauthorized || err.code === Code.Internal))
641
+ throw new CredentialRefusal(err.code);
642
+ throw err;
643
+ }
644
+ return {
645
+ subject: out.subject,
646
+ groups: out.groups ?? [],
647
+ expiresAt: new Date(out.expires_at),
648
+ };
649
+ },
650
+ };
651
+ }
652
+ /**
653
+ * The extension's container provider of type as the host reaches it over
654
+ * the wire (extproc's remoteContainer): each call one
655
+ * container_provider.* request, its answer checked as the host reads it.
656
+ */
657
+ containerProvider(type) {
658
+ const call = async (schema, method, p) => result(schema, `container_provider.${method}`, await this.#conn.call(`container_provider.${method}`, { type, ...p }));
659
+ const done = t.object({}, { open: true });
660
+ return {
661
+ plan: (owner, policy, needs, launch) => call(ContainerPlan, "plan", {
662
+ owner,
663
+ config: containerPayload(policy.config),
664
+ paths: policy.paths ?? {},
665
+ needs,
666
+ launch,
667
+ ...(policy.placement ? { placement: policy.placement } : {}),
668
+ }),
669
+ create: (plan, labels) => call(ContainerCreated, "create", { plan, labels }),
670
+ signal: async (ref, signal) => {
671
+ await call(done, "signal", { ref, signal });
672
+ },
673
+ stop: async (ref, graceMs) => {
674
+ await call(done, "stop", {
675
+ ref,
676
+ ...(graceMs > 0 ? { grace_millis: Math.floor(graceMs) } : {}),
677
+ });
678
+ },
679
+ inspect: (ref) => call(ContainerState, "inspect", { ref }),
680
+ list: async (owner) => (await call(ContainerList, "list", { owner })).containers.filter((s) => hostLabelled(owner, s)),
681
+ remove: async (ref) => {
682
+ await call(done, "remove", { ref });
683
+ },
684
+ forward: async (config) => (await call(ContainerForward, "forward", {
685
+ config: containerPayload(config),
686
+ })).address ?? "",
687
+ place: (owner, config, prefer) => call(Placement, "place", {
688
+ owner,
689
+ config: containerPayload(config),
690
+ ...(prefer ? { prefer } : {}),
691
+ }),
692
+ siteRun: async (placement, c) => {
693
+ const stdin = c.stdin === undefined ? undefined : toBytes(c.stdin);
694
+ const out = await call(SiteResult, "site_run", {
695
+ placement,
696
+ command: {
697
+ argv: c.argv,
698
+ ...(c.dir ? { dir: c.dir } : {}),
699
+ ...(c.env?.length ? { env: c.env } : {}),
700
+ ...(stdin?.length ? { stdin: base64(stdin) } : {}),
701
+ ...(c.timeoutMs ? { timeout_millis: Math.floor(c.timeoutMs) } : {}),
702
+ },
703
+ });
704
+ return {
705
+ exitCode: out.exit_code,
706
+ stdout: bytes(out.stdout),
707
+ stderr: bytes(out.stderr),
708
+ truncated: out.truncated === true,
709
+ };
710
+ },
711
+ collect: async (ref) => {
712
+ await call(done, "collect", { ref });
713
+ },
714
+ reattach: (ref, at) => call(ContainerCreated, "reattach", {
715
+ ref,
716
+ pin: at.pin,
717
+ paths: at.paths,
718
+ ...(at.tokenFile ? { token_file: at.tokenFile } : {}),
719
+ ...(at.sameHost ? { same_host: true } : {}),
720
+ }),
721
+ };
722
+ }
723
+ /**
724
+ * The extension's resource provider of type as the host reaches it over
725
+ * the wire (extproc's remoteProvider): each call one provider.* or
726
+ * validate request. reconcile and sweep answer the provider's
727
+ * provider.owner_status from status while they run, and an acquisition
728
+ * given a site runs its site.run there, as the host does.
729
+ */
730
+ resourceProvider(type) {
731
+ const decl = this.#ext.manifest.provides.resources?.find((r) => r.type === type);
732
+ const call = async (schema, method, p) => result(schema, method, await this.#conn.call(method, { type, ...p }));
733
+ const passes = async (status, fn) => {
734
+ const id = randomBytes(8).toString("hex");
735
+ this.#reconciles.set(id, status);
736
+ try {
737
+ return await fn(id);
738
+ }
739
+ finally {
740
+ this.#reconciles.delete(id);
741
+ }
742
+ };
743
+ const validate = (kind, config, mode) => call(ValidateResult, "validate", {
744
+ kind,
745
+ config: config ?? {},
746
+ ...(mode ? { mode } : {}),
747
+ });
748
+ return {
749
+ acquire: async (owner, config, r = {}) => {
750
+ let siteCall;
751
+ if (r.site !== undefined && decl?.sites) {
752
+ siteCall = randomBytes(8).toString("hex");
753
+ this.#siteCalls.set(siteCall, { type, site: r.site });
754
+ }
755
+ try {
756
+ const out = await call(ResourceResult, "provider.acquire", {
757
+ owner,
758
+ config: { schema: "core.config.resource.v1", data: config ?? {} },
759
+ ...(r.mode ? { mode: r.mode } : {}),
760
+ params: r.params ?? {},
761
+ ...(r.hostEnv && Object.keys(r.hostEnv).length > 0
762
+ ? { host_env: r.hostEnv }
763
+ : {}),
764
+ ...(r.files?.length ? { files: r.files } : {}),
765
+ ...(siteCall ? { site: { id: r.site, call: siteCall } } : {}),
766
+ });
767
+ return {
768
+ resource: out.resource,
769
+ log: out.log ?? "",
770
+ setupFailed: out.setup_failed === true,
771
+ };
772
+ }
773
+ finally {
774
+ if (siteCall)
775
+ this.#siteCalls.delete(siteCall);
776
+ }
777
+ },
778
+ lookup: async (owner, ref) => (await call(ResourceResult, "provider.lookup", { owner, ref }))
779
+ .resource,
780
+ reconcile: (status) => passes(status, (id) => call(ResourceReport, "provider.reconcile", { reconcile: id })),
781
+ sweep: (status) => passes(status, (id) => call(ResourceSweepReport, "provider.sweep", { reconcile: id })),
782
+ unsaved: async () => (await call(ProviderUnsavedResult, "provider.unsaved", {})).resources ??
783
+ [],
784
+ modeDefault: async (config) => (await validate("resource_mode", config)).mode ?? "",
785
+ sandboxWorkspace: async (config, mode) => {
786
+ await validate("resource_sandbox", config, mode);
787
+ },
788
+ needsSite: async (config) => (await validate("resource_site", config)).site === true,
789
+ };
790
+ }
791
+ /**
792
+ * The extension's sandbox provider of type as the host reaches it over
793
+ * the wire (extproc's remoteSandbox): plan answers the plan with the
794
+ * digest the host pins (sandboxDigest), and adopt is one call.
795
+ */
796
+ sandboxProvider(type) {
797
+ return {
798
+ plan: async (owner, policy, needs, launch) => {
799
+ const plan = result(SandboxPlan, "sandbox_provider.plan", await this.#conn.call("sandbox_provider.plan", {
800
+ type,
801
+ owner,
802
+ config: {
803
+ schema: "core.config.sandbox.v1",
804
+ data: policy.config ?? {},
805
+ },
806
+ paths: policy.paths ?? {},
807
+ needs,
808
+ launch,
809
+ }));
810
+ return { ...plan, digest: sandboxDigest(plan.argv ?? [], plan.data) };
811
+ },
812
+ adopt: async (plan, parent, root) => {
813
+ await this.#conn.call("sandbox_provider.adopt", {
814
+ type,
815
+ plan,
816
+ parent,
817
+ root,
818
+ });
819
+ },
820
+ };
821
+ }
822
+ /**
823
+ * The extension's tunnel provider of type as the host runs it (extproc's
824
+ * remoteTunnel): start holds one tunnel.run open, taking the URLs the
825
+ * run publishes as the host does (refusing one checkPublicURL refuses),
826
+ * until stop cancels it.
827
+ */
828
+ tunnelProvider(type) {
829
+ return {
830
+ start: (addr, config) => {
831
+ const run = randomBytes(8).toString("hex");
832
+ const urls = [];
833
+ const refused = [];
834
+ // next hands out each URL the run publishes once, in order,
835
+ // refused ones included.
836
+ const published = [];
837
+ let read = 0;
838
+ const waiting = [];
839
+ this.#tunnelRuns.set(run, (url, refuse) => {
840
+ (refuse ? refused : urls).push(url);
841
+ published.push({ url, refused: refuse });
842
+ for (const w of waiting.splice(0))
843
+ w();
844
+ });
845
+ const abort = new AbortController();
846
+ const ended = this.#conn
847
+ .call("tunnel.run", {
848
+ type,
849
+ run,
850
+ addr,
851
+ config: { schema: "core.config.tunnel.v2", data: config ?? {} },
852
+ }, abort.signal)
853
+ .then(() => ({
854
+ stopped: abort.signal.aborted,
855
+ }), (err) => ({
856
+ stopped: abort.signal.aborted,
857
+ ...(abort.signal.aborted ? {} : { error: err }),
858
+ }))
859
+ .finally(() => this.#tunnelRuns.delete(run));
860
+ const take = () => {
861
+ const got = published[read++];
862
+ if (got.refused)
863
+ throw new Error(`the host refused the URL ${JSON.stringify(got.url)}: a public URL is an http(s) URL with a host and no credentials`);
864
+ return got.url;
865
+ };
866
+ return {
867
+ urls,
868
+ refused,
869
+ next: async () => {
870
+ if (read < published.length)
871
+ return take();
872
+ const more = await Promise.race([
873
+ new Promise((resolve) => waiting.push(() => resolve(true))),
874
+ ended,
875
+ ]);
876
+ if (more === true && read < published.length)
877
+ return take();
878
+ throw more === true
879
+ ? new Error("the tunnel run published nothing")
880
+ : (more.error ??
881
+ new Error("the tunnel run ended before publishing a URL"));
882
+ },
883
+ ended,
884
+ stop: async () => {
885
+ abort.abort();
886
+ await ended;
887
+ },
888
+ };
889
+ },
890
+ validate: async (config) => {
891
+ await this.#conn.call("validate", { kind: "tunnel", type, config });
892
+ },
893
+ };
894
+ }
895
+ /**
896
+ * The extension's executor of name as the host reaches it over the wire
897
+ * (extproc's remoteExecutor): run, recover and resume each one call,
898
+ * their persist_recovery answered by the persist the call was given
899
+ * (refused without one), the handle's wait one executor.wait, and each
900
+ * control one call, refused without one when the manifest doesn't
901
+ * declare it.
902
+ */
903
+ executor(name) {
904
+ const decl = this.#ext.manifest.provides.executors?.find((x) => x.name === name);
905
+ return testExecutor(name, {
906
+ call: (method, p, signal) => this.#conn.call(method, p, signal),
907
+ open: (run, persist, confine) => {
908
+ const r = { persist, err: undefined, confine };
909
+ this.#runs.set(run, r);
910
+ return { persistErr: () => r.err };
911
+ },
912
+ close: (run) => this.#runs.delete(run),
913
+ sweeps: this.#sweeps,
914
+ decl,
915
+ });
916
+ }
917
+ /**
918
+ * The extension's backup destination of type under one configured
919
+ * target, as the host reaches it over the wire (extproc's
920
+ * remoteBackupDestination). Unless given, the target's name is
921
+ * "sdktest-destination" and its config empty.
922
+ */
923
+ backupDestination(type, o = {}) {
924
+ const target = {
925
+ type,
926
+ name: o.name ?? "sdktest-destination",
927
+ config: {
928
+ schema: "core.config.backup_destination.v1",
929
+ data: o.config ?? {},
930
+ },
931
+ };
932
+ const done = t.object({}, { open: true });
933
+ return {
934
+ put: async (bundle, file, body) => {
935
+ const upload = randomBytes(16).toString("hex");
936
+ const source = body instanceof Uint8Array
937
+ ? (async function* () {
938
+ yield body;
939
+ })()
940
+ : body;
941
+ const it = source[Symbol.asyncIterator]();
942
+ const held = { rest: new Uint8Array() };
943
+ let started = false;
944
+ try {
945
+ for (let offset = 0;;) {
946
+ const want = Math.min(file.size - offset, MaxChunkBytes);
947
+ const chunk = await readUpTo(it, held, want);
948
+ if (chunk.length < want)
949
+ throw new Error(`reading ${file.path}: unexpected end`);
950
+ const final = offset + want === file.size;
951
+ started = true;
952
+ result(done, "backup_destination.write", await this.#conn.call("backup_destination.write", {
953
+ target,
954
+ bundle,
955
+ path: file.path,
956
+ size: file.size,
957
+ upload,
958
+ offset,
959
+ ...(chunk.length > 0 ? { chunk: base64(chunk) } : {}),
960
+ ...(final ? { final: true } : {}),
961
+ }));
962
+ offset += want;
963
+ if (final)
964
+ return;
965
+ }
966
+ }
967
+ catch (err) {
968
+ if (started)
969
+ await this.#conn
970
+ .call("backup_destination.abort", { upload })
971
+ .catch(() => { });
972
+ throw err;
973
+ }
974
+ finally {
975
+ await it.return?.();
976
+ }
977
+ },
978
+ list: async () => result(BackupListResult, "backup_destination.list", await this.#conn.call("backup_destination.list", { target })).bundles ?? [],
979
+ files: async (bundle) => (result(BackupFilesResult, "backup_destination.files", await this.#conn.call("backup_destination.files", {
980
+ target,
981
+ bundle,
982
+ })).files ?? []).map((f) => ({ path: f.path, size: f.size })),
983
+ read: async (bundle, path, offset, length) => {
984
+ const out = result(BackupReadResult, "backup_destination.read", await this.#conn.call("backup_destination.read", {
985
+ target,
986
+ bundle,
987
+ path,
988
+ offset,
989
+ length: Math.min(length, MaxChunkBytes),
990
+ }));
991
+ return { chunk: bytes(out.chunk), eof: out.eof === true };
992
+ },
993
+ };
994
+ }
995
+ /** A run's brokers, as extproc's confine serves them. */
996
+ async #confine(method, raw) {
997
+ const runID = params(t.object({ run_id: t.string() }, { open: true }), raw).run_id;
998
+ const run = this.#runs.get(runID);
999
+ if (run === undefined)
1000
+ throw new ProtocolError(Code.Conflict, "run is not served by this process");
1001
+ const sandbox = method.startsWith("sandbox.");
1002
+ const broker = sandbox ? this.#o.sandbox : this.#o.container;
1003
+ if (!(sandbox ? run.confine.sandbox : run.confine.container) || !broker)
1004
+ throw new ProtocolError(Code.Unsupported, `the binding declares no ${sandbox ? "sandbox" : "container"}`);
1005
+ const plan = (p) => ({
1006
+ argv: p.argv,
1007
+ ...(p.env?.length ? { env: p.env } : {}),
1008
+ ...(p.signals ? { signals: p.signals } : {}),
1009
+ ...(p.summary ? { summary: p.summary } : {}),
1010
+ ...(p.data ? { data: p.data } : {}),
1011
+ ...(p.dir ? { dir: p.dir } : {}),
1012
+ });
1013
+ switch (method) {
1014
+ case "sandbox.plan": {
1015
+ const p = params(LaunchParams, raw);
1016
+ return plan(await broker.plan(p.needs, p.launch, runID));
1017
+ }
1018
+ case "container.launch": {
1019
+ const p = params(LaunchParams, raw);
1020
+ return plan(await broker.launch(p.needs, p.launch, runID));
1021
+ }
1022
+ case "sandbox.adopt":
1023
+ await broker.adopt(params(SandboxAdoptParams, raw).parent, runID);
1024
+ return {};
1025
+ case "container.reattach": {
1026
+ const b = broker;
1027
+ if (b.reattach === undefined)
1028
+ throw new ProtocolError(Code.NotAdoptable, "no reattach");
1029
+ return plan(await b.reattach(params(ContainerReattachParams, raw).run, runID));
1030
+ }
1031
+ default: {
1032
+ const e = await broker.adopt(params(ContainerAdoptParams, raw).alive, runID);
1033
+ return {
1034
+ ...(e.exited ? { exited: true } : {}),
1035
+ ...(e.exitCode ? { exit_code: e.exitCode } : {}),
1036
+ ...(e.interrupted ? { interrupted: true } : {}),
1037
+ };
1038
+ }
1039
+ }
1040
+ }
1041
+ /**
1042
+ * Sends the extension's exporter a batch of lifecycle records
1043
+ * (telemetry.export), as the host's telemetry pipeline does. Only an
1044
+ * extension that declares exporters is sent any.
1045
+ */
1046
+ async exportTelemetry(records) {
1047
+ if (!this.#ext.manifest.provides.exporters)
1048
+ throw new Error("sdk: the extension declares no exporter (exporters)");
1049
+ await this.#conn.call("telemetry.export", { records });
1050
+ }
1051
+ /**
1052
+ * Sends the extension one collection of the host's meter
1053
+ * (telemetry.metrics), as the host does only for an extension with the
1054
+ * telemetry.metrics permission.
1055
+ */
1056
+ async exportMetrics(metrics) {
1057
+ if (!this.#allows("telemetry.metrics"))
1058
+ throw new Error("sdk: the extension lacks the telemetry.metrics permission");
1059
+ await this.#conn.call("telemetry.metrics", { metrics });
1060
+ }
1061
+ /**
1062
+ * Hands the extension one of the host's named telemetry events
1063
+ * (telemetry.sink), as the host hands each to every extension with the
1064
+ * telemetry.sink permission, and returns whether it was sent: one
1065
+ * without the permission gets nothing. at defaults to the clock's now.
1066
+ */
1067
+ async sink(e) {
1068
+ if (!this.#allows("telemetry.sink"))
1069
+ return false;
1070
+ await this.#conn.call("telemetry.sink", {
1071
+ ...(e.scopeId ? { scope_id: e.scopeId } : {}),
1072
+ name: e.name,
1073
+ at: e.at ?? this.clock.now(),
1074
+ ...(e.properties === undefined ? {} : { properties: e.properties }),
1075
+ });
1076
+ return true;
1077
+ }
1078
+ /**
1079
+ * Asks for the extension's environment layer for a run
1080
+ * (run.environment), as the host does: an extension that doesn't
1081
+ * declare run_environment has none; files for a run with no filesDir
1082
+ * are dropped; files checkRunFiles refuses fail the call as they fail
1083
+ * the run (ProtocolError invalid); and env is what the host applies,
1084
+ * without the variables it skips (appliedEnv).
1085
+ */
1086
+ async runEnvironment(r) {
1087
+ if (!this.#ext.manifest.provides.run_environment)
1088
+ return {};
1089
+ const out = result(RunEnvironmentResult, "run.environment", await this.#conn.call("run.environment", {
1090
+ owner: r.owner,
1091
+ ...(r.connection ? { connection: r.connection } : {}),
1092
+ ...(r.binding ? { binding: r.binding } : {}),
1093
+ ...(r.filesDir ? { files_dir: r.filesDir } : {}),
1094
+ }));
1095
+ const files = r.filesDir ? out.files : undefined;
1096
+ const refused = checkRunFiles(files);
1097
+ if (refused !== undefined)
1098
+ throw invalid(refused);
1099
+ const env = appliedEnv(out.env);
1100
+ return {
1101
+ ...(Object.keys(env).length > 0 ? { env } : {}),
1102
+ ...(files !== undefined && Object.keys(files).length > 0
1103
+ ? { files: { ...files } }
1104
+ : {}),
1105
+ };
1106
+ }
1107
+ /**
1108
+ * Asks what a Work proposes (config.candidate), as the host does: an
1109
+ * extension that doesn't declare config_candidate, or lacks the
1110
+ * config.read permission, is never asked and has none (undefined), as is
1111
+ * a Work it proposes nothing on. A candidate whose handle the host
1112
+ * doesn't hold is refused (ProtocolError not_found), as the daemon
1113
+ * refuses to serve it; configText(handle) is the text behind one it
1114
+ * does, as the operator is served it.
1115
+ */
1116
+ async configCandidate(work) {
1117
+ if (!this.#ext.manifest.provides.config_candidate ||
1118
+ !this.#allows("config.read"))
1119
+ return undefined;
1120
+ const c = candidateOf(result(ConfigCandidateResult, "config.candidate", await this.#conn.call("config.candidate", { work })));
1121
+ if (c?.handle && this.#config.text(c.handle) === undefined)
1122
+ throw new ProtocolError(Code.NotFound, "the candidate's handle is not one the host holds");
1123
+ return c;
1124
+ }
1125
+ /** The config text behind a handle the host gave out, unredacted, as the operator is served it; undefined for one it doesn't hold. */
1126
+ configText(handle) {
1127
+ return this.#config.text(handle);
1128
+ }
1129
+ /**
1130
+ * Runs the extension's setup flow of type (setup.run), as `open-conduit
1131
+ * init <type>` does: its setup.* callbacks are answered from o for this
1132
+ * run alone, and any quoting another run ID is refused as conflict.
1133
+ * Returns what the flow answered and what the operator saw. A flow the
1134
+ * manifest doesn't declare is refused without a call.
1135
+ */
1136
+ async setup(type, o = {}) {
1137
+ if (this.#ext.manifest.provides.setup?.type !== type)
1138
+ throw new Error(`sdk: the extension declares no setup ${type}`);
1139
+ const run = `setup-${++this.#calls}`;
1140
+ const session = new TestSetupSession(o);
1141
+ this.#setups.set(run, session);
1142
+ try {
1143
+ const out = result(SetupRunResult, "setup.run", await this.#conn.call("setup.run", {
1144
+ run,
1145
+ type,
1146
+ ...(o.args !== undefined && o.args.length > 0
1147
+ ? { args: o.args }
1148
+ : {}),
1149
+ ...(o.config === undefined
1150
+ ? {}
1151
+ : { config: Buffer.from(o.config).toString("base64") }),
1152
+ cwd: o.cwd ?? "/sdktest/work",
1153
+ state_dir: o.stateDir ?? this.stateDir,
1154
+ ...(o.dryRun ? { dry_run: true } : {}),
1155
+ }));
1156
+ return { result: out, record: session.record };
1157
+ }
1158
+ finally {
1159
+ this.#setups.delete(run);
1160
+ }
1161
+ }
1162
+ // In-transaction and routing hooks, asked as the host asks them.
1163
+ /** The timers the extension has armed, by ID. */
1164
+ timers() {
1165
+ return [...this.#timers.values()].map((x) => ({
1166
+ ...x,
1167
+ timer: { ...x.timer },
1168
+ }));
1169
+ }
1170
+ /**
1171
+ * Fires one of the extension's armed timers, as the host does at its
1172
+ * fire_at (the clock is not moved): it asks the timer's recurrence for
1173
+ * the occurrence and the next timer (recurrence.next), checks both as
1174
+ * the runtime does, accepts the occurrence in the timer's scope and
1175
+ * re-arms the next, or drops the timer when there is none. A refused
1176
+ * answer (ProtocolError invalid, unauthorized or schema) changes
1177
+ * nothing, and the timer stays due, as an aborted firing leaves it.
1178
+ */
1179
+ async fireTimer(id) {
1180
+ const armed = this.#timers.get(id);
1181
+ if (armed === undefined)
1182
+ throw new ProtocolError(Code.NotFound, `no timer ${id} is armed`);
1183
+ const fired = armed.timer;
1184
+ const now = this.now();
1185
+ const out = result(RecurrenceNextResult, "recurrence.next", await this.#conn.call("recurrence.next", {
1186
+ kind: armed.kind,
1187
+ spec: armed.spec,
1188
+ fired,
1189
+ now,
1190
+ }));
1191
+ const occ = out.occurrence;
1192
+ if (occ !== undefined) {
1193
+ // As extproc's adapter, then the runtime's recurrence step.
1194
+ if (!this.#ownFamily(occ.type) ||
1195
+ !inNamespace(this.#ext.manifest.name, occ.source ?? "", "/"))
1196
+ throw unauthorized("occurrence is not the extension's");
1197
+ this.#checkWrite(occ.data);
1198
+ if (!occ.id ||
1199
+ !occ.delivery_id ||
1200
+ occ.source !== fired.event.source ||
1201
+ (occ.causation_id && occ.causation_id !== fired.event.causation_id))
1202
+ throw invalid("an occurrence needs an ID and delivery ID, and keeps the timer's source and causal parent");
1203
+ }
1204
+ const next = out.next;
1205
+ if (next !== undefined) {
1206
+ if (next.id !== fired.id ||
1207
+ !(Date.parse(next.fire_at) > Date.parse(fired.fire_at)) ||
1208
+ !(Date.parse(next.fire_at) > Date.parse(now)) ||
1209
+ next.event.id === fired.event.id ||
1210
+ (next.event.source === fired.event.source &&
1211
+ next.event.delivery_id === fired.event.delivery_id))
1212
+ throw invalid("the next timer keeps the timer's ID, fires later and carries a new event identity");
1213
+ this.#checkTimerEvent(next.event);
1214
+ }
1215
+ const firing = {};
1216
+ if (occ !== undefined)
1217
+ firing.occurrence = this.#accept(armed.scopeId, occ, "").accepted;
1218
+ if (next === undefined)
1219
+ this.#timers.delete(id);
1220
+ else {
1221
+ const rearmed = { ...next, revision: (fired.revision ?? 0) + 1 };
1222
+ this.#timers.set(id, { ...armed, timer: rearmed });
1223
+ firing.next = rearmed;
1224
+ }
1225
+ return firing;
1226
+ }
1227
+ /**
1228
+ * Asks the extension's dependency filter whether event matches filter
1229
+ * (dependency.filter), as core does for an Event on a wait's
1230
+ * dependency. An extension that doesn't declare dependency_filter
1231
+ * matches everything, as core matches without a filter; one that
1232
+ * refuses the call (unreadable or undeclared) does not match.
1233
+ */
1234
+ async dependencyFilter(filter, event) {
1235
+ if (!this.#ext.manifest.provides.dependency_filter)
1236
+ return true;
1237
+ try {
1238
+ return result(DependencyFilterResult, "dependency.filter", await this.#conn.call("dependency.filter", { filter, event })).match;
1239
+ }
1240
+ catch (err) {
1241
+ if (err instanceof ProtocolError &&
1242
+ (err.code === Code.Schema ||
1243
+ err.code === Code.Undeclared ||
1244
+ err.code === Code.NotFound))
1245
+ return false;
1246
+ throw err;
1247
+ }
1248
+ }
1249
+ /**
1250
+ * Asks the extension's operation gate about a call to another
1251
+ * extension's operation (operation.gate), as the toolbelt does:
1252
+ * undefined lets it through, a plan parks the caller. An extension
1253
+ * without the declaration or the operation.gate permission is never
1254
+ * asked, nor about a call outside its scopes. The host fails closed: an
1255
+ * OperationError reaches the caller as it is, and anything else (a
1256
+ * protocol error, an unreadable plan) refuses the call as gate_failed.
1257
+ */
1258
+ async gate(call) {
1259
+ if (!this.#ext.manifest.provides.operation_gate ||
1260
+ !this.#allows("operation.gate"))
1261
+ return undefined;
1262
+ const a = this.#authority(call.authority ?? {});
1263
+ if (!this.#scopes.has(a.scope_id))
1264
+ return undefined;
1265
+ try {
1266
+ const out = result(OperationGateResult, "operation.gate", await this.#conn.call("operation.gate", {
1267
+ operation: call.operation,
1268
+ owner: call.owner,
1269
+ authority: a,
1270
+ input: call.input ?? { data: {} },
1271
+ ...(call.capability ? { capability: call.capability } : {}),
1272
+ ...(call.wants ? { wants: call.wants } : {}),
1273
+ }));
1274
+ if (out.wait !== undefined)
1275
+ this.#checkWrite(out.wait.output);
1276
+ return out.wait;
1277
+ }
1278
+ catch (err) {
1279
+ if (err instanceof OperationError)
1280
+ throw err;
1281
+ throw new OperationError("gate_failed", `${this.#ext.manifest.name} could not decide whether this call may proceed, so it was refused`);
1282
+ }
1283
+ }
1284
+ /**
1285
+ * Asks the extension's start gate about a Work's first attempt
1286
+ * (work.admit), as the runtime does: undefined lets the start through,
1287
+ * a hold holds the Work until host.settleHold settles it (holds()). An
1288
+ * extension without the declaration or the work.start_gate permission
1289
+ * is never asked, nor about Work outside its scopes; what it throws
1290
+ * refuses the start for now.
1291
+ */
1292
+ async admit(call) {
1293
+ if (!this.#ext.manifest.provides.start_gate ||
1294
+ !this.#allows("work.start_gate") ||
1295
+ !this.#scopes.has(call.work.scope_id))
1296
+ return undefined;
1297
+ const out = result(WorkAdmitResult, "work.admit", await this.#conn.call("work.admit", {
1298
+ work: call.work,
1299
+ binding: call.binding ?? "sdktest",
1300
+ event: call.event,
1301
+ }));
1302
+ if (out.hold === undefined)
1303
+ return undefined;
1304
+ const reason = out.hold.reason ?? "";
1305
+ this.#holds.set(call.work.id, reason);
1306
+ if (!this.#works.some((w) => w.id === call.work.id))
1307
+ this.#works.push(call.work);
1308
+ return { reason };
1309
+ }
1310
+ /** The Work the extension's start gate holds now, by ID, with each hold's reason. */
1311
+ holds() {
1312
+ return Object.fromEntries(this.#holds);
1313
+ }
1314
+ /** How each hold the extension settled ended, by Work ID: "admitted" or "cancelled". */
1315
+ settled() {
1316
+ return Object.fromEntries(this.#settled);
1317
+ }
1318
+ /** The Work the extension cancelled (work.cancel), by ID, with each reason. */
1319
+ cancelled() {
1320
+ return Object.fromEntries(this.#cancelled);
1321
+ }
1322
+ /**
1323
+ * Resolves a wait target of kind in a scope through the extension
1324
+ * (target.resolve), as the host does: only a kind it declares, only in
1325
+ * its scopes, and nothing when it answers a type that isn't one of its
1326
+ * families or the call fails.
1327
+ */
1328
+ async resolveTarget(scopeId, kind, name) {
1329
+ if (!(this.#ext.manifest.provides.targets ?? []).includes(kind) ||
1330
+ !this.#scopes.has(scopeId))
1331
+ return undefined;
1332
+ let out;
1333
+ try {
1334
+ out = result(TargetResolveResult, "target.resolve", await this.#conn.call("target.resolve", {
1335
+ scope_id: scopeId,
1336
+ kind,
1337
+ name,
1338
+ }));
1339
+ }
1340
+ catch {
1341
+ return undefined;
1342
+ }
1343
+ const types = out.types ?? [];
1344
+ if (!out.ok || !types.every((x) => this.#ownFamily(x)))
1345
+ return undefined;
1346
+ return { key: out.key, types };
1347
+ }
1348
+ /**
1349
+ * Tells the extension an execution's container segment ended
1350
+ * (segment.ended), and waits for it, though the host doesn't: what it
1351
+ * throws is returned rather than thrown, as the host ignores it. An
1352
+ * extension without segment_end is never told.
1353
+ */
1354
+ async segmentEnded(executionId) {
1355
+ if (!this.#ext.manifest.provides.segment_end)
1356
+ return undefined;
1357
+ try {
1358
+ await this.#conn.call("segment.ended", { execution_id: executionId });
1359
+ return undefined;
1360
+ }
1361
+ catch (err) {
1362
+ return err;
1363
+ }
1364
+ }
1365
+ /**
1366
+ * Renders an Event for an agent's prompt through the extension
1367
+ * (event.render), as the host does: undefined, the host's generic
1368
+ * rendering, for an extension without render, an Event of a family it
1369
+ * doesn't own or a payload it can't read, a failed call, or no answer.
1370
+ */
1371
+ async render(event) {
1372
+ if (!this.#ext.manifest.provides.render || !this.#ownFamily(event.type))
1373
+ return undefined;
1374
+ try {
1375
+ this.#checkWrite(event.data);
1376
+ const out = result(EventRenderResult, "event.render", await this.#conn.call("event.render", { event }));
1377
+ return out.ok ? (out.text ?? "") : undefined;
1378
+ }
1379
+ catch {
1380
+ return undefined;
1381
+ }
1382
+ }
1383
+ #checkTimerEvent(e) {
1384
+ if (!this.#ownFamily(e.type) ||
1385
+ !inNamespace(this.#ext.manifest.name, e.source ?? "", "/"))
1386
+ throw unauthorized("timer event is not the extension's");
1387
+ this.#checkWrite(e.data);
1388
+ if (!e.id || !e.delivery_id)
1389
+ throw invalid("a timer's Event needs an ID and a delivery ID");
1390
+ }
1391
+ #allows(permission) {
1392
+ return this.#ext.manifest.permissions?.includes(permission) ?? false;
1393
+ }
1394
+ // What the extension wrote.
1395
+ /** A KV value, or undefined. */
1396
+ kv(namespace, key) {
1397
+ return this.#kv.get(namespace)?.get(key);
1398
+ }
1399
+ /** A KV value as UTF-8 text, or undefined. */
1400
+ kvText(namespace, key) {
1401
+ const v = this.kv(namespace, key);
1402
+ return v === undefined ? undefined : new TextDecoder().decode(v);
1403
+ }
1404
+ /** Every accepted Event, in order, seeded ones included. */
1405
+ events() {
1406
+ return this.#events.map((e) => e.accepted);
1407
+ }
1408
+ /** The sources the last configure registered. */
1409
+ sources() {
1410
+ return [...this.#sources.values()];
1411
+ }
1412
+ /** Committed artifacts, in order. */
1413
+ artifacts() {
1414
+ return [...this.#artifacts];
1415
+ }
1416
+ /** The progress line wait.progress last set for a Work ("" for none). */
1417
+ progress(workId) {
1418
+ return this.#progress.get(workId) ?? "";
1419
+ }
1420
+ /** The telemetry events the extension captured (telemetry.capture), in order, each at the time the host recorded. */
1421
+ captured() {
1422
+ return this.#captured.map((e) => ({ ...e }));
1423
+ }
1424
+ // Serving the extension's calls.
1425
+ #authority(a) {
1426
+ const scope = a.scope_id ?? [...this.#scopes][0] ?? "";
1427
+ const execution = a.execution_id ?? "sdktest-execution";
1428
+ return {
1429
+ scope_id: scope,
1430
+ work_id: a.work_id ?? "sdktest-work",
1431
+ execution_id: execution,
1432
+ lease: a.lease ?? { execution_id: execution, owner: "sdktest", epoch: 1 },
1433
+ expires_at: a.expires_at ??
1434
+ new Date(new Date(this.now()).getTime() + 3_600_000).toISOString(),
1435
+ operations: a.operations ??
1436
+ (this.#ext.manifest.provides.operations ?? []).map((d) => d.name),
1437
+ event_types: a.event_types ??
1438
+ (this.#ext.manifest.provides.families ?? []).map((f) => f.type),
1439
+ ...(a.trigger_id ? { trigger_id: a.trigger_id } : {}),
1440
+ ...(a.connection ? { connection: a.connection } : {}),
1441
+ ...(a.work_kinds ? { work_kinds: a.work_kinds } : {}),
1442
+ };
1443
+ }
1444
+ async #emit(a, plan) {
1445
+ const e = plan.event;
1446
+ if (!(a.event_types ?? []).includes(e.type) || !this.#ownFamily(e.type))
1447
+ throw new ProtocolError(Code.Undeclared, "family not declared");
1448
+ if (e.id ||
1449
+ e.source ||
1450
+ e.causation_id ||
1451
+ e.work_id ||
1452
+ e.execution_id ||
1453
+ e.received_at)
1454
+ throw unauthorized("the host assigns an emission's identity, source and causation");
1455
+ if (!e.delivery_id)
1456
+ throw invalid("an emission needs a delivery ID");
1457
+ this.#checkWrite(e.data);
1458
+ const event = {
1459
+ ...e,
1460
+ id: `emit/${digest(`${a.execution_id}\x00${e.delivery_id}`)}`,
1461
+ source: `execution/${a.execution_id}`,
1462
+ work_id: a.work_id,
1463
+ execution_id: a.execution_id,
1464
+ };
1465
+ const { accepted, added } = this.#accept(a.scope_id, event, plan.cause || a.trigger_id || "");
1466
+ const info = this.#causal.get(accepted.event.id ?? "");
1467
+ const out = { output: undefined, event: accepted, added };
1468
+ if (!plan.commit_id)
1469
+ return out;
1470
+ const commit = result(EmitCommit, "emit.commit", await this.#conn.call("emit.commit", {
1471
+ commit_id: plan.commit_id,
1472
+ emitted: { event: accepted, added, root: info.root, depth: info.depth },
1473
+ }));
1474
+ for (const r of commit.records ?? [])
1475
+ this.#ownNamespace(r.namespace, r.key);
1476
+ if (added)
1477
+ for (const r of commit.records ?? [])
1478
+ this.#put(r.namespace, r.key, bytes(r.value));
1479
+ out.output = commit.output.data;
1480
+ return out;
1481
+ }
1482
+ async #handle(method, raw, _signal) {
1483
+ switch (method) {
1484
+ case "kv.get": {
1485
+ const p = params(KVGetParams, raw);
1486
+ this.#ownNamespace(p.namespace, p.key);
1487
+ const v = this.kv(p.namespace, p.key);
1488
+ return v === undefined
1489
+ ? { found: false, entry: { key: "", value: null, version: "" } }
1490
+ : {
1491
+ found: true,
1492
+ entry: { key: p.key, value: base64(v), version: kvVersion(v) },
1493
+ };
1494
+ }
1495
+ case "kv.list": {
1496
+ const p = params(KVListParams, raw);
1497
+ this.#ownNamespace(p.namespace, "-");
1498
+ const entries = [...(this.#kv.get(p.namespace) ?? new Map()).entries()]
1499
+ .filter(([k]) => k.startsWith(p.prefix ?? ""))
1500
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
1501
+ .map(([key, v]) => ({
1502
+ key,
1503
+ value: base64(v),
1504
+ version: kvVersion(v),
1505
+ }));
1506
+ return { entries };
1507
+ }
1508
+ case "kv.commit": {
1509
+ const p = params(KVCommitParams, raw);
1510
+ this.#checkBatch(p.checks ?? [], p.puts ?? [], p.deletes ?? []);
1511
+ if ((p.puts?.length ?? 0) + (p.deletes?.length ?? 0) === 0)
1512
+ throw invalid("empty batch");
1513
+ this.#checks(p.checks ?? []);
1514
+ this.#apply(p.puts ?? [], p.deletes ?? []);
1515
+ return {};
1516
+ }
1517
+ case "event.accept":
1518
+ return this.#eventAccept(params(EventAcceptParams, raw));
1519
+ case "ingress.deliver":
1520
+ return this.#deliver(params(IngressDeliverParams, raw));
1521
+ case "secret.resolve": {
1522
+ const p = params(SecretResolveParams, raw);
1523
+ if (p.probe_grant) {
1524
+ // A probe run's grant reads its one connection, until the run ends.
1525
+ const g = this.#probeGrants.get(p.probe_grant);
1526
+ if (g === undefined ||
1527
+ g.scopeId !== p.scope_id ||
1528
+ g.connection !== p.connection)
1529
+ throw unauthorized("no such probe grant");
1530
+ return {
1531
+ values: Object.fromEntries(p.names.filter((n) => n in g.values).map((n) => [n, g.values[n]])),
1532
+ };
1533
+ }
1534
+ if (!this.#scopes.has(p.scope_id))
1535
+ throw unauthorized("scope is not configured for this extension");
1536
+ let values;
1537
+ if (p.connection) {
1538
+ values = this.#o.connectionSecrets?.find((c) => c.scopeId === p.scope_id && c.connection === p.connection)?.values;
1539
+ if (values === undefined)
1540
+ throw unauthorized("connection is not bound to the extension in the scope");
1541
+ }
1542
+ else if (p.binding) {
1543
+ values = this.#o.bindingSecrets?.find((b) => b.scopeId === p.scope_id && b.binding === p.binding)?.values;
1544
+ if (values === undefined)
1545
+ throw unauthorized("binding's executor is not one of the extension's in the scope");
1546
+ }
1547
+ else
1548
+ values = this.#o.secrets?.[p.scope_id] ?? {};
1549
+ return {
1550
+ values: Object.fromEntries(p.names.filter((n) => n in values).map((n) => [n, values[n]])),
1551
+ };
1552
+ }
1553
+ case "state.events":
1554
+ case "state.work_events": {
1555
+ const p = params(StateParams, raw);
1556
+ const limit = p.limit && p.limit > 0 && p.limit <= 1000 ? p.limit : 1000;
1557
+ if (method === "state.work_events" && !p.id)
1558
+ return [];
1559
+ return this.#events
1560
+ .filter((e) => e.accepted.sequence > (p.after ?? 0) &&
1561
+ this.#scopes.has(e.scopeId) &&
1562
+ (method === "state.events" ||
1563
+ e.accepted.event.work_id === p.id ||
1564
+ e.accepted.routed_work_id === p.id))
1565
+ .slice(0, limit)
1566
+ .map((e) => ({ ...e.accepted, scope_id: e.scopeId }));
1567
+ }
1568
+ case "state.works":
1569
+ return this.#queryWorks(params(StateParams, raw));
1570
+ case "state.pending": {
1571
+ const p = params(StateParams, raw);
1572
+ const w = this.#works.find((x) => x.id === p.id && this.#scopes.has(x.scope_id));
1573
+ if (w === undefined)
1574
+ throw new ProtocolError(Code.NotFound, "not found");
1575
+ return this.#o.pending?.[w.id] ?? [];
1576
+ }
1577
+ case "execution.persist_recovery": {
1578
+ const p = params(PersistRecoveryParams, raw);
1579
+ const run = this.#runs.get(p.run_id);
1580
+ if (run === undefined)
1581
+ throw new ProtocolError(Code.NotFound, "unknown run");
1582
+ if (run.persist === undefined)
1583
+ throw new ProtocolError(Code.Unsupported, "no persistence");
1584
+ try {
1585
+ await run.persist(p.state);
1586
+ }
1587
+ catch (err) {
1588
+ run.err = err;
1589
+ throw new ProtocolError(Code.Conflict, "persistence refused");
1590
+ }
1591
+ return {};
1592
+ }
1593
+ case "executor.known": {
1594
+ const p = params(ExecutorKnownParams, raw);
1595
+ const known = this.#sweeps.get(p.sweep);
1596
+ if (known === undefined)
1597
+ throw new ProtocolError(Code.NotFound, "unknown sweep");
1598
+ if (p.executions.length > 256)
1599
+ throw invalid("more than MaxKnownBatch executions");
1600
+ const got = new Set(await known(p.executions));
1601
+ return { known: p.executions.filter((id) => got.has(id)) };
1602
+ }
1603
+ case "resource.acquire":
1604
+ case "resource.lookup": {
1605
+ const run = params(t.object({ run_id: t.string() }, { open: true }), raw);
1606
+ if (!this.#runs.has(run.run_id))
1607
+ throw new ProtocolError(Code.NotFound, "unknown run");
1608
+ const r = this.#o.resources;
1609
+ const got = method === "resource.acquire"
1610
+ ? r?.acquire?.(params(ResourceAcquireParams, raw))
1611
+ : r?.lookup?.(params(ResourceLookupParams, raw).ref);
1612
+ if (got === undefined)
1613
+ throw new ProtocolError(Code.ResourceNotFound, "the binding declares no resource provider");
1614
+ return { resource: got };
1615
+ }
1616
+ case "sandbox.plan":
1617
+ case "sandbox.adopt":
1618
+ case "container.launch":
1619
+ case "container.adopt":
1620
+ case "container.reattach":
1621
+ return this.#confine(method, raw);
1622
+ case "provider.owner_status": {
1623
+ const p = params(OwnerStatusParams, raw);
1624
+ const status = this.#reconciles.get(p.reconcile);
1625
+ if (status === undefined)
1626
+ throw new ProtocolError(Code.Conflict, "no provider.reconcile in progress under that ID");
1627
+ const st = await status(p.owner);
1628
+ return {
1629
+ known: st.known ?? false,
1630
+ execution_done: st.executionDone ?? false,
1631
+ execution_succeeded: st.executionSucceeded ?? false,
1632
+ work_done: st.workDone ?? false,
1633
+ work_succeeded: st.workSucceeded ?? false,
1634
+ ...(st.mounts?.length ? { mounts: st.mounts } : {}),
1635
+ };
1636
+ }
1637
+ case "site.run": {
1638
+ const p = params(SiteRunParams, raw);
1639
+ const declared = this.#ext.manifest.provides.resources?.some((r) => r.type === p.type && r.sites);
1640
+ if (!declared)
1641
+ throw new ProtocolError(Code.Unauthorized, "the extension declares no resource type with sites by that name");
1642
+ let id = p.site ?? "";
1643
+ if (p.call) {
1644
+ const at = this.#siteCalls.get(p.call);
1645
+ if (at === undefined || at.type !== p.type)
1646
+ throw new ProtocolError(Code.Conflict, "no provider.acquire in progress under that call");
1647
+ if (id !== "" && id !== at.site)
1648
+ throw new ProtocolError(Code.Unauthorized, "the call's acquisition is at another site");
1649
+ id = at.site;
1650
+ }
1651
+ else if (id === "")
1652
+ throw new ProtocolError(Code.Invalid, "site.run names no call and no site");
1653
+ const site = this.#o.sites?.[id];
1654
+ if (site === undefined)
1655
+ throw new ProtocolError(Code.SiteUnavailable, "no such site");
1656
+ const c = p.command;
1657
+ const out = await site({
1658
+ argv: [...(c.argv ?? [])],
1659
+ dir: c.dir ?? "",
1660
+ env: [...(c.env ?? [])],
1661
+ stdin: bytes(c.stdin),
1662
+ timeoutMs: c.timeout_millis ?? 0,
1663
+ });
1664
+ const stdout = toBytes(out.stdout ?? "");
1665
+ const stderr = toBytes(out.stderr ?? "");
1666
+ return {
1667
+ exit_code: out.exitCode,
1668
+ ...(stdout.length ? { stdout: base64(stdout) } : {}),
1669
+ ...(stderr.length ? { stderr: base64(stderr) } : {}),
1670
+ };
1671
+ }
1672
+ case "tunnel.url": {
1673
+ const p = params(TunnelURLParams, raw);
1674
+ const publish = this.#tunnelRuns.get(p.run);
1675
+ if (publish === undefined)
1676
+ throw new ProtocolError(Code.Conflict, "no tunnel.run in progress under that ID");
1677
+ // Webhooks are pointed at it: only what a public_url could be.
1678
+ if (p.url !== "" && !checkPublicURL(p.url)) {
1679
+ publish(p.url, true);
1680
+ throw new ProtocolError(Code.Invalid, "a public URL is an http(s) URL with a host and no credentials");
1681
+ }
1682
+ publish(p.url, false);
1683
+ return {};
1684
+ }
1685
+ case "config.base":
1686
+ case "config.edit":
1687
+ case "config.validate":
1688
+ case "config.trace":
1689
+ // As the host's catalogue refuses config.* without the permission.
1690
+ if (!this.#allows("config.read"))
1691
+ throw new ProtocolError(Code.Undeclared, `${method} needs the config.read permission`);
1692
+ return this.#config.serve(method, raw);
1693
+ case "setup.print":
1694
+ case "setup.prompt":
1695
+ case "setup.choose":
1696
+ case "setup.open_url":
1697
+ case "setup.store_secret":
1698
+ case "setup.look_path":
1699
+ case "setup.run_command": {
1700
+ const p = params(t.object({ run: t.string() }, { open: true }), raw);
1701
+ const session = this.#setups.get(p.run);
1702
+ if (session === undefined)
1703
+ throw new ProtocolError(Code.Conflict, "no setup run in progress under that ID");
1704
+ return session.serve(method, raw);
1705
+ }
1706
+ case "telemetry.capture": {
1707
+ // As the host's catalogue and extproc's capture check it.
1708
+ if (!this.#allows("telemetry.capture"))
1709
+ throw new ProtocolError(Code.Undeclared, "telemetry.capture needs the telemetry.capture permission");
1710
+ const p = params(t.object({
1711
+ scope_id: t.optional(t.string()),
1712
+ name: t.string(),
1713
+ at: t.optional(t.string()),
1714
+ properties: t.optional(t.record(t.any())),
1715
+ }, { open: true }), raw);
1716
+ if (p.scope_id && !this.#scopes.has(p.scope_id))
1717
+ throw new ProtocolError(Code.Unauthorized, "scope is not configured for this extension");
1718
+ if (p.name === "" ||
1719
+ Buffer.byteLength(p.name, "utf8") > 128 ||
1720
+ /[\0\n]/.test(p.name))
1721
+ throw invalid("an event name of at most 128 bytes");
1722
+ if (p.properties !== undefined && "scope" in p.properties)
1723
+ throw invalid("the scope goes in scope_id, not the properties");
1724
+ if (Buffer.byteLength(JSON.stringify(p.properties ?? null), "utf8") >
1725
+ 64 << 10)
1726
+ throw invalid("properties of at most 64 KiB");
1727
+ const zero = p.at === undefined || p.at.startsWith("0001-01-01");
1728
+ this.#captured.push({
1729
+ ...(p.scope_id ? { scope_id: p.scope_id } : {}),
1730
+ name: p.name,
1731
+ at: zero ? this.clock.now() : p.at,
1732
+ ...(p.properties === undefined ? {} : { properties: p.properties }),
1733
+ });
1734
+ return {};
1735
+ }
1736
+ case "timer.arm": {
1737
+ const p = params(TimerArmParams, raw);
1738
+ if (!this.#scopes.has(p.scope_id))
1739
+ throw unauthorized("scope is not configured for this extension");
1740
+ if (!(this.#ext.manifest.provides.recurrences ?? []).includes(p.kind))
1741
+ throw new ProtocolError(Code.Undeclared, "recurrence not declared");
1742
+ this.#checkTimerEvent(p.timer.event);
1743
+ if (p.timer.event.causation_id)
1744
+ throw invalid("a recurring timer's Event has no causal parent");
1745
+ if (p.spec === undefined || p.spec === null)
1746
+ throw invalid("a recurrence spec is a JSON value");
1747
+ if (Buffer.byteLength(JSON.stringify(p.spec), "utf8") > 64 << 10)
1748
+ throw invalid("a recurrence spec of at most 64 KiB");
1749
+ const old = this.#timers.get(p.timer.id);
1750
+ if ((old?.timer.revision ?? 0) !== p.expected ||
1751
+ (old === undefined && p.expected !== 0))
1752
+ throw new ProtocolError(Code.Conflict, "timer revision changed");
1753
+ this.#timers.set(p.timer.id, {
1754
+ scopeId: p.scope_id,
1755
+ timer: { ...p.timer, revision: p.expected + 1 },
1756
+ kind: p.kind,
1757
+ spec: p.spec,
1758
+ });
1759
+ return {};
1760
+ }
1761
+ case "timer.cancel": {
1762
+ const p = params(TimerCancelParams, raw);
1763
+ const old = this.#timers.get(p.id);
1764
+ if (old === undefined)
1765
+ return {};
1766
+ if (!this.#ownFamily(old.timer.event.type))
1767
+ throw unauthorized("timer is not the extension's");
1768
+ if ((old.timer.revision ?? 0) !== p.expected)
1769
+ throw new ProtocolError(Code.Conflict, "timer revision changed");
1770
+ this.#timers.delete(p.id);
1771
+ return {};
1772
+ }
1773
+ case "work.cancel": {
1774
+ const p = params(WorkCancelParams, raw);
1775
+ const w = this.#works.find((x) => x.id === p.work_id);
1776
+ if (w === undefined)
1777
+ throw new ProtocolError(Code.NotFound, "no such Work");
1778
+ if (!(this.#ext.manifest.provides.work_kinds ?? []).some((k) => k.kind === w.kind))
1779
+ throw unauthorized("work is not of the extension's kinds");
1780
+ if (p.expected !== 0 && p.expected !== w.revision)
1781
+ throw new ProtocolError(Code.Conflict, "work revision changed");
1782
+ if (!this.#cancelled.has(w.id))
1783
+ this.#cancelled.set(w.id, p.reason);
1784
+ return { event_id: `sdktest-cancel/${w.id}` };
1785
+ }
1786
+ case "work.settle_hold": {
1787
+ if (!this.#allows("work.start_gate"))
1788
+ throw new ProtocolError(Code.Undeclared, "work.settle_hold needs the work.start_gate permission");
1789
+ const p = params(WorkSettleHoldParams, raw);
1790
+ // As Control.SettleGateHold: idempotent per key, a key reused
1791
+ // for another Work a conflict, and a Work the gate doesn't hold
1792
+ // (never held, or settled under another key) not_found, as the
1793
+ // host answers it.
1794
+ const prior = this.#settleKeys.get(p.key);
1795
+ if (prior !== undefined) {
1796
+ if (prior.work !== p.work_id)
1797
+ throw new ProtocolError(Code.Conflict, "the key settled another Work");
1798
+ return { event_id: prior.event };
1799
+ }
1800
+ if (!this.#holds.has(p.work_id))
1801
+ throw new ProtocolError(Code.NotFound, "the Work is not held by this extension's start gate");
1802
+ const id = `sdktest-settle/${p.key}`;
1803
+ this.#settleKeys.set(p.key, { work: p.work_id, event: id });
1804
+ this.#holds.delete(p.work_id);
1805
+ this.#settled.set(p.work_id, p.admit ? "admitted" : "cancelled");
1806
+ if (!p.admit)
1807
+ this.#cancelled.set(p.work_id, p.reason ?? "");
1808
+ return { event_id: id };
1809
+ }
1810
+ case "event.render_owned": {
1811
+ const p = params(EventRenderOwnedParams, raw);
1812
+ const text = this.#o.renderOwned?.(p.event);
1813
+ return text === undefined ? { ok: false } : { text, ok: true };
1814
+ }
1815
+ case "wait.target": {
1816
+ const p = params(TargetResolveParams, raw);
1817
+ if (!this.#scopes.has(p.scope_id))
1818
+ throw unauthorized("scope is not configured for this extension");
1819
+ const fn = this.#o.waitTargets;
1820
+ if (fn === undefined)
1821
+ throw new ProtocolError(Code.Unsupported, "wait.target");
1822
+ const found = fn(p.scope_id, p.kind, p.name);
1823
+ return found === undefined
1824
+ ? { key: { source: "", external_id: "" }, ok: false }
1825
+ : { key: found.key, types: found.types, ok: true };
1826
+ }
1827
+ case "scope.authorize": {
1828
+ const p = params(ScopeAuthorizeParams, raw);
1829
+ if (!this.#scopes.has(p.from))
1830
+ throw unauthorized("scope is not configured for this extension");
1831
+ if (p.kind !== "read" && p.kind !== "file")
1832
+ throw invalid("kind is read or file");
1833
+ const fn = this.#o.authorize;
1834
+ if (fn === undefined)
1835
+ throw new ProtocolError(Code.Unsupported, "scope.authorize");
1836
+ const reason = fn(p.kind, p.from, p.to);
1837
+ return reason === undefined
1838
+ ? { allowed: true }
1839
+ : { allowed: false, reason };
1840
+ }
1841
+ case "action.list":
1842
+ case "request.list":
1843
+ case "action.submit":
1844
+ return this.#act(method, raw);
1845
+ case "wait.progress": {
1846
+ const p = params(t.object({ work_id: t.string(), progress: t.string() }, { open: true }), raw);
1847
+ this.#progress.set(p.work_id, p.progress);
1848
+ return {};
1849
+ }
1850
+ case "artifact.create": {
1851
+ const p = params(t.object({ media_type: t.string() }, { open: true }), raw);
1852
+ const id = `writer-${++this.#calls}`;
1853
+ this.#writers.set(id, { mediaType: p.media_type, chunks: [] });
1854
+ return { writer: id };
1855
+ }
1856
+ case "artifact.write":
1857
+ case "artifact.commit":
1858
+ case "artifact.abort": {
1859
+ const p = params(t.object({ writer: t.string(), chunk: t.optional(t.string()) }, { open: true }), raw);
1860
+ const w = this.#writers.get(p.writer);
1861
+ if (w === undefined)
1862
+ throw new ProtocolError(Code.NotFound, "unknown writer");
1863
+ if (method === "artifact.write") {
1864
+ w.chunks.push(bytes(p.chunk));
1865
+ return {};
1866
+ }
1867
+ this.#writers.delete(p.writer);
1868
+ if (method === "artifact.abort")
1869
+ return {};
1870
+ const data = new Uint8Array(Buffer.concat(w.chunks));
1871
+ const sha256 = createHash("sha256").update(data).digest("hex");
1872
+ const ref = {
1873
+ id: `artifact-${this.#artifacts.length + 1}`,
1874
+ size: data.length,
1875
+ media_type: w.mediaType,
1876
+ sha256,
1877
+ };
1878
+ this.#artifacts.push({ ref, mediaType: w.mediaType, data });
1879
+ return ref;
1880
+ }
1881
+ }
1882
+ throw new ProtocolError(Code.Unsupported, `${method} is not served by the test host`);
1883
+ }
1884
+ #act(method, raw) {
1885
+ // As the host's permission catalogue checks it.
1886
+ if (!this.#allows("action.submit"))
1887
+ throw new ProtocolError(Code.Undeclared, `${method} needs the action.submit permission`);
1888
+ const a = this.#o.actions;
1889
+ if (method === "action.list") {
1890
+ const p = params(ActionListParams, raw);
1891
+ if (!this.#scopes.has(p.scope_id))
1892
+ throw unauthorized("scope is not configured for this extension");
1893
+ if (a?.offers === undefined)
1894
+ throw new ProtocolError(Code.Unsupported, "action.list");
1895
+ return { actions: a.offers(p.scope_id, p.work_id ?? "") };
1896
+ }
1897
+ if (method === "request.list") {
1898
+ const p = params(RequestListParams, raw);
1899
+ if (!this.#scopes.has(p.scope_id))
1900
+ throw unauthorized("scope is not configured for this extension");
1901
+ if (a?.requests === undefined)
1902
+ throw new ProtocolError(Code.Unsupported, "request.list");
1903
+ return { requests: a.requests(p.scope_id, p.work_id) };
1904
+ }
1905
+ const p = params(ActionSubmitParams, raw);
1906
+ if (!this.#scopes.has(p.scope_id))
1907
+ throw unauthorized("scope is not configured for this extension");
1908
+ if (a?.submit === undefined)
1909
+ throw new ProtocolError(Code.Unsupported, "action.submit");
1910
+ const name = this.#ext.manifest.name;
1911
+ const r = a.submit({
1912
+ scopeId: p.scope_id,
1913
+ workId: p.work_id ?? "",
1914
+ provider: p.provider ?? "",
1915
+ action: p.action,
1916
+ input: p.input ?? "",
1917
+ caller: { kind: name, id: p.caller },
1918
+ key: p.key,
1919
+ });
1920
+ const { accepted, added } = this.#accept(p.scope_id, {
1921
+ source: "sdktest.actions",
1922
+ delivery_id: `${name}/${p.key}`,
1923
+ ...r.event,
1924
+ }, "");
1925
+ return {
1926
+ event: accepted,
1927
+ added,
1928
+ ...(r.message ? { message: r.message } : {}),
1929
+ };
1930
+ }
1931
+ /** state.works as the host answers it (StateParams.Query, storage.SelectWorks). */
1932
+ #queryWorks(p) {
1933
+ if (p.scope_id && !this.#scopes.has(p.scope_id))
1934
+ throw unauthorized("scope is not configured for this extension");
1935
+ const order = p.order ?? "";
1936
+ if (!["", "created", "-created", "updated", "-updated"].includes(order) ||
1937
+ (p.limit ?? 0) < 0 ||
1938
+ (p.states ?? []).some((s) => !workStates.includes(s)) ||
1939
+ (p.updated_since !== undefined &&
1940
+ Number.isNaN(Date.parse(p.updated_since))) ||
1941
+ (p.cursor !== undefined && Number.isNaN(Date.parse(p.cursor.at))))
1942
+ throw invalid("malformed works query");
1943
+ const limit = Math.min(p.limit ?? 0, MaxWorksPage);
1944
+ const byUpdated = order.endsWith("updated");
1945
+ const desc = order.startsWith("-");
1946
+ // A Work's position: its time as an instant, then its ID.
1947
+ const key = (at, id) => ({ at: Date.parse(at), id });
1948
+ const keyOf = (w) => key(byUpdated ? w.updated_at : w.created_at, w.id);
1949
+ const cmp = (a, b) => (a.at !== b.at ? a.at - b.at : a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
1950
+ const since = p.updated_since === undefined ? undefined : Date.parse(p.updated_since);
1951
+ const cursor = p.cursor === undefined ? undefined : key(p.cursor.at, p.cursor.id);
1952
+ const selected = this.#works
1953
+ .filter((w) => this.#scopes.has(w.scope_id) &&
1954
+ (!p.states?.length || p.states.includes(w.state)) &&
1955
+ (!p.scope_id || w.scope_id === p.scope_id) &&
1956
+ (!p.kind || w.kind === p.kind) &&
1957
+ (!p.parent_id || w.parent_id === p.parent_id) &&
1958
+ (!p.sources?.length || p.sources.includes(workSource(w))) &&
1959
+ (!p.executor || w.latest_executor === p.executor) &&
1960
+ (since === undefined || Date.parse(w.updated_at) >= since) &&
1961
+ (!p.correlation ||
1962
+ (w.correlation_keys ?? []).some((k) => k.source === p.correlation.source &&
1963
+ k.external_id === p.correlation.external_id)))
1964
+ .sort((a, b) => desc ? cmp(keyOf(b), keyOf(a)) : cmp(keyOf(a), keyOf(b)))
1965
+ .filter((w) => cursor === undefined ||
1966
+ (desc ? cmp(keyOf(w), cursor) < 0 : cmp(keyOf(w), cursor) > 0));
1967
+ return limit > 0 ? selected.slice(0, limit) : selected;
1968
+ }
1969
+ /**
1970
+ * The host's write rule (Manifest.CheckWrite): a payload an extension
1971
+ * writes is absent, or names the current version of one of its own
1972
+ * declared schemas.
1973
+ */
1974
+ #checkWrite(data) {
1975
+ const schema = data?.schema ?? "";
1976
+ const value = data?.data;
1977
+ if (schema === "" && (value === undefined || value === null))
1978
+ return;
1979
+ const name = this.#ext.manifest.name;
1980
+ if (!inNamespace(name, schema, "."))
1981
+ throw new ProtocolError(Code.Schema, `schema "${schema}" is outside namespace "${name}"`);
1982
+ const m = /^(.+)\.v([1-9][0-9]{0,8})$/.exec(schema);
1983
+ const decl = m && this.#ext.manifest.provides.schemas?.find((d) => d.name === m[1]);
1984
+ const current = decl ? decl.versions[decl.versions.length - 1] : undefined;
1985
+ if (!m || current === undefined || Number(m[2]) !== current)
1986
+ throw new ProtocolError(Code.Schema, `schema "${schema}" is not the current version of a schema the extension declares`);
1987
+ }
1988
+ async #deliver(p) {
1989
+ const src = this.#sources.get(p.name);
1990
+ if (src === undefined)
1991
+ throw unauthorized("not a source this extension registered");
1992
+ const pushed = result(PushResult, "ingress.push", await this.#conn.call("ingress.push", {
1993
+ name: p.name,
1994
+ source: src.source,
1995
+ delivery: {
1996
+ ...p.delivery,
1997
+ received_at: p.delivery.received_at || this.now(),
1998
+ },
1999
+ }));
2000
+ const out = { accepted: [], added: [] };
2001
+ const events = [
2002
+ ...(pushed.events ?? []),
2003
+ ...(pushed.observations ?? []).map((o) => o.event),
2004
+ ];
2005
+ // Checked before any is accepted, so a refused delivery accepts nothing.
2006
+ for (const e of events)
2007
+ this.#checkWrite(e.data);
2008
+ for (const e of events) {
2009
+ const r = this.#accept(src.source.scope_id, { ...e, source: e.source || src.source.namespace }, "");
2010
+ out.accepted.push(r.accepted);
2011
+ out.added.push(r.added);
2012
+ }
2013
+ return out;
2014
+ }
2015
+ #eventAccept(p) {
2016
+ if (!p.parent)
2017
+ throw unauthorized("a subprocess never mints a causal root outside ingress");
2018
+ const e = p.event;
2019
+ const name = this.#ext.manifest.name;
2020
+ if (!this.#ownFamily(e.type))
2021
+ throw new ProtocolError(Code.Undeclared, "family not declared");
2022
+ if (!e.source || !inNamespace(name, e.source, "/") || !e.delivery_id)
2023
+ throw unauthorized("source is outside the extension's namespace");
2024
+ if (e.causation_id || e.execution_id)
2025
+ throw unauthorized("causation and execution are assigned by the host");
2026
+ this.#checkWrite(e.data);
2027
+ this.#checkBatch(p.checks ?? [], p.records ?? [], p.deletes ?? []);
2028
+ if (!this.#scopes.has(p.scope_id))
2029
+ throw unauthorized("scope is not configured for this extension");
2030
+ const parent = this.#causal.get(p.parent);
2031
+ if (parent === undefined)
2032
+ throw unauthorized("parent is not an accepted event");
2033
+ if (parent.scopeId !== p.scope_id)
2034
+ throw unauthorized("parent is outside the scope");
2035
+ this.#checks(p.checks ?? []);
2036
+ const r = this.#accept(p.scope_id, { ...e, id: `ext/${digest(`${e.source}\x00${e.delivery_id}`)}` }, p.parent);
2037
+ if (r.added)
2038
+ this.#apply(p.records ?? [], p.deletes ?? []);
2039
+ return { event: r.accepted, added: r.added };
2040
+ }
2041
+ /** Records e in scope, deduplicated by ID or delivery, as a root or derived from parent. */
2042
+ #accept(scopeId, e, parent) {
2043
+ const id = e.id || `ext/${digest(`${e.source ?? ""}\x00${e.delivery_id ?? ""}`)}`;
2044
+ for (const x of this.#events) {
2045
+ const a = x.accepted.event;
2046
+ if (a.id === id ||
2047
+ (e.delivery_id &&
2048
+ a.source === e.source &&
2049
+ a.delivery_id === e.delivery_id))
2050
+ return { accepted: x.accepted, added: false };
2051
+ }
2052
+ const received = e.received_at || this.now();
2053
+ const event = {
2054
+ ...e,
2055
+ id,
2056
+ received_at: received,
2057
+ occurred_at: e.occurred_at || received,
2058
+ ...(parent ? { causation_id: parent } : {}),
2059
+ };
2060
+ const p = parent ? this.#causal.get(parent) : undefined;
2061
+ this.#causal.set(id, {
2062
+ scopeId,
2063
+ root: p?.root ?? id,
2064
+ depth: p === undefined ? 0 : p.depth + 1,
2065
+ });
2066
+ const accepted = {
2067
+ event,
2068
+ sequence: this.#events.length + 1,
2069
+ routed: false,
2070
+ };
2071
+ this.#events.push({ scopeId, accepted });
2072
+ return { accepted, added: true };
2073
+ }
2074
+ #source(name) {
2075
+ const s = this.#sources.get(name);
2076
+ if (s === undefined)
2077
+ throw new Error(`sdktest: no source ${name}; configure registered ${[...this.#sources.keys()].join(", ") || "none"}`);
2078
+ return s;
2079
+ }
2080
+ #ownFamily(type) {
2081
+ return (this.#ext.manifest.provides.families ?? []).some((f) => f.type === type);
2082
+ }
2083
+ #ownNamespace(ns, key) {
2084
+ if (!key || !inNamespace(this.#ext.manifest.name, ns, "."))
2085
+ throw unauthorized(`namespace ${ns} is not owned by ${this.#ext.manifest.name}`);
2086
+ }
2087
+ #checkBatch(checks, puts, deletes) {
2088
+ for (const c of checks) {
2089
+ this.#ownNamespace(c.namespace, c.key);
2090
+ if (Boolean(c.absent) === Boolean(c.version))
2091
+ throw invalid("a check names a version or absence");
2092
+ }
2093
+ for (const p of puts) {
2094
+ this.#ownNamespace(p.namespace, p.key);
2095
+ if (p.value === null)
2096
+ throw invalid("a put needs a value");
2097
+ }
2098
+ for (const d of deletes)
2099
+ this.#ownNamespace(d.namespace, d.key);
2100
+ }
2101
+ #checks(checks) {
2102
+ for (const c of checks) {
2103
+ const v = this.kv(c.namespace, c.key);
2104
+ if (v === undefined ? !c.absent : c.absent || kvVersion(v) !== c.version)
2105
+ throw new ProtocolError(Code.Conflict, "precondition failed");
2106
+ }
2107
+ }
2108
+ #apply(puts, deletes) {
2109
+ for (const p of puts)
2110
+ this.#put(p.namespace, p.key, bytes(p.value));
2111
+ for (const d of deletes)
2112
+ this.#kv.get(d.namespace)?.delete(d.key);
2113
+ }
2114
+ #put(ns, key, value) {
2115
+ let m = this.#kv.get(ns);
2116
+ if (m === undefined)
2117
+ this.#kv.set(ns, (m = new Map()));
2118
+ m.set(key, new Uint8Array(value));
2119
+ }
2120
+ }
2121
+ /** The Work states a query may name (domain.WorkState). */
2122
+ const workStates = [
2123
+ "ready",
2124
+ "running",
2125
+ "waiting",
2126
+ "completed",
2127
+ "failed",
2128
+ "cancelled",
2129
+ ];
2130
+ /** The most Work one state.works page holds (protocol.MaxWorksPage). */
2131
+ const MaxWorksPage = 1000;
2132
+ /** storage.WorkSource: the source of a Work's subject key, or its kind. */
2133
+ function workSource(w) {
2134
+ return ((w.correlation_keys ?? []).find((k) => k.source !== "core.work")?.source ??
2135
+ w.kind);
2136
+ }
2137
+ /** protocol.Namespace (sep ".") and protocol.SourceNamespace (sep "/"). */
2138
+ function inNamespace(name, ns, sep) {
2139
+ return (ns === name || (ns.startsWith(name + sep) && ns.length > name.length + 1));
2140
+ }
2141
+ /** A sandbox plan's digest as the host pins it (extension.SandboxDigest). */
2142
+ export function sandboxDigest(argv, data) {
2143
+ return ("sha256:" +
2144
+ createHash("sha256").update(JSON.stringify({ argv, data })).digest("hex"));
2145
+ }
2146
+ /** A plan's digest as the host pins it (extension.ContainerDigest). */
2147
+ export function containerDigest(image, data) {
2148
+ return ("sha256:" +
2149
+ createHash("sha256").update(JSON.stringify({ image, data })).digest("hex"));
2150
+ }
2151
+ const containerPayload = (config) => ({
2152
+ schema: "core.config.container.v1",
2153
+ data: config ?? {},
2154
+ });
2155
+ function hostLabelled(owner, s) {
2156
+ return (owner.execution_id === "" ||
2157
+ s.ref.labels?.[ContainerLabel.Execution] === owner.execution_id);
2158
+ }
2159
+ export { checkResourceProvider, checkSandboxProvider, checkTunnelProvider, } from "./providertest.js";
2160
+ export { checkContainerForwarder, checkContainerPlacer, checkContainerProvider, } from "./containertest.js";
2161
+ export { ForwardAuthority } from "./forwardca.js";
2162
+ export { checkActions, checkPanels, checkRequests, testScope, testWork, } from "./actiontest.js";
2163
+ export { TestToolbelt, checkExecutor, checkInjectExecutor, checkStateSweeper, checkTurnEnds, testRunRequest, } from "./executortest.js";
2164
+ export { artifactCases, backupCases, checkArtifactStore, checkBackupDestination, testArtifactProvider, } from "./storetest.js";
2165
+ export { Redacted, configHash, redactConfig, } from "./setuptest.js";