@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
package/dist/host.d.ts CHANGED
@@ -118,6 +118,8 @@ export type InstanceHandle = Readonly<{
118
118
  authorizeGitPush: (facts: InvocationFacts, question: GitPushQuestion) => Promise<GitPushVerdict>;
119
119
  /** Forward an admitted HTTP request to the backend. */
120
120
  fetch: (facts: InvocationFacts, request: Request) => Promise<Response>;
121
+ /** Hand an admitted Region connect to the Instance; answers its socket upgrade. */
122
+ regionConnect: (facts: InvocationFacts, request: Request) => Promise<Response>;
121
123
  /** Invoke a declared read Gill through the same immutable invocation frame. */
122
124
  gill: (facts: InvocationFacts, api: AppApi, source: string, input: GillCall) => Promise<InstanceResult<GillReply>>;
123
125
  /** Invoke one declared App method; an App refusal is a refused reply. */
package/dist/host.js CHANGED
@@ -14,7 +14,7 @@ import { gillRequestSchema, decodeGillReply, decodeDeclaredGillResponse, } from
14
14
  import { causeClass } from "./cause-class.js";
15
15
  import { appStorageKeyNameSchema, appStorageWriteSchema, appStorageResetSchema, } from "@fungi.computer/agar/storage";
16
16
  import { guestLimits } from "./guest-policy.js";
17
- import { APP_INVOCATION_CEILING_MS, admittedCallerFacts, admittedMethodCallerFacts, invocationAuthorityOf, invocationCallerContext, invocationFacts, } from "./invocation.js";
17
+ import { APP_INVOCATION_CEILING_MS, admittedCallerFacts, admittedRegionConnectFacts, admittedMethodCallerFacts, invocationAuthorityOf, invocationCallerContext, invocationFacts, } from "./invocation.js";
18
18
  import { appFacetResponse } from "./backend-request.js";
19
19
  import { endTime, startTime } from "hono/timing";
20
20
  import { bodyLimit } from "hono/body-limit";
@@ -1218,6 +1218,7 @@ export function oysterRouteTable(host) {
1218
1218
  uiUrl,
1219
1219
  backendUrl: `/apps/${installation.installationId}/backend`,
1220
1220
  methodsUrl: `/apps/${installation.installationId}/methods/`,
1221
+ regionUrl: `/apps/${installation.installationId}/region`,
1221
1222
  };
1222
1223
  if (context.req.header("Accept") === "application/json")
1223
1224
  return Response.json(config, {
@@ -1279,6 +1280,24 @@ export function oysterRouteTable(host) {
1279
1280
  .fetch(admittedCallerFacts(installation, release, invocationCallerContext(principal, host.computerId ?? null, host.tenantId), decision.grants), request);
1280
1281
  return appFacetResponse(response);
1281
1282
  });
1283
+ // A Region socket is the same backend admission, then a native upgrade.
1284
+ table.get("/apps/:installationId/region", appRoute(), async (context, { principal }) => {
1285
+ if (context.req.header("Upgrade") !== "websocket")
1286
+ return refusal(426, "Expected a WebSocket");
1287
+ // A browser always names its page: a cross-site page cannot ride the session.
1288
+ if (!sameOriginReadRequest(context.req.raw))
1289
+ return refusal(403, "Cross-site Region connect refused");
1290
+ const installation = await enabled(context);
1291
+ if (installation === null)
1292
+ return refusal(404, "Not found");
1293
+ const release = await releaseOf(installation.release);
1294
+ const decision = admits(await gateFacts(installation, release, principal), { kind: "backend" });
1295
+ if (decision.kind === "refused")
1296
+ return refusal(403, decision.code);
1297
+ return host.instances
1298
+ .get(selectionOf(installation).instanceId, limits)
1299
+ .regionConnect(admittedRegionConnectFacts(installation, release, invocationCallerContext(principal, host.computerId ?? null, host.tenantId)), context.req.raw);
1300
+ });
1282
1301
  table.put("/apps/:installationId/gills", owner("direct-or-app"), async (context, { principal }) => {
1283
1302
  const caller = invocationCallerContext(principal, host.computerId ?? null, host.tenantId);
1284
1303
  const installation = await enabled(context);
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { type BackgroundSyncRefusal } from "@fungi.computer/puffball/background-
2
2
  import { type AppGitPushFact, type GitPushQuestion, type GitPushVerdict } from "@fungi.computer/agar/git";
3
3
  import * as Effect from "effect/Effect";
4
4
  import * as Schema from "effect/Schema";
5
- import type { DurableBackend } from "@fungi.computer/puffball/backend";
5
+ import { type AppRegionEvent, type AppRegionReply, type DurableBackend } from "@fungi.computer/puffball/backend";
6
6
  import type { Release, Sha256Digest } from "@fungi.computer/puffball";
7
7
  import type { AppMethodReply } from "@fungi.computer/agar/backend";
8
8
  import type { AppApi } from "@fungi.computer/puffball";
@@ -129,6 +129,13 @@ export type InstancePorts<Host> = Readonly<{
129
129
  */
130
130
  connect: (backend: Backend, frame: InvocationFrame<Host>) => Effect.Effect<AppBackendConnection, Error>;
131
131
  }>;
132
+ /** A Region event as a supervisor hands it to the runtime; a connect carries no caller of its own. */
133
+ export type AppRegionHostEvent = Readonly<{
134
+ kind: "connect";
135
+ connection: string;
136
+ }> | Exclude<AppRegionEvent, {
137
+ kind: "connect";
138
+ }>;
132
139
  /** One admitted connection to a running App backend. */
133
140
  export type AppBackendConnection = Readonly<{
134
141
  /** Ask the App about the whole external push under this admitted connection. */
@@ -137,6 +144,8 @@ export type AppBackendConnection = Readonly<{
137
144
  onGitPush?: (fact: AppGitPushFact) => Effect.Effect<void, Error>;
138
145
  /** Settle the refused member lane, without binding authority. */
139
146
  syncRefused?: (refusal: BackgroundSyncRefusal) => Effect.Effect<void, Error>;
147
+ /** Deliver one supervisor Region event; the App answers with a bounded reply. */
148
+ region?: (event: AppRegionEvent) => Effect.Effect<AppRegionReply, Error>;
140
149
  /** Send an HTTP request to the backend. */
141
150
  fetch: (request: Request) => Effect.Effect<Response, Error>;
142
151
  /** Invoke a declared backend method under the connection's immutable frame;
@@ -166,6 +175,11 @@ export type AppInstance<Host> = Readonly<{
166
175
  onGitPush: (frame: InvocationFrame<Host>, fact: AppGitPushFact) => Effect.Effect<void, Error>;
167
176
  /** Deliver a zero-grant refusal to an active, freshly selected backend. */
168
177
  syncRefused: (frame: InvocationFrame<Host>, refusal: BackgroundSyncRefusal) => Effect.Effect<void, Error>;
178
+ /**
179
+ * Deliver a supervisor Region event under exact live Instance selection. A
180
+ * connect's caller is the frame's own host-attested context, never an input.
181
+ */
182
+ region: (frame: InvocationFrame<Host>, event: AppRegionHostEvent) => Effect.Effect<AppRegionReply, Error>;
169
183
  /** Read the current Instance record, resuming an interrupted purge. */
170
184
  inspect: () => Effect.Effect<Instance | null, Error>;
171
185
  }>;
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { instanceIdSchema } from "./instance-id.js";
5
5
  import * as Effect from "effect/Effect";
6
6
  import * as Schema from "effect/Schema";
7
7
  import { releaseIdSchema, appIdSchema } from "@fungi.computer/puffball/effect";
8
+ import { appRegionEventSchema, appRegionReplySchema, } from "@fungi.computer/puffball/backend";
8
9
  import { appFacetRequest, appFacetResponse } from "./backend-request.js";
9
10
  import { appApiSchema } from "@fungi.computer/puffball/app";
10
11
  import { bootFailureSchema, BootGateError, } from "./boot-gate.js";
@@ -330,8 +331,26 @@ export function createAppInstance(ports) {
330
331
  ? Effect.fail(new Error("App background refusal handler unavailable"))
331
332
  : connection.syncRefused(refusal)));
332
333
  }));
334
+ const region = (frame, raw) => {
335
+ const subject = frame.facts.subject;
336
+ if (subject.kind !== "lifecycle" ||
337
+ subject.name !== "onRegion" ||
338
+ subject.event !== raw.kind ||
339
+ frame.facts.grants.length !== 0)
340
+ return failure("invalid_invocation_facts");
341
+ return Effect.try({
342
+ try: () => appRegionEventSchema.parse(raw.kind === "connect" ? { ...raw, caller: subject.context } : raw),
343
+ catch: (cause) => new Error("Region event invalid", { cause }),
344
+ }).pipe(Effect.flatMap((event) => connect(frame).pipe(Effect.flatMap((connection) => connection.region === undefined
345
+ ? Effect.fail(new Error("App Region handler unavailable"))
346
+ : connection.region(event)), Effect.flatMap((reply) => Effect.try({
347
+ try: () => appRegionReplySchema.parse(reply),
348
+ catch: (cause) => new Error("Region reply invalid", { cause }),
349
+ })))));
350
+ };
333
351
  return {
334
352
  syncRefused,
353
+ region,
335
354
  prepare,
336
355
  apply,
337
356
  fetch,
@@ -4,11 +4,14 @@ import type { VerifiedRelease } from "./release.js";
4
4
  import type { Installation } from "./apps/installation.js";
5
5
  import { type InvocationGrants } from "./apps/gate.js";
6
6
  import * as Schema from "effect/Schema";
7
+ import type { AppRegionEvent } from "@fungi.computer/puffball/backend";
7
8
  import { type AppBackendBindingName, type AppMethodCallContext, type WorkflowAttestation } from "@fungi.computer/puffball/app";
8
9
  import { type BackgroundOrigin, type ClaimedJobAdmission } from "@fungi.computer/puffball/background-replay";
9
10
  import { type InstanceId } from "./index.js";
10
11
  /** One App invocation may hold authority for at most the Hub grant's lifetime. */
11
12
  export declare const APP_INVOCATION_CEILING_MS = 60000;
13
+ /** One kind of supervisor-delivered Region event. */
14
+ export type AppRegionEventKind = AppRegionEvent["kind"];
12
15
  /** Host-admitted facts; shape decoding does not establish host authority. */
13
16
  export declare const invocationFactsSchema: Schema.Struct<{
14
17
  readonly instanceId: Schema.Codec<InstanceId, string, never, never>;
@@ -174,6 +177,138 @@ export declare const invocationFactsSchema: Schema.Struct<{
174
177
  readonly kind: Schema.Literal<"lifecycle">;
175
178
  readonly name: Schema.Literal<"onGitPush">;
176
179
  readonly eventId: Schema.NonEmptyString;
180
+ }>, Schema.Struct<{
181
+ readonly kind: Schema.Literal<"lifecycle">;
182
+ readonly name: Schema.Literal<"onRegion">;
183
+ /** The supervisor event; only a connect carries a host-stamped caller. */
184
+ readonly event: Schema.Literals<readonly ["connect", "message", "close", "alarm"]>;
185
+ readonly context: Schema.optionalKey<Schema.declareConstructor<{
186
+ scope: {
187
+ kind: "team";
188
+ teamId: string;
189
+ } | {
190
+ kind: "standalone";
191
+ tenant: string;
192
+ };
193
+ computerId: string | null;
194
+ actor: {
195
+ kind: "member";
196
+ memberId: string;
197
+ } | {
198
+ kind: "agent";
199
+ agentId: string;
200
+ } | {
201
+ kind: "team-key";
202
+ keyId: string;
203
+ };
204
+ backgroundLane?: string | undefined;
205
+ backgroundOrigin?: {
206
+ method: string;
207
+ seal: string;
208
+ } | undefined;
209
+ role?: "member" | "owner" | "admin" | undefined;
210
+ soleMember?: true | undefined;
211
+ workflow?: {
212
+ workflowId: string;
213
+ runId: string;
214
+ nodeId: string;
215
+ armedBy: {
216
+ kind: "member";
217
+ memberId: string;
218
+ } | {
219
+ kind: "agent";
220
+ agentId: string;
221
+ } | {
222
+ kind: "team-key";
223
+ keyId: string;
224
+ };
225
+ } | undefined;
226
+ idempotencyKey?: string | undefined;
227
+ }, {
228
+ scope: {
229
+ kind: "team";
230
+ teamId: string;
231
+ } | {
232
+ kind: "standalone";
233
+ tenant: string;
234
+ };
235
+ computerId: string | null;
236
+ actor: {
237
+ kind: "member";
238
+ memberId: string;
239
+ } | {
240
+ kind: "agent";
241
+ agentId: string;
242
+ } | {
243
+ kind: "team-key";
244
+ keyId: string;
245
+ };
246
+ backgroundLane?: string | undefined;
247
+ backgroundOrigin?: {
248
+ method: string;
249
+ seal: string;
250
+ } | undefined;
251
+ role?: "member" | "owner" | "admin" | undefined;
252
+ soleMember?: true | undefined;
253
+ workflow?: {
254
+ workflowId: string;
255
+ runId: string;
256
+ nodeId: string;
257
+ armedBy: {
258
+ kind: "member";
259
+ memberId: string;
260
+ } | {
261
+ kind: "agent";
262
+ agentId: string;
263
+ } | {
264
+ kind: "team-key";
265
+ keyId: string;
266
+ };
267
+ } | undefined;
268
+ idempotencyKey?: string | undefined;
269
+ }, readonly [], {
270
+ scope: {
271
+ kind: "team";
272
+ teamId: string;
273
+ } | {
274
+ kind: "standalone";
275
+ tenant: string;
276
+ };
277
+ computerId: string | null;
278
+ actor: {
279
+ kind: "member";
280
+ memberId: string;
281
+ } | {
282
+ kind: "agent";
283
+ agentId: string;
284
+ } | {
285
+ kind: "team-key";
286
+ keyId: string;
287
+ };
288
+ backgroundLane?: string | undefined;
289
+ backgroundOrigin?: {
290
+ method: string;
291
+ seal: string;
292
+ } | undefined;
293
+ role?: "member" | "owner" | "admin" | undefined;
294
+ soleMember?: true | undefined;
295
+ workflow?: {
296
+ workflowId: string;
297
+ runId: string;
298
+ nodeId: string;
299
+ armedBy: {
300
+ kind: "member";
301
+ memberId: string;
302
+ } | {
303
+ kind: "agent";
304
+ agentId: string;
305
+ } | {
306
+ kind: "team-key";
307
+ keyId: string;
308
+ };
309
+ } | undefined;
310
+ idempotencyKey?: string | undefined;
311
+ }>>;
177
312
  }>, Schema.Struct<{
178
313
  readonly kind: Schema.Literal<"lifecycle">;
179
314
  readonly name: Schema.Literal<"syncRefused">;
@@ -189,6 +324,11 @@ export declare const invocationFactsSchema: Schema.Struct<{
189
324
  }>;
190
325
  /** The immutable authority and attribution supplied at host admission. */
191
326
  export type InvocationFacts = typeof invocationFactsSchema.Type;
327
+ /**
328
+ * The host-attested caller a frame carries, if any: every call, and a Region
329
+ * connect. Instance owners check its scope against their own binding.
330
+ */
331
+ export declare function invocationCaller(facts: InvocationFacts): AppMethodCallContext | undefined;
192
332
  /** Method name/effect taken from a verified API; raw backend requests have no method. */
193
333
  export type InvocationMethod = NonNullable<Extract<InvocationFacts["subject"], {
194
334
  kind: "call";
@@ -272,10 +412,35 @@ export declare const invocationFacts: {
272
412
  role?: AppMethodCallContext["role"];
273
413
  idempotencyKey: string;
274
414
  }>, deadline: InvocationDeadline) => InvocationFacts;
415
+ /**
416
+ * A Region event under the Instance's current authority: no binding grants,
417
+ * and a caller only on a connect the host has just admitted.
418
+ */
419
+ fromRegion: (authority: Omit<InvocationAuthority, "grants">, event: AppRegionEventKind, deadline: InvocationDeadline, context?: AppMethodCallContext) => InvocationFacts;
275
420
  };
276
421
  /** Authority comes from the admitted installation and its verified backend bytes. */
277
422
  export declare function invocationAuthorityOf(installation: Installation, release: VerifiedRelease, ancestry?: readonly InstanceId[]): InvocationAuthority;
278
423
  /** Mint standalone facts only after host caller and Release admission. */
279
424
  export declare function admittedCallerFacts(installation: Installation, release: VerifiedRelease, context: AppMethodCallContext, grants: InvocationGrants, ancestry?: readonly InstanceId[], sessionId?: string, agentPolicy?: InvocationAgentPolicy, method?: InvocationMethod, origin?: BackgroundOrigin): InvocationFacts;
425
+ /**
426
+ * Mint a Region connect only after host caller and Release admission. The
427
+ * Instance itself refuses a Release whose verified profile is not region.
428
+ */
429
+ export declare function admittedRegionConnectFacts(installation: Installation, release: VerifiedRelease, context: AppMethodCallContext): InvocationFacts;
280
430
  /** Seal the host-verified named method after its current admission checks. */
281
431
  export declare function admittedMethodCallerFacts(host: Pick<OysterHost, "backgroundOriginKey">, installation: Installation, release: VerifiedRelease, context: AppMethodCallContext, grants: InvocationGrants, method: InvocationMethod, ancestry?: readonly InstanceId[], sessionId?: string, agentPolicy?: InvocationAgentPolicy): Promise<InvocationFacts>;
432
+ /** The private header a host uses to hand an admitted Region connect to its Instance. */
433
+ export declare const regionAdmissionHeader = "x-fungi-region-admission";
434
+ /** Host side: the admitted connect facts ride the Instance's own upgrade request. */
435
+ export declare function regionAdmissionRequest(request: Request, facts: InvocationFacts, limits: Readonly<{
436
+ cpuMs: number;
437
+ subRequests: number;
438
+ }>): Request;
439
+ /** Instance side: read the host's admission; null when this is no Region connect. */
440
+ export declare function readRegionAdmission(request: Request): {
441
+ facts: InvocationFacts;
442
+ limits: Readonly<{
443
+ cpuMs: number;
444
+ subRequests: number;
445
+ }>;
446
+ } | null;
@@ -17,6 +17,7 @@ const grantsSchema = Schema.Array(Schema.Struct({
17
17
  name: grant.binding,
18
18
  operations: grant.operations,
19
19
  }))))));
