@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,1822 @@
1
+ // Declaring each surface once, and serving it.
2
+ //
3
+ // extension() starts an Extension whose manifest is derived from what is
4
+ // registered on it, as the Go SDK's sdk.New does: operation, check, task,
5
+ // entryType and family each register a handler and the declaration that
6
+ // enables it, so the two cannot disagree. main() answers the packaging
7
+ // subcommands (package-manifest, package-certification) and otherwise
8
+ // serves protocol version 1 on stdin and stdout until stdin closes.
9
+ import { randomBytes } from "node:crypto";
10
+ import { actionsHandler, pageDecl, } from "./actions.js";
11
+ import { probeHandler } from "./probe.js";
12
+ import { resourceHandler, site, } from "./resources.js";
13
+ import { sandboxHandler, } from "./sandbox.js";
14
+ import { candidateResult, setupHost, setupResult, } from "./setup.js";
15
+ import {} from "./telemetry.js";
16
+ import { tunnelHandler, } from "./tunnel.js";
17
+ import { BackupUploads, backupHandler, } from "./backup.js";
18
+ import { Writable } from "node:stream";
19
+ import { Code, ConfigError, CredentialRefusal, OperationError, ProtocolError, SecretRefusal, } from "./errors.js";
20
+ import { Host, base64, toBytes } from "./host.js";
21
+ import { ExecutorRuns, executorHandler, } from "./executor.js";
22
+ import { Conn, laneOf } from "./jsonrpc.js";
23
+ import { check, diagnose, isRecord, matches, t, } from "./schema.js";
24
+ import { BackupAbortParams, BackupFilesParams, BackupListParams, BackupReadParams, BackupWriteParams, CheckRunParams, ConfigureParams, ContainerProviderCreateParams, ContainerProviderForwardParams, ContainerProviderListParams, ContainerProviderPlaceParams, ContainerProviderPlanParams, ContainerProviderReattachParams, ContainerProviderRefParams, ContainerProviderSiteRunParams, CredentialVerifyParams, EmitCommitParams, IngressPushParams, IngressReconcileParams, InitializeParams, OperationParams, RouteMatchParams, RouteSamplesParams, RunEnvironmentParams, SetupRunParams, ConfigCandidateParams, SecretDeleteParams, SecretServeParams, SecretStoreParams, TaskRunParams, TelemetryEvent, TelemetryExportParams, TelemetryMetricsParams, ValidateParams, ViewRenderParams, WebhookHandleParams, WorkActParams, WorkActionsParams, WorkAnnotateParams, WorkKindTriggerParams, WorkRequestsParams, ProbeRunParams, DependencyFilterParams, EventRenderParams, OperationGateParams, RecurrenceNextParams, SegmentEndedParams, TargetResolveParams, WorkAdmitParams, } from "./wire.js";
25
+ /**
26
+ * The labels the host gives a container it asks a provider to create
27
+ * (extension.ContainerLabel*): list a container by them, and never act on
28
+ * one that doesn't carry the host's.
29
+ */
30
+ export const ContainerLabel = {
31
+ /** The host's container label (ContainerContext.hostLabel). */
32
+ Host: "dev.open-conduit.host",
33
+ Execution: "dev.open-conduit.execution",
34
+ Work: "dev.open-conduit.work",
35
+ Segment: "dev.open-conduit.segment",
36
+ Digest: "dev.open-conduit.digest",
37
+ };
38
+ /** The protocol versions this SDK speaks. */
39
+ export const ProtocolVersions = [1];
40
+ /** Decodes config through schema, reporting what it refuses at each field. */
41
+ async function validateConfig(schema, config, extra) {
42
+ const c = config ?? {};
43
+ if (!matches(schema, c)) {
44
+ const diagnostics = diagnose(schema, c);
45
+ if (diagnostics.length > 0)
46
+ throw new ConfigError(diagnostics);
47
+ throw new ProtocolError(Code.Invalid, "invalid extension config");
48
+ }
49
+ try {
50
+ await extra?.(c);
51
+ }
52
+ catch (err) {
53
+ if (err instanceof ConfigError)
54
+ throw err;
55
+ throw new ProtocolError(Code.Invalid, "invalid extension config");
56
+ }
57
+ }
58
+ /** Starts an extension named name whose manifest its registrations fill in. */
59
+ export function extension(name, o) {
60
+ return new Extension(name, o);
61
+ }
62
+ export class Extension {
63
+ manifest;
64
+ #operations = new Map();
65
+ #checks = new Map();
66
+ #tasks = new Map();
67
+ #entryTypes = new Map();
68
+ #routes = new Map();
69
+ #triggers = new Map();
70
+ #secrets = new Map();
71
+ #verifiers = new Map();
72
+ #containers = new Map();
73
+ #resources = new Map();
74
+ #sandboxes = new Map();
75
+ #tunnels = new Map();
76
+ #backups = new Map();
77
+ #executors = new Map();
78
+ #probes = new Map();
79
+ #actions;
80
+ #annotate;
81
+ #exporter;
82
+ #metrics;
83
+ #sink;
84
+ #runEnvironment;
85
+ #configCandidate;
86
+ #setup;
87
+ #recurrences = new Map();
88
+ #targets = new Map();
89
+ #filter;
90
+ #gate;
91
+ #startGate;
92
+ #segmentEnd;
93
+ #render;
94
+ #migrate;
95
+ #certification;
96
+ constructor(name, o) {
97
+ // In the Go manifest's field order, so the written file reads the same.
98
+ this.manifest = {
99
+ protocol: [...ProtocolVersions],
100
+ name,
101
+ version: o.version,
102
+ ...(o.title === undefined ? {} : { title: o.title }),
103
+ ...(o.summary === undefined ? {} : { summary: o.summary }),
104
+ command: o.command ?? [`${name}-extension`],
105
+ ...(o.kvVersion ? { kv_version: o.kvVersion } : {}),
106
+ ...(o.permissions?.length ? { permissions: [...o.permissions] } : {}),
107
+ provides: o.playbooks ? { playbooks: o.playbooks } : {},
108
+ };
109
+ }
110
+ /** Registers a request/response toolbelt operation and declares it. */
111
+ operation(name, spec) {
112
+ const output = spec.output ?? `${name}.v1`;
113
+ return this.#operation(name, "handler", spec, async (input, ctx) => ({
114
+ schema: output,
115
+ data: (await spec.handler(input, ctx)) ?? null,
116
+ }), spec.serves === undefined ? {} : { serves: spec.serves });
117
+ }
118
+ /**
119
+ * Registers an operation that suspends the calling Work until an Event
120
+ * (or a time) comes, and declares it with kind wait: "wait until this
121
+ * ticket is resolved".
122
+ */
123
+ wait(name, spec) {
124
+ const output = spec.output ?? `${name}.v1`;
125
+ return this.#operation(name, "wait", spec, async (input, ctx) => {
126
+ const plan = await spec.handler(input, ctx);
127
+ return {
128
+ wait: plan.wait,
129
+ ...(plan.dependencies?.length
130
+ ? { dependencies: plan.dependencies }
131
+ : {}),
132
+ output: { schema: output, data: plan.output ?? null },
133
+ };
134
+ });
135
+ }
136
+ /**
137
+ * Registers an operation that emits one Event of a family the extension
138
+ * declares, and declares it with kind emit (and commit, when spec.commit).
139
+ */
140
+ emit(name, spec) {
141
+ const output = spec.output ?? `${name}.v1`;
142
+ return this.#operation(name, "emit", spec, async (input, ctx) => {
143
+ const plan = await spec.handler(input, ctx);
144
+ if (plan.commit !== undefined && !spec.commit)
145
+ throw new Error(`sdk: operation ${name} returned a commit but is not declared with commit: true`);
146
+ return {
147
+ plan: {
148
+ event: plan.event,
149
+ ...(plan.cause ? { cause: plan.cause } : {}),
150
+ ...(plan.once ? { once: plan.once } : {}),
151
+ },
152
+ commit: plan.commit === undefined
153
+ ? undefined
154
+ : (emitted) => {
155
+ const c = plan.commit(emitted);
156
+ return {
157
+ ...(c.records?.length
158
+ ? {
159
+ records: c.records.map((r) => ({
160
+ namespace: r.namespace,
161
+ key: r.key,
162
+ value: base64(toBytes(r.value)),
163
+ })),
164
+ }
165
+ : {}),
166
+ output: { schema: output, data: c.output ?? null },
167
+ };
168
+ },
169
+ };
170
+ }, spec.commit ? { commit: true } : {});
171
+ }
172
+ #operation(name, kind, spec, run, extra = {}) {
173
+ if (this.#operations.has(name))
174
+ throw new Error(`sdk: operation ${name} is registered twice`);
175
+ const input = spec.input;
176
+ this.#operations.set(name, {
177
+ kind,
178
+ run: async (data, ctx) => {
179
+ // Refused before the handler runs, so it only ever sees what its type says.
180
+ if (!matches(input, data))
181
+ throw new OperationError("bad_request", `${name}: ${check(input, data)}`);
182
+ return run(data, ctx);
183
+ },
184
+ });
185
+ // In the Go declaration's field order, so the written manifest reads the same.
186
+ const decl = {
187
+ name,
188
+ kind,
189
+ ...(extra.commit ? { commit: true } : {}),
190
+ ...(spec.summary === undefined ? {} : { summary: spec.summary }),
191
+ ...(spec.guidance === undefined ? {} : { guidance: spec.guidance }),
192
+ input: json(input),
193
+ ...(spec.wants === undefined ? {} : { wants: spec.wants }),
194
+ ...(extra.serves === undefined ? {} : { serves: extra.serves }),
195
+ };
196
+ (this.manifest.provides.operations ??= []).push(decl);
197
+ return this;
198
+ }
199
+ /** Declares a scope entry type: an "extensions" entry in a scope's config. */
200
+ entryType(type, spec) {
201
+ return this.#entryType(type, spec.config, spec.validate, async (entries, ctx) => {
202
+ await spec.configure?.(entries, ctx);
203
+ return [];
204
+ });
205
+ }
206
+ /**
207
+ * Declares a scope entry type whose entries own event sources, with the
208
+ * families they observe. Each configuration generation, sources names
209
+ * the sources the entries register; the host then reconciles each every
210
+ * intervalSeconds through reconcile, pushes deliveries to it through
211
+ * push, and sends requests on its webhook path (/<source name>) to
212
+ * webhook.
213
+ */
214
+ ingressType(type, spec) {
215
+ const name = this.manifest.name;
216
+ const families = spec.families.map((f) => ({
217
+ type: f.type,
218
+ re_derivable: f.re_derivable,
219
+ ...(f.loss ? { loss: f.loss } : {}),
220
+ }));
221
+ const handlers = spec;
222
+ this.#entryType(type, spec.config, spec.validate, async (entries, ctx) => {
223
+ const sources = await spec.sources(entries, ctx);
224
+ return sources.map((s) => {
225
+ if (!inNamespace(name, s.name))
226
+ throw new ProtocolError(Code.Invalid, `source ${s.name} must be named ${name} or begin with ${name}/`);
227
+ if (!inNamespace(name, s.namespace))
228
+ throw new ProtocolError(Code.Invalid, `source ${s.name}: namespace ${s.namespace} must be ${name} or begin with ${name}/`);
229
+ if (!(s.intervalSeconds >= 1))
230
+ throw new ProtocolError(Code.Invalid, `source ${s.name}: intervalSeconds must be at least one`);
231
+ const webhook = spec.webhook !== undefined && s.webhook !== false;
232
+ if (webhook && !s.name.startsWith(`${name}/`))
233
+ throw new ProtocolError(Code.Invalid, `source ${s.name}: a source with a webhook must be named ${name}/<more>, so its path is under /${name}/`);
234
+ return {
235
+ spec: { ...s, webhook },
236
+ type: handlers,
237
+ decl: {
238
+ name: s.name,
239
+ source: { namespace: s.namespace, scope_id: s.scopeId },
240
+ interval_seconds: Math.floor(s.intervalSeconds),
241
+ families,
242
+ },
243
+ };
244
+ });
245
+ }, true);
246
+ const provides = this.manifest.provides;
247
+ // A family two ingress types share is declared once.
248
+ for (const f of spec.families)
249
+ if (!provides.families?.some((x) => x.type === f.type))
250
+ (provides.families ??= []).push(f);
251
+ if (spec.webhook !== undefined) {
252
+ provides.webhooks = true;
253
+ if (spec.webhookMaxBytes !== undefined)
254
+ provides.webhook_max_bytes = Math.max(provides.webhook_max_bytes ?? 0, Math.floor(spec.webhookMaxBytes));
255
+ }
256
+ return this;
257
+ }
258
+ #entryType(type, config, validate, configure, ingress = false) {
259
+ if (this.#entryTypes.has(type))
260
+ throw new Error(`sdk: entry type ${type} is registered twice`);
261
+ const decode = (e) => {
262
+ // An absent config is an empty one, as Go reads it.
263
+ const c = e.config ?? {};
264
+ if (!matches(config, c))
265
+ throw new ProtocolError(Code.Invalid, `${type} entry in scope ${e.scope_id}: ${check(config, c)}`);
266
+ return {
267
+ scopeId: e.scope_id,
268
+ name: e.name ?? "",
269
+ config: c,
270
+ secrets: e.secrets ?? [],
271
+ ...(e.connection ? { connection: e.connection } : {}),
272
+ };
273
+ };
274
+ this.#entryTypes.set(type, {
275
+ validate: (c) => validateConfig(config, c, validate),
276
+ // Decoded even with no hook, so a bad config fails configure rather than passing silently.
277
+ configure: (entries, ctx) => configure(entries.filter((e) => e.type === type).map(decode), ctx),
278
+ });
279
+ (this.manifest.provides.extensions ??= []).push(ingress ? { type, ingress: true } : { type });
280
+ return this;
281
+ }
282
+ /**
283
+ * Registers a route handler and declares it: what an Event does (open
284
+ * Work, reach the Work it already has, or nothing). A spec with samples
285
+ * is declared as offering them, so route traces and the routes.decisions
286
+ * certification apply; one with config has its routes' config checked.
287
+ */
288
+ route(handler, spec) {
289
+ if (this.#routes.has(handler))
290
+ throw new Error(`sdk: route handler ${handler} is registered twice`);
291
+ const schema = spec.config;
292
+ const decode = (p) => {
293
+ const c = p.data ?? {};
294
+ if (schema !== undefined && !matches(schema, c))
295
+ throw new ProtocolError(Code.Invalid, `route config: ${check(schema, c)}`);
296
+ return c;
297
+ };
298
+ this.#routes.set(handler, {
299
+ validate: async (c) => {
300
+ if (schema !== undefined)
301
+ await validateConfig(schema, c);
302
+ },
303
+ match: async (input, ctx) => spec.match({ ...input, config: decode(input.route.config) }, ctx),
304
+ samples: async (p, ctx) => spec.samples === undefined
305
+ ? []
306
+ : spec.samples({
307
+ scope: p.scope,
308
+ route: p.route,
309
+ now: p.now,
310
+ config: decode(p.route.config),
311
+ }, ctx),
312
+ });
313
+ (this.manifest.provides.routes ??= []).push({
314
+ handler,
315
+ ...(schema === undefined ? {} : { config: true }),
316
+ ...(spec.samples === undefined ? {} : { samples: true }),
317
+ });
318
+ return this;
319
+ }
320
+ /** Declares a kind of Work the extension's routes create, with its lifecycle. */
321
+ workKind(kind, spec = {}) {
322
+ if (spec.trigger !== undefined)
323
+ this.#triggers.set(kind, spec.trigger);
324
+ (this.manifest.provides.work_kinds ??= []).push({
325
+ kind,
326
+ ...(spec.standing ? { standing: true } : {}),
327
+ ...(spec.trigger ? { trigger: true } : {}),
328
+ ...(spec.timed ? { timed: true } : {}),
329
+ ...(spec.runOnce ? { run_once: true } : {}),
330
+ });
331
+ return this;
332
+ }
333
+ /**
334
+ * Registers a secret reference scheme and declares it (manifest
335
+ * secret_schemes): config may then name a secret as
336
+ * "<scheme>:<reference>", and the host asks serve for its value only
337
+ * when the slot's authorised consumer needs it. A spec with store and
338
+ * delete declares the scheme writable, so the daemon's secret store can
339
+ * write to it (settings.secret_store).
340
+ */
341
+ secretScheme(scheme, spec) {
342
+ if (this.#secrets.has(scheme))
343
+ throw new Error(`sdk: secret scheme ${scheme} is registered twice`);
344
+ const writable = spec.store !== undefined;
345
+ if (writable !== (spec.delete !== undefined))
346
+ throw new Error(`sdk: secret scheme ${scheme} needs both store and delete to be writable`);
347
+ this.#secrets.set(scheme, spec);
348
+ (this.manifest.provides.secret_schemes ??= []).push({
349
+ scheme,
350
+ ...(spec.summary === undefined ? {} : { summary: spec.summary }),
351
+ ...(writable ? { writable: true } : {}),
352
+ });
353
+ return this;
354
+ }
355
+ /**
356
+ * Registers a credential verifier type and declares it (manifest
357
+ * verifiers): an admin may then trust an issuer of the type, whose
358
+ * config validate (kind verifier) checks against spec.config and
359
+ * spec.validate, and the host asks verify, through credential.verify,
360
+ * about each bearer credential it didn't issue itself.
361
+ */
362
+ verifier(type, spec) {
363
+ if (this.#verifiers.has(type))
364
+ throw new Error(`sdk: verifier type ${type} is registered twice`);
365
+ const schema = spec.config;
366
+ this.#verifiers.set(type, {
367
+ validate: async (c) => {
368
+ if (schema === undefined) {
369
+ try {
370
+ await spec.validate?.((c ?? {}));
371
+ }
372
+ catch (err) {
373
+ if (err instanceof ConfigError)
374
+ throw err;
375
+ throw new ProtocolError(Code.Invalid, "invalid extension config");
376
+ }
377
+ return;
378
+ }
379
+ await validateConfig(schema, c, spec.validate);
380
+ },
381
+ verify: async (p, ctx) => {
382
+ const config = p.config.data ?? {};
383
+ // A stored issuer config passed validate; one that no longer
384
+ // matches (a package upgrade changed the schema) verifies nothing.
385
+ if (schema !== undefined && !matches(schema, config))
386
+ throw new CredentialRefusal();
387
+ let got;
388
+ try {
389
+ got = await spec.verify({
390
+ type: p.type,
391
+ issuer: p.issuer,
392
+ config: config,
393
+ token: p.token,
394
+ }, ctx);
395
+ }
396
+ catch (err) {
397
+ // Neither the credential nor the verifier's reason crosses: the
398
+ // host answers 401 whatever it was.
399
+ if (err instanceof CredentialRefusal)
400
+ throw new ProtocolError(Code.Unauthorized, "credential refused");
401
+ throw new ProtocolError(Code.Internal, "credential verifier failed");
402
+ }
403
+ const at = got?.expiresAt;
404
+ if (!(at instanceof Date) || Number.isNaN(at.getTime()))
405
+ throw new ProtocolError(Code.Internal, "credential verifier answered without a valid expiresAt");
406
+ return {
407
+ subject: got.subject,
408
+ ...(got.groups && got.groups.length > 0
409
+ ? { groups: [...got.groups] }
410
+ : {}),
411
+ expires_at: at.toISOString(),
412
+ };
413
+ },
414
+ });
415
+ (this.manifest.provides.verifiers ??= []).push({
416
+ type,
417
+ ...(spec.fields && spec.fields.length > 0 ? { fields: spec.fields } : {}),
418
+ });
419
+ return this;
420
+ }
421
+ /**
422
+ * Registers a container provider type and declares it (manifest
423
+ * containers), with forward, place, collect and reattach as the spec
424
+ * gives them: a binding's container config may then name the type, the
425
+ * host checks it through validate (kind container) against
426
+ * spec.settings and spec.validate, and binds it to each attempt through
427
+ * container_provider.*.
428
+ */
429
+ containerProvider(type, spec) {
430
+ if (this.#containers.has(type))
431
+ throw new Error(`sdk: container provider type ${type} is registered twice`);
432
+ if ((spec.place === undefined) !== (spec.siteRun === undefined))
433
+ throw new Error(`sdk: container provider type ${type} needs both place and siteRun to place launches`);
434
+ this.#containers.set(type, containerHandler(spec));
435
+ (this.manifest.provides.containers ??= []).push({
436
+ type,
437
+ ...(spec.forward ? { forward: true } : {}),
438
+ ...(spec.probe ? { probe: true } : {}),
439
+ ...(spec.place ? { place: true } : {}),
440
+ ...(spec.collect ? { collect: true } : {}),
441
+ ...(spec.reattach ? { reattach: true } : {}),
442
+ });
443
+ return this;
444
+ }
445
+ /**
446
+ * Registers a resource provider type and declares it (manifest
447
+ * resources), with mode_default, sandbox, sweep, unsaved and sites as
448
+ * the spec gives them: a binding's resource config may then name the
449
+ * type, the host checks it through validate (kind resource, and the
450
+ * resource_mode, resource_sandbox and resource_site checks) and binds it
451
+ * to each attempt through provider.*.
452
+ */
453
+ resourceProvider(type, spec) {
454
+ if (this.#resources.has(type))
455
+ throw new Error(`sdk: resource provider type ${type} is registered twice`);
456
+ const h = resourceHandler(type, spec, params);
457
+ this.#resources.set(type, h);
458
+ (this.manifest.provides.resources ??= []).push({ type, ...h.decl });
459
+ return this;
460
+ }
461
+ /**
462
+ * Registers a process sandbox provider type and declares it (manifest
463
+ * sandboxes): a binding's sandbox config may then name the type, the
464
+ * host checks it through validate (kind sandbox) against spec.config and
465
+ * spec.validate, and binds it to each attempt through
466
+ * sandbox_provider.plan and adopt.
467
+ */
468
+ sandboxProvider(type, spec) {
469
+ if (this.#sandboxes.has(type))
470
+ throw new Error(`sdk: sandbox provider type ${type} is registered twice`);
471
+ this.#sandboxes.set(type, sandboxHandler(type, spec, params));
472
+ (this.manifest.provides.sandboxes ??= []).push({ type });
473
+ return this;
474
+ }
475
+ /**
476
+ * Registers a tunnel provider type and declares it (manifest tunnels):
477
+ * settings.webhooks.tunnel may then name the type, its config checked
478
+ * through validate (kind tunnel) against spec.config and spec.validate,
479
+ * and the host runs it through tunnel.run for as long as it wants the
480
+ * tunnel.
481
+ */
482
+ tunnelProvider(type, spec) {
483
+ if (this.#tunnels.has(type))
484
+ throw new Error(`sdk: tunnel provider type ${type} is registered twice`);
485
+ this.#tunnels.set(type, tunnelHandler(type, spec, params));
486
+ (this.manifest.provides.tunnels ??= []).push({
487
+ type,
488
+ ...(spec.fields && spec.fields.length > 0 ? { fields: spec.fields } : {}),
489
+ });
490
+ return this;
491
+ }
492
+ /**
493
+ * Registers a backup destination type and declares it (manifest
494
+ * backup_destinations): settings.backup.destinations may then name the
495
+ * type, whose config validate (kind backup_destination) checks against
496
+ * spec.config and spec.validate, and the host stores bundles with it
497
+ * through backup_destination.*.
498
+ */
499
+ backupDestination(type, spec) {
500
+ if (this.#backups.has(type))
501
+ throw new Error(`sdk: backup destination type ${type} is registered twice`);
502
+ this.#backups.set(type, backupHandler(spec, validateConfig));
503
+ (this.manifest.provides.backup_destinations ??= []).push({
504
+ type,
505
+ ...(spec.fields && spec.fields.length > 0 ? { fields: spec.fields } : {}),
506
+ });
507
+ return this;
508
+ }
509
+ /**
510
+ * Registers an executor and declares it (manifest executors), with the
511
+ * capabilities spec.capabilities names and the controls (stop, forget,
512
+ * sweep, live, attach, container_attach, interactive_launch) and
513
+ * answers (resource_mode, playbook, version_probe, folder_config) its
514
+ * handlers give: a binding may then name it, its config checked through
515
+ * validate (kind executor) against spec.config and spec.validate, and
516
+ * the host runs, recovers, resumes, observes and drives its attempts
517
+ * through executor.*. A capability whose handler is missing is refused
518
+ * here, as the host would refuse the binding.
519
+ */
520
+ executor(name, spec) {
521
+ if (this.#executors.has(name))
522
+ throw new Error(`sdk: executor ${name} is registered twice`);
523
+ const h = executorHandler(name, spec, validateConfig);
524
+ const names = (x) => [
525
+ x.decl.name,
526
+ ...(x.decl.launch_names ?? []),
527
+ ];
528
+ for (const other of this.#executors.values())
529
+ for (const n of names(h))
530
+ if (names(other).includes(n))
531
+ throw new Error(`sdk: executor ${name}: ${n} repeats an executor name or launch name`);
532
+ this.#executors.set(name, h);
533
+ (this.manifest.provides.executors ??= []).push(h.decl);
534
+ return this;
535
+ }
536
+ /**
537
+ * Registers the extension's actions, requests and panels on scopes and
538
+ * Work and declares them (manifest actions, panels, secret_actions,
539
+ * entry_named): list offers actions on a target, act authorises one
540
+ * invocation as the Event the host accepts under core.action, requests
541
+ * reports what a person is asked to decide, and panels shows documents
542
+ * whose buttons name the listed actions. list and act come together;
543
+ * panels may stand alone, without buttons.
544
+ */
545
+ actions(spec) {
546
+ if (this.#actions !== undefined)
547
+ throw new Error("sdk: actions are registered twice");
548
+ if ((spec.list === undefined) !== (spec.act === undefined))
549
+ throw new Error("sdk: actions need both list and act");
550
+ if (spec.list === undefined && spec.panels === undefined)
551
+ throw new Error("sdk: actions need list and act, or panels");
552
+ if (spec.requests !== undefined && spec.list === undefined)
553
+ throw new Error("sdk: requests need the actions that answer them");
554
+ if (spec.secretActions && spec.list === undefined)
555
+ throw new Error("sdk: secretActions needs actions");
556
+ this.#actions = actionsHandler(spec);
557
+ const provides = this.manifest.provides;
558
+ if (spec.list !== undefined)
559
+ provides.actions = true;
560
+ if (spec.secretActions)
561
+ provides.secret_actions = true;
562
+ if (spec.panels !== undefined)
563
+ provides.panels = true;
564
+ if (spec.entryNamed)
565
+ provides.entry_named = true;
566
+ return this;
567
+ }
568
+ /** Registers the extension's Work annotations, name/value lines on each Work's view, and declares them (manifest annotate). */
569
+ annotate(fn) {
570
+ if (this.#annotate !== undefined)
571
+ throw new Error("sdk: annotate is registered twice");
572
+ this.#annotate = fn;
573
+ this.manifest.provides.annotate = true;
574
+ return this;
575
+ }
576
+ /**
577
+ * Registers the extension's telemetry exporter and declares it (manifest
578
+ * exporters): the host sends it batches of its lifecycle records through
579
+ * telemetry.export, and shutdown when it shuts the extension down.
580
+ */
581
+ exporter(spec) {
582
+ if (this.#exporter !== undefined)
583
+ throw new Error("sdk: an exporter is registered twice");
584
+ this.#exporter = spec;
585
+ this.manifest.provides.exporters = true;
586
+ return this;
587
+ }
588
+ /**
589
+ * Registers what receives each collection of the host's meter, and asks
590
+ * for the permission that sends it (telemetry.metrics).
591
+ */
592
+ metrics(fn) {
593
+ if (this.#metrics !== undefined)
594
+ throw new Error("sdk: metrics are registered twice");
595
+ this.#metrics = fn;
596
+ this.#permit("telemetry.metrics");
597
+ return this;
598
+ }
599
+ /**
600
+ * Registers the extension's telemetry sink, and asks for the permission
601
+ * that sends it every named telemetry event the host records
602
+ * (telemetry.sink). Capturing one is host.capture, under the
603
+ * telemetry.capture permission, which Options.permissions asks for.
604
+ */
605
+ sink(fn) {
606
+ if (this.#sink !== undefined)
607
+ throw new Error("sdk: a sink is registered twice");
608
+ this.#sink = fn;
609
+ this.#permit("telemetry.sink");
610
+ return this;
611
+ }
612
+ /**
613
+ * Registers the extension's run environment and declares it (manifest
614
+ * run_environment): the host asks it for a layer of environment
615
+ * variables and files for each run of a Work in a scope that uses the
616
+ * extension, through run.environment.
617
+ */
618
+ runEnvironment(fn) {
619
+ if (this.#runEnvironment !== undefined)
620
+ throw new Error("sdk: a run environment is registered twice");
621
+ this.#runEnvironment = fn;
622
+ this.manifest.provides.run_environment = true;
623
+ return this;
624
+ }
625
+ /**
626
+ * Registers what the extension's Work proposes for the operator to
627
+ * review and apply, and declares it (manifest config_candidate): the
628
+ * host asks fn about a Work of a kind the extension owns through
629
+ * config.candidate. It asks for the config.read permission, without
630
+ * which the extension has no handles to propose and the host never asks,
631
+ * and which serves the host's config service (host.configBase,
632
+ * configEdit, configValidate and configTrace).
633
+ */
634
+ configCandidate(fn) {
635
+ if (this.#configCandidate !== undefined)
636
+ throw new Error("sdk: a config candidate is registered twice");
637
+ this.#configCandidate = fn;
638
+ this.manifest.provides.config_candidate = true;
639
+ this.#permit("config.read");
640
+ return this;
641
+ }
642
+ /**
643
+ * Registers the extension's `open-conduit init <type>` flow and declares
644
+ * it (manifest setup): the host runs it through setup.run, and answers
645
+ * the setup.* callbacks its SetupHost makes while it lasts. A package
646
+ * declares at most one.
647
+ */
648
+ setup(spec) {
649
+ if (this.#setup !== undefined)
650
+ throw new Error("sdk: a setup flow is registered twice");
651
+ this.#setup = spec;
652
+ this.manifest.provides.setup = {
653
+ type: spec.type,
654
+ summary: spec.summary,
655
+ ...(spec.usage ? { usage: spec.usage } : {}),
656
+ ...(spec.firstRun ? { first_run: true } : {}),
657
+ };
658
+ return this;
659
+ }
660
+ /**
661
+ * Registers a calendar recurrence kind and declares it (manifest
662
+ * recurrences): host.armTimer arms a timer of the kind, and each time it
663
+ * fires the host asks fn for the occurrence and the next timer
664
+ * (recurrence.next), inside the transaction that fires it. fn is
665
+ * synchronous and gets no host (see RecurrenceFn).
666
+ */
667
+ recurrence(kind, fn) {
668
+ if (this.#recurrences.has(kind))
669
+ throw new Error(`sdk: recurrence ${kind} is registered twice`);
670
+ this.#recurrences.set(kind, fn);
671
+ (this.manifest.provides.recurrences ??= []).push(kind);
672
+ return this;
673
+ }
674
+ /**
675
+ * Registers the filter of the extension's wait operations' dependencies
676
+ * and declares it (manifest dependency_filter; it needs a wait
677
+ * operation): the host asks fn whether an Event on a dependency matches
678
+ * the filter the wait put on it (dependency.filter), inside its
679
+ * transaction. fn is synchronous and gets no host.
680
+ */
681
+ dependencyFilter(fn) {
682
+ if (this.#filter !== undefined)
683
+ throw new Error("sdk: a dependency filter is registered twice");
684
+ this.#filter = fn;
685
+ this.manifest.provides.dependency_filter = true;
686
+ return this;
687
+ }
688
+ /**
689
+ * Registers the extension's gate on other extensions' operations and
690
+ * declares it (manifest operation_gate), asking for the operation.gate
691
+ * permission, which the operator consents to at install and without
692
+ * which the host never asks: the host asks fn about every toolbelt call
693
+ * to another extension's operation in the extension's scopes
694
+ * (operation.gate), and it may let the call through, park the caller or
695
+ * refuse it.
696
+ */
697
+ operationGate(fn) {
698
+ if (this.#gate !== undefined)
699
+ throw new Error("sdk: an operation gate is registered twice");
700
+ this.#gate = fn;
701
+ this.manifest.provides.operation_gate = true;
702
+ this.#permit("operation.gate");
703
+ return this;
704
+ }
705
+ /**
706
+ * Registers the extension's start gate and declares it (manifest
707
+ * start_gate), asking for the work.start_gate permission, which the
708
+ * operator consents to at install and without which the host never
709
+ * asks: the host asks fn before the first attempt of any Work in the
710
+ * extension's scopes starts (work.admit), and it may hold the Work until
711
+ * host.settleHold admits or cancels it.
712
+ */
713
+ startGate(fn) {
714
+ if (this.#startGate !== undefined)
715
+ throw new Error("sdk: a start gate is registered twice");
716
+ this.#startGate = fn;
717
+ this.manifest.provides.start_gate = true;
718
+ this.#permit("work.start_gate");
719
+ return this;
720
+ }
721
+ /**
722
+ * Registers the resolver of a wait target kind ("job" for a
723
+ * `job:<name>` condition another extension's wait operation names) and
724
+ * declares it (manifest targets): the host asks fn through
725
+ * target.resolve. The Event types it answers must be the extension's own
726
+ * families.
727
+ */
728
+ target(kind, fn) {
729
+ if (this.#targets.has(kind))
730
+ throw new Error(`sdk: target kind ${kind} is registered twice`);
731
+ this.#targets.set(kind, fn);
732
+ (this.manifest.provides.targets ??= []).push(kind);
733
+ return this;
734
+ }
735
+ /**
736
+ * Registers what the extension does when an execution's container
737
+ * segment ends, revoking what it issued for it, and declares it
738
+ * (manifest segment_end; segment.ended).
739
+ */
740
+ onSegmentEnd(fn) {
741
+ if (this.#segmentEnd !== undefined)
742
+ throw new Error("sdk: a segment end is registered twice");
743
+ this.#segmentEnd = fn;
744
+ this.manifest.provides.segment_end = true;
745
+ return this;
746
+ }
747
+ /**
748
+ * Registers how the extension renders Events of its own families for an
749
+ * agent's prompt and declares it (manifest render; event.render). The
750
+ * host bounds each call and falls back to its generic rendering when fn
751
+ * answers undefined, throws or is slow.
752
+ */
753
+ render(fn) {
754
+ if (this.#render !== undefined)
755
+ throw new Error("sdk: render is registered twice");
756
+ this.#render = fn;
757
+ this.manifest.provides.render = true;
758
+ return this;
759
+ }
760
+ #permit(permission) {
761
+ const permissions = (this.manifest.permissions ??= []);
762
+ if (!permissions.includes(permission))
763
+ permissions.push(permission);
764
+ }
765
+ /**
766
+ * Declares a page of the extension's own in the operator's web view
767
+ * (manifest pages): a session of one of its Work kinds, started from a
768
+ * scope with one of its entries, drawn by core from the entry's actions
769
+ * and the session's panels. It needs actions, and the entry type, work
770
+ * kind and route it names declared too, which the host checks.
771
+ */
772
+ page(id, spec) {
773
+ const pages = (this.manifest.provides.pages ??= []);
774
+ if (pages.some((p) => p.id === id))
775
+ throw new Error(`sdk: page ${id} is declared twice`);
776
+ if (pages.length >= 4)
777
+ throw new Error("sdk: more than 4 pages");
778
+ pages.push(pageDecl(id, spec));
779
+ return this;
780
+ }
781
+ /**
782
+ * Registers a read-only setup probe and declares it (manifest probes):
783
+ * the host lists it as "<extension>.<name>" to setup sessions and runs
784
+ * it through probe.serve, with its declared arguments only.
785
+ */
786
+ probe(name, spec) {
787
+ if (this.#probes.has(name))
788
+ throw new Error(`sdk: probe ${name} is registered twice`);
789
+ const h = probeHandler(name, spec);
790
+ this.#probes.set(name, h);
791
+ (this.manifest.provides.probes ??= []).push(h.info);
792
+ return this;
793
+ }
794
+ /** Registers a doctor check and declares it. */
795
+ check(name, fn, o = {}) {
796
+ this.#checks.set(name, fn);
797
+ (this.manifest.provides.checks ??= []).push(o.deep ? { name, deep: true } : { name });
798
+ return this;
799
+ }
800
+ /** Registers a task the host runs every intervalSeconds (at least one) and declares it. */
801
+ task(name, intervalSeconds, fn) {
802
+ this.#tasks.set(name, fn);
803
+ (this.manifest.provides.tasks ??= []).push({
804
+ name,
805
+ interval_seconds: Math.floor(intervalSeconds),
806
+ });
807
+ return this;
808
+ }
809
+ /** Declares event families the extension derives through host.accept or emits (an ingress type's come with it). */
810
+ family(...families) {
811
+ (this.manifest.provides.families ??= []).push(...families);
812
+ return this;
813
+ }
814
+ /**
815
+ * Declares a payload schema the extension writes and reads, named
816
+ * <extension>.<thing> and written as <name>.v<N>: the versions it can
817
+ * read, ascending, the highest being the one it writes. The host refuses
818
+ * an Event (ingress, event.accept or emitted) whose data names any other.
819
+ */
820
+ schema(name, ...versions) {
821
+ if (versions.length === 0 ||
822
+ versions.some((v, i) => !Number.isInteger(v) || v < 1 || (i > 0 && v <= versions[i - 1])))
823
+ throw new Error(`sdk: schema ${name} needs positive, strictly increasing versions`);
824
+ (this.manifest.provides.schemas ??= []).push({
825
+ name,
826
+ versions: [...versions],
827
+ });
828
+ return this;
829
+ }
830
+ /** Upgrades the extension's KV namespaces to kvVersion. It must be idempotent: a crash mid-way retries it. */
831
+ onMigrate(fn) {
832
+ this.#migrate = fn;
833
+ return this;
834
+ }
835
+ /** Sets the package's certification.json content (package-certification). */
836
+ certification(file) {
837
+ this.#certification = file;
838
+ return this;
839
+ }
840
+ /** Serves the extension on input and output (tests pass a pair of in-memory streams). */
841
+ serve(input, output) {
842
+ return new Server(this, input, output);
843
+ }
844
+ /**
845
+ * The entry point of a packaged extension: `package-manifest` prints the
846
+ * manifest, `package-certification` the certification file, and anything
847
+ * else serves on stdin and stdout until stdin closes, then exits.
848
+ */
849
+ async main(argv = process.argv.slice(2)) {
850
+ if (argv.length === 1 && argv[0] === "package-manifest")
851
+ return print(this.manifest);
852
+ if (argv.length === 1 && argv[0] === "package-certification")
853
+ return this.#certification === undefined
854
+ ? undefined
855
+ : print(this.#certification);
856
+ // stdout carries the protocol, so a stray console.log would corrupt it: send those to stderr.
857
+ const stdout = process.stdout;
858
+ const protocolWrite = stdout.write.bind(stdout);
859
+ stdout.write = process.stderr.write.bind(process.stderr);
860
+ const out = new Writable({
861
+ write(chunk, _encoding, done) {
862
+ protocolWrite(chunk, done);
863
+ },
864
+ });
865
+ await this.serve(process.stdin, out).done;
866
+ // An extension never outlives its host, whatever timers it left running.
867
+ process.exit(0);
868
+ }
869
+ /** @internal */
870
+ _served() {
871
+ return {
872
+ operations: this.#operations,
873
+ checks: this.#checks,
874
+ tasks: this.#tasks,
875
+ entryTypes: this.#entryTypes,
876
+ routes: this.#routes,
877
+ triggers: this.#triggers,
878
+ secrets: this.#secrets,
879
+ verifiers: this.#verifiers,
880
+ containers: this.#containers,
881
+ resources: this.#resources,
882
+ sandboxes: this.#sandboxes,
883
+ tunnels: this.#tunnels,
884
+ backups: this.#backups,
885
+ executors: this.#executors,
886
+ probes: this.#probes,
887
+ actions: this.#actions,
888
+ annotate: this.#annotate,
889
+ exporter: this.#exporter,
890
+ metrics: this.#metrics,
891
+ sink: this.#sink,
892
+ runEnvironment: this.#runEnvironment,
893
+ configCandidate: this.#configCandidate,
894
+ setup: this.#setup,
895
+ recurrences: this.#recurrences,
896
+ targets: this.#targets,
897
+ filter: this.#filter,
898
+ gate: this.#gate,
899
+ startGate: this.#startGate,
900
+ segmentEnd: this.#segmentEnd,
901
+ render: this.#render,
902
+ migrate: this.#migrate,
903
+ };
904
+ }
905
+ }
906
+ /** protocol.SourceNamespace: the name itself, or it and "/" and more. */
907
+ function inNamespace(name, ns) {
908
+ return (ns === name || (ns.startsWith(`${name}/`) && ns.length > name.length + 1));
909
+ }
910
+ function json(schema) {
911
+ // A round trip through JSON gives the schema exactly as the manifest file holds it.
912
+ const plain = JSON.parse(JSON.stringify(schema));
913
+ return isRecord(plain) ? plain : {};
914
+ }
915
+ function print(v) {
916
+ return new Promise((resolve) => process.stdout.write(JSON.stringify(v, null, 2) + "\n", () => resolve()));
917
+ }
918
+ function notFound(method) {
919
+ return new ProtocolError(Code.MethodNotFound, `no such method ${method}`);
920
+ }
921
+ /**
922
+ * Runs a secret scheme's handler: a SecretRefusal answers its code, and
923
+ * anything else thrown crosses as a fixed internal error, so neither the
924
+ * provider's error text nor a value it carries reaches the host, a log or
925
+ * the operator. A cancelled request still answers as cancelled.
926
+ */
927
+ async function secretCall(fn) {
928
+ try {
929
+ return await fn();
930
+ }
931
+ catch (err) {
932
+ if (err instanceof SecretRefusal)
933
+ return { code: err.code };
934
+ throw new ProtocolError(Code.Internal, "secret provider failed");
935
+ }
936
+ }
937
+ const typed = t.object({ type: t.string() }, { open: true });
938
+ const named = t.object({ executor: t.optional(t.string()) }, { open: true });
939
+ /** The container config's provider settings, decoded, or undefined when they don't match the schema. */
940
+ function containerConfig(schema, raw) {
941
+ const c = isRecord(raw) ? raw : {};
942
+ const provider = c.provider ?? {};
943
+ if (schema !== undefined && !matches(schema, provider))
944
+ return undefined;
945
+ return { ...c, provider };
946
+ }
947
+ function containerState(s) {
948
+ const { started_at, ...rest } = s;
949
+ const out = { ...rest, ref: containerRef(s.ref) };
950
+ const at = started_at instanceof Date
951
+ ? Number.isNaN(started_at.getTime())
952
+ ? ""
953
+ : started_at.toISOString()
954
+ : (started_at ?? "");
955
+ if (at !== "")
956
+ out.started_at = at;
957
+ return out;
958
+ }
959
+ function containerRef(r) {
960
+ return r.labels && Object.keys(r.labels).length > 0
961
+ ? { id: r.id, labels: { ...r.labels } }
962
+ : { id: r.id };
963
+ }
964
+ function containerCreated(c) {
965
+ const out = {
966
+ ref: containerRef(c.ref),
967
+ argv: [...(c.argv ?? [])],
968
+ };
969
+ if (c.daemon)
970
+ out.daemon = c.daemon;
971
+ if (c.env && c.env.length > 0)
972
+ out.env = [...c.env];
973
+ if (c.record !== undefined)
974
+ out.record = c.record;
975
+ return out;
976
+ }
977
+ function outputBytes(b) {
978
+ if (b === undefined)
979
+ return undefined;
980
+ const bytes = typeof b === "string" ? new TextEncoder().encode(b) : b;
981
+ return bytes.length === 0 ? undefined : base64(bytes);
982
+ }
983
+ /** A container provider type's validate and container_provider.* methods, as protocol/sdk serves sdk.Extension.Containers. */
984
+ function containerHandler(spec) {
985
+ const schema = spec.settings;
986
+ // A stored binding passed validate; one whose settings no longer match
987
+ // (a package upgrade changed the schema) runs nothing.
988
+ const config = (raw) => {
989
+ const c = containerConfig(schema, raw);
990
+ if (c === undefined)
991
+ throw new ProtocolError(Code.SandboxUnavailable, "the binding's container settings don't match the provider's");
992
+ return c;
993
+ };
994
+ return {
995
+ validate: async (raw) => {
996
+ const c = isRecord(raw) ? raw : {};
997
+ if (schema !== undefined) {
998
+ const provider = c.provider ?? {};
999
+ if (!matches(schema, provider)) {
1000
+ const diagnostics = diagnose(schema, provider).map((d) => ({
1001
+ ...d,
1002
+ path: `/provider${d.path}`,
1003
+ }));
1004
+ if (diagnostics.length > 0)
1005
+ throw new ConfigError(diagnostics);
1006
+ throw new ProtocolError(Code.Invalid, "invalid container config");
1007
+ }
1008
+ }
1009
+ try {
1010
+ await spec.validate?.(config(c));
1011
+ }
1012
+ catch (err) {
1013
+ if (err instanceof ConfigError)
1014
+ throw err;
1015
+ throw new ProtocolError(Code.Invalid, "invalid container config");
1016
+ }
1017
+ },
1018
+ serve: async (method, raw, ctx) => {
1019
+ switch (method) {
1020
+ case "container_provider.plan": {
1021
+ const p = params(ContainerProviderPlanParams, raw);
1022
+ const plan = await spec.plan({
1023
+ type: p.type,
1024
+ owner: p.owner,
1025
+ config: config(p.config.data),
1026
+ paths: p.paths,
1027
+ needs: p.needs,
1028
+ launch: p.launch,
1029
+ placement: p.placement ?? "",
1030
+ }, ctx);
1031
+ const out = { image: plan.image, data: plan.data };
1032
+ if (plan.summary)
1033
+ out.summary = plan.summary;
1034
+ return out;
1035
+ }
1036
+ case "container_provider.create": {
1037
+ const p = params(ContainerProviderCreateParams, raw);
1038
+ return containerCreated(await spec.create({ plan: p.plan, labels: p.labels ?? {} }, ctx));
1039
+ }
1040
+ case "container_provider.signal": {
1041
+ const p = params(ContainerProviderRefParams, raw);
1042
+ await spec.signal(p.ref, p.signal ?? "", ctx);
1043
+ return {};
1044
+ }
1045
+ case "container_provider.stop": {
1046
+ const p = params(ContainerProviderRefParams, raw);
1047
+ await spec.stop(p.ref, p.grace_millis ?? 0, ctx);
1048
+ return {};
1049
+ }
1050
+ case "container_provider.inspect": {
1051
+ const p = params(ContainerProviderRefParams, raw);
1052
+ return containerState(await spec.inspect(p.ref, ctx));
1053
+ }
1054
+ case "container_provider.list": {
1055
+ const p = params(ContainerProviderListParams, raw);
1056
+ const states = await spec.list(p.owner, ctx);
1057
+ return { containers: states.map(containerState) };
1058
+ }
1059
+ case "container_provider.remove": {
1060
+ const p = params(ContainerProviderRefParams, raw);
1061
+ await spec.remove(p.ref, ctx);
1062
+ return {};
1063
+ }
1064
+ case "container_provider.forward": {
1065
+ if (spec.forward === undefined)
1066
+ break;
1067
+ const p = params(ContainerProviderForwardParams, raw);
1068
+ const address = await spec.forward(config(p.config.data), ctx);
1069
+ return address ? { address } : {};
1070
+ }
1071
+ case "container_provider.place": {
1072
+ if (spec.place === undefined)
1073
+ break;
1074
+ const p = params(ContainerProviderPlaceParams, raw);
1075
+ const at = await spec.place({
1076
+ owner: p.owner,
1077
+ config: config(p.config.data),
1078
+ prefer: p.prefer ?? "",
1079
+ }, ctx);
1080
+ const out = { id: at.id, daemon: at.daemon };
1081
+ if (at.summary)
1082
+ out.summary = at.summary;
1083
+ return out;
1084
+ }
1085
+ case "container_provider.site_run": {
1086
+ if (spec.siteRun === undefined)
1087
+ break;
1088
+ const p = params(ContainerProviderSiteRunParams, raw);
1089
+ const c = p.command;
1090
+ const r = await spec.siteRun(p.placement, {
1091
+ argv: [...(c.argv ?? [])],
1092
+ dir: c.dir ?? "",
1093
+ env: [...(c.env ?? [])],
1094
+ stdin: bytes(c.stdin),
1095
+ timeoutMs: c.timeout_millis ?? 0,
1096
+ toolbelt: c.toolbelt ?? "",
1097
+ tokenFile: c.token_file ?? "",
1098
+ }, ctx);
1099
+ const out = { exit_code: r.exitCode };
1100
+ const stdout = outputBytes(r.stdout);
1101
+ const stderr = outputBytes(r.stderr);
1102
+ if (stdout !== undefined)
1103
+ out.stdout = stdout;
1104
+ if (stderr !== undefined)
1105
+ out.stderr = stderr;
1106
+ if (r.truncated)
1107
+ out.truncated = true;
1108
+ return out;
1109
+ }
1110
+ case "container_provider.collect": {
1111
+ if (spec.collect === undefined)
1112
+ break;
1113
+ const p = params(ContainerProviderRefParams, raw);
1114
+ await spec.collect(p.ref, ctx);
1115
+ return {};
1116
+ }
1117
+ case "container_provider.reattach": {
1118
+ if (spec.reattach === undefined)
1119
+ break;
1120
+ const p = params(ContainerProviderReattachParams, raw);
1121
+ return containerCreated(await spec.reattach(p.ref, {
1122
+ pin: p.pin,
1123
+ paths: p.paths,
1124
+ tokenFile: p.token_file ?? "",
1125
+ sameHost: p.same_host === true,
1126
+ }, ctx));
1127
+ }
1128
+ }
1129
+ throw notFound(method);
1130
+ },
1131
+ };
1132
+ }
1133
+ /** Decodes a request's params, refusing malformed ones as jsonrpc.Params does in Go. */
1134
+ function params(schema, raw) {
1135
+ const p = raw ?? {};
1136
+ if (!matches(schema, p))
1137
+ throw new ProtocolError(Code.Invalid, "malformed params");
1138
+ return p;
1139
+ }
1140
+ /** One served connection. */
1141
+ export class Server {
1142
+ host;
1143
+ #ext;
1144
+ #conn;
1145
+ #ready = false;
1146
+ #draining = false;
1147
+ #stateDir = "";
1148
+ #configDir = "";
1149
+ #containerDirs = {};
1150
+ #executorDirs = {};
1151
+ #resourceDirs = {};
1152
+ /** The handles of the attempts this connection started. */
1153
+ #runs = new ExecutorRuns(() => randomBytes(8).toString("hex"));
1154
+ #containerHost = "";
1155
+ #formerHosts = [];
1156
+ /** The container bindings the last configure named. */
1157
+ #containerUses = [];
1158
+ /** The sources the last configure registered, by name. */
1159
+ #sources = new Map();
1160
+ /** Emissions' commits, by commit ID, until the host has had its chance to call them. */
1161
+ #commits = new Map();
1162
+ /** The backup uploads in progress. */
1163
+ #uploads;
1164
+ constructor(ext, input, output) {
1165
+ this.#ext = ext;
1166
+ this.#conn = new Conn(input, output, (method, raw, signal) => this.#handle(method, raw, signal), {
1167
+ lane: laneOf,
1168
+ onProtocolError: (reason) => process.stderr.write(`open-conduit sdk: ${reason}\n`),
1169
+ });
1170
+ this.host = new Host((method, p, signal) => this.#conn.call(method, p, signal), () => ({ stateDir: this.#stateDir, configDir: this.#configDir }));
1171
+ this.#uploads = new BackupUploads((type) => ext._served().backups.get(type), this.host);
1172
+ void this.#conn.done.then(() => this.#uploads.close());
1173
+ }
1174
+ /** Resolves when the connection ends. */
1175
+ get done() {
1176
+ return this.#conn.done;
1177
+ }
1178
+ /** The private state directory the host gave at initialize. */
1179
+ get stateDir() {
1180
+ return this.#stateDir;
1181
+ }
1182
+ /** The operator's config file's directory the host named at initialize ("" for none), against which a relative path in a config resolves. */
1183
+ get configDir() {
1184
+ return this.#configDir;
1185
+ }
1186
+ /** Ends the connection. */
1187
+ close() {
1188
+ this.#conn.close();
1189
+ }
1190
+ async #handle(method, raw, signal) {
1191
+ if (method === "initialize")
1192
+ return this.#initialize(params(InitializeParams, raw));
1193
+ // The host must know the manifest before anything else is served.
1194
+ if (!this.#ready)
1195
+ throw new ProtocolError(Code.Invalid, "initialize first");
1196
+ if (this.#draining)
1197
+ throw new ProtocolError(Code.ShuttingDown, "shutting down");
1198
+ const served = this.#ext._served();
1199
+ switch (method) {
1200
+ case "configure":
1201
+ return this.#configure(params(ConfigureParams, raw), signal);
1202
+ case "shutdown":
1203
+ this.#draining = true;
1204
+ // As the Go SDK shuts its Exporter down: what it throws is ignored.
1205
+ try {
1206
+ await served.exporter?.shutdown?.({ host: this.host, signal });
1207
+ }
1208
+ catch {
1209
+ // The host is shutting the extension down either way.
1210
+ }
1211
+ return {};
1212
+ case "validate": {
1213
+ const p = params(ValidateParams, raw);
1214
+ // The host shows the operator a ConfigError's diagnostics; of any
1215
+ // other refusal, only that the config is invalid.
1216
+ if (p.kind === "extension")
1217
+ await served.entryTypes.get(p.type)?.validate(p.config);
1218
+ if (p.kind === "route")
1219
+ await served.routes.get(p.type)?.validate(p.config);
1220
+ if (p.kind === "verifier")
1221
+ await served.verifiers.get(p.type)?.validate(p.config);
1222
+ if (p.kind === "container")
1223
+ await served.containers.get(p.type)?.validate(p.config);
1224
+ if (p.kind === "resource" ||
1225
+ p.kind === "resource_mode" ||
1226
+ p.kind === "resource_sandbox" ||
1227
+ p.kind === "resource_site") {
1228
+ const r = served.resources.get(p.type);
1229
+ return r === undefined ? {} : r.validate(p);
1230
+ }
1231
+ if (p.kind === "sandbox")
1232
+ await served.sandboxes.get(p.type)?.validate(p.config);
1233
+ if (p.kind === "tunnel")
1234
+ await served.tunnels.get(p.type)?.validate(p.config);
1235
+ if (p.kind === "backup_destination")
1236
+ await served.backups.get(p.type)?.validate(p.config);
1237
+ if (p.kind === "executor")
1238
+ await served.executors.get(p.type)?.validate(p.config);
1239
+ if (p.kind === "executor_mode" ||
1240
+ p.kind === "executor_playbook" ||
1241
+ p.kind === "executor_probe" ||
1242
+ p.kind === "executor_folder") {
1243
+ const x = served.executors.get(p.type);
1244
+ if (x !== undefined)
1245
+ return x.answer(p);
1246
+ // As a type without the hook answers: no mode, playbook or
1247
+ // probe, and the folder's config unchanged.
1248
+ return p.kind === "executor_folder" ? { config: p.config ?? {} } : {};
1249
+ }
1250
+ return {};
1251
+ }
1252
+ case "operation.call":
1253
+ case "operation.wait":
1254
+ case "operation.emit": {
1255
+ const p = params(OperationParams, raw);
1256
+ const op = served.operations.get(p.operation);
1257
+ if (op === undefined)
1258
+ throw new ProtocolError(Code.Undeclared, "unknown operation");
1259
+ if (method !== `operation.${op.kind === "handler" ? "call" : op.kind}`)
1260
+ throw new ProtocolError(Code.Undeclared, "operation kind mismatch");
1261
+ const out = await op.run(p.input.data ?? {}, {
1262
+ host: this.host,
1263
+ authority: p.authority,
1264
+ requestId: p.request_id ?? "",
1265
+ signal,
1266
+ });
1267
+ if (op.kind === "handler")
1268
+ return { output: out };
1269
+ if (op.kind === "wait")
1270
+ return out;
1271
+ const { plan, commit } = out;
1272
+ if (commit === undefined)
1273
+ return plan;
1274
+ // Random, as Go's newID: a restarted process must never answer an ID the host holds from before with another emission's commit.
1275
+ const id = randomBytes(12).toString("hex");
1276
+ this.#commits.set(id, commit);
1277
+ // Dropped oldest first, whether the host called them or never did
1278
+ // (its transaction failed before acceptance).
1279
+ for (const old of this.#commits.keys()) {
1280
+ if (this.#commits.size <= 1024)
1281
+ break;
1282
+ this.#commits.delete(old);
1283
+ }
1284
+ return { ...plan, commit_id: id };
1285
+ }
1286
+ case "emit.commit": {
1287
+ const p = params(EmitCommitParams, raw);
1288
+ // It stays callable: the host may ask again when its transaction
1289
+ // runs again, possibly over a different acceptance.
1290
+ const commit = this.#commits.get(p.commit_id);
1291
+ if (commit === undefined)
1292
+ throw new ProtocolError(Code.NotFound, "unknown commit");
1293
+ return commit(p.emitted);
1294
+ }
1295
+ case "ingress.push": {
1296
+ const p = params(IngressPushParams, raw);
1297
+ const s = this.#source(p.name);
1298
+ if (s.type.push === undefined)
1299
+ throw notFound(method);
1300
+ const d = p.delivery;
1301
+ return s.type.push(s.spec, {
1302
+ id: d.id,
1303
+ receivedAt: d.received_at,
1304
+ ...(d.content_type ? { contentType: d.content_type } : {}),
1305
+ body: bytes(d.body),
1306
+ }, { host: this.host, signal });
1307
+ }
1308
+ case "ingress.reconcile": {
1309
+ const p = params(IngressReconcileParams, raw);
1310
+ const s = this.#source(p.name);
1311
+ if (s.type.reconcile === undefined)
1312
+ return { scan_id: p.scan.scan_id || "none", complete: false };
1313
+ return s.type.reconcile(s.spec, p.scan, { host: this.host, signal });
1314
+ }
1315
+ case "webhook.handle":
1316
+ return this.#webhook(params(WebhookHandleParams, raw), signal);
1317
+ case "route.match": {
1318
+ const p = params(RouteMatchParams, raw);
1319
+ const route = served.routes.get(p.handler);
1320
+ if (route === undefined)
1321
+ throw notFound(method);
1322
+ return route.match(p.input, { host: this.host, signal });
1323
+ }
1324
+ case "route.samples": {
1325
+ const p = params(RouteSamplesParams, raw);
1326
+ const route = served.routes.get(p.handler);
1327
+ if (route === undefined)
1328
+ throw notFound(method);
1329
+ return { samples: await route.samples(p, { host: this.host, signal }) };
1330
+ }
1331
+ case "work_kind.trigger": {
1332
+ const p = params(WorkKindTriggerParams, raw);
1333
+ const trigger = served.triggers.get(p.kind);
1334
+ if (trigger === undefined)
1335
+ throw notFound(method);
1336
+ return { index: trigger(p.inputs ?? []) };
1337
+ }
1338
+ case "recurrence.next": {
1339
+ const p = params(RecurrenceNextParams, raw);
1340
+ const fn = served.recurrences.get(p.kind);
1341
+ if (fn === undefined)
1342
+ throw notFound(method);
1343
+ const next = fn({ spec: p.spec ?? null, fired: p.fired, now: p.now });
1344
+ return {
1345
+ ...(next?.occurrence ? { occurrence: next.occurrence } : {}),
1346
+ ...(next?.next ? { next: next.next } : {}),
1347
+ };
1348
+ }
1349
+ case "dependency.filter": {
1350
+ const p = params(DependencyFilterParams, raw);
1351
+ if (served.filter === undefined)
1352
+ throw notFound(method);
1353
+ return { match: served.filter(p.filter, p.event) === true };
1354
+ }
1355
+ case "operation.gate": {
1356
+ const p = params(OperationGateParams, raw);
1357
+ if (served.gate === undefined)
1358
+ throw notFound(method);
1359
+ const plan = await served.gate({
1360
+ operation: p.operation,
1361
+ owner: p.owner,
1362
+ authority: p.authority,
1363
+ input: p.input,
1364
+ capability: p.capability ?? "",
1365
+ wants: p.wants ?? "",
1366
+ }, { host: this.host, signal });
1367
+ if (plan === undefined)
1368
+ return {};
1369
+ return {
1370
+ wait: {
1371
+ wait: plan.wait,
1372
+ ...(plan.dependencies?.length
1373
+ ? { dependencies: plan.dependencies }
1374
+ : {}),
1375
+ output: plan.output,
1376
+ },
1377
+ };
1378
+ }
1379
+ case "work.admit": {
1380
+ const p = params(WorkAdmitParams, raw);
1381
+ if (served.startGate === undefined)
1382
+ throw notFound(method);
1383
+ const hold = await served.startGate({ work: p.work, binding: p.binding, event: p.event }, { host: this.host, signal });
1384
+ if (hold === undefined)
1385
+ return {};
1386
+ return { hold: hold.reason ? { reason: hold.reason } : {} };
1387
+ }
1388
+ case "target.resolve": {
1389
+ const p = params(TargetResolveParams, raw);
1390
+ const fn = served.targets.get(p.kind);
1391
+ if (fn === undefined)
1392
+ throw notFound(method);
1393
+ const found = await fn({ scopeId: p.scope_id, name: p.name }, { host: this.host, signal });
1394
+ if (found === undefined)
1395
+ return { key: { source: "", external_id: "" }, ok: false };
1396
+ return {
1397
+ key: found.key,
1398
+ ...(found.types.length > 0 ? { types: [...found.types] } : {}),
1399
+ ok: true,
1400
+ };
1401
+ }
1402
+ case "segment.ended": {
1403
+ const p = params(SegmentEndedParams, raw);
1404
+ if (served.segmentEnd === undefined)
1405
+ throw notFound(method);
1406
+ await served.segmentEnd(p.execution_id, { host: this.host, signal });
1407
+ return {};
1408
+ }
1409
+ case "event.render": {
1410
+ const p = params(EventRenderParams, raw);
1411
+ if (served.render === undefined)
1412
+ throw notFound(method);
1413
+ const text = await served.render(p.event, { host: this.host, signal });
1414
+ return text === undefined ? { ok: false } : { text, ok: true };
1415
+ }
1416
+ case "task.run": {
1417
+ const fn = served.tasks.get(params(TaskRunParams, raw).task);
1418
+ if (fn === undefined)
1419
+ throw notFound(method);
1420
+ return (await fn({ host: this.host, signal })) ?? {};
1421
+ }
1422
+ case "secret.serve": {
1423
+ const p = params(SecretServeParams, raw);
1424
+ const spec = served.secrets.get(p.scheme);
1425
+ if (spec === undefined)
1426
+ throw notFound(method);
1427
+ const ctx = { host: this.host, signal };
1428
+ return secretCall(async () => {
1429
+ const value = await spec.serve({ scheme: p.scheme, reference: p.reference }, ctx);
1430
+ // An empty value is no value: the host refuses it as empty.
1431
+ return typeof value === "string" && value !== ""
1432
+ ? { value }
1433
+ : { code: "empty" };
1434
+ });
1435
+ }
1436
+ case "secret.store": {
1437
+ const p = params(SecretStoreParams, raw);
1438
+ const store = served.secrets.get(p.scheme)?.store;
1439
+ if (store === undefined)
1440
+ throw notFound(method);
1441
+ const ctx = { host: this.host, signal };
1442
+ return secretCall(async () => {
1443
+ const reference = await store({
1444
+ scheme: p.scheme,
1445
+ name: p.name,
1446
+ value: p.value,
1447
+ config: p.config ?? undefined,
1448
+ owner: p.owner,
1449
+ }, ctx);
1450
+ return typeof reference === "string" && reference !== ""
1451
+ ? { reference }
1452
+ : { code: "no_reference" };
1453
+ });
1454
+ }
1455
+ case "secret.delete": {
1456
+ const p = params(SecretDeleteParams, raw);
1457
+ const del = served.secrets.get(p.scheme)?.delete;
1458
+ if (del === undefined)
1459
+ throw notFound(method);
1460
+ const ctx = { host: this.host, signal };
1461
+ return secretCall(async () => {
1462
+ await del({ scheme: p.scheme, reference: p.reference, owner: p.owner }, ctx);
1463
+ return {};
1464
+ });
1465
+ }
1466
+ case "backup_destination.write":
1467
+ return this.#uploads.write(params(BackupWriteParams, raw));
1468
+ case "backup_destination.abort":
1469
+ return this.#uploads.abort(params(BackupAbortParams, raw));
1470
+ case "backup_destination.list":
1471
+ return this.#uploads.list(params(BackupListParams, raw), {
1472
+ host: this.host,
1473
+ signal,
1474
+ });
1475
+ case "backup_destination.files":
1476
+ return this.#uploads.files(params(BackupFilesParams, raw), {
1477
+ host: this.host,
1478
+ signal,
1479
+ });
1480
+ case "backup_destination.read":
1481
+ return this.#uploads.read(params(BackupReadParams, raw), {
1482
+ host: this.host,
1483
+ signal,
1484
+ });
1485
+ case "credential.verify": {
1486
+ const p = params(CredentialVerifyParams, raw);
1487
+ const v = served.verifiers.get(p.type);
1488
+ if (v === undefined)
1489
+ throw notFound(method);
1490
+ return v.verify(p, { host: this.host, signal });
1491
+ }
1492
+ case "container_provider.plan":
1493
+ case "container_provider.create":
1494
+ case "container_provider.signal":
1495
+ case "container_provider.stop":
1496
+ case "container_provider.inspect":
1497
+ case "container_provider.list":
1498
+ case "container_provider.remove":
1499
+ case "container_provider.forward":
1500
+ case "container_provider.place":
1501
+ case "container_provider.site_run":
1502
+ case "container_provider.collect":
1503
+ case "container_provider.reattach": {
1504
+ const type = params(typed, raw).type;
1505
+ const c = served.containers.get(type);
1506
+ if (c === undefined)
1507
+ throw notFound(method);
1508
+ return c.serve(method, raw, {
1509
+ host: this.host,
1510
+ signal,
1511
+ dir: this.#containerDirs[type] ?? "",
1512
+ hostLabel: this.#containerHost,
1513
+ formerHosts: [...this.#formerHosts],
1514
+ uses: this.#containerUses.filter((u) => u.provider === type),
1515
+ });
1516
+ }
1517
+ case "provider.acquire":
1518
+ case "provider.lookup":
1519
+ case "provider.reconcile":
1520
+ case "provider.sweep":
1521
+ case "provider.unsaved": {
1522
+ const type = params(typed, raw).type;
1523
+ const r = served.resources.get(type);
1524
+ if (r === undefined)
1525
+ throw notFound(method);
1526
+ const ctx = { host: this.host, signal };
1527
+ return r.serve(method, raw, {
1528
+ ...ctx,
1529
+ dir: this.#resourceDirs[type] ?? "",
1530
+ stateDir: this.#stateDir,
1531
+ site: (id) => site(ctx, type, id),
1532
+ });
1533
+ }
1534
+ case "sandbox_provider.plan":
1535
+ case "sandbox_provider.adopt": {
1536
+ const type = params(typed, raw).type;
1537
+ const sb = served.sandboxes.get(type);
1538
+ if (sb === undefined)
1539
+ throw notFound(method);
1540
+ return sb.serve(method, raw, {
1541
+ host: this.host,
1542
+ signal,
1543
+ stateDir: this.#stateDir,
1544
+ });
1545
+ }
1546
+ case "tunnel.run": {
1547
+ const type = params(typed, raw).type;
1548
+ const tn = served.tunnels.get(type);
1549
+ if (tn === undefined)
1550
+ throw notFound(method);
1551
+ return tn.run(raw, { host: this.host, signal });
1552
+ }
1553
+ case "executor.run":
1554
+ case "executor.recover":
1555
+ case "executor.resume":
1556
+ case "executor.wait":
1557
+ case "executor.sweep":
1558
+ case "executor.interrupt":
1559
+ case "executor.inject":
1560
+ case "executor.stop":
1561
+ case "executor.forget":
1562
+ case "executor.attach":
1563
+ case "executor.live":
1564
+ case "executor.container_attach":
1565
+ case "executor.interactive_launch": {
1566
+ const name = params(named, raw).executor ?? "";
1567
+ const x = served.executors.get(name);
1568
+ if (x === undefined)
1569
+ throw notFound(method);
1570
+ return x.serve(method, raw, {
1571
+ host: this.host,
1572
+ signal,
1573
+ stateDir: this.#executorDirs[name] || this.#stateDir,
1574
+ }, this.#runs);
1575
+ }
1576
+ case "work.actions": {
1577
+ const list = served.actions?.list;
1578
+ if (list === undefined)
1579
+ throw notFound(method);
1580
+ return list(params(WorkActionsParams, raw).target, {
1581
+ host: this.host,
1582
+ signal,
1583
+ });
1584
+ }
1585
+ case "work.act": {
1586
+ const act = served.actions?.act;
1587
+ if (act === undefined)
1588
+ throw notFound(method);
1589
+ return act(params(WorkActParams, raw), { host: this.host, signal });
1590
+ }
1591
+ case "work.requests": {
1592
+ const requests = served.actions?.requests;
1593
+ if (requests === undefined)
1594
+ throw notFound(method);
1595
+ return requests(params(WorkRequestsParams, raw).target, {
1596
+ host: this.host,
1597
+ signal,
1598
+ });
1599
+ }
1600
+ case "view.render": {
1601
+ const panels = served.actions?.panels;
1602
+ if (panels === undefined)
1603
+ throw notFound(method);
1604
+ return panels(params(ViewRenderParams, raw).target, {
1605
+ host: this.host,
1606
+ signal,
1607
+ });
1608
+ }
1609
+ case "telemetry.export": {
1610
+ const p = params(TelemetryExportParams, raw);
1611
+ const exporter = served.exporter;
1612
+ if (exporter === undefined)
1613
+ throw notFound(method);
1614
+ await exporter.export(p.records ?? [], { host: this.host, signal });
1615
+ return {};
1616
+ }
1617
+ case "telemetry.metrics": {
1618
+ const p = params(TelemetryMetricsParams, raw);
1619
+ const metrics = served.metrics;
1620
+ if (metrics === undefined)
1621
+ throw notFound(method);
1622
+ await metrics(p.metrics ?? [], { host: this.host, signal });
1623
+ return {};
1624
+ }
1625
+ case "telemetry.sink": {
1626
+ const p = params(TelemetryEvent, raw);
1627
+ const sink = served.sink;
1628
+ if (sink === undefined)
1629
+ throw notFound(method);
1630
+ await sink(p, { host: this.host, signal });
1631
+ return {};
1632
+ }
1633
+ case "run.environment": {
1634
+ const p = params(RunEnvironmentParams, raw);
1635
+ const fn = served.runEnvironment;
1636
+ if (fn === undefined)
1637
+ throw notFound(method);
1638
+ const layer = await fn({
1639
+ owner: p.owner,
1640
+ connection: p.connection ?? "",
1641
+ binding: p.binding ?? "",
1642
+ filesDir: p.files_dir ?? "",
1643
+ }, { host: this.host, signal });
1644
+ const out = {};
1645
+ if (layer.env !== undefined && Object.keys(layer.env).length > 0)
1646
+ out.env = { ...layer.env };
1647
+ if (layer.files !== undefined && Object.keys(layer.files).length > 0)
1648
+ out.files = { ...layer.files };
1649
+ return out;
1650
+ }
1651
+ case "work.annotate": {
1652
+ const annotate = served.annotate;
1653
+ if (annotate === undefined)
1654
+ throw notFound(method);
1655
+ const lines = await annotate(params(WorkAnnotateParams, raw).work, {
1656
+ host: this.host,
1657
+ signal,
1658
+ });
1659
+ return lines.length > 0
1660
+ ? {
1661
+ annotations: lines.map((a) => ({ name: a.name, value: a.value })),
1662
+ }
1663
+ : {};
1664
+ }
1665
+ case "config.candidate": {
1666
+ const p = params(ConfigCandidateParams, raw);
1667
+ const fn = served.configCandidate;
1668
+ if (fn === undefined)
1669
+ throw notFound(method);
1670
+ return candidateResult(await fn(p.work, { host: this.host, signal }));
1671
+ }
1672
+ case "setup.run": {
1673
+ const p = params(SetupRunParams, raw);
1674
+ const setup = served.setup;
1675
+ if (setup === undefined || setup.type !== p.type)
1676
+ throw notFound(method);
1677
+ const ctx = { host: this.host, signal };
1678
+ return setupResult(await setup.run([...(p.args ?? [])], setupHost(this.host, p, signal), ctx));
1679
+ }
1680
+ case "probe.serve": {
1681
+ const p = params(ProbeRunParams, raw);
1682
+ const probe = served.probes.get(p.name);
1683
+ if (probe === undefined)
1684
+ throw notFound(method);
1685
+ return probe.serve(p, { host: this.host, signal });
1686
+ }
1687
+ case "check.run": {
1688
+ const p = params(CheckRunParams, raw);
1689
+ const fn = served.checks.get(p.check);
1690
+ if (fn === undefined)
1691
+ throw notFound(method);
1692
+ try {
1693
+ return result(true, await fn({
1694
+ host: this.host,
1695
+ deep: p.deep === true,
1696
+ config: p.config,
1697
+ signal,
1698
+ }));
1699
+ }
1700
+ catch (err) {
1701
+ return result(false, err instanceof Error ? err.message : String(err));
1702
+ }
1703
+ }
1704
+ }
1705
+ throw notFound(method);
1706
+ }
1707
+ #initialize(p) {
1708
+ const offered = p.protocol_versions ?? [];
1709
+ const common = offered.filter((v) => this.#ext.manifest.protocol.includes(v));
1710
+ if (common.length === 0)
1711
+ throw new ProtocolError(Code.UnsupportedVersion, "no common protocol version");
1712
+ this.#ready = true;
1713
+ this.#stateDir = p.state_dir;
1714
+ this.#configDir = p.config_dir ?? "";
1715
+ this.#containerDirs = { ...(p.container_dirs ?? {}) };
1716
+ this.#executorDirs = { ...(p.executor_dirs ?? {}) };
1717
+ this.#resourceDirs = { ...(p.resource_dirs ?? {}) };
1718
+ this.#containerHost = p.container_host ?? "";
1719
+ this.#formerHosts = [...(p.container_former_hosts ?? [])];
1720
+ return {
1721
+ protocol_version: Math.max(...common),
1722
+ manifest: this.#ext.manifest,
1723
+ };
1724
+ }
1725
+ async #configure(p, signal) {
1726
+ const { entryTypes, migrate } = this.#ext._served();
1727
+ const ctx = { host: this.host, signal };
1728
+ if (p.kv.stored < p.kv.declared) {
1729
+ // From layout 0 there is nothing stored to migrate, so no migration is needed.
1730
+ if (migrate === undefined && p.kv.stored !== 0)
1731
+ throw new ProtocolError(Code.Unsupported, "no KV migration");
1732
+ await migrate?.(p.kv.stored, p.kv.declared, ctx);
1733
+ }
1734
+ const sources = new Map();
1735
+ const decls = [];
1736
+ const paths = [];
1737
+ for (const entryType of entryTypes.values())
1738
+ for (const r of await entryType.configure(p.entries ?? [], ctx)) {
1739
+ const { decl, ...registered } = r;
1740
+ if (sources.has(decl.name))
1741
+ throw new ProtocolError(Code.Invalid, `source ${decl.name} is registered twice`);
1742
+ sources.set(decl.name, registered);
1743
+ decls.push(decl);
1744
+ if (registered.spec.webhook)
1745
+ paths.push(`/${decl.name}`);
1746
+ }
1747
+ // Replaced only once the whole generation is read, so a refused one keeps the last.
1748
+ this.#sources = sources;
1749
+ this.#containerUses = [...(p.containers ?? [])];
1750
+ const out = {
1751
+ kv_version: this.#ext.manifest.kv_version ?? 0,
1752
+ };
1753
+ if (decls.length > 0)
1754
+ out.sources = decls;
1755
+ if (paths.length > 0)
1756
+ out.webhook_paths = paths;
1757
+ return out;
1758
+ }
1759
+ #source(name) {
1760
+ const s = this.#sources.get(name);
1761
+ if (s === undefined)
1762
+ throw new ProtocolError(Code.NotFound, "unknown source");
1763
+ return s;
1764
+ }
1765
+ async #webhook(p, signal) {
1766
+ // The source whose path is the request's, or the deepest one above it.
1767
+ let found;
1768
+ for (const [name, s] of this.#sources) {
1769
+ const path = `/${name}`;
1770
+ if (s.spec.webhook &&
1771
+ s.type.webhook !== undefined &&
1772
+ (p.path === path || p.path.startsWith(`${path}/`)) &&
1773
+ (found === undefined || name.length > found.spec.name.length))
1774
+ found = s;
1775
+ }
1776
+ if (found === undefined)
1777
+ return { status: 404 };
1778
+ const source = found;
1779
+ const headers = new Headers();
1780
+ for (const [k, vs] of Object.entries(p.header ?? {}))
1781
+ for (const v of vs)
1782
+ headers.append(k, v);
1783
+ const request = {
1784
+ path: p.path,
1785
+ method: p.method,
1786
+ query: p.query ?? "",
1787
+ headers,
1788
+ body: bytes(p.body),
1789
+ receivedAt: p.received_at,
1790
+ forwardId: p.forward_id ?? "",
1791
+ };
1792
+ try {
1793
+ const r = await source.type.webhook(source.spec, request, {
1794
+ host: this.host,
1795
+ signal,
1796
+ deliver: (d) => this.host.deliver(source.spec.name, { ...d, receivedAt: d.receivedAt ?? p.received_at }, signal),
1797
+ });
1798
+ const out = { status: r.status ?? 200 };
1799
+ if (r.headers !== undefined)
1800
+ out.header = Object.fromEntries(Object.entries(r.headers).map(([k, v]) => [
1801
+ k,
1802
+ Array.isArray(v) ? v : [v],
1803
+ ]));
1804
+ if (r.body !== undefined)
1805
+ out.body = base64(toBytes(r.body));
1806
+ return out;
1807
+ }
1808
+ catch (err) {
1809
+ // The sender retries a 5xx; nothing is accepted until deliver answers.
1810
+ process.stderr.write(`open-conduit sdk: webhook ${p.path}: ${err instanceof Error ? err.message : String(err)}\n`);
1811
+ return { status: 500 };
1812
+ }
1813
+ }
1814
+ }
1815
+ function bytes(b64) {
1816
+ return b64 === undefined
1817
+ ? new Uint8Array()
1818
+ : new Uint8Array(Buffer.from(b64, "base64"));
1819
+ }
1820
+ function result(ok, detail) {
1821
+ return detail === "" ? { ok } : { ok, detail };
1822
+ }