@fungi.computer/oyster 0.32.0 → 0.34.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 (77) hide show
  1. package/README.md +59 -0
  2. package/dist/app-sandbox.d.ts +2 -2
  3. package/dist/app-sandbox.js +2 -2
  4. package/dist/app-test-copies.d.ts +87 -0
  5. package/dist/app-test-copies.js +170 -0
  6. package/dist/app-test-copy-page.d.ts +4 -0
  7. package/dist/app-test-copy-page.js +89 -0
  8. package/dist/approval-deadline.d.ts +2 -0
  9. package/dist/approval-deadline.js +7 -0
  10. package/dist/approval-home.d.ts +26 -3
  11. package/dist/approval-home.js +148 -18
  12. package/dist/apps/index.d.ts +1 -1
  13. package/dist/apps/index.js +1 -1
  14. package/dist/browser/operations.d.ts +1 -1
  15. package/dist/cloudflare.d.ts +68 -3
  16. package/dist/cloudflare.js +214 -3
  17. package/dist/embed-metafiles.js +2 -2
  18. package/dist/embed-scripts.js +1 -1
  19. package/dist/host.d.ts +20 -4
  20. package/dist/host.js +314 -3
  21. package/dist/installation-operations.d.ts +247 -8
  22. package/dist/installation-operations.js +145 -7
  23. package/dist/installation-recovery-page.d.ts +24 -0
  24. package/dist/installation-recovery-page.js +168 -0
  25. package/dist/mcp.js +42 -13
  26. package/dist/older-oyster-store.d.ts +1 -1
  27. package/dist/older-oyster-store.js +2 -4
  28. package/dist/page/app-permissions.js +8 -7
  29. package/dist/page/computer-handles.d.ts +0 -1
  30. package/dist/page/mount.d.ts +2 -101
  31. package/dist/page/mount.js +1 -22
  32. package/dist/page-config.d.ts +102 -0
  33. package/dist/page-config.js +24 -0
  34. package/dist/page-script.js +2 -2
  35. package/dist/platform-skills.generated.d.ts +5 -2
  36. package/dist/platform-skills.generated.js +6 -2
  37. package/dist/recovery-style.d.ts +5 -0
  38. package/dist/recovery-style.js +32 -0
  39. package/dist/standalone/agents.d.ts +1 -1
  40. package/dist/standalone/agents.js +43 -7
  41. package/dist/standalone/computer-fleet.js +3 -0
  42. package/dist/standalone/computer.d.ts +6 -2
  43. package/dist/standalone/computer.js +27 -14
  44. package/dist/standalone/media.js +7 -2
  45. package/dist/standalone/preview.d.ts +21 -20
  46. package/dist/standalone/preview.js +147 -151
  47. package/dist/standalone/registry.d.ts +14 -21
  48. package/dist/standalone/registry.js +74 -28
  49. package/dist/standalone/worker.js +6 -3
  50. package/dist/starter-agent.d.ts +6 -2
  51. package/dist/starter-agent.js +25 -4
  52. package/dist/upgrade/old-worker-http.d.ts +2 -0
  53. package/dist/upgrade/old-worker-http.js +22 -0
  54. package/dist/upgrade/old-worker-readonly.d.ts +14 -0
  55. package/dist/upgrade/old-worker-readonly.js +22 -0
  56. package/dist/upgrade/old-worker-sql.d.ts +10 -0
  57. package/dist/upgrade/old-worker-sql.js +68 -0
  58. package/dist/upgrade/old-worker-stream.d.ts +12 -0
  59. package/dist/upgrade/old-worker-stream.js +54 -0
  60. package/dist/upgrade/private-stage.d.ts +23 -0
  61. package/dist/upgrade/private-stage.js +109 -0
  62. package/dist/upgrade/standalone-001.d.ts +16 -0
  63. package/dist/upgrade/standalone-001.js +31 -0
  64. package/dist/upgrade/standalone-01.d.ts +37 -0
  65. package/dist/upgrade/standalone-01.js +55 -0
  66. package/dist/upgrade/standalone-02.d.ts +37 -0
  67. package/dist/upgrade/standalone-02.js +55 -0
  68. package/dist/workers.d.ts +45 -14
  69. package/dist/workers.js +198 -21
  70. package/docs/api/README.md +8 -3
  71. package/docs/api/apps.md +21 -0
  72. package/docs/api/cloudflare.md +57 -0
  73. package/docs/api/host.md +263 -25
  74. package/docs/api/page/mount.md +13 -81
  75. package/docs/api/workers-git.md +246 -1
  76. package/docs/api/workers.md +518 -95
  77. package/package.json +38 -24
@@ -5,6 +5,7 @@ import { ApprovalLedger, } from "@fungi.computer/approvals";
5
5
  import { invokeModuleOperation } from "@fungi.computer/mycelium/remote";