20
+ const appRegionEventKinds = ["connect", "message", "close", "alarm"];
20
21
  /** Host-admitted facts; shape decoding does not establish host authority. */
21
22
  export const invocationFactsSchema = Schema.Struct({
22
23
  instanceId: instanceIdSchema,
@@ -50,6 +51,13 @@ export const invocationFactsSchema = Schema.Struct({
50
51
  name: Schema.Literal("onGitPush"),
51
52
  eventId: Schema.NonEmptyString,
52
53
  }),
54
+ Schema.Struct({
55
+ kind: Schema.Literal("lifecycle"),
56
+ name: Schema.Literal("onRegion"),
57
+ /** The supervisor event; only a connect carries a host-stamped caller. */
58
+ event: Schema.Literals(appRegionEventKinds),
59
+ context: Schema.optionalKey(appMethodCallContextSchema),
60
+ }),
53
61
  Schema.Struct({
54
62
  kind: Schema.Literal("lifecycle"),
55
63
  name: Schema.Literal("syncRefused"),
@@ -64,6 +72,11 @@ export const invocationFactsSchema = Schema.Struct({
64
72
  (facts.subject.kind !== "lifecycle" ||
65
73
  facts.subject.name !== "syncRefused" ||
66
74
  facts.grants.length === 0) &&
75
+ (facts.subject.kind !== "lifecycle" ||
76
+ facts.subject.name !== "onRegion" ||
77
+ (facts.grants.length === 0 &&
78
+ (facts.subject.event === "connect") ===
79
+ (facts.subject.context !== undefined))) &&
67
80
  (facts.subject.kind !== "call" ||
68
81
  facts.subject.agentPolicy === undefined ||
69
82
  facts.subject.context.actor.kind === "agent") &&
@@ -83,6 +96,15 @@ export const invocationFactsSchema = Schema.Struct({
83
96
  mayDefer(facts.subject.context, facts.ancestry) &&
84
97
  facts.subject.replay.lane ===
85
98
  actorLane(facts.subject.context.actor))))));
99
+ /**
100
+ * The host-attested caller a frame carries, if any: every call, and a Region
101
+ * connect. Instance owners check its scope against their own binding.
102
+ */
103
+ export function invocationCaller(facts) {
104
+ if (facts.subject.kind === "call")
105
+ return facts.subject.context;
106
+ return facts.subject.name === "onRegion" ? facts.subject.context : undefined;
107
+ }
86
108
  /** Block replay capability effects before job-origin admission; storage permits claiming/settling. */
87
109
  export function assertBackgroundBinding(frame, binding) {
88
110
  if (frame.signal.aborted ||
@@ -411,6 +433,18 @@ export const invocationFacts = {
411
433
  context.role = input.role;
412
434
  return invocationFacts.fromCaller(authority, context, deadline);
413
435
  },
436
+ /**
437
+ * A Region event under the Instance's current authority: no binding grants,
438
+ * and a caller only on a connect the host has just admitted.
439
+ */
440
+ fromRegion: (authority, event, deadline, context) => parseFacts({
441
+ ...authority,
442
+ grants: [],
443
+ subject: context === undefined
444
+ ? { kind: "lifecycle", name: "onRegion", event }
445
+ : { kind: "lifecycle", name: "onRegion", event, context },
446
+ deadlineAt: Math.min(deadline.deadlineAt, deadline.grantExpiresAt),
447
+ }),
414
448
  };
415
449
  /** Authority comes from the admitted installation and its verified backend bytes. */
416
450
  export function invocationAuthorityOf(installation, release, ancestry = []) {
@@ -436,6 +470,15 @@ export function admittedCallerFacts(installation, release, context, grants, ance
436
470
  ? context
437
471
  : backgroundContext(context, ancestry, method, origin), { deadlineAt, grantExpiresAt: deadlineAt }, method, sessionId, agentPolicy);
438
472
  }
473
+ /**
474
+ * Mint a Region connect only after host caller and Release admission. The
475
+ * Instance itself refuses a Release whose verified profile is not region.
476
+ */
477
+ export function admittedRegionConnectFacts(installation, release, context) {
478
+ const deadlineAt = Date.now() + APP_INVOCATION_CEILING_MS;
479
+ const { instanceId, selection, artifactDigest, ancestry } = invocationAuthorityOf(installation, release);
480
+ return invocationFacts.fromRegion({ instanceId, selection, artifactDigest, ancestry }, "connect", { deadlineAt, grantExpiresAt: deadlineAt }, context);
481
+ }
439
482
  /** Seal the host-verified named method after its current admission checks. */
440
483
  export async function admittedMethodCallerFacts(host, installation, release, context, grants, method, ancestry = [], sessionId, agentPolicy) {
441
484
  if (release.api?.methods[method.name]?.effect !== method.effect)
@@ -452,3 +495,27 @@ export async function admittedMethodCallerFacts(host, installation, release, con
452
495
  }
453
496
  return admittedCallerFacts(installation, release, context, grants, ancestry, sessionId, agentPolicy, method, origin);
454
497
  }
498
+ /** The private header a host uses to hand an admitted Region connect to its Instance. */
499
+ export const regionAdmissionHeader = "x-fungi-region-admission";
500
+ const regionAdmissionSchema = Schema.fromJsonString(Schema.Struct({
501
+ facts: invocationFactsSchema,
502
+ limits: Schema.Struct({ cpuMs: Schema.Number, subRequests: Schema.Number }),
503
+ }));
504
+ /** Host side: the admitted connect facts ride the Instance's own upgrade request. */
505
+ export function regionAdmissionRequest(request, facts, limits) {
506
+ if (facts.subject.kind !== "lifecycle" ||
507
+ facts.subject.name !== "onRegion" ||
508
+ facts.subject.event !== "connect")
509
+ throw new Error("Region admission needs connect facts");
510
+ const headers = new Headers({ Upgrade: "websocket" });
511
+ headers.set(regionAdmissionHeader, Schema.encodeSync(regionAdmissionSchema)({ facts, limits }));
512
+ // Only the upgrade and the host's admission cross; no browser header does.
513
+ return new Request(request.url, { method: "GET", headers });
514
+ }
515
+ /** Instance side: read the host's admission; null when this is no Region connect. */
516
+ export function readRegionAdmission(request) {
517
+ const header = request.headers.get(regionAdmissionHeader);
518
+ if (header === null || request.headers.get("Upgrade") !== "websocket")
519
+ return null;
520
+ return Schema.decodeUnknownSync(regionAdmissionSchema)(header);
521
+ }
package/dist/keys.d.ts CHANGED
@@ -5,8 +5,9 @@ export type OysterKeyCapability = "apps.read" | "apps.use" | "agents.use" | "com
5
5
  /**
6
6
  * `apps.use` also reaches `apps.read` (one level, per `defineGrants`'s own
7
7
  * `implies`): a key that may change an App's data may also read it.
8
- * `computer.use` has no narrower capability under it; the Computer is on or
9
- * off, host-wide.
8
+ * `computer.use` has no narrower capability under it. Over all Computers it
9
+ * follows the owner's current selection; over selected Computer ids it stays
10
+ * on those Computers whatever the owner selects.
10
11
  * `agents.use` selects Agent ids independently of App grants.
11
12
  * `machine.enroll` admits enrollment only; it implies no App or Computer access.
12
13
  * The enrollment owner, not this vocabulary, owns one-use consumption.
@@ -14,7 +15,7 @@ export type OysterKeyCapability = "apps.read" | "apps.use" | "agents.use" | "com
14
15
  export declare const oysterKeyVocabulary: GrantVocabulary<OysterKeyCapability>;
15
16
  /** A grant reaching every current and future installation for `capability`. */
16
17
  export declare function allInstallations(capability: "apps.read" | "apps.use"): Grant<OysterKeyCapability>;
17
- /** The grant that turns on the Computer for a key, host-wide; there is no narrower target. */
18
+ /** The grant that turns on the owner's currently selected Computer for a key. */
18
19
  export declare const computerUseGrant: Grant<OysterKeyCapability>;
19
20
  /** One key's durable record, in the shape a host's own App reads. */
20
21
  export type OysterKeyRecord = KeyRecord<OysterKeyCapability>;
package/dist/keys.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Oyster's own Ear Tag vocabulary: named keys an owner issues for selected
3
- * Apps and Agents, its Computer or machine enrollment. App grants never imply
3
+ * Apps, Agents and Computers, or machine enrollment. App grants never imply
4
4
  * Agent access. A key's id is its name, so name-derived identities stay stable.
5
5
  * What a key reaches is decided only in `authorization.ts`.
6
6
  */
@@ -8,8 +8,9 @@ import { defineGrants } from "@fungi.computer/ear-tag/grants";
8
8
  /**
9
9
  * `apps.use` also reaches `apps.read` (one level, per `defineGrants`'s own
10
10
  * `implies`): a key that may change an App's data may also read it.
11
- * `computer.use` has no narrower capability under it; the Computer is on or
12
- * off, host-wide.
11
+ * `computer.use` has no narrower capability under it. Over all Computers it
12
+ * follows the owner's current selection; over selected Computer ids it stays
13
+ * on those Computers whatever the owner selects.
13
14
  * `agents.use` selects Agent ids independently of App grants.
14
15
  * `machine.enroll` admits enrollment only; it implies no App or Computer access.
15
16
  * The enrollment owner, not this vocabulary, owns one-use consumption.
@@ -28,7 +29,7 @@ export const oysterKeyVocabulary = defineGrants({
28
29
  export function allInstallations(capability) {
29
30
  return { capability, targets: { kind: "all" } };
30
31
  }
31
- /** The grant that turns on the Computer for a key, host-wide; there is no narrower target. */
32
+ /** The grant that turns on the owner's currently selected Computer for a key. */
32
33
  export const computerUseGrant = {
33
34
  capability: "computer.use",
34
35
  targets: { kind: "all" },
@@ -1,6 +1,6 @@
1
1
  import { DurableObject } from "cloudflare:workers";
2
2
  import type { OysterHost, OysterMcp } from "./host.js";
3
- import { type TenantScope } from "./tenant.js";
3
+ import { type TenantPrincipal, type TenantScope } from "./tenant.js";
4
4
  /** Worker Loader used by the existing Mycelium sandbox. */
5
5
  export type OysterMcpOwnerEnv = Readonly<{
6
6
  LOADER: WorkerLoader;
@@ -17,11 +17,12 @@ export type OysterMcpTenantPin = Readonly<{
17
17
  */
18
18
  export declare class OysterMcpOwner<Env extends OysterMcpOwnerEnv = OysterMcpOwnerEnv> extends DurableObject<Env> {
19
19
  #private;
20
- constructor(ctx: DurableObjectState, env: Env, createHost: (env: Env, scope: TenantScope) => OysterHost | Promise<OysterHost>);
20
+ /** `createHost` given a principal builds the host that principal's catalog uses. */
21
+ constructor(ctx: DurableObjectState, env: Env, createHost: (env: Env, scope: TenantScope, principal?: TenantPrincipal) => OysterHost | Promise<OysterHost>);
21
22
  /** Trusted host RPC: the namespace and pin are never selected by guest headers. */
22
23
  serve(request: Request, tenant: OysterMcpTenantPin): Promise<Response>;
23
24
  }
24
25
  /** Bind the owner to the deployment's existing host factory and options. */
25
- export declare function createOysterMcpOwner<Env extends OysterMcpOwnerEnv>(host: (env: Env, scope: TenantScope) => OysterHost | Promise<OysterHost>): new (ctx: DurableObjectState, env: Env) => OysterMcpOwner<Env>;
26
+ export declare function createOysterMcpOwner<Env extends OysterMcpOwnerEnv>(host: (env: Env, scope: TenantScope, principal?: TenantPrincipal) => OysterHost | Promise<OysterHost>): new (ctx: DurableObjectState, env: Env) => OysterMcpOwner<Env>;
26
27
  /** Frontends own no SDK state and cannot close another isolate's sessions. */
27
28
  export declare function remoteOysterMcp(binding: DurableObjectNamespace<OysterMcpOwner> | undefined, scope: TenantScope): OysterMcp;
package/dist/mcp-owner.js CHANGED
@@ -2,7 +2,7 @@ import { DurableObject } from "cloudflare:workers";
2
2
  import { nanoid } from "@fungi.computer/cairn";
3
3
  import { createCodemodeSandbox } from "@fungi.computer/mycelium/workers";
4
4
  import * as Schema from "effect/Schema";
5
- import { tenantIdSchema, tenantScope } from "./tenant.js";
5
+ import { tenantIdSchema, tenantScope, } from "./tenant.js";
6
6
  /**
7
7
  * The MCP protocol SDK builds hundreds of schemas when it loads. Only the first
8
8
  * MCP request needs them, so the owner loads it then and the Worker's startup
@@ -34,6 +34,7 @@ const eventSchema = Schema.Struct({
34
34
  export class OysterMcpOwner extends DurableObject {
35
35
  #mcp;
36
36
  #createHost;
37
+ /** `createHost` given a principal builds the host that principal's catalog uses. */
37
38
  constructor(ctx, env, createHost) {
38
39
  super(ctx, env);
39
40
  this.#createHost = createHost;
@@ -121,7 +122,7 @@ export class OysterMcpOwner extends DurableObject {
121
122
  catalog: protocol.mycelium.createMcpCatalog({
122
123
  // Each acquisition captures the current durable selection. Existing
123
124
  // operation handles retain the Computer captured by their own catalog.
124
- load: async (principal) => protocol.catalog.oysterMcpCatalogLoad(await this.#createHost(this.env, scope))(principal),
125
+ load: async (principal) => protocol.catalog.oysterMcpCatalogLoad(await this.#createHost(this.env, scope, principal))(principal),
125
126
  sandbox: createCodemodeSandbox(this.env.LOADER),
126
127
  }),
127
128
  authenticate: async (incoming) => {
@@ -18,7 +18,8 @@ import { AppError, createCapabilityRegistry, } from "@fungi.computer/agar";
18
18
  import { appStorage } from "@fungi.computer/agar/storage";
19
19
  import { approvals } from "@fungi.computer/agar/approvals";
20
20
  import { oysterStorageHandle } from "./storage.js";
21
- import { appBackend, appMethods } from "@fungi.computer/agar/backend";
21
+ import { appBackend, appMethods, appRegion, } from "@fungi.computer/agar/backend";
22
+ import { oysterRegionHost } from "./region.js";
22
23
  import { computerList, computerPorts, computerProcesses, computerReadFile, computerTerminal, computerWriteFile, } from "@fungi.computer/agar/computer";
23
24
  import { agentList, agentManage, agentSessionRead, agentSessionWrite, } from "@fungi.computer/agar/agents";
24
25
  import { mediaGeneration } from "@fungi.computer/agar/media";
@@ -496,6 +497,9 @@ export async function oysterAppCapabilities(options) {
496
497
  handle: new Methods(config.methodsUrl, options.computerTarget),
497
498
  },
498
499
  ...capabilities,
500
+ ...(config.regionUrl === undefined
501
+ ? []
502
+ : [{ ...appRegion, handle: oysterRegionHost(config.regionUrl) }]),
499
503
  ...(config.appsOpen && options.appOpen
500
504
  ? [{ ...appsOpen, handle: new AppOpen(options.appOpen) }]
501
505
  : []),
@@ -0,0 +1,6 @@
1
+ import { AppRegionHost } from "@fungi.computer/agar/host";
2
+ /**
3
+ * Oyster's page opens each Region socket itself, same-origin with its own
4
+ * session, so no credential or socket URL ever reaches the sandboxed App.
5
+ */
6
+ export declare function oysterRegionHost(regionUrl: string): AppRegionHost;
@@ -0,0 +1,12 @@
1
+ import { AppRegionHost } from "@fungi.computer/agar/host";
2
+ /**
3
+ * Oyster's page opens each Region socket itself, same-origin with its own
4
+ * session, so no credential or socket URL ever reaches the sandboxed App.
5
+ */
6
+ export function oysterRegionHost(regionUrl) {
7
+ return new AppRegionHost(() => {
8
+ const url = new URL(regionUrl, window.location.href);
9
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
10
+ return new WebSocket(url);
11
+ });
12
+ }
@@ -83,6 +83,8 @@ export declare const oysterAppConfigSchema: Schema.Struct<{
83
83
  readonly uiUrl: Schema.String;
84
84
  readonly backendUrl: Schema.String;
85
85
  readonly methodsUrl: Schema.String;
86
+ /** The admitted Region socket door; absent when the App has no backend. */
87
+ readonly regionUrl: Schema.optional<Schema.String>;
86
88
  readonly capabilities: Schema.$Array<Schema.Struct<{
87
89
  readonly id: Schema.String;
88
90
  readonly version: Schema.Number;
@@ -21,5 +21,7 @@ export const oysterAppConfigSchema = Schema.Struct({
21
21
  uiUrl: Schema.String,
22
22
  backendUrl: Schema.String,
23
23
  methodsUrl: Schema.String,
24
+ /** The admitted Region socket door; absent when the App has no backend. */
25
+ regionUrl: Schema.optional(Schema.String),
24
26
  capabilities: Schema.Array(capabilityDescriptorSchema),
25
27
  });