@fungi.computer/oyster 0.33.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.
@@ -5,9 +5,13 @@ export const starterAgent = {
5
5
  name: "Shiitake",
6
6
  requestId: "starter-agent:v1",
7
7
  };
8
+ /** Seed only a missing Home file; the host supplies an atomic create-if-absent. */
9
+ export async function seedStarterHome(writeIfMissing) {
10
+ await writeIfMissing("AGENTS.md", '## First conversation\nYour person is new to Fungi. In your first conversation, load the\n`setup-fungi` skill with skill.load({name: "setup-fungi"}) and follow it.\nWhen setup is finished, delete this section.\n');
11
+ }
8
12
  const ledgerRowSchema = z.strictObject({
9
13
  version: z.number().int(),
10
- outcome: z.enum(["created", "team-not-empty"]),
14
+ outcome: z.enum(["seed-pending", "created", "team-not-empty"]),
11
15
  agent_id: z.string().nullable(),
12
16
  at: z.number(),
13
17
  });
@@ -30,7 +34,7 @@ export function createStarterLedger(sql) {
30
34
  };
31
35
  },
32
36
  record(row) {
33
- sql.exec("INSERT INTO starter_agent(id, version, outcome, agent_id, at) VALUES(1, ?, ?, ?, ?) ON CONFLICT(id) DO NOTHING", row.version, row.outcome, row.agentId, row.at);
37
+ sql.exec("INSERT INTO starter_agent(id, version, outcome, agent_id, at) VALUES(1, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET outcome = excluded.outcome WHERE starter_agent.outcome = 'seed-pending' AND excluded.outcome = 'created' AND starter_agent.agent_id = excluded.agent_id", row.version, row.outcome, row.agentId, row.at);
34
38
  },
35
39
  };
36
40
  }