6
6
  import { keyAppAccess, oysterPrincipalIsOwner } from "./authorization.js";
7
7
  import { sha256 } from "./release.js";
8
+ const cancellationPruneLimit = 128;
8
9
  const identity = z.string().min(1).max(256);
9
10
  const targetSchema = z.strictObject({
10
11
  actor: hostActorSchema,
@@ -17,24 +18,54 @@ const callSchema = targetSchema.extend({
17
18
  authorityFence: identity,
18
19
  idempotencyKey: identity,
19
20
  input: z.json(),
21
+ deadlineAt: z.number().int().nonnegative(),
20
22
  });
23
+ /** Ledger lifecycle names stay internal; every tool uses the same expiry code. */
24
+ function callOutcome(result) {
25
+ return result.kind === "refused"
26
+ ? {
27
+ ...result,
28
+ reason: result.reason === "expired" ? "approval_expired" : result.reason,
29
+ }
30
+ : result;
31
+ }
32
+ function callKey(call) {
33
+ return JSON.stringify([
34
+ call.actor,
35
+ call.installationId,
36
+ call.sessionId,
37
+ call.operation,
38
+ call.idempotencyKey,
39
+ ]);
40
+ }
21
41
  const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Json));
22
42
  const intentRow = Schema.decodeUnknownSync(Schema.Struct({ target_json: Schema.String }));
43
+ const wakeRow = Schema.decodeUnknownSync(Schema.Struct({ at: Schema.NullOr(Schema.Number) }));
23
44
  /** The registry's durable App effect home. Mycelium still owns operation/schema invocation. */
