@fungi.computer/oyster 0.37.2 → 0.38.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 (86) hide show
  1. package/README.md +5 -4
  2. package/dist/agents.js +9 -2
  3. package/dist/app-builds.d.ts +1 -1
  4. package/dist/app-region.d.ts +94 -0
  5. package/dist/app-region.js +316 -0
  6. package/dist/authorization.d.ts +58 -9
  7. package/dist/authorization.js +56 -11
  8. package/dist/boot-host-script.js +1 -1
  9. package/dist/build/candidate-builder.d.ts +1 -1
  10. package/dist/build/candidate-cli.mjs +284 -17
  11. package/dist/build/effect.d.ts +3 -3
  12. package/dist/build/submission-contract.d.ts +1 -1
  13. package/dist/build/workspace-build.d.ts +2 -2
  14. package/dist/channels/discord-replies.d.ts +8 -1
  15. package/dist/channels/discord-replies.js +80 -29
  16. package/dist/cloudflare.d.ts +1 -0
  17. package/dist/cloudflare.js +11 -0
  18. package/dist/credential-migration-001.d.ts +14 -0
  19. package/dist/credential-migration-001.js +13 -0
  20. package/dist/credential-migration-002.d.ts +38 -0
  21. package/dist/credential-migration-002.js +74 -0
  22. package/dist/embed-metafiles.js +2 -2
  23. package/dist/embed-scripts.js +1 -1
  24. package/dist/host.d.ts +2 -0
  25. package/dist/host.js +20 -1
  26. package/dist/index.d.ts +15 -1
  27. package/dist/index.js +19 -0
  28. package/dist/invocation.d.ts +165 -0
  29. package/dist/invocation.js +67 -0
  30. package/dist/keys.d.ts +4 -3
  31. package/dist/keys.js +5 -4
  32. package/dist/mcp-owner.d.ts +4 -3
  33. package/dist/mcp-owner.js +3 -2
  34. package/dist/page/mount.js +5 -1
  35. package/dist/page/region.d.ts +6 -0
  36. package/dist/page/region.js +12 -0
  37. package/dist/page-config.d.ts +2 -0
  38. package/dist/page-config.js +2 -0
  39. package/dist/page-script.js +2 -2
  40. package/dist/source/seed-receipt.d.ts +1 -1
  41. package/dist/source/template-seed.d.ts +1 -1
  42. package/dist/standalone/agent-connections.d.ts +49 -1
  43. package/dist/standalone/agent-connections.js +101 -12
  44. package/dist/standalone/agent-self.js +2 -1
  45. package/dist/standalone/agents.d.ts +7 -3
  46. package/dist/standalone/agents.js +42 -19
  47. package/dist/standalone/computer-fleet.d.ts +12 -6
  48. package/dist/standalone/computer-fleet.js +70 -29
  49. package/dist/standalone/computer.js +39 -14
  50. package/dist/standalone/instance.d.ts +3 -1
  51. package/dist/standalone/instance.js +8 -0
  52. package/dist/standalone/model-key-vault.d.ts +33 -4
  53. package/dist/standalone/model-key-vault.js +74 -17
  54. package/dist/standalone/preview.js +11 -10
  55. package/dist/standalone/try-cli.d.ts +12 -2
  56. package/dist/standalone/try-cli.js +170 -32
  57. package/dist/standalone/try-worker.d.ts +2 -0
  58. package/dist/standalone/try-worker.js +15 -0
  59. package/dist/standalone/worker.js +3 -3
  60. package/dist/standalone/workflow-host.d.ts +1 -1
  61. package/dist/standalone/workflows.d.ts +3 -3
  62. package/dist/standalone/workflows.js +7 -0
  63. package/dist/testing/capabilities.d.ts +2 -0
  64. package/dist/testing/capabilities.js +2 -0
  65. package/dist/webhook-custody.d.ts +14 -3
  66. package/dist/webhook-custody.js +165 -43
  67. package/dist/webhooks.d.ts +1 -1
  68. package/dist/webhooks.js +15 -3
  69. package/dist/workers-git.d.ts +24 -8
  70. package/dist/workers-git.js +105 -15
  71. package/dist/workers.d.ts +16 -0
  72. package/dist/workers.js +95 -5
  73. package/docs/api/apps.md +31 -31
  74. package/docs/api/authorization.md +119 -17
  75. package/docs/api/build-contract.md +8 -8
  76. package/docs/api/build.md +163 -174
  77. package/docs/api/cloudflare.md +171 -0
  78. package/docs/api/host.md +1 -0
  79. package/docs/api/index.md +23 -0
  80. package/docs/api/invocation.md +623 -23
  81. package/docs/api/keys.md +6 -6
  82. package/docs/api/pack.md +3 -3
  83. package/docs/api/page/mount.md +22 -20
  84. package/docs/api/workers-git.md +273 -157
  85. package/docs/api/workers.md +257 -175
  86. package/package.json +19 -18