@@ -52,8 +56,16 @@ async function settle(host) {
52
56
  try {
53
57
  if (!host.isOwner())
54
58
  return "not-owner";
55
- if ((await host.ledger.read()) !== undefined)
56
- return "already-offered";
59
+ const previous = await host.ledger.read();
60
+ if (previous !== undefined) {
61
+ if (previous.outcome !== "seed-pending")
62
+ return "already-offered";
63
+ if (previous.agentId === null || host.seedHome === undefined)
64
+ throw new Error("Pending starter has no Home seed owner");
65
+ await host.seedHome(previous.agentId);
66
+ await host.ledger.record({ ...previous, outcome: "created" });
67
+ return "created";
68
+ }
57
69
  const at = (host.now ?? Date.now)();
58
70
  if ((await host.agentCount()) > 0) {
59
71
  await host.ledger.record({
@@ -70,6 +82,15 @@ async function settle(host) {
70
82
  });
71
83
  if (result.status === "unfunded")
72
84
  return "unfunded";
85
+ if (host.seedHome !== undefined) {
86
+ await host.ledger.record({
87
+ version: starterAgent.version,
88
+ outcome: "seed-pending",
89
+ agentId: result.agentId,
90
+ at,
91
+ });
92
+ await host.seedHome(result.agentId);
93
+ }
73
94
  await host.ledger.record({
74
95
  version: starterAgent.version,
75
96
  outcome: "created",
package/dist/workers.d.ts CHANGED
@@ -3,6 +3,7 @@ import type { HostActor, AppMethodCallContext } from "@fungi.computer/puffball/a
3
3
  import { type OysterApprovalCall } from "./approval-home.js";
4
4
  import { type BootCapabilityGrant, type BootCapabilityLease } from "./boot-capability.js";
5
5
  import { type Installation } from "./apps/installation.js";
6
+ import { type UiBootCheckOutcome } from "./boot-gate.js";
6
7
  import { type BrowserBinding } from "./browser/sessions.js";
7
8
  import { type InstallationOperationRequest, type InstallationOperationReply } from "./installation-operations.js";
8
9
  import { installationWorkerEntrypoint } from "./installation-execution.js";
@@ -19,7 +20,7 @@ import { r2FileSource } from "./r2-files.js";
19
20
  import { type FileSource } from "./files.js";
20
21
  import { DurableObject, type WorkerEntrypoint } from "cloudflare:workers";
21
22
  import * as Schema from "effect/Schema";
22
- import type { Release } from "@fungi.computer/puffball";
23
+ import { type Release } from "@fungi.computer/puffball";
23
24
  import { type Backend, type Instance, type OwnerState } from "./index.js";
24
25
  import { r2ArtifactStore, type FrameBindingReply, type FrameBindingMethod, type FrameBindingProps } from "./cloudflare.js";
25
26
  import type { AppTestCopy, AppTestCopyAuthority } from "./app-test-copies.js";
@@ -78,7 +79,7 @@ export type OysterWorkerEnv = Readonly<{
78
79
  /** Worker Loader that runs App backends. */
79
80
  LOADER: WorkerLoader;
80
81
  }>;
81
- /** The installation registry: one SQLite-backed Durable Object per Oyster. */
82
+ /** Installation metadata and UI verdicts in one SQLite-backed Durable Object per tenant. */
82
83
  export declare class OysterRegistry<Env extends OysterWorkerEnv = OysterWorkerEnv> extends DurableObject<Env> {
83
84
  #private;
84
85
  /** The plain root has the same single owner-key host as OysterInstance. */
@@ -87,17 +88,14 @@ export declare class OysterRegistry<Env extends OysterWorkerEnv = OysterWorkerEn
87
88
  approvalSubmit(pin: Readonly<{
88
89
  tenantId: string;
89
90
  origin: string;
90
- }>, call: OysterApprovalCall): Promise<{
91
- readonly kind: "pending_approval";
92
- readonly recordId: string;
93
- readonly description: {
94
- readonly title: string;
95
- readonly inputBytes: number;
96
- readonly inputSha256: string;
97
- };
98
- } | import("@fungi.computer/approvals").ApprovalApplyResult>;
91
+ }>, call: OysterApprovalCall): Promise<import("./approval-home.js").OysterApprovalResult>;
92
+ /** Cancellation has the same trusted host identity as submission, never App input. */
93
+ approvalCancel(pin: Readonly<{
94
+ tenantId: string;
95
+ origin: string;
96
+ }>, call: OysterApprovalCall): Promise<void>;
99
97
  private approvalHome;
100
- /** Recover approved work from the durable home, not a last-request memory pin. */
98
+ /** Expire approvals; no alarm may dispatch a waiting call's App write. */
101
99
  private approvalAlarm;
102
100
  /** Read a bounded page for the current member of the pinned native home. */
103
101
  approvalList(pin: Readonly<{
@@ -123,6 +121,10 @@ export declare class OysterRegistry<Env extends OysterWorkerEnv = OysterWorkerEn
123
121
  readonly title: string;
124
122
  readonly inputBytes: number;
125
123
  readonly inputSha256: string;
124
+ readonly app?: {
125
+ readonly displayName: string;
126
+ readonly operationLabel: string;
127
+ } | undefined;
126
128
  };
127
129
  readonly by: {
128
130
  readonly kind: "human";
@@ -134,8 +136,8 @@ export declare class OysterRegistry<Env extends OysterWorkerEnv = OysterWorkerEn
134
136
  readonly state: "pending" | "expired" | "denied" | "applied" | "requested" | "approved" | "claimed" | "outcome_unknown";
135
137
  readonly updatedAt: number;
136
138
  readonly module: string;
137
- readonly recordId: string;
138
139
  readonly authorityFence: string;
140
+ readonly recordId: string;
139
141
  readonly requester: {
140
142
  readonly principalId: string;
141
143
  readonly agentId: string | null;
@@ -234,6 +236,21 @@ export declare class OysterRegistry<Env extends OysterWorkerEnv = OysterWorkerEn
234
236
  compareAndPut(installation: Installation, expectedAuthorityVersion: number, expectedGeneration: string, tenantId?: TenantId): Promise<InstallationCommit>;
235
237
  private writeInstallation;
236
238
  private decode;
239
+ /** Trusted host verdicts, local to this tenant, origin, Release and check version. */
240
+ bootUiResult(input: Readonly<{
241
+ tenantId: string;
242
+ origin: string;
243
+ releaseId: string;
244
+ artifactDigest: string;
245
+ checkVersion: string;
246
+ }> & (Readonly<{
247
+ kind: "read";
248
+ }> | Readonly<{
249
+ kind: "record";
250
+ outcome: Exclude<UiBootCheckOutcome, {
251
+ kind: "not_checked";
252
+ }>;
253
+ }>)): UiBootCheckOutcome | null;
237
254
  /** Issue, resolve, or revoke one bounded capability without storing its token. */
238
255
  bootCapability(input: Readonly<{
239
256
  kind: "issue";
package/dist/workers.js CHANGED
@@ -6,8 +6,8 @@ import { z } from "zod";
6
6
  import { bootCapabilityGrantSchema, bootCapabilityLeaseSchema, reportBootPage, validateCapabilityAssetSet, } from "./boot-capability.js";
7
7
  import { serveBootCapability } from "./boot-capability-route.js";
8
8
  import { installationSchema, isCommittedInstallation, } from "./apps/installation.js";
9
- import { BOOT_DEADLINE_MS, BOOT_TRANSPORT_GRACE_MS, readBootUi, } from "./boot-gate.js";
10
- import { checkBootPage } from "./browser/boot.js";
9
+ import { BOOT_DEADLINE_MS, BOOT_TRANSPORT_GRACE_MS, readBootUi, uiBootCheckOutcomeSchema, } from "./boot-gate.js";
10
+ import { BOOT_CHECK_VERSION, checkBootPage } from "./browser/boot.js";
11
11
  import { bindingSessions } from "./browser/sessions.js";
12
12
  import { registryInstallations } from "./internal/registry-installations.js";
13
13
  import { migrateInstallationRows } from "./installation-migration.js";
@@ -34,6 +34,7 @@ import { DurableObject } from "cloudflare:workers";
34
34
  import * as Effect from "effect/Effect";
35
35
  import * as Schema from "effect/Schema";
36
36
  import * as Stream from "effect/Stream";
37
+ import { parseReleaseId, parseSha256Digest, } from "@fungi.computer/puffball";
37
38
  import { releaseSchema } from "@fungi.computer/puffball/effect";
38
39
  import { AppInstanceError, } from "./index.js";
39
40
  import { createCloudflareAppInstance, createCloudflareAppTestCopies, r2ArtifactStore, createCloudflareInvocationGate, edgeVerifiedObjectCache, decodeFrameBindingProps, captureFrameBindingReply, frameBindingEntrypoint, backgroundFrameMethods, } from "./cloudflare.js";
@@ -62,11 +63,13 @@ const bootCapabilityRows = z.array(z.strictObject({
62
63
  expires_at: z.number().int(),
63
64
  record: z.string().max(2_000_000),
64
65
  }));
66
+ const recordedBootOutcome = uiBootCheckOutcomeSchema.refine((outcome) => outcome.kind !== "not_checked", "An inconclusive UI check is not a Release verdict");
67
+ const bootResultRow = z.strictObject({ record: z.string() });
65
68
  const approvalHomePinRow = Schema.Struct({
66
69
  tenant_id: tenantIdSchema,
67
70
  origin: Schema.String,
68
71
  });
69
- /** The installation registry: one SQLite-backed Durable Object per Oyster. */
72
+ /** Installation metadata and UI verdicts in one SQLite-backed Durable Object per tenant. */
70
73
  export class OysterRegistry extends DurableObject {
71
74
  #installationStore;
72
75
  /** Decided once, before this version writes anything, and never revised. */
@@ -81,6 +84,10 @@ export class OysterRegistry extends DurableObject {
81
84
  approvalSubmit(pin, call) {
82
85
  return this.approvalHome(pin).submit(call);
83
86
  }
87
+ /** Cancellation has the same trusted host identity as submission, never App input. */
88
+ approvalCancel(pin, call) {
89
+ return this.approvalHome(pin).cancel(call);
90
+ }
84
91
  approvalHome(pin) {
85
92
  const scope = tenantScope(Schema.decodeUnknownSync(tenantIdSchema)(pin.tenantId), pin.origin);
86
93
  if (this.ctx.id.name !== scope.durableName("registry"))
@@ -116,7 +123,7 @@ export class OysterRegistry extends DurableObject {
116
123
  });
117
124
  return this.#approval;
118
125
  }
119
- /** Recover approved work from the durable home, not a last-request memory pin. */
126
+ /** Expire approvals; no alarm may dispatch a waiting call's App write. */
120
127
  async approvalAlarm() {
121
128
  const raw = this.ctx.storage.sql
122
129
  .exec("SELECT tenant_id, origin FROM oyster_approval_home WHERE id = 1")
@@ -166,6 +173,7 @@ export class OysterRegistry extends DurableObject {
166
173
  migrateInstallationRows(ctx.storage);
167
174
  this.#installationStore = createInstallationStoreGeneration(ctx.storage);
168
175
  ctx.storage.sql.exec("CREATE TABLE IF NOT EXISTS boot_capabilities (id TEXT PRIMARY KEY, token_digest TEXT NOT NULL, expires_at INTEGER NOT NULL, record TEXT NOT NULL) STRICT");
176
+ ctx.storage.sql.exec("CREATE TABLE IF NOT EXISTS oyster_boot_results (origin TEXT NOT NULL, release_id TEXT NOT NULL, artifact_digest TEXT NOT NULL, check_version TEXT NOT NULL, record TEXT NOT NULL, PRIMARY KEY (origin, release_id, artifact_digest, check_version)) STRICT");
169
177
  ensureAppSourceTables(ctx.storage.sql);
170
178
  this.#installationOperations = createInstallationOperations({
171
179
  owner: ctx.storage,
@@ -438,6 +446,25 @@ export class OysterRegistry extends DurableObject {
438
446
  const { record } = Schema.decodeUnknownSync(recordRow)(row);
439
447
  return installationSchema.parse(JSON.parse(record));
440
448
  }
449
+ /** Trusted host verdicts, local to this tenant, origin, Release and check version. */
450
+ bootUiResult(input) {
451
+ const scope = tenantScope(Schema.decodeUnknownSync(tenantIdSchema)(input.tenantId), input.origin);
452
+ if (this.ctx.id.name !== scope.durableName("registry"))
453
+ throw new Error("Boot result namespace does not match tenant");
454
+ const releaseId = parseReleaseId(input.releaseId);
455
+ const artifactDigest = parseSha256Digest(input.artifactDigest);
456
+ const checkVersion = z.string().min(1).parse(input.checkVersion);
457
+ if (input.kind === "record") {
458
+ const outcome = recordedBootOutcome.parse(input.outcome);
459
+ this.ctx.storage.sql.exec("INSERT INTO oyster_boot_results (origin, release_id, artifact_digest, check_version, record) VALUES (?, ?, ?, ?, ?) ON CONFLICT (origin, release_id, artifact_digest, check_version) DO NOTHING", scope.origin, releaseId, artifactDigest, checkVersion, JSON.stringify(outcome));
460
+ }
461
+ const row = this.ctx.storage.sql
462
+ .exec("SELECT record FROM oyster_boot_results WHERE origin = ? AND release_id = ? AND artifact_digest = ? AND check_version = ?", scope.origin, releaseId, artifactDigest, checkVersion)
463
+ .toArray()[0];
464
+ return row === undefined
465
+ ? null
466
+ : recordedBootOutcome.parse(JSON.parse(bootResultRow.parse(row).record));
467
+ }
441
468
  /** Issue, resolve, or revoke one bounded capability without storing its token. */
442
469
  bootCapability(input) {
443
470
  if (input.kind === "issue") {
@@ -1214,20 +1241,38 @@ export function serveOysterBootCapability(request, env, scope) {
1214
1241
  /**
1215
1242
  * The standalone UI boot check: the Worker's own BROWSER binding opens the
1216
1243
  * pinned `/_boot/` page on the host-selected origin, with a capability in
1217
- * that tenant's registry. Without a BROWSER binding the UI is not checked.
1244
+ * that tenant's registry. Definitive results survive separate installations
1245
+ * and registry restarts, but never cross an origin, tenant or check version.
1246
+ * Without a BROWSER binding an unchecked UI remains not checked.
1218
1247
  */
1219
1248
  function oysterBootUi(env, scope) {
1220
1249
  const artifacts = r2ArtifactStore(env.RELEASES);
1221
1250
  const capabilities = registryBootCapabilities(env, scope);
1222
1251
  const sessions = env.BROWSER === undefined ? null : bindingSessions(env.BROWSER);
1223
- return (release) => reportBootPage({
1224
- origin: scope.origin,
1225
- check: sessions === null ? null : (target) => checkBootPage(sessions, target),
1226
- readUi: () => readBootUi(artifacts, release),
1227
- bucket: env.RELEASES,
1228
- capabilities,
1229
- now: Date.now,
1230
- });
1252
+ const registry = () => env.REGISTRY.getByName(scope.durableName("registry"));
1253
+ return async (release) => {
1254
+ const key = {
1255
+ tenantId: scope.tenantId,
1256
+ origin: scope.origin,
1257
+ releaseId: release.releaseId,
1258
+ artifactDigest: release.artifact.artifactDigest,
1259
+ checkVersion: BOOT_CHECK_VERSION,
1260
+ };
1261
+ const recorded = await registry().bootUiResult({ ...key, kind: "read" });
1262
+ if (recorded !== null)
1263
+ return recordedBootOutcome.parse(recorded);
1264
+ const outcome = await reportBootPage({
1265
+ origin: scope.origin,
1266
+ check: sessions === null ? null : (target) => checkBootPage(sessions, target),
1267
+ readUi: () => readBootUi(artifacts, release),
1268
+ bucket: env.RELEASES,
1269
+ capabilities,
1270
+ now: Date.now,
1271
+ });
1272
+ if (outcome.kind === "not_checked")
1273
+ return outcome;
1274
+ return recordedBootOutcome.parse(await registry().bootUiResult({ ...key, kind: "record", outcome }));
1275
+ };
1231
1276
  }
1232
1277
  /**
1233
1278
  * Create an Oyster host backed by this Worker environment's registry,
@@ -1248,7 +1293,29 @@ export function oysterWorkerHost(env, auth, options = {}) {
1248
1293
  });
1249
1294
  let host = {
1250
1295
  approvals: {
1251
- submit: (call) => registry().approvalSubmit({ tenantId: scope.tenantId, origin: scope.origin }, call),
1296
+ submit: async (call, signal) => {
1297
+ const cancelled = () => signal.aborted;
1298
+ if (cancelled())
1299
+ return { kind: "refused", reason: "cancelled" };
1300
+ const home = registry();
1301
+ const result = home.approvalSubmit(pin, call);
1302
+ const aborted = Promise.withResolvers();
1303
+ const onAbort = () => {
1304
+ aborted.resolve(undefined);
1305
+ };
1306
+ signal.addEventListener("abort", onAbort, { once: true });
1307
+ try {
1308
+ if (cancelled())
1309
+ onAbort();
1310
+ await Promise.race([result, aborted.promise]);
1311
+ if (cancelled())
1312
+ await home.approvalCancel(pin, call);
1313
+ return await result;
1314
+ }
1315
+ finally {
1316
+ signal.removeEventListener("abort", onAbort);
1317
+ }
1318
+ },
1252
1319
  },
1253
1320
  auth,
1254
1321
  workbench: {
package/docs/api/apps.md CHANGED
@@ -2400,3 +2400,24 @@ longer listed by the host.
2400
2400
  #### Returns
2401
2401
 
2402
2402
  [`PermissionScreen`](#permissionscreen)
2403
+
2404
+ ---
2405
+
2406
+ ### appCallTargetName()
2407
+
2408
+ ```ts
2409
+ function appCallTargetName(directory, appId): string;
2410
+ ```
2411
+
2412
+ The directory's display name for an App-call target, else the shared plain copy.
2413
+
2414
+ #### Parameters
2415
+
2416
+ | Parameter | Type |
2417
+ | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2418
+ | `directory` | \| `Readonly`\<\{ `apps`: readonly `Readonly`\<\{ `appId`: `string`; `displayName?`: `string`; \}\>[]; `installing?`: readonly `Readonly`\<\{ `appId?`: `string`; `displayName`: `string`; \}\>[]; \}\> \| `null` |
2419
+ | `appId` | `string` |
2420
+
2421
+ #### Returns
2422
+
2423
+ `string`
package/docs/api/host.md CHANGED
@@ -94,6 +94,45 @@ Observed sibling identity and nonrenewing deadline, never live host grants.
94
94
 
95
95
  ---
96
96
 
97
+ ### OysterApprovalResult
98
+
99
+ ```ts
100
+ type OysterApprovalResult =
101
+ | Exclude<
102
+ ApprovalApplyResult,
103
+ {
104
+ kind: "refused";
105
+ }
106
+ >
107
+ | Readonly<{
108
+ kind: "denied";
109
+ by: string;
110
+ note?: string;
111
+ message: string;
112
+ }>
113
+ | Readonly<{
114
+ kind: "refused";
115
+ reason:
116
+ | Exclude<
117
+ Extract<
118
+ ApprovalApplyResult,
119
+ {
120
+ kind: "refused";
121
+ }
122
+ >["reason"],
123
+ "expired"
124
+ >
125
+ | "approval_expired"
126
+ | "cancelled";
127
+ denialNote?: string;
128
+ }>;
129
+ ```
130
+
131
+ The originating call receives the output or this terminal decision, never a
132
+ pending notice.
133
+
134
+ ---
135
+
97
136
  ### CapabilityMethodKind
98
137
 
99
138
  ```ts
@@ -405,17 +444,7 @@ Variables: TimingVariables;
405
444
  ```ts
406
445
  type OysterHost = Readonly<{
407
446
  approvals?: Readonly<{
408
- submit: Promise<
409
- | {
410
- kind: Schema.Literal<"pending_approval">;
411
- recordId: Schema.String;
412
- description: Schema.Struct<{
413
- title: Schema.String;
414
- inputBytes: Schema.Int;
415
- inputSha256: Schema.String;
416
- }>;
417
- }
418
- | ApprovalApplyResult>;
447
+ submit: Promise<OysterApprovalResult>;
419
448
  }>;
420
449
  workflows?: (principal) => Promise<
421
450
  | {
@@ -146,11 +146,11 @@ One isolated App connection, with the slots this host admitted for it.
146
146
  ### appSandbox
147
147
 
148
148
  ```ts
149
- const appSandbox: "allow-scripts allow-modals allow-popups allow-forms" =
150
- "allow-scripts allow-modals allow-popups allow-forms";
149
+ const appSandbox: "allow-scripts allow-modals allow-popups allow-popups-to-escape-sandbox allow-forms" =
150
+ "allow-scripts allow-modals allow-popups allow-popups-to-escape-sandbox allow-forms";
151
151
  ```
152
152
 
153
- The sandbox every installed App frame runs in, shell-mounted or not.
153
+ Apps stay opaque; external tabs need their own origin for preview cookies.
154
154
 
155
155
  ## Functions
156
156