24
45
  export class OysterApprovalHome {
25
46
  host;
26
47
  ledger;
48
+ active = new Map();
49
+ waiting = new Map();
27
50
  // The home's artifact store and capability configuration are fixed, unlike
28
51
  // the authority read fresh from current() for every recheck and dispatch.
29
52
  surfaces;
30
53
  constructor(host) {
31
54
  this.host = host;
32
55
  host.owner.sql.exec("CREATE TABLE IF NOT EXISTS oyster_approval_targets (record_id TEXT PRIMARY KEY, target_json TEXT NOT NULL) STRICT");
56
+ // A cancellation is terminal intent for this call identity, even if its
57
+ // submit RPC arrives later or this home restarts before it arrives.
58
+ host.owner.sql.exec("CREATE TABLE IF NOT EXISTS oyster_approval_cancellations (call_key TEXT PRIMARY KEY, expires_at INTEGER NOT NULL) STRICT");
59
+ host.owner.sql.exec("CREATE INDEX IF NOT EXISTS oyster_approval_cancellations_expiry ON oyster_approval_cancellations (expires_at)");
60
+ this.pruneCancellations();
33
61
  this.ledger = this.createLedger();
34
62
  // A new native home represents boot, before any live call can claim work.
35
63
  while (this.ledger.recoverClaims().length > 0) {
36
64
  // Each bounded batch settles part of the finite orphan set.
37
65
  }
66
+ while (this.ledger.withdrawWaiting() > 0) {
67
+ // No waiting call survived this native home's restart.
68
+ }
38
69
  }
39
70
  createLedger(persistIntent) {
40
71
  const home = { kind: "oyster", id: this.host.scope.tenantId };
@@ -46,6 +77,56 @@ export class OysterApprovalHome {
46
77
  async submit(raw) {
47
78
  // Maintained decoder snapshots the host's serialized call before any await.
48
79
  const call = callSchema.parse(raw);
80
+ // This check survives deletion of the marker: an expired envelope can
81
+ // never register fresh work, including an automatically approved write.
82
+ if (call.deadlineAt <= Date.now())
83
+ return { kind: "refused", reason: "approval_expired" };
84
+ const key = callKey(call);
85
+ if (this.host.owner.sql
86
+ .exec("SELECT call_key FROM oyster_approval_cancellations WHERE call_key = ?", key)
87
+ .toArray().length > 0)
88
+ return { kind: "refused", reason: "cancelled" };
89
+ if (this.active.has(key))
90
+ return { kind: "refused", reason: "in-flight" };
91
+ const controller = new AbortController();
92
+ this.active.set(key, controller);
93
+ try {
94
+ return await this.run(call, controller.signal);
95
+ }
96
+ finally {
97
+ this.active.delete(key);
98
+ }
99
+ }
100
+ /** Trusted host cancellation, pinned to the same caller and operation identity. */
101
+ async cancel(raw) {
102
+ const call = callSchema.parse(raw);
103
+ const key = callKey(call);
104
+ await this.host.commit(() => {
105
+ this.pruneCancellations();
106
+ this.host.owner.sql.exec("INSERT OR IGNORE INTO oyster_approval_cancellations (call_key, expires_at) VALUES (?, ?)", key, call.deadlineAt);
107
+ this.active.get(key)?.abort();
108
+ return Promise.resolve();
109
+ }, () => this.nextWakeAt());
110
+ }
111
+ pruneCancellations() {
112
+ this.host.owner.sql.exec("DELETE FROM oyster_approval_cancellations WHERE call_key IN (SELECT call_key FROM oyster_approval_cancellations WHERE expires_at <= ? ORDER BY expires_at LIMIT ?)", Date.now(), cancellationPruneLimit);
113
+ }
114
+ nextWakeAt() {
115
+ const cancellation = wakeRow(this.host.owner.sql
116
+ .exec("SELECT MIN(expires_at) AS at FROM oyster_approval_cancellations")
117
+ .toArray()[0]).at;
118
+ const approval = this.ledger.nextWakeAt();
119
+ if (cancellation === null)
120
+ return approval;
121
+ return approval === null ? cancellation : Math.min(approval, cancellation);
122
+ }
123
+ async run(call, signal) {
124
+ const cancelled = () => signal.aborted;
125
+ const expiresAt = Math.min(Date.now() + 5 * 60_000, call.deadlineAt - 30_000);
126
+ if (cancelled())
127
+ return { kind: "refused", reason: "cancelled" };
128
+ if (call.deadlineAt <= Date.now())
129
+ return { kind: "refused", reason: "approval_expired" };
49
130
  const actor = call.actor;
50
131
  const target = targetSchema.parse({
51
132
  actor: call.actor,
@@ -74,15 +155,56 @@ export class OysterApprovalHome {
74
155
  authorityFence: call.authorityFence,
75
156
  idempotencyKey: call.idempotencyKey,
76
157
  inputJson: JSON.stringify(call.input),
77
- }), () => ledger.nextWakeAt());
158
+ expiresAt,
159
+ }), () => this.nextWakeAt());
78
160
  if (staged.kind === "refused")
79
- return staged;
80
- // Only this call's own policy approval applies inline; a retry reports
81
- // status and leaves every other approved record to the home's work loop.
82
- if (!staged.created || staged.record.state !== "approved")
83
- return ledger.outcome(staged.record);
84
- // The native commit is complete before any external effect can run.
85
- return ledger.applyInline(staged.record.recordId, this.execution());
161
+ return callOutcome(staged);
162
+ const recordId = staged.record.recordId;
163
+ try {
164
+ if (ledger.get(recordId)?.state === "pending" && !cancelled())
165
+ await new Promise((resolve) => {
166
+ const finish = () => {
167
+ clearTimeout(timer);
168
+ signal.removeEventListener("abort", finish);
169
+ this.waiting.delete(recordId);
170
+ resolve();
171
+ };
172
+ const timer = setTimeout(finish, Math.max(0, expiresAt - Date.now()));
173
+ this.waiting.set(recordId, finish);
174
+ signal.addEventListener("abort", finish, { once: true });
175
+ // The answer may have arrived while the native commit was finishing.
176
+ if (cancelled() || ledger.get(recordId)?.state !== "pending")
177
+ finish();
178
+ });
179
+ if (cancelled())
180
+ return { kind: "refused", reason: "cancelled" };
181
+ const record = ledger.get(recordId);
182
+ if (record?.state === "denied" &&
183
+ record.reason === "declined" &&
184
+ record.by?.kind === "human") {
185
+ const by = record.by.memberId;
186
+ const denied = {
187
+ kind: "denied",
188
+ by,
189
+ message: `Denied by ${by}.${record.denialNote === undefined ? "" : ` User-provided note: ${JSON.stringify(record.denialNote)}`}`,
190
+ };
191
+ return record.denialNote === undefined
192
+ ? denied
193
+ : { ...denied, note: record.denialNote };
194
+ }
195
+ if (record?.state === "pending" || record?.state === "expired")
196
+ return { kind: "refused", reason: "approval_expired" };
197
+ if (record?.state === "approved" &&
198
+ record.by?.kind !== "policy" &&
199
+ Date.now() >= expiresAt)
200
+ return { kind: "refused", reason: "approval_expired" };
201
+ // Native commit completed before the waiting caller claims the effect.
202
+ const deadlineAt = Math.min(call.deadlineAt, Date.now() + 30_000);
203
+ return callOutcome(await ledger.apply(recordId, this.execution(signal, deadlineAt)));
204
+ }
205
+ finally {
206
+ ledger.withdraw(recordId);
207
+ }
86
208
  }
87
209
  /** Bind each read/decision to current membership, not the renderer's actor bytes. */
88
210
  capability(rawActor) {
@@ -108,17 +230,20 @@ export class OysterApprovalHome {
108
230
  (await this.resolve(record, actor)).kind === "authorized",
109
231
  };
110
232
  },
111
- decision: async (recordId) => {
112
- await this.ledger.apply(recordId, this.execution());
233
+ decision: (recordId) => {
234
+ this.waiting.get(recordId)?.();
235
+ return Promise.resolve();
113
236
  },
114
237
  });
