@open-conduit/sdk 7.0.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/actions.d.ts +145 -0
  2. package/dist/actions.js +281 -0
  3. package/dist/actiontest.d.ts +80 -0
  4. package/dist/actiontest.js +190 -0
  5. package/dist/artifactstore.d.ts +133 -0
  6. package/dist/artifactstore.js +364 -0
  7. package/dist/backup.d.ts +99 -0
  8. package/dist/backup.js +178 -0
  9. package/dist/containertest.d.ts +71 -0
  10. package/dist/containertest.js +294 -0
  11. package/dist/errors.d.ts +28 -0
  12. package/dist/errors.js +37 -0
  13. package/dist/executor.d.ts +374 -0
  14. package/dist/executor.js +556 -0
  15. package/dist/executortest.d.ts +183 -0
  16. package/dist/executortest.js +534 -0
  17. package/dist/extension.d.ts +496 -1
  18. package/dist/extension.js +1152 -4
  19. package/dist/feed.d.ts +20 -0
  20. package/dist/feed.js +88 -0
  21. package/dist/forward.d.ts +38 -0
  22. package/dist/forward.js +163 -0
  23. package/dist/forwardca.d.ts +21 -0
  24. package/dist/forwardca.js +144 -0
  25. package/dist/hooks.d.ts +108 -0
  26. package/dist/hooks.js +13 -0
  27. package/dist/host.d.ts +166 -2
  28. package/dist/host.js +235 -2
  29. package/dist/index.d.ts +27 -3
  30. package/dist/index.js +14 -2
  31. package/dist/probe.d.ts +61 -0
  32. package/dist/probe.js +92 -0
  33. package/dist/providertest.d.ts +59 -0
  34. package/dist/providertest.js +168 -0
  35. package/dist/resources.d.ts +208 -0
  36. package/dist/resources.js +303 -0
  37. package/dist/sandbox.d.ts +84 -0
  38. package/dist/sandbox.js +85 -0
  39. package/dist/setup.d.ts +145 -0
  40. package/dist/setup.js +179 -0
  41. package/dist/setuptest.d.ts +90 -0
  42. package/dist/setuptest.js +319 -0
  43. package/dist/storetest.d.ts +64 -0
  44. package/dist/storetest.js +740 -0
  45. package/dist/telemetry.d.ts +86 -0
  46. package/dist/telemetry.js +46 -0
  47. package/dist/testing.d.ts +591 -2
  48. package/dist/testing.js +1460 -6
  49. package/dist/toolbelt.d.ts +91 -0
  50. package/dist/toolbelt.js +216 -0
  51. package/dist/tunnel.d.ts +62 -0
  52. package/dist/tunnel.js +93 -0
  53. package/dist/wire.d.ts +4060 -348
  54. package/dist/wire.js +1583 -0
  55. package/package.json +1 -1
package/dist/extension.js CHANGED
@@ -7,12 +7,34 @@
7
7
  // subcommands (package-manifest, package-certification) and otherwise
8
8
  // serves protocol version 1 on stdin and stdout until stdin closes.
9
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";
10
18
  import { Writable } from "node:stream";
11
- import { Code, ConfigError, OperationError, ProtocolError } from "./errors.js";
19
+ import { Code, ConfigError, CredentialRefusal, OperationError, ProtocolError, SecretRefusal, } from "./errors.js";
12
20
  import { Host, base64, toBytes } from "./host.js";
21
+ import { ExecutorRuns, executorHandler, } from "./executor.js";
13
22
  import { Conn, laneOf } from "./jsonrpc.js";
14
- import { check, diagnose, isRecord, matches, } from "./schema.js";
15
- import { CheckRunParams, ConfigureParams, EmitCommitParams, IngressPushParams, IngressReconcileParams, InitializeParams, OperationParams, RouteMatchParams, RouteSamplesParams, TaskRunParams, ValidateParams, WebhookHandleParams, WorkKindTriggerParams, } from "./wire.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
+ };
16
38
  /** The protocol versions this SDK speaks. */
17
39
  export const ProtocolVersions = [1];
18
40
  /** Decodes config through schema, reporting what it refuses at each field. */
@@ -45,6 +67,30 @@ export class Extension {
45
67
  #entryTypes = new Map();
46
68
  #routes = new Map();
47
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;
48
94
  #migrate;
49
95
  #certification;
50
96
  constructor(name, o) {
@@ -284,6 +330,467 @@ export class Extension {
284
330
  });
285
331
  return this;
286
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
+ }
287
794
  /** Registers a doctor check and declares it. */
288
795
  check(name, fn, o = {}) {
289
796
  this.#checks.set(name, fn);
@@ -368,6 +875,30 @@ export class Extension {
368
875
  entryTypes: this.#entryTypes,
369
876
  routes: this.#routes,
370
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,
371
902
  migrate: this.#migrate,
372
903
  };
373
904
  }
@@ -387,6 +918,218 @@ function print(v) {
387
918
  function notFound(method) {
388
919
  return new ProtocolError(Code.MethodNotFound, `no such method ${method}`);
389
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
+ }
390
1133
  /** Decodes a request's params, refusing malformed ones as jsonrpc.Params does in Go. */
391
1134
  function params(schema, raw) {
392
1135
  const p = raw ?? {};
@@ -402,17 +1145,31 @@ export class Server {
402
1145
  #ready = false;
403
1146
  #draining = false;
404
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 = [];
405
1158
  /** The sources the last configure registered, by name. */
406
1159
  #sources = new Map();
407
1160
  /** Emissions' commits, by commit ID, until the host has had its chance to call them. */
408
1161
  #commits = new Map();
1162
+ /** The backup uploads in progress. */
1163
+ #uploads;
409
1164
  constructor(ext, input, output) {
410
1165
  this.#ext = ext;
411
1166
  this.#conn = new Conn(input, output, (method, raw, signal) => this.#handle(method, raw, signal), {
412
1167
  lane: laneOf,
413
1168
  onProtocolError: (reason) => process.stderr.write(`open-conduit sdk: ${reason}\n`),
414
1169
  });
415
- this.host = new Host((method, p, signal) => this.#conn.call(method, p, signal));
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());
416
1173
  }
417
1174
  /** Resolves when the connection ends. */
418
1175
  get done() {
@@ -422,6 +1179,10 @@ export class Server {
422
1179
  get stateDir() {
423
1180
  return this.#stateDir;
424
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
+ }
425
1186
  /** Ends the connection. */
426
1187
  close() {
427
1188
  this.#conn.close();
@@ -440,6 +1201,13 @@ export class Server {
440
1201
  return this.#configure(params(ConfigureParams, raw), signal);
441
1202
  case "shutdown":
442
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
+ }
443
1211
  return {};
444
1212
  case "validate": {
445
1213
  const p = params(ValidateParams, raw);
@@ -449,6 +1217,36 @@ export class Server {
449
1217
  await served.entryTypes.get(p.type)?.validate(p.config);
450
1218
  if (p.kind === "route")
451
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
+ }
452
1250
  return {};
453
1251
  }
454
1252
  case "operation.call":
@@ -537,12 +1335,355 @@ export class Server {
537
1335
  throw notFound(method);
538
1336
  return { index: trigger(p.inputs ?? []) };
539
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
+ }
540
1416
  case "task.run": {
541
1417
  const fn = served.tasks.get(params(TaskRunParams, raw).task);
542
1418
  if (fn === undefined)
543
1419
  throw notFound(method);
544
1420
  return (await fn({ host: this.host, signal })) ?? {};
545
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
+ }
546
1687
  case "check.run": {
547
1688
  const p = params(CheckRunParams, raw);
548
1689
  const fn = served.checks.get(p.check);
@@ -570,6 +1711,12 @@ export class Server {
570
1711
  throw new ProtocolError(Code.UnsupportedVersion, "no common protocol version");
571
1712
  this.#ready = true;
572
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 ?? [])];
573
1720
  return {
574
1721
  protocol_version: Math.max(...common),
575
1722
  manifest: this.#ext.manifest,
@@ -599,6 +1746,7 @@ export class Server {
599
1746
  }
600
1747
  // Replaced only once the whole generation is read, so a refused one keeps the last.
601
1748
  this.#sources = sources;
1749
+ this.#containerUses = [...(p.containers ?? [])];
602
1750
  const out = {
603
1751
  kv_version: this.#ext.manifest.kv_version ?? 0,
604
1752
  };