@fungi.computer/oyster 0.47.1 → 0.47.3

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.
@@ -623,6 +623,7 @@ export declare class AgentDirectory extends DurableObject<StandaloneAgentEnv> {
623
623
  /** The starter Agent's one-row ledger and the Agent total it reads, for the owner's ensure. */
624
624
  readStarter(): StarterLedgerRow | undefined;
625
625
  recordStarter(row: StarterLedgerRow): void;
626
+ forgetStarter(): void;
626
627
  /** Every Agent in the directory, archived ones included. */
627
628
  agentTotal(): number;
628
629
  /** Resolve the existing recorded creator for host-side owner admission. */
@@ -2400,6 +2400,9 @@ export class AgentDirectory extends DurableObject {
2400
2400
  recordStarter(row) {
2401
2401
  this.starterLedger.record(row);
2402
2402
  }
2403
+ forgetStarter() {
2404
+ this.starterLedger.forget();
2405
+ }
2403
2406
  /** Every Agent in the directory, archived ones included. */
2404
2407
  agentTotal() {
2405
2408
  return this.directory.list(this.grant()).length;
@@ -2714,6 +2717,13 @@ export function standaloneAgents(env, scope) {
2714
2717
  const directory = () => scope === undefined
2715
2718
  ? env.AGENT_DIRECTORY.getByName(directoryName)
2716
2719
  : agentDirectoryForScope(env, scope);
2720
+ // The starter's state lives in the directory's storage: this adapter is
2721
+ // rebuilt for every Worker request, so it remembers nothing itself.
2722
+ const starterLedger = {
2723
+ read: () => directory().readStarter(),
2724
+ record: (row) => directory().recordStarter(row),
2725
+ forget: () => directory().forgetStarter(),
2726
+ };
2717
2727
  const toAgent = (entry) => ({
2718
2728
  agentId: entry.agentId,
2719
2729
  name: entry.name,
@@ -2749,7 +2759,7 @@ export function standaloneAgents(env, scope) {
2749
2759
  return agent.setArchived(archived);
2750
2760
  },
2751
2761
  create: created,
2752
- ensureStarter: (principal) => {
2762
+ ensureStarter: (principal, keepAlive) => {
2753
2763
  const owner = directory();
2754
2764
  const reportStarterFailure = (cause) => {
2755
2765
  void redactedFailure(cause).then((text) => {
@@ -2757,10 +2767,8 @@ export function standaloneAgents(env, scope) {
2757
2767
  });
2758
2768
  };
2759
2769
  return ensureStarterAgent({
2760
- ledger: {
2761
- read: () => owner.readStarter(),
2762
- record: (row) => owner.recordStarter(row),
2763
- },
2770
+ ledger: starterLedger,
2771
+ keepAlive,
2764
2772
  isOwner: () => oysterPrincipalIsOwner(principal),
2765
2773
  agentCount: () => owner.agentTotal(),
2766
2774
  // The ordinary create, then the ordinary owner attach of the host's own
@@ -17,23 +17,45 @@ export declare const starterAgent: {
17
17
  export declare function seedStarterHome(
18
18
  /** Where this host keeps Home's AGENTS.md. */
19
19
  instructionsPath: string, writeIfMissing: (path: string, content: string) => Promise<void>): Promise<void>;
20
- /** What the ledger remembers: that the starter was settled, never to be offered again. */
20
+ /** Why the last create or Home seed attempt failed, in plain words. */
21
+ export type StarterFailure = Readonly<{
22
+ reason: string;
23
+ at: number;
24
+ }>;
25
+ /**
26
+ * What the ledger remembers, durably, so a restart or a fresh Worker request
27
+ * resumes the starter instead of forgetting it. `creating` is recorded before
28
+ * the create starts, so a create cut off after reserving the Agent is replayed
29
+ * by its `requestId`, never read as a Team that already had Agents.
30
+ * `seed-pending` means the starter exists but its Home is not seeded yet.
31
+ * `attemptAt` is when the running attempt started: within the bound it is
32
+ * still running somewhere; past it, with no `failure`, it was cut off.
33
+ */
21
34
  export type StarterLedgerRow = Readonly<{
22
35
  version: number;
23
- outcome: "seed-pending" | "created" | "team-not-empty";
36
+ outcome: "creating" | "seed-pending" | "created" | "team-not-empty";
24
37
  agentId: string | null;
25
38
  at: number;
39
+ attemptAt: number | null;
40
+ failure: StarterFailure | null;
26
41
  }>;
27
42
  /** One row per Team in the host's own SQLite. */
28
43
  export type StarterLedgerStore = Readonly<{
29
44
  read(): StarterLedgerRow | undefined;
30
- /** First write wins, except completing the same pending starter's seed. */
45
+ /**
46
+ * First write wins. Afterwards only an unsettled starter moves on: a
47
+ * `creating` row to its next attempt, `seed-pending` or `created`; a
48
+ * `seed-pending` row to its next attempt or `created`, for the same Agent.
49
+ */
31
50
  record(row: StarterLedgerRow): void;
51
+ /** Drop a `creating` row whose create was refused for funding. */
52
+ forget(): void;
32
53
  }>;
33
54
  /** The ledger as the policy reads it; a host across an RPC awaits its store. */
34
55
  export type StarterLedger = Readonly<{
35
56
  read(): StarterLedgerRow | undefined | Promise<StarterLedgerRow | undefined>;
36
57
  record(row: StarterLedgerRow): void | Promise<void>;
58
+ forget(): void | Promise<void>;
37
59
  }>;
38
60
  /** The host's ordinary create, as the starter sees it. */
39
61
  export type StarterCreateResult = Readonly<{
@@ -53,19 +75,85 @@ export type StarterAgentHost = Readonly<{
53
75
  name: string;
54
76
  requestId: string;
55
77
  }): Promise<StarterCreateResult>;
56
- /** Hosts with a Home seed it atomically; failure leaves a retryable ledger row. */
78
+ /**
79
+ * Hosts with a Home seed it atomically. The seed runs in the background,
80
+ * bounded by `timeoutMs`; a failure leaves a retryable ledger row.
81
+ */
57
82
  seedHome?(agentId: string): Promise<void>;
83
+ /**
84
+ * Keep background work alive after the read answers: a stateless Worker
85
+ * passes its `waitUntil`. A host whose process outlives the read omits it;
86
+ * work cut off anyway is resumed from the ledger by a later offer.
87
+ */
88
+ keepAlive?: ((work: Promise<unknown>) => void) | undefined;
89
+ /** How long the create or one Home seed may take before it counts as failed; default 60 s. */
90
+ timeoutMs?: number;
91
+ /** How long a read waits for the create before answering `starting`; default 5 s. */
92
+ readWaitMs?: number;
93
+ /**
94
+ * Whether this offer starts a create or seed that last failed again (the
95
+ * default). A status read passes false, so a failure stays visible until a
96
+ * retry. An attempt that was cut off is always resumed.
97
+ */
98
+ retryFailedSeed?: boolean;
99
+ /**
100
+ * Why the create or seed failed, in plain words for the owner, completing
101
+ * "Your Computer didn't start: ...". One that ran out of time arrives as a
102
+ * `StarterTimeout`.
103
+ */
104
+ describeSeedFailure?(cause: unknown): string;
58
105
  /** Where a failed attempt is reported; the caller's read never fails. */
59
106
  report?(cause: unknown): void;
60
107
  now?(): number;
61
108
  }>;
62
- /** How one offer of the starter Agent settled; only `created` made an Agent. */
63
- export type StarterOutcome = "created" | "already-offered" | "team-not-empty" | "unfunded" | "not-owner" | "failed";
109
+ /** The default bound on the starter's create and on one Home seed. */
110
+ export declare const starterTimeoutMs = 60000;
111
+ /** The default time a read waits for the starter's create. */
112
+ export declare const starterReadWaitMs = 5000;
113
+ /** A create or Home seed that did not finish within its bound. */
114
+ export declare class StarterTimeout extends Error {
115
+ readonly timeoutMs: number;
116
+ constructor(timeoutMs: number);
117
+ }
118
+ /**
119
+ * Where the starter stands, for the owner's first run: `starting` while its
120
+ * create runs (or is owed), `seeding` while its Home seed runs (or is owed),
121
+ * `failed` with the plain reason of the last attempt (`agentId` null when the
122
+ * create itself failed), `ready` once seeded, `none` when there is no starter.
123
+ */
124
+ export type StarterSeedStatus = Readonly<{
125
+ state: "none";
126
+ }> | Readonly<{
127
+ state: "starting";
128
+ }> | Readonly<{
129
+ state: "seeding";
130
+ agentId: string;
131
+ }> | Readonly<{
132
+ state: "ready";
133
+ agentId: string;
134
+ }> | Readonly<{
135
+ state: "failed";
136
+ agentId: string | null;
137
+ reason: string;
138
+ at: number;
139
+ }>;
140
+ /**
141
+ * How one offer of the starter Agent settled. `created` and `seeding` both
142
+ * mean the Agent exists; `seeding` means its Home seed is still running;
143
+ * `starting` means its create is still running.
144
+ */
145
+ export type StarterOutcome = "created" | "seeding" | "starting" | "already-offered" | "team-not-empty" | "unfunded" | "not-owner" | "failed";
64
146
  /** Open the one-row ledger in the host's own SQLite. */
65
147
  export declare function createStarterLedger(sql: WatchdogSqliteOwner["sql"]): StarterLedgerStore;
66
148
  /**
67
149
  * Offer the starter Agent if this Team never had its chance. Safe to call on
68
150
  * every owner directory read: concurrent calls share one attempt, and the
69
151
  * host's `requestId` replay makes a second attempt return the same Agent.
152
+ * It waits at most `readWaitMs` for the create and never for the Home seed:
153
+ * both run on in the background, bounded, and `starterSeedStatus` says how
154
+ * they went. Everything it knows is in the ledger, so an attempt cut off by
155
+ * a restart is resumed by the next offer once its bound has passed.
70
156
  */
71
157
  export declare function ensureStarterAgent(host: StarterAgentHost): Promise<StarterOutcome>;
158
+ /** Where the starter stands, read from the ledger alone. */
159
+ export declare function starterSeedStatus(ledger: StarterLedger): Promise<StarterSeedStatus>;
@@ -45,19 +45,48 @@ work and where it lives on my Computer, how they like updates.)
45
45
  - Never save secrets, keys, passwords or payment details here.
46
46
  - Keep this file under 200 lines; tidy it when it grows.
47
47
  `;
48
+ /** The default bound on the starter's create and on one Home seed. */
49
+ export const starterTimeoutMs = 60_000;
50
+ /** The default time a read waits for the starter's create. */
51
+ export const starterReadWaitMs = 5_000;
52
+ /** A create or Home seed that did not finish within its bound. */
53
+ export class StarterTimeout extends Error {
54
+ timeoutMs;
55
+ constructor(timeoutMs) {
56
+ const seconds = Math.max(1, Math.round(timeoutMs / 1000));
57
+ super(`it did not answer within ${String(seconds)} second${seconds === 1 ? "" : "s"}`);
58
+ this.timeoutMs = timeoutMs;
59
+ this.name = "StarterTimeout";
60
+ }
61
+ }
48
62
  const ledgerRowSchema = z.strictObject({
49
63
  version: z.number().int(),
50
- outcome: z.enum(["seed-pending", "created", "team-not-empty"]),
64
+ outcome: z.enum(["creating", "seed-pending", "created", "team-not-empty"]),
51
65
  agent_id: z.string().nullable(),
52
66
  at: z.number(),
67
+ attempt_at: z.number().nullable(),
68
+ failure_reason: z.string().nullable(),
69
+ failure_at: z.number().nullable(),
53
70
  });
71
+ const ledgerColumnsSchema = z.array(z.object({ name: z.string() }));
54
72
  /** Open the one-row ledger in the host's own SQLite. */
55
73
  export function createStarterLedger(sql) {
56
- sql.exec("CREATE TABLE IF NOT EXISTS starter_agent (id INTEGER PRIMARY KEY CHECK (id = 1), version INTEGER NOT NULL, outcome TEXT NOT NULL, agent_id TEXT, at INTEGER NOT NULL) STRICT");
74
+ sql.exec("CREATE TABLE IF NOT EXISTS starter_agent (id INTEGER PRIMARY KEY CHECK (id = 1), version INTEGER NOT NULL, outcome TEXT NOT NULL, agent_id TEXT, at INTEGER NOT NULL, attempt_at INTEGER, failure_reason TEXT, failure_at INTEGER) STRICT");
75
+ // A ledger stored before attempts were durable has none of their columns.
76
+ const columns = new Set(ledgerColumnsSchema
77
+ .parse(sql.exec("PRAGMA table_info(starter_agent)").toArray())
78
+ .map(({ name }) => name));
79
+ for (const [column, type] of [
80
+ ["attempt_at", "INTEGER"],
81
+ ["failure_reason", "TEXT"],
82
+ ["failure_at", "INTEGER"],
83
+ ])
84
+ if (!columns.has(column))
85
+ sql.exec(`ALTER TABLE starter_agent ADD COLUMN ${column} ${type}`);
57
86
  return {
58
87
  read() {
59
88
  const row = sql
60
- .exec("SELECT version, outcome, agent_id, at FROM starter_agent WHERE id = 1")
89
+ .exec("SELECT version, outcome, agent_id, at, attempt_at, failure_reason, failure_at FROM starter_agent WHERE id = 1")
61
90
  .toArray()[0];
62
91
  if (row === undefined)
63
92
  return undefined;
@@ -67,10 +96,17 @@ export function createStarterLedger(sql) {
67
96
  outcome: stored.outcome,
68
97
  agentId: stored.agent_id,
69
98
  at: stored.at,
99
+ attemptAt: stored.attempt_at,
100
+ failure: stored.failure_reason === null || stored.failure_at === null
101
+ ? null
102
+ : { reason: stored.failure_reason, at: stored.failure_at },
70
103
  };
71
104
  },
72
105
  record(row) {
73
- 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);
106
+ sql.exec("INSERT INTO starter_agent(id, version, outcome, agent_id, at, attempt_at, failure_reason, failure_at) VALUES(1, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET outcome = excluded.outcome, agent_id = excluded.agent_id, attempt_at = excluded.attempt_at, failure_reason = excluded.failure_reason, failure_at = excluded.failure_at WHERE (starter_agent.outcome = 'creating' AND excluded.outcome IN ('creating', 'seed-pending', 'created')) OR (starter_agent.outcome = 'seed-pending' AND excluded.outcome IN ('seed-pending', 'created') AND starter_agent.agent_id = excluded.agent_id)", row.version, row.outcome, row.agentId, row.at, row.attemptAt, row.failure?.reason ?? null, row.failure?.at ?? null);
107
+ },
108
+ forget() {
109
+ sql.exec("DELETE FROM starter_agent WHERE outcome = 'creating'");
74
110
  },
75
111
  };
76
112
  }
@@ -79,6 +115,10 @@ const inFlight = new WeakMap();
79
115
  * Offer the starter Agent if this Team never had its chance. Safe to call on
80
116
  * every owner directory read: concurrent calls share one attempt, and the
81
117
  * host's `requestId` replay makes a second attempt return the same Agent.
118
+ * It waits at most `readWaitMs` for the create and never for the Home seed:
119
+ * both run on in the background, bounded, and `starterSeedStatus` says how
120
+ * they went. Everything it knows is in the ledger, so an attempt cut off by
121
+ * a restart is resumed by the next offer once its bound has passed.
82
122
  */
83
123
  export function ensureStarterAgent(host) {
84
124
  const running = inFlight.get(host.ledger);
@@ -88,55 +128,203 @@ export function ensureStarterAgent(host) {
88
128
  inFlight.set(host.ledger, attempt);
89
129
  return attempt;
90
130
  }
131
+ /** Where the starter stands, read from the ledger alone. */
132
+ export async function starterSeedStatus(ledger) {
133
+ const row = await ledger.read();
134
+ if (row === undefined || row.outcome === "team-not-empty")
135
+ return { state: "none" };
136
+ const { agentId, failure } = row;
137
+ if (row.outcome === "creating")
138
+ return failure === null
139
+ ? { state: "starting" }
140
+ : { state: "failed", agentId: null, ...failure };
141
+ if (agentId === null)
142
+ return { state: "none" };
143
+ if (row.outcome === "created")
144
+ return { state: "ready", agentId };
145
+ return failure === null
146
+ ? { state: "seeding", agentId }
147
+ : { state: "failed", agentId, ...failure };
148
+ }
149
+ function withDeadline(work, timeoutMs) {
150
+ let timer;
151
+ let expired = false;
152
+ const deadline = new Promise((_, reject) => {
153
+ timer = setTimeout(() => {
154
+ expired = true;
155
+ reject(new StarterTimeout(timeoutMs));
156
+ }, timeoutMs);
157
+ });
158
+ const bounded = Promise.race([work, deadline]).finally(() => {
159
+ clearTimeout(timer);
160
+ });
161
+ return { bounded, timedOut: () => expired };
162
+ }
163
+ function describe(host, cause) {
164
+ if (host.describeSeedFailure !== undefined)
165
+ return host.describeSeedFailure(cause);
166
+ return cause instanceof Error
167
+ ? cause.message
168
+ : "the Computer did not say why";
169
+ }
170
+ /** Record why `attempt` failed; a row that has moved on since keeps its state. */
171
+ async function fail(host, attempt, cause) {
172
+ host.report?.(cause);
173
+ await host.ledger.record({
174
+ ...attempt,
175
+ failure: { reason: describe(host, cause), at: (host.now ?? Date.now)() },
176
+ });
177
+ }
178
+ /** Whether `row`'s attempt may still be running somewhere. */
179
+ function attemptLive(host, row) {
180
+ return (row.failure === null &&
181
+ row.attemptAt !== null &&
182
+ (host.now ?? Date.now)() <
183
+ row.attemptAt + (host.timeoutMs ?? starterTimeoutMs));
184
+ }
185
+ /**
186
+ * Run `work` within the bound: on success `done` records the result; on
187
+ * failure the attempt's row records why. The read never awaits it.
188
+ */
189
+ function runBounded(host, attempt, work) {
190
+ const { bounded, timedOut } = withDeadline(work, host.timeoutMs ?? starterTimeoutMs);
191
+ const settled = bounded.then((value) => value, async (cause) => {
192
+ try {
193
+ await fail(host, attempt, cause);
194
+ }
195
+ catch (recordCause) {
196
+ // Reported; the attempt's row stays live until its bound passes.
197
+ host.report?.(recordCause);
198
+ }
199
+ return "failed";
200
+ });
201
+ // Work that outlives its bound may still finish and record its result; one
202
+ // that fails after its timeout was recorded is reported too.
203
+ const late = work.catch((cause) => {
204
+ if (timedOut())
205
+ host.report?.(cause);
206
+ });
207
+ host.keepAlive?.(Promise.all([settled, late]));
208
+ return settled;
209
+ }
210
+ /** Start the Home seed for an existing starter, recording the attempt first. */
211
+ async function startSeed(host, seedHome, row, agentId) {
212
+ const attempt = {
213
+ ...row,
214
+ outcome: "seed-pending",
215
+ agentId,
216
+ attemptAt: (host.now ?? Date.now)(),
217
+ failure: null,
218
+ };
219
+ await host.ledger.record(attempt);
220
+ const seeded = Promise.resolve()
221
+ .then(() => seedHome(agentId))
222
+ .then(() => host.ledger.record({ ...attempt, outcome: "created" }));
223
+ void runBounded(host, attempt, seeded);
224
+ }
225
+ /**
226
+ * Record the `creating` attempt, then run the host's create with its
227
+ * continuation attached, so a create that lands after a read stopped waiting
228
+ * still records the starter and seeds it.
229
+ */
230
+ async function startCreate(host, row) {
231
+ const attempt = {
232
+ ...row,
233
+ outcome: "creating",
234
+ agentId: null,
235
+ attemptAt: (host.now ?? Date.now)(),
236
+ failure: null,
237
+ };
238
+ await host.ledger.record(attempt);
239
+ const landed = Promise.resolve()
240
+ .then(() => host.create({
241
+ name: starterAgent.name,
242
+ requestId: starterAgent.requestId,
243
+ }))
244
+ .then(async (result) => {
245
+ if (result.status === "unfunded") {
246
+ await host.ledger.forget();
247
+ return "unfunded";
248
+ }
249
+ if (host.seedHome === undefined) {
250
+ await host.ledger.record({
251
+ ...attempt,
252
+ outcome: "created",
253
+ agentId: result.agentId,
254
+ attemptAt: null,
255
+ });
256
+ return "created";
257
+ }
258
+ await startSeed(host, host.seedHome, attempt, result.agentId);
259
+ return "seeding";
260
+ });
261
+ return runBounded(host, attempt, landed);
262
+ }
91
263
  async function settle(host) {
92
264
  try {
93
265
  if (!host.isOwner())
94
266
  return "not-owner";
95
- const previous = await host.ledger.read();
96
- if (previous !== undefined) {
97
- if (previous.outcome !== "seed-pending")
98
- return "already-offered";
99
- if (previous.agentId === null || host.seedHome === undefined)
100
- throw new Error("Pending starter has no Home seed owner");
101
- await host.seedHome(previous.agentId);
102
- await host.ledger.record({ ...previous, outcome: "created" });
103
- return "created";
104
- }
105
- const at = (host.now ?? Date.now)();
106
- if ((await host.agentCount()) > 0) {
107
- await host.ledger.record({
267
+ const row = await host.ledger.read();
268
+ const retry = host.retryFailedSeed !== false;
269
+ if (row === undefined) {
270
+ const at = (host.now ?? Date.now)();
271
+ if ((await host.agentCount()) > 0) {
272
+ await host.ledger.record({
273
+ version: starterAgent.version,
274
+ outcome: "team-not-empty",
275
+ agentId: null,
276
+ at,
277
+ attemptAt: null,
278
+ failure: null,
279
+ });
280
+ return "team-not-empty";
281
+ }
282
+ return await waitForCreate(host, startCreate(host, {
108
283
  version: starterAgent.version,
109
- outcome: "team-not-empty",
284
+ outcome: "creating",
110
285
  agentId: null,
111
286
  at,
112
- });
113
- return "team-not-empty";
287
+ attemptAt: null,
288
+ failure: null,
289
+ }));
114
290
  }
115
- const result = await host.create({
116
- name: starterAgent.name,
117
- requestId: starterAgent.requestId,
118
- });
119
- if (result.status === "unfunded")
120
- return "unfunded";
121
- if (host.seedHome !== undefined) {
122
- await host.ledger.record({
123
- version: starterAgent.version,
124
- outcome: "seed-pending",
125
- agentId: result.agentId,
126
- at,
127
- });
128
- await host.seedHome(result.agentId);
291
+ if (row.outcome === "created" || row.outcome === "team-not-empty")
292
+ return "already-offered";
293
+ const live = attemptLive(host, row);
294
+ if (row.outcome === "creating") {
295
+ if (live)
296
+ return "starting";
297
+ if (row.failure !== null && !retry)
298
+ return "failed";
299
+ return await waitForCreate(host, startCreate(host, row));
129
300
  }
130
- await host.ledger.record({
131
- version: starterAgent.version,
132
- outcome: "created",
133
- agentId: result.agentId,
134
- at,
135
- });
136
- return "created";
301
+ const { agentId } = row;
302
+ if (agentId === null || host.seedHome === undefined)
303
+ throw new Error("Pending starter has no Home seed owner");
304
+ if (live)
305
+ return "seeding";
306
+ if (row.failure !== null && !retry)
307
+ return "failed";
308
+ await startSeed(host, host.seedHome, row, agentId);
309
+ return "seeding";
137
310
  }
138
311
  catch (cause) {
139
312
  host.report?.(cause);
140
313
  return "failed";
141
314
  }
142
315
  }
316
+ /** Wait at most `readWaitMs` for the create; past that the read answers `starting`. */
317
+ async function waitForCreate(host, outcome) {
318
+ let waited;
319
+ const readWait = new Promise((resolve) => {
320
+ waited = setTimeout(() => {
321
+ resolve("starting");
322
+ }, host.readWaitMs ?? starterReadWaitMs);
323
+ });
324
+ try {
325
+ return await Promise.race([outcome, readWait]);
326
+ }
327
+ finally {
328
+ clearTimeout(waited);
329
+ }
330
+ }
@@ -0,0 +1,13 @@
1
+ import * as Stream from "effect/Stream";
2
+ import type { AppStorageEvent, AppStorageError, AppStorageResult } from "@fungi.computer/agar/storage";
3
+ import type { StorageWatch } from "./storage-watch-wire.js";
4
+ /** The owner's answer for one key: its change stream, or why it refuses it. */
5
+ export type StorageKeyWatch = AppStorageResult<Stream.Stream<AppStorageEvent | null, AppStorageError>>;
6
+ /**
7
+ * Merge the owner's per-key change streams into one stream of server-sent
8
+ * watch frames, each key admitted by `openKey` under fresh authority. A
9
+ * refused key is a `rejected` frame carrying its code while the rest keep
10
+ * flowing. The result is pull-driven, and cancelling it interrupts every key's
11
+ * own subscription.
12
+ */
13
+ export declare function storageWatchStream(watches: readonly StorageWatch[], openKey: (watch: StorageWatch) => Promise<StorageKeyWatch>): ReadableStream<Uint8Array>;
@@ -0,0 +1,19 @@
1
+ import * as Effect from "effect/Effect";
2
+ import * as Stream from "effect/Stream";
3
+ /**
4
+ * Merge the owner's per-key change streams into one stream of server-sent
5
+ * watch frames, each key admitted by `openKey` under fresh authority. A
6
+ * refused key is a `rejected` frame carrying its code while the rest keep
7
+ * flowing. The result is pull-driven, and cancelling it interrupts every key's
8
+ * own subscription.
9
+ */
10
+ export function storageWatchStream(watches, openKey) {
11
+ const encoder = new TextEncoder();
12
+ const encode = (frame) => encoder.encode(`event: watch\ndata: ${JSON.stringify(frame)}\n\n`);
13
+ const one = (watch, index) => Stream.unwrap(Effect.map(Effect.promise(() => openKey(watch)), (opened) => opened.kind === "rejected"
14
+ ? Stream.make(encode({ watch: index, kind: "rejected", code: opened.code }))
15
+ : opened.value.pipe(Stream.map((event) => encode(event === null
16
+ ? { watch: index, kind: "ready" }
17
+ : { watch: index, kind: "changed", event })))));
18
+ return Stream.toReadableStream(Stream.mergeAll(watches.map(one), { concurrency: "unbounded" }));
19
+ }
@@ -0,0 +1,29 @@
1
+ import * as Schema from "effect/Schema";
2
+ /** One page watches many storage keys; browsers cap HTTP/1.1 hosts at six connections. */
3
+ export declare const maxStorageWatches = 64;
4
+ /** One watched storage key, named by the installation that owns it. */
5
+ export declare const storageWatchSchema: Schema.Tuple<readonly [Schema.String, Schema.String]>;
6
+ export type StorageWatch = typeof storageWatchSchema.Type;
7
+ /**
8
+ * What the shared stream says about one watch, by its position in the request:
9
+ * the key is ready, the key changed, or the owner refused the watch with the
10
+ * same code a dedicated read would have carried.
11
+ */
12
+ export declare const storageWatchFrameSchema: Schema.Union<readonly [Schema.Struct<{
13
+ readonly watch: Schema.Number;
14
+ readonly kind: Schema.Literal<"ready">;
15
+ }>, Schema.Struct<{
16
+ readonly watch: Schema.Number;
17
+ readonly kind: Schema.Literal<"changed">;
18
+ readonly event: Schema.Struct<{
19
+ readonly appId: Schema.String;
20
+ readonly key: Schema.String;
21
+ readonly scope: Schema.Literals<readonly ["team", "member"]>;
22
+ readonly revision: Schema.Int;
23
+ }>;
24
+ }>, Schema.Struct<{
25
+ readonly watch: Schema.Number;
26
+ readonly kind: Schema.Literal<"rejected">;
27
+ readonly code: Schema.Literals<readonly ["invalid", "undeclared_key", "scope_not_declared", "owner_required", "too_large", "quota_exceeded", "conflict", "unavailable"]>;
28
+ }>]>;
29
+ export type StorageWatchFrame = typeof storageWatchFrameSchema.Type;
@@ -0,0 +1,24 @@
1
+ import * as Schema from "effect/Schema";
2
+ import { appStorageErrorCodeSchema, appStorageEventSchema, } from "@fungi.computer/agar/storage";
3
+ /** One page watches many storage keys; browsers cap HTTP/1.1 hosts at six connections. */
4
+ export const maxStorageWatches = 64;
5
+ /** One watched storage key, named by the installation that owns it. */
6
+ export const storageWatchSchema = Schema.Tuple([Schema.String, Schema.String]);
7
+ /**
8
+ * What the shared stream says about one watch, by its position in the request:
9
+ * the key is ready, the key changed, or the owner refused the watch with the
10
+ * same code a dedicated read would have carried.
11
+ */
12
+ export const storageWatchFrameSchema = Schema.Union([
13
+ Schema.Struct({ watch: Schema.Number, kind: Schema.Literal("ready") }),
14
+ Schema.Struct({
15
+ watch: Schema.Number,
16
+ kind: Schema.Literal("changed"),
17
+ event: appStorageEventSchema,
18
+ }),
19
+ Schema.Struct({
20
+ watch: Schema.Number,
21
+ kind: Schema.Literal("rejected"),
22
+ code: appStorageErrorCodeSchema,
23
+ }),
24
+ ]);
package/dist/workers.d.ts CHANGED
@@ -8,6 +8,7 @@ import { type BrowserBinding } from "./browser/sessions.js";
8
8
  import { type InstallationOperationRequest, type InstallationOperationReply } from "./installation-operations.js";
9
9
  import { installationWorkerEntrypoint } from "./installation-execution.js";
10
10
  export { installationWorkerEntrypoint };
11
+ import type { StorageWatch } from "./storage-watch-wire.js";
11
12
  import { type BackgroundSyncRefusal } from "@fungi.computer/puffball/background-replay";
12
13
  import { type TenantScope, type TenantId } from "./tenant.js";
13
14
  import { type GillCall, type GillReply } from "@fungi.computer/gills";
@@ -213,8 +214,8 @@ export declare class OysterRegistry<Env extends OysterWorkerEnv = OysterWorkerEn
213
214
  storageClaim(installationId: string, ownerId: string, input: AppStorageClaim): Promise<AppStorageResult<AppStorageClaimed>>;
214
215
  /** Storage for a live owner method frame; no guest-selected installation or member. */
215
216
  storageBackend(raw: InvocationFacts, method: string, args: readonly unknown[], tenantId: TenantId): Promise<OysterBindingResult>;
216
- /** Open the existing App-storage invalidation stream under fresh owner admission. */
217
- storageEvents(installationId: string, ownerId: string, key: string): Promise<Response>;
217
+ /** Watch many storage keys as one stream, each under fresh owner admission. */
218
+ storageWatch(ownerId: string, watches: readonly StorageWatch[]): ReadableStream<Uint8Array>;
218
219
  private storageResult;
219
220
  private storageOwner;
220
221
  /**