115
238
  }
116
- /** One native alarm quantum; apply owns the fresh grant/fence check and single claim. */
117
- async reconcile() {
239
+ /** Alarms expire records only. They never execute a former call's effect. */
240
+ reconcile() {
241
+ this.pruneCancellations();
118
242
  this.ledger.expirePending();
119
- for (const recordId of this.ledger.pendingApplications())
120
- await this.ledger.apply(recordId, this.execution());
121
- return this.ledger.nextWakeAt();
243
+ for (const [recordId, finish] of this.waiting)
244
+ if (this.ledger.get(recordId)?.state !== "pending")
245
+ finish();
246
+ return Promise.resolve(this.nextWakeAt());
122
247
  }
123
248
  async resolve(record, answerer) {
124
249
  const raw = this.host.owner.sql
@@ -200,10 +325,16 @@ export class OysterApprovalHome {
200
325
  };
201
326
  return { kind: "authorized", module, fence };
202
327
  }
203
- execution() {
328
+ execution(callerSignal, deadlineAt) {
329
+ const signal = AbortSignal.any([
330
+ callerSignal,
331
+ AbortSignal.timeout(Math.max(0, deadlineAt - Date.now())),
332
+ ]);
204
333
  return {
205
334
  recheck: async (record) => {
335
+ signal.throwIfAborted();
206
336
  const current = await this.resolve(record);
337
+ signal.throwIfAborted();
207
338
  return current.kind === "refused"
208
339
  ? current
209
340
  : { kind: "authorized", authorityFence: current.fence };
@@ -211,12 +342,11 @@ export class OysterApprovalHome {
211
342
  dispatch: async ({ record, input }) => {
212
343
  // Reconstruct again at dispatch; never widen a captured operation or fence.
213
344
  const current = await this.resolve(record);
345
+ signal.throwIfAborted();
214
346
  if (current.kind === "refused")
215
347
  return current;
216
348
  if (current.fence !== record.authorityFence)
217
349
  return { kind: "refused", reason: "not-granted" };
218
- const deadlineAt = Date.now() + 30_000;
219
- const signal = AbortSignal.timeout(30_000);
220
350
  const output = await invokeModuleOperation(current.module, record.operation, input, {
221
351
  executionId: "approval:" + record.recordId,
222
352
  toolCallId: "approval:" + record.recordId,
@@ -1,6 +1,6 @@
1
1
  /** Installation records and pure admission rules; tenant state and commits stay host-owned. */
2
2
  export { applyGrantCommand, appAuthoritySchema, grantCommandSchema, type AppAuthority, type GrantCommand, type GrantContext, type GrantRefusal, applyInstallationCommand, approvedGrantSchema, declaredOperationsSchema, installationCommandSchema, installationIdSchema, installationRefusalSchema, installationSchema, type Approval, type ApprovedGrant, type CapabilityOperationDescriptor, type DeclaredOperations, grantChangeSchema, type GrantChange, type Installation, type InstallationCommand, type InstallationContext, type InstallationReader, type InstallationRefusal, type InstallationUpdate, type ResourceRef, unstampedFingerprint, } from "./installation.js";
3
- export { permissionPinsSchema, permissionSaveSchema, type PermissionPins, appPermissionsWireSchema, appPermissionPageSchema, permissionScreen, draftOf, editPermissions, planGrantChange, rebaseDraft, type PermissionDraft, type PermissionEdit, type PermissionScreen, type AppPermissionsWire, type AppPermissionsPort, type AppPermissionsViewData, grantRequestFor, pendingCapabilities, type GrantRequestDecision, type ResourceOption, } from "./permissions.js";
3
+ export { permissionPinsSchema, permissionSaveSchema, type PermissionPins, appPermissionsWireSchema, appPermissionPageSchema, permissionScreen, draftOf, editPermissions, planGrantChange, rebaseDraft, type PermissionDraft, type PermissionEdit, type PermissionScreen, type AppPermissionsWire, type AppPermissionsPort, type AppPermissionsViewData, grantRequestFor, pendingCapabilities, type GrantRequestDecision, appCallTargetName, type ResourceOption, } from "./permissions.js";
4
4
  export { admits, admitMethodMetadata, appInvocationCeiling, approvedBindingGrants, scopedBindings, grantsFor, gateRefusalSchema, gateRequestSchema, invocationGrantsSchema, type AppMethodDeclaration, type AppMethodMetadataDecision, type GateDecision, type GateFacts, type GateRequest, type HostPrincipal, type InvocationGrants, } from "./gate.js";
5
5
  export { deriveDeclaredOperations, appCallOperation } from "./operations.js";
6
6
  export { appToolPolicySchema, type AppToolAccess, type AppToolEntry, type AppToolPolicy, } from "./tools.js";
@@ -1,6 +1,6 @@
1
1
  /** Installation records and pure admission rules; tenant state and commits stay host-owned. */
2
2
  export { applyGrantCommand, appAuthoritySchema, grantCommandSchema, applyInstallationCommand, approvedGrantSchema, declaredOperationsSchema, installationCommandSchema, installationIdSchema, installationRefusalSchema, installationSchema, grantChangeSchema, unstampedFingerprint, } from "./installation.js";
3
- export { permissionPinsSchema, permissionSaveSchema, appPermissionsWireSchema, appPermissionPageSchema, permissionScreen, draftOf, editPermissions, planGrantChange, rebaseDraft, grantRequestFor, pendingCapabilities, } from "./permissions.js";
3
+ export { permissionPinsSchema, permissionSaveSchema, appPermissionsWireSchema, appPermissionPageSchema, permissionScreen, draftOf, editPermissions, planGrantChange, rebaseDraft, grantRequestFor, pendingCapabilities, appCallTargetName, } from "./permissions.js";
4
4
  export { admits, admitMethodMetadata, appInvocationCeiling, approvedBindingGrants, scopedBindings, grantsFor, gateRefusalSchema, gateRequestSchema, invocationGrantsSchema, } from "./gate.js";
5
5
  export { deriveDeclaredOperations, appCallOperation } from "./operations.js";
6
6
  export { appToolPolicySchema, } from "./tools.js";
@@ -124,8 +124,8 @@ export declare const closeResultSchema: z.ZodObject<{
124
124
  leaseId: z.ZodString;
125
125
  closed: z.ZodLiteral<true>;
126
126
  provider: z.ZodEnum<{
127
- closed: "closed";
128
127
  closing: "closing";
128
+ closed: "closed";
129
129
  }>;
130
130
  }, z.core.$strict>;
131
131
  /** Parsed `markdown` input. */
@@ -5,16 +5,18 @@ import { WorkerEntrypoint } from "cloudflare:workers";
5
5
  import { type GuestLimits } from "./guest-policy.js";
6
6
  export type { GuestLimits } from "./guest-policy.js";
7
7
  import type { ArtifactHeads, ArtifactDeletes, ArtifactStore, ArtifactStreams, VerifiedObjectCache } from "./release.js";
8
- import { type AppBackendBindingName } from "@fungi.computer/puffball/app";
8
+ import { type AppBackendBindingName, type AppMethodCallContext } from "@fungi.computer/puffball/app";
9
9
  import { type InvocationFrame, type InvocationGate } from "./invocation.js";
10
+ import * as Effect from "effect/Effect";
10
11
  import * as Schema from "effect/Schema";
11
12
  import { z } from "zod";
12
13
  import type { ResourceRef } from "./apps/installation.js";
13
- import type { Release } from "@fungi.computer/puffball";
14
+ import type { Release, AppApi } from "@fungi.computer/puffball";
14
15
  import { type UiBootCheckOutcome } from "./boot-gate.js";
16
+ import { type AppTestCopy, type AppTestCopyAuthority, type AppTestCopyPorts } from "./app-test-copies.js";
15
17
  export { checkBackendConstruction } from "./boot-construction.js";
16
18
  import type { WatchdogSqliteOwner } from "@fungi.computer/watchdog";
17
- import { AppInstanceError, type AppInstance, type InstancePorts } from "./index.js";
19
+ import { AppInstanceError, type AppInstance, type Backend, type InstancePorts } from "./index.js";
18
20
  /**
19
21
  * The zone's edge cache as a {@link VerifiedObjectCache}: each verified object
20
22
  * under a digest-named key on `origin` that no route serves. A failed write is
@@ -122,6 +124,69 @@ export type AppInstanceLoader<FacetClass> = Readonly<{
122
124
  getDurableObjectClass: (exportName: string) => FacetClass;
123
125
  }>;
124
126
  }>;
127
+ /** Verified code and its declaration travel together at the copy boundary. */
128
+ export type AppTestCopyBackend = Backend & Readonly<{
129
+ api: AppApi | null;
130
+ }>;
131
+ /**
132
+ * Disposable App-data siblings use the same native facade and wire decoder as
133
+ * live invocation, but no invocation frame, binding factory or live host env.
134
+ * The surrounding Instance owns current authority and shared alarm scheduling.
135
+ */
136
+ export declare function createCloudflareAppTestCopies<FacetClass>(ctx: AppInstanceContext<FacetClass>, loader: AppInstanceLoader<FacetClass> | undefined, ports: Pick<AppTestCopyPorts, "source" | "wake"> & Readonly<{
137
+ limits?: () => GuestLimits;
138
+ resolve: (releaseId: AppTestCopy["selection"]["releaseId"]) => Effect.Effect<AppTestCopyBackend, Error>;
139
+ }>, limits?: Partial<GuestLimits>): {
140
+ /** Clone current App data once under the retained request and fixed deadline. */
141
+ open: (authority: AppTestCopyAuthority, requestId: string) => Effect.Effect<{
142
+ selection: {
143
+ readonly instanceId: import("./instance-id.js").InstanceId;
144
+ readonly owner: {
145
+ readonly kind: "installation" | "deployment";
146
+ readonly id: string;
147
+ };
148
+ readonly appId: import("@fungi.computer/puffball").AppId;
149
+ readonly releaseId: import("@fungi.computer/puffball").ReleaseId;
150
+ readonly authorityVersion: number;
151
+ };
152
+ storeGeneration: string;
153
+ copyId: string;
154
+ expiresAt: number;
155
+ }, Error | AppInstanceError, never>;
156
+ /** Observe the sibling, retiring expired or unavailable source selections. */
157
+ inspect: (authority: AppTestCopyAuthority) => Effect.Effect<{
158
+ selection: {
159
+ readonly instanceId: import("./instance-id.js").InstanceId;
160
+ readonly owner: {
161
+ readonly kind: "installation" | "deployment";
162
+ readonly id: string;
163
+ };
164
+ readonly appId: import("@fungi.computer/puffball").AppId;
165
+ readonly releaseId: import("@fungi.computer/puffball").ReleaseId;
166
+ readonly authorityVersion: number;
167
+ };
168
+ storeGeneration: string;
169
+ copyId: string;
170
+ expiresAt: number;
171
+ } | null, Error | AppInstanceError, never>;
172
+ /** Discard only this resource, retaining its latest request receipt. */
173
+ discard: (authority: AppTestCopyAuthority, copyId: string) => Effect.Effect<boolean, Error, never>;
174
+ /** Shared native alarm cleanup; incomplete phases need no source service. */
175
+ expire: () => Effect.Effect<void, Error, never>;
176
+ /** Retire the sibling when its owning installation loses authority. */
177
+ revoke: () => Effect.Effect<void, Error, never>;
178
+ /** Run ordinary backend HTTP with bounded bodies and no live bindings. */
179
+ fetch: (authority: AppTestCopyAuthority, copyId: string, request: Request) => Effect.Effect<Response, Error | AppInstanceError, never>;
180
+ /** Use the ordinary typed facade and verified method codecs, without live grants. */
181
+ call: (authority: AppTestCopyAuthority, copyId: string, method: string, input: Schema.Json, caller: AppMethodCallContext) => Effect.Effect<{
182
+ kind: "ok";
183
+ value: z.core.util.JSONType;
184
+ } | {
185
+ kind: "refused";
186
+ code: "invalid" | "unavailable" | "conflict" | "forbidden" | "not_found";
187
+ message: string;
188
+ }, Error | AppInstanceError, never>;
189
+ };
125
190
  /** Stop the shared native App facet at cohort drain or revocation. */
126
191
  export declare function createCloudflareInvocationGate<Host, FacetClass>(ctx: Pick<AppInstanceContext<FacetClass>, "facets">, close: (frame: InvocationFrame<Host>) => Promise<void>): InvocationGate<Host>;
127
192
  /**
@@ -1,4 +1,56 @@
1
- import { appMethodReplySchema } from "@fungi.computer/agar/backend";
1
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
16
+ env.stack.push({ value: value, dispose: dispose, async: async });
17
+ }
18
+ else if (async) {
19
+ env.stack.push({ async: true });
20
+ }
21
+ return value;
22
+ };
23
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
24
+ return function (env) {
25
+ function fail(e) {
26
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
27
+ env.hasError = true;
28
+ }
29
+ var r, s = 0;
30
+ function next() {
31
+ while (r = env.stack.pop()) {
32
+ try {
33
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
34
+ if (r.dispose) {
35
+ var result = r.dispose.call(r.value);
36
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
37
+ }
38
+ else s |= 1;
39
+ }
40
+ catch (e) {
41
+ fail(e);
42
+ }
43
+ }
44
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
45
+ if (env.hasError) throw env.error;
46
+ }
47
+ return next();
48
+ };
49
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
50
+ var e = new Error(message);
51
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
+ });
53
+ import { appBackendComputerHeader, appMethodReplySchema, } from "@fungi.computer/agar/backend";
2
54
  import { nativeGitFrameMethods } from "@fungi.computer/agar/git-rpc";
3
55
  import { rpcHandleSchema, rpcMethod } from "@fungi.computer/agar/rpc";
4
56
  import { facetInvocationModule, facetFrameBindingModule, } from "./facet-invocation.js";
@@ -10,13 +62,17 @@ import { WorkerEntrypoint } from "cloudflare:workers";
10
62
  import { guestLimits } from "./guest-policy.js";
11
63
  import { headContentObject } from "./build/content-objects.js";
12
64
  import { appBackendBindingKinds, } from "@fungi.computer/puffball/app";
13
- import { isAppApiMethodName } from "@fungi.computer/puffball/app-method-runtime";
65
+ import { isAppApiMethodName, parseAppMethodCallContext, } from "@fungi.computer/puffball/app-method-runtime";
66
+ import { appMethodSchemas } from "@fungi.computer/forage";
14
67
  import { createInvocationGate, invocationFrameIdSchema, } from "./invocation.js";
15
68
  import * as Effect from "effect/Effect";
69
+ import * as Exit from "effect/Exit";
16
70
  import * as Schema from "effect/Schema";
17
71
  import { z } from "zod";
18
72
  import { BACKEND_CONSTRUCTION_FACET, checkBackendConstruction, } from "./boot-construction.js";
19
- import { BootGateError } from "./boot-gate.js";
73
+ import { BOOT_DEADLINE_MS, BootGateError, } from "./boot-gate.js";
74
+ import { appFacetRequest, appFacetResponse } from "./backend-request.js";
75
+ import { createAppTestCopies, } from "./app-test-copies.js";
20
76
  export { checkBackendConstruction } from "./boot-construction.js";
21
77
  import { createAppInstance, AppInstanceError, instanceIdSchema, instanceSchema, appInstanceErrorCodeSchema, } from "./index.js";
22
78
  const bindingWire = createFrameBindingWire(appInstanceErrorCodeSchema.literals);
@@ -270,6 +326,161 @@ const facetInvocationSchema = rpcHandleSchema({
270
326
  invoke: rpcMethod(z.union([z.json(), z.undefined()])).input(z.tuple([z.string(), z.array(z.unknown()), z.unknown()])),
271
327
  http: rpcMethod(facetHttpReplySchema).input(z.tuple([facetHttpInputSchema, z.unknown()])),
272
328
  });
329
+ /**
330
+ * Disposable App-data siblings use the same native facade and wire decoder as
331
+ * live invocation, but no invocation frame, binding factory or live host env.
332
+ * The surrounding Instance owns current authority and shared alarm scheduling.
333
+ */
334
+ export function createCloudflareAppTestCopies(ctx, loader, ports, limits) {
335
+ const name = "test-copy";
336
+ const instanceId = ctx.id.name;
337
+ if (!instanceId)
338
+ throw new Error("Named Instance required");
339
+ const copies = createAppTestCopies({
340
+ owner: ctx.storage,
341
+ now: Date.now,
342
+ source: () => ports
343
+ .source()
344
+ .pipe(Effect.flatMap((source) => source !== null && source.instance.instanceId !== instanceId
345
+ ? Effect.fail(new AppInstanceError("instance_identity_mismatch"))
346
+ : Effect.succeed(source))),
347
+ wake: ports.wake,
348
+ clone: () => Effect.try({
349
+ try: () => {
350
+ if (loader === undefined)
351
+ throw new AppInstanceError("boot_runner_unavailable");
352
+ if (ctx.facets.clone === undefined)
353
+ throw new AppInstanceError("boot_clone_unavailable");
354
+ ctx.facets.clone("app", name);
355
+ },
356
+ catch: (cause) => cause instanceof AppInstanceError
357
+ ? cause
358
+ : new AppInstanceError("boot_clone_unavailable", { cause }),
359
+ }),
360
+ purge: () => Effect.try({
361
+ try: () => {
362
+ try {
363
+ ctx.facets.abort(name, new AppInstanceError("revoked"));
364
+ }
365
+ finally {
366
+ ctx.facets.delete(name);
367
+ }
368
+ },
369
+ catch: (cause) => new AppInstanceError("boot_cleanup_failed", { cause }),
370
+ }),
371
+ });
372
+ const bounded = (program) => program.pipe(Effect.timeoutOrElse({
373
+ duration: BOOT_DEADLINE_MS,
374
+ orElse: () => Effect.fail(new AppInstanceError("expired")),
375
+ }));
376
+ const closeOnFailure = (authority, copyId, program) => bounded(program).pipe(Effect.onExit((exit) => Exit.isFailure(exit)
377
+ ? copies.discard(authority, copyId).pipe(Effect.asVoid)
378
+ : Effect.void));
379
+ const execute = (authority, copyId, invoke) => closeOnFailure(authority, copyId, copies.withCopy(authority, copyId, (copy) => Effect.gen(function* () {
380
+ const artifact = yield* ports.resolve(copy.selection.releaseId);
381
+ const budget = guestLimits(ports.limits?.() ?? limits);
382
+ if (artifact.release.appId !== copy.selection.appId ||
383
+ artifact.release.releaseId !== copy.selection.releaseId)
384
+ return yield* Effect.fail(new AppInstanceError("instance_release_mismatch"));
385
+ return yield* Effect.tryPromise({
386
+ try: async () => {
387
+ const env_1 = { stack: [], error: void 0, hasError: false };
388
+ try {
389
+ if (loader === undefined)
390
+ throw new AppInstanceError("boot_runner_unavailable");
391
+ // Native get also memoizes the child class. End prior execution
392
+ // before selecting the current budget; abort preserves copied SQLite.
393
+ ctx.facets.abort(name, new AppInstanceError("revoked"));
394
+ const stub = __addDisposableResource(env_1, facetInvocationSchema.parse(ctx.facets.get(name, () => ({
395
+ class: loader
396
+ .get(`copy:${instanceId}:${copy.copyId}:${artifact.digest}:${String(budget.cpuMs)}:${String(budget.subRequests)}`, () => ({
397
+ compatibilityDate: artifact.backend.compatibilityDate,
398
+ mainModule: "invocation.js",
399
+ modules: {
400
+ "backend.js": artifact.backend.code,
401
+ "invocation.js": facetInvocationModule(artifact.backend.exportName),
402
+ "frame-binding-wire.js": facetFrameBindingModule,
403
+ },
404
+ env: {},
405
+ globalOutbound: null,
406
+ limits: budget,
407
+ }))
408
+ .getDurableObjectClass("AppInvocation"),
409
+ }))), false);
410
+ return await invoke(stub, artifact);
411
+ }
412
+ catch (e_1) {
413
+ env_1.error = e_1;
414
+ env_1.hasError = true;
415
+ }
416
+ finally {
417
+ __disposeResources(env_1);
418
+ }
419
+ },
420
+ catch: (cause) => cause instanceof AppInstanceError
421
+ ? cause
422
+ : cause instanceof Error
423
+ ? guestFailure(cause)
424
+ : new Error("Test copy execution failed"),
425
+ });
426
+ })));
427
+ return {
428
+ /** Clone current App data once under the retained request and fixed deadline. */
429
+ open: (authority, requestId) => bounded(copies.open(authority, requestId)),
430
+ /** Observe the sibling, retiring expired or unavailable source selections. */
431
+ inspect: (authority) => bounded(copies.inspect(authority)),
432
+ /** Discard only this resource, retaining its latest request receipt. */
433
+ discard: copies.discard,
434
+ /** Shared native alarm cleanup; incomplete phases need no source service. */
435
+ expire: copies.expire,
436
+ /** Retire the sibling when its owning installation loses authority. */
437
+ revoke: copies.revoke,
438
+ /** Run ordinary backend HTTP with bounded bodies and no live bindings. */
439
+ fetch: (authority, copyId, request) => execute(authority, copyId, async (stub) => {
440
+ const safe = appFacetRequest(request);
441
+ safe.headers.delete(appBackendComputerHeader);
442
+ const reply = facetHttpReplySchema.parse(await stub.http({
443
+ url: safe.url,
444
+ method: safe.method,
445
+ headers: [...safe.headers],
446
+ body: await readHttpBody(safe.body, requestBodyCeiling),
447
+ }, {}));
448
+ const body = await readHttpBody(reply.body, replyBodyCeiling);
449
+ return appFacetResponse(new Response(body, {
450
+ status: reply.status,
451
+ statusText: reply.statusText,
452
+ headers: reply.headers,
453
+ }));
454
+ }),
455
+ /** Use the ordinary typed facade and verified method codecs, without live grants. */
456
+ call: (authority, copyId, method, input, caller) => execute(authority, copyId, async (stub, artifact) => {
457
+ const decoded = parseAppMethodCallContext(caller, true);
458
+ if (decoded.actor.kind !== "member" ||
459
+ decoded.role !== "owner" ||
460
+ artifact.api === null ||
461
+ !isAppApiMethodName(method) ||
462
+ !Object.hasOwn(artifact.api.methods, method))
463
+ throw new AppInstanceError("invalid_invocation_facts");
464
+ const codec = appMethodSchemas(artifact.api)[method];
465
+ if (codec === undefined)
466
+ throw new AppInstanceError("invalid_invocation_facts");
467
+ // Attribution is not a live call frame: no Computer, workflow or durable lane.
468
+ const context = parseAppMethodCallContext({
469
+ actor: decoded.actor,
470
+ role: "owner",
471
+ computerId: null,
472
+ }, true);
473
+ const reply = Schema.decodeUnknownSync(Schema.Json)(await stub.invoke(method, [codec.input.parse(input), context], {}));
474
+ if (new TextEncoder().encode(JSON.stringify(reply)).byteLength >
475
+ MAX_APP_REPLY_BYTES)
476
+ throw new Error("App result too large");
477
+ const parsed = appMethodReplySchema.parse(reply);
478
+ if (parsed.kind === "ok")
479
+ codec.output.parse(parsed.value);
480
+ return parsed;
481
+ }),
482
+ };
483
+ }
273
484
  /** Stop the shared native App facet at cohort drain or revocation. */
274
485
  export function createCloudflareInvocationGate(ctx, close) {
275
486
  return createInvocationGate({