@@ -24,6 +24,10 @@ import { oysterKeyVocabulary, } from "./keys.js";
24
24
  import { agentCapabilities, agentApprovalRoutes, connectionRoutes, modelKeyRoutes, } from "./agents.js";
25
25
  import { createArtifactsRestNamespace, } from "@fungi.computer/burrow";
26
26
  import { attemptWebhook } from "./webhook-delivery.js";
27
+ import * as Effect from "effect/Effect";
28
+ import * as Result from "effect/Result";
29
+ import { CredentialError } from "@fungi.computer/veil/credential-store";
30
+ import { credentialMigration002, } from "./credential-migration-002.js";
27
31
  import { createRecipientDeliveries, } from "./event-recipients.js";
28
32
  import { createOyster, } from "./host.js";
29
33
  import { oysterPrincipalIsOwner, owner as ownerRoute, routes as routeTable, } from "./authorization.js";
@@ -503,6 +507,35 @@ const deliveryRow = Schema.Struct({
503
507
  updated_at: Schema.Number,
504
508
  });
505
509
  const typesSchema = Schema.fromJsonString(Schema.Array(Schema.String));
510
+ const subscriptionContext = (id) => ["webhook-subscription", id];
511
+ const columnNames = Schema.Array(Schema.Struct({ name: Schema.String }));
512
+ function ensureSubscriptions(sql) {
513
+ sql.exec(`CREATE TABLE IF NOT EXISTS oyster_subscriptions (
514
+ id TEXT PRIMARY KEY, installation_id TEXT NOT NULL, url TEXT NOT NULL, sealed_secret TEXT NOT NULL,
515
+ types TEXT NOT NULL, created_at INTEGER NOT NULL) STRICT`);
516
+ }
517
+ const legacySubscription = Schema.Struct({
518
+ id: Schema.String,
519
+ installation_id: Schema.String,
520
+ url: Schema.String,
521
+ secret: Schema.String,
522
+ types: Schema.String,
523
+ created_at: Schema.Number,
524
+ });
525
+ /** Migration 002's step: a subscription's signing secret is sealed. */
526
+ const webhookSubscriptions002 = {
527
+ table: "oyster_subscriptions",
528
+ plaintext: (columns) => columns.includes("secret"),
529
+ secretColumns: ["secret"],
530
+ ensure: ensureSubscriptions,
531
+ async seal(sealer, raw) {
532
+ const { secret, ...row } = Schema.decodeUnknownSync(legacySubscription)(raw);
533
+ return {
534
+ ...row,
535
+ sealed_secret: await sealer.seal(subscriptionContext(row.id), secret),
536
+ };
537
+ },
538
+ };
506
539
  function toSubscription(row) {
507
540
  const decoded = Schema.decodeUnknownSync(subscriptionRow)(row);
508
541
  return {
@@ -517,15 +550,15 @@ function toSubscription(row) {
517
550
  * The tenant's App event delivery owner: webhook subscriptions with signed,
518
551
  * retried deliveries, and host recipients with durable per-recipient records.
519
552
  * An emit commits here and returns; every delivery happens on the alarm.
553
+ * Signing secrets rest only in this object's S1 envelope.
520
554
  */
521
555
  export class OysterWebhooks extends DurableObject {
522
556
  #recipients;
557
+ #secrets;
523
558
  constructor(ctx, env) {
524
559
  super(ctx, env);
560
+ ensureSubscriptions(ctx.storage.sql);
525
561
  ctx.storage.sql.exec(`
526
- CREATE TABLE IF NOT EXISTS oyster_subscriptions (
527
- id TEXT PRIMARY KEY, installation_id TEXT NOT NULL, url TEXT NOT NULL, secret TEXT NOT NULL,
528
- types TEXT NOT NULL, created_at INTEGER NOT NULL) STRICT;
529
562
  CREATE TABLE IF NOT EXISTS oyster_deliveries (
530
563
  id TEXT PRIMARY KEY, subscription TEXT NOT NULL, type TEXT NOT NULL, body TEXT NOT NULL,
531
564
  state TEXT NOT NULL, attempts INTEGER NOT NULL, next_at INTEGER NOT NULL,
@@ -538,6 +571,29 @@ export class OysterWebhooks extends DurableObject {
538
571
  wake: (at) => this.wakeBy(at),
539
572
  deliver: (recipient, event) => this.deliverToRecipient({ recipient, event }),
540
573
  });
574
+ // Plaintext secrets an older Oyster left are sealed by the next alarm,
575
+ // which the platform retries while no keyring is configured.
576
+ const columns = Schema.decodeUnknownSync(columnNames)(ctx.storage.sql.exec("PRAGMA table_info(oyster_subscriptions)").toArray()).map(({ name }) => name);
577
+ if (webhookSubscriptions002.plaintext(columns))
578
+ void ctx.blockConcurrencyWhile(() => this.wakeBy(Date.now()));
579
+ }
580
+ /** The host's S1 sealer for this object; none means no keyring is configured. */
581
+ credentialSealer() {
582
+ return undefined;
583
+ }
584
+ secrets() {
585
+ if (this.#secrets !== undefined)
586
+ return this.#secrets;
587
+ const sealer = this.credentialSealer();
588
+ this.#secrets = {
589
+ sealer,
590
+ ready: credentialMigration002({
591
+ store: this.ctx.storage,
592
+ sealer,
593
+ tables: [webhookSubscriptions002],
594
+ }),
595
+ };
596
+ return this.#secrets;
541
597
  }
542
598
  /**
543
599
  * A root that names host recipients delivers to them here. This host has
@@ -557,7 +613,7 @@ export class OysterWebhooks extends DurableObject {
557
613
  return this.#recipients.deliveries(recipient);
558
614
  }
559
615
  /** Subscribe `url` to an installation's events; returns the secret once. */
560
- subscribe(input) {
616
+ async subscribe(input) {
561
617
  const secret = input.secret ??
562
618
  `whsec_${btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(24))))}`;
563
619
  const subscription = {
@@ -567,7 +623,21 @@ export class OysterWebhooks extends DurableObject {
567
623
  types: [...input.types],
568
624
  createdAt: Date.now(),
569
625
  };
570
- this.ctx.storage.sql.exec("INSERT INTO oyster_subscriptions (id, installation_id, url, secret, types, created_at) VALUES (?, ?, ?, ?, ?, ?)", subscription.id, subscription.installationId, subscription.url, secret, JSON.stringify(subscription.types), subscription.createdAt);
626
+ let sealed;
627
+ try {
628
+ const { sealer, ready } = this.secrets();
629
+ await ready();
630
+ if (sealer === undefined)
631
+ throw new CredentialError("unavailable");
632
+ sealed = await sealer.seal(subscriptionContext(subscription.id), secret);
633
+ }
634
+ catch (cause) {
635
+ // Domain refusals cross the DO RPC boundary as data.
636
+ if (cause instanceof CredentialError && cause.code === "unavailable")
637
+ return { error: "unavailable" };
638
+ throw cause;
639
+ }
640
+ this.ctx.storage.sql.exec("INSERT INTO oyster_subscriptions (id, installation_id, url, sealed_secret, types, created_at) VALUES (?, ?, ?, ?, ?, ?)", subscription.id, subscription.installationId, subscription.url, sealed, JSON.stringify(subscription.types), subscription.createdAt);
571
641
  return { subscription, secret };
572
642
  }
573
643
  /** Every subscription. */
@@ -625,17 +695,30 @@ export class OysterWebhooks extends DurableObject {
625
695
  /** Deliver due webhooks and recipient rows, then schedule the next retry. */
626
696
  async alarm() {
627
697
  await this.#recipients.drain();
698
+ const { sealer, ready } = this.secrets();
699
+ await ready();
628
700
  const now = Date.now();
629
701
  const due = this.ctx.storage.sql
630
702
  .exec("SELECT id, subscription, type, body, attempts FROM oyster_deliveries WHERE state = 'pending' AND next_at <= ? ORDER BY next_at LIMIT 25", now)
631
703
  .toArray();
632
704
  await Promise.all(due.map(async (delivery) => {
633
705
  const target = this.ctx.storage.sql
634
- .exec("SELECT url, secret FROM oyster_subscriptions WHERE id = ?", delivery.subscription)
706
+ .exec("SELECT url, sealed_secret FROM oyster_subscriptions WHERE id = ?", delivery.subscription)
635
707
  .toArray()[0];
636
708
  let status = null;
637
- if (target !== undefined) {
638
- const attempt = await attemptWebhook(target, delivery);
709
+ // A secret that does not open counts as a failed attempt: retried,
710
+ // then failed like a refusal, never sent unsigned.
711
+ const secret = target === undefined
712
+ ? undefined
713
+ : await Effect.runPromise(Effect.result(Effect.tryPromise(async () => {
714
+ if (sealer === undefined)
715
+ throw new CredentialError("unavailable");
716
+ return sealer.open(subscriptionContext(delivery.subscription), target.sealed_secret);
717
+ })));
718
+ if (target !== undefined &&
719
+ secret !== undefined &&
720
+ Result.isSuccess(secret)) {
721
+ const attempt = await attemptWebhook({ url: target.url, secret: secret.success }, delivery);
639
722
  status = attempt.kind === "response" ? attempt.status : null;
640
723
  }
641
724
  const attempts = delivery.attempts + 1;
@@ -810,10 +893,13 @@ export function gitAdminRoutes(env, scope) {
810
893
  const body = Schema.decodeUnknownOption(subscribeSchema)(await context.req.json());
811
894
  if (body._tag === "None")
812
895
  return Response.json({ error: "Invalid subscription" }, { status: 400 });
813
- return Response.json(await env.WEBHOOKS.getByName(scope.durableName("webhooks")).subscribe({
896
+ const created = await env.WEBHOOKS.getByName(scope.durableName("webhooks")).subscribe({
814
897
  ...body.value,
815
898
  types: body.value.types ?? [],
816
- }), { status: 201 });
899
+ });
900
+ return "error" in created
901
+ ? Response.json(created, { status: 503 })
902
+ : Response.json(created, { status: 201 });
817
903
  });
818
904
  routes.get("/api/webhooks", owner, async () => Response.json(await env.WEBHOOKS.getByName(scope.durableName("webhooks")).subscriptions()));
819
905
  routes.get("/api/webhooks/:id/deliveries", owner, async (context) => Response.json(await env.WEBHOOKS.getByName(scope.durableName("webhooks")).deliveries(context.req.param("id"))));
@@ -853,12 +939,12 @@ export function oysterGitRoot(options) {
853
939
  state.admissions.set(request, resolved);
854
940
  return resolved;
855
941
  },
856
- hostFor(env, scope, request) {
942
+ hostFor(env, scope, request, principal) {
857
943
  const state = stateOf(env);
858
944
  return oysterGitWorkerHost(env, options, {
859
945
  scope,
860
946
  auth: pinnedTenantAuth(state.tenancy, scope, state.admissions, state.authentications),
861
- }, request);
947
+ }, request, principal);
862
948
  },
863
949
  };
864
950
  }
@@ -1092,7 +1178,7 @@ export function oysterWorkerGit(env, options, frame) {
1092
1178
  * One selected tenant's whole host from a root's options. Roots reach it through
1093
1179
  * `oysterGitRoot(options).hostFor`; a cold directory passes its own resolved tenant.
1094
1180
  */
1095
- export async function oysterGitWorkerHost(env, options, selected, request) {
1181
+ export async function oysterGitWorkerHost(env, options, selected, request, principal) {
1096
1182
  const { scope, auth } = selected;
1097
1183
  // The one path to a key's liveness: the stored owner id is re-checked
1098
1184
  // against the live, current owner on every read (S3 inherits this port,
@@ -1110,7 +1196,11 @@ export async function oysterGitWorkerHost(env, options, selected, request) {
1110
1196
  });
1111
1197
  return current !== null && oysterPrincipalIsOwner(current) ? key : null;
1112
1198
  };
1113
- const workspace = (await options.workspace?.(env, keysLive, scope, request === undefined ? undefined : { request, auth })) ?? {
1199
+ const workspace = (await options.workspace?.(env, keysLive, scope, request !== undefined
1200
+ ? { request, auth }
1201
+ : principal === undefined
1202
+ ? undefined
1203
+ : { principal })) ?? {
1114
1204
  computerId: scope.computerName("workspace"),
1115
1205
  files: r2FileSource(env.RELEASES, scope.workspacePrefix),
1116
1206
  };
@@ -1214,5 +1304,5 @@ function pinnedTenantAuth(tenancy, scope, admissions, authentications) {
1214
1304
  }
1215
1305
  /** Deploy the MCP owner from the same root as createOysterGitWorker. */
1216
1306
  export function createOysterGitMcpOwner(root) {
1217
- return createOysterMcpOwner((env, scope) => root.hostFor(env, scope));
1307
+ return createOysterMcpOwner((env, scope, principal) => root.hostFor(env, scope, undefined, principal));
1218
1308
  }
package/dist/workers.d.ts CHANGED
@@ -399,6 +399,8 @@ export declare class OysterInstance<Env extends OysterWorkerEnv = OysterWorkerEn
399
399
  /** Content-addressed backends are verified once per Instance, not per call. */
400
400
  private readonly backends;
401
401
  private readonly gitJournal;
402
+ /** A `region` Release's sockets and wake, supervised natively here. */
403
+ private readonly region;
402
404
  constructor(ctx: DurableObjectState, env: Env);
403
405
  /** Every wake owner shares the native alarm; none may postpone another. */
404
406
  private scheduleWake;
@@ -448,6 +450,20 @@ export declare class OysterInstance<Env extends OysterWorkerEnv = OysterWorkerEn
448
450
  prepare(state: OwnerState, release: Release, limits?: GuestLimits, tenant?: Pick<TenantScope, "tenantId" | "origin">): Promise<InstanceResult<import("./boot-gate.js").UiBootCheckOutcome | null>>;
449
451
  /** Activate the exact committed selection under the host's tenant pin. */
450
452
  apply(state: OwnerState, release: Release, limits: GuestLimits | undefined, tenant: Pick<TenantScope, "tenantId" | "origin">): Promise<InstanceResult<Instance>>;
453
+ /**
454
+ * The Instance's private door for an admitted Region connect: only its own
455
+ * host reaches this stub, carrying connect facts it has just attested.
456
+ */
457
+ fetch(request: Request): Promise<Response>;
458
+ /** Route a hibernated Region socket's frame to the supervisor. */
459
+ webSocketMessage(socket: WebSocket, message: string | ArrayBuffer): Promise<void>;
460
+ /** Route a hibernated Region socket's close to the supervisor, which answers it. */
461
+ webSocketClose(socket: WebSocket, code: number, reason: string): Promise<void>;
462
+ /**
463
+ * A later Region event runs under the Instance's current authority: its
464
+ * applied, active selection and verified bytes, with no caller or grants.
465
+ */
466
+ private regionEvent;
451
467
  /** Forward an admitted HTTP request to the App backend. */
452
468
  backend(facts: InvocationFacts, request: Request, limits?: GuestLimits, tenantId?: TenantId): Promise<Response>;
453
469
  /** Deliver a Git push through the same selected-Instance admission as methods. */
package/dist/workers.js CHANGED
@@ -38,7 +38,8 @@ import { parseReleaseId, parseSha256Digest, } from "@fungi.computer/puffball";
38
38
  import { releaseSchema } from "@fungi.computer/puffball/effect";
39
39
  import { AppInstanceError, } from "./index.js";
40
40
  import { createCloudflareAppInstance, createCloudflareAppTestCopies, r2ArtifactStore, createCloudflareInvocationGate, edgeVerifiedObjectCache, decodeFrameBindingProps, captureFrameBindingReply, frameBindingEntrypoint, backgroundFrameMethods, } from "./cloudflare.js";
41
- import { invocationFactsSchema, assertBackgroundBinding, admitBackgroundFrame, } from "./invocation.js";
41
+ import { createAppRegion, durableAppRegionNative, isAppRegionSocket, } from "./app-region.js";
42
+ import { invocationFactsSchema, invocationCaller, invocationFacts as hostInvocationFacts, readRegionAdmission, regionAdmissionRequest, assertBackgroundBinding, admitBackgroundFrame, } from "./invocation.js";
42
43
  import { deliverBackground, deliverGitPush } from "./internal/delivery.js";
43
44
  import { reportSlowInvocation } from "./internal/invocation-timing.js";
44
45
  import { releaseCache } from "./internal/host-gate.js";
@@ -625,8 +626,11 @@ function instanceHandle(target, scope, budget) {
625
626
  authorizeGitPush: (facts, question) => target.authorizeGitPush(facts, question, budget, tenantId),
626
627
  onGitPush: (facts, fact) => target.onGitPush(facts, fact, budget, tenantId),
627
628
  syncRefused: (facts, refusal) => target.syncRefused(facts, refusal, budget, tenantId),
629
+ regionConnect: (facts, request) => target.fetch(regionAdmissionRequest(request, facts, guestLimits(budget))),
628
630
  };
629
631
  }
632
+ /** One Region event's frame lifetime; a wake or message is short work. */
633
+ const regionEventCeilingMs = 30_000;
630
634
  /**
631
635
  * One App Instance: Oyster's lifecycle supervisor in this Durable Object's
632
636
  * SQLite and the App backend in its `app` facet.
@@ -643,6 +647,8 @@ export class OysterInstance extends DurableObject {
643
647
  /** Content-addressed backends are verified once per Instance, not per call. */
644
648
  backends;
645
649
  gitJournal;
650
+ /** A `region` Release's sockets and wake, supervised natively here. */
651
+ region;
646
652
  constructor(ctx, env) {
647
653
  super(ctx, env);
648
654
  ctx.storage.sql.exec("CREATE TABLE IF NOT EXISTS oyster_releases (release_id TEXT PRIMARY KEY, release TEXT NOT NULL) STRICT");
@@ -656,6 +662,11 @@ export class OysterInstance extends DurableObject {
656
662
  this.backends = backendCache(r2ArtifactStore(env.RELEASES));
657
663
  this.runtime = this.createRuntime(this.limits);
658
664
  this.frames = createCloudflareInvocationGate(ctx, (frame) => this.closeBackground(frame));
665
+ this.region = createAppRegion(durableAppRegionNative(ctx, (at) => this.scheduleWake(at)),
666
+ // A connect only ever runs in its admitting frame, never from here.
667
+ (event) => event.kind === "connect"
668
+ ? Promise.reject(new AppInstanceError("invalid_invocation_facts"))
669
+ : this.regionEvent(event));
659
670
  this.testCopies = createCloudflareAppTestCopies(ctx, env.LOADER, {
660
671
  limits: () => this.limits,
661
672
  source: () => Effect.tryPromise({
@@ -953,6 +964,7 @@ export class OysterInstance extends DurableObject {
953
964
  const settled = await Promise.allSettled([
954
965
  this.gitJournal.then((journal) => journal.alarm()),
955
966
  Effect.runPromise(this.testCopies.expire()),
967
+ this.region.alarm(),
956
968
  ]);
957
969
  const failed = settled.find((outcome) => outcome.status === "rejected");
958
970
  if (failed !== undefined)
@@ -972,8 +984,10 @@ export class OysterInstance extends DurableObject {
972
984
  if (installationId !== this.installationId())
973
985
  throw new AppInstanceError("instance_owner_mismatch");
974
986
  await this.frames.revoke(new AppInstanceError("revoked"), runId === undefined ? undefined : { runId });
975
- if (runId === undefined)
987
+ if (runId === undefined) {
988
+ this.region.fence("Installation changed");
976
989
  await Effect.runPromise(this.testCopies.revoke());
990
+ }
977
991
  }
978
992
  /** One registry read re-admits a guest binding packet against its frame. */
979
993
  async assertCurrent(frame) {
@@ -1004,9 +1018,10 @@ export class OysterInstance extends DurableObject {
1004
1018
  const facts = Schema.decodeUnknownSync(invocationFactsSchema, {
1005
1019
  onExcessProperty: "error",
1006
1020
  })(raw);
1007
- if (facts.subject.kind === "call" &&
1008
- (facts.subject.context.scope.kind !== "standalone" ||
1009
- facts.subject.context.scope.tenant !== this.scope().tenantId))
1021
+ const caller = invocationCaller(facts);
1022
+ if (caller !== undefined &&
1023
+ (caller.scope.kind !== "standalone" ||
1024
+ caller.scope.tenant !== this.scope().tenantId))
1010
1025
  throw new AppInstanceError("installation_tenant_mismatch");
1011
1026
  if (facts.instanceId !== this.ctx.id.name ||
1012
1027
  facts.selection.owner.kind !== "installation" ||
@@ -1155,12 +1170,87 @@ export class OysterInstance extends DurableObject {
1155
1170
  this.ctx.storage.sql.exec("INSERT INTO oyster_owner (id, installation_id) VALUES (1, ?) ON CONFLICT(id) DO NOTHING", state.owner.id);
1156
1171
  });
1157
1172
  this.rememberRelease(release);
1173
+ const before = await Effect.runPromise(this.runtime.inspect());
1158
1174
  const applied = await result(this.runtimeFor(limits).apply(state));
1175
+ // A new selection, authority or status closes Region sockets and drops
1176
+ // the App's wake: every reconnect re-admits. App data stays.
1177
+ if (!applied.ok ||
1178
+ applied.value.status !== "active" ||
1179
+ before?.authorityVersion !== applied.value.authorityVersion ||
1180
+ before.releaseId !== applied.value.releaseId)
1181
+ this.region.fence("Installation changed");
1159
1182
  if (!(await committed()))
1160
1183
  return { ok: false, code: "stale_authority" };
1161
1184
  return applied;
1162
1185
  });
1163
1186
  }
1187
+ /**
1188
+ * The Instance's private door for an admitted Region connect: only its own
1189
+ * host reaches this stub, carrying connect facts it has just attested.
1190
+ */
1191
+ async fetch(request) {
1192
+ let admitted;
1193
+ try {
1194
+ admitted = readRegionAdmission(request);
1195
+ }
1196
+ catch {
1197
+ return new Response(null, { status: 400 });
1198
+ }
1199
+ if (admitted === null)
1200
+ return new Response(null, { status: 426 });
1201
+ const { facts, limits } = admitted;
1202
+ try {
1203
+ return await this.withFrame(facts, guestLimits(limits), (runtime, frame) => {
1204
+ const caller = invocationCaller(frame.facts);
1205
+ if (caller === undefined ||
1206
+ frame.host.artifact.backend.runtime.kind !== "region")
1207
+ throw new AppInstanceError("invalid_invocation_facts");
1208
+ return this.region.connect(caller, (event) => Effect.runPromise(runtime.region(frame, event.kind === "connect"
1209
+ ? { kind: "connect", connection: event.connection }
1210
+ : event)));
1211
+ }, this.scope().tenantId);
1212
+ }
1213
+ catch (error) {
1214
+ return Response.json({ error: error instanceof AppInstanceError ? error.code : "failed" }, { status: error instanceof AppInstanceError ? 403 : 502 });
1215
+ }
1216
+ }
1217
+ /** Route a hibernated Region socket's frame to the supervisor. */
1218
+ async webSocketMessage(socket, message) {
1219
+ if (isAppRegionSocket(this.ctx, socket))
1220
+ await this.region.message(socket, message);
1221
+ }
1222
+ /** Route a hibernated Region socket's close to the supervisor, which answers it. */
1223
+ async webSocketClose(socket, code, reason) {
1224
+ if (isAppRegionSocket(this.ctx, socket))
1225
+ await this.region.close(socket, code, reason);
1226
+ }
1227
+ /**
1228
+ * A later Region event runs under the Instance's current authority: its
1229
+ * applied, active selection and verified bytes, with no caller or grants.
1230
+ */
1231
+ async regionEvent(event) {
1232
+ const instance = await Effect.runPromise(this.runtime.inspect());
1233
+ if (instance?.status !== "active")
1234
+ throw new AppInstanceError("disabled");
1235
+ const release = this.release(instance.releaseId);
1236
+ const resolved = await this.backends(release);
1237
+ if (resolved?.backend.runtime.kind !== "region")
1238
+ throw new AppInstanceError("invalid_invocation_facts");
1239
+ const deadlineAt = Date.now() + regionEventCeilingMs;
1240
+ const selection = {
1241
+ instanceId: instance.instanceId,
1242
+ owner: instance.owner,
1243
+ appId: instance.appId,
1244
+ releaseId: instance.releaseId,
1245
+ authorityVersion: instance.authorityVersion,
1246
+ };
1247
+ return this.withFrame(hostInvocationFacts.fromRegion({
1248
+ instanceId: instance.instanceId,
1249
+ selection,
1250
+ artifactDigest: resolved.digest,
1251
+ ancestry: [],
1252
+ }, event.kind, { deadlineAt, grantExpiresAt: deadlineAt }), undefined, (runtime, frame) => Effect.runPromise(runtime.region(frame, event)), this.scope().tenantId);
1253
+ }
1164
1254
  /** Forward an admitted HTTP request to the App backend. */
1165
1255
  async backend(facts, request, limits, tenantId = defaultTenant) {
1166
1256
  try {