@fungi.computer/oyster 0.13.1 → 0.14.1

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.
@@ -8,8 +8,6 @@ export declare function agentMail(options: Omit<ConstructorParameters<typeof Age
8
8
  mailRoom: Readonly<{
9
9
  fanOut: (settlement: import("@fungi.computer/bird-dog").BirdDogSettlement) => import("effect/Effect").Effect<void, import("@fungi.computer/bird-dog/effect").BirdDogError>;
10
10
  postMail?: ((mail: import("@fungi.computer/bird-dog").BirdDogMail) => import("effect/Effect").Effect<void, import("@fungi.computer/bird-dog/effect").BirdDogError>) | undefined;
11
- drainOutbox: () => import("effect/Effect").Effect<void, import("@fungi.computer/bird-dog/effect").BirdDogError>;
12
- nextWakeAt: () => import("effect/Effect").Effect<number | undefined, import("@fungi.computer/bird-dog/effect").BirdDogError>;
13
11
  }> & {
14
12
  stageAcceptedNotice: (mail: import("@fungi.computer/bird-dog").BirdDogMail, scopeId: string) => void;
15
13
  };
@@ -20,7 +18,7 @@ export declare function agentMail(options: Omit<ConstructorParameters<typeof Age
20
18
  readJob: (jobId: string) => Promise<import("@fungi.computer/watchdog").WatchdogReadResult>;
21
19
  tickConcurrent: () => Promise<WatchdogTickResult>;
22
20
  }>) => {
23
- execute: (job: {
21
+ retryPolicy: (job: {
24
22
  readonly lane: string;
25
23
  readonly state: "running";
26
24
  readonly queue: string;
@@ -29,19 +27,48 @@ export declare function agentMail(options: Omit<ConstructorParameters<typeof Age
29
27
  readonly jobId: string;
30
28
  readonly recovery?: {
31
29
  readonly maxRecoveries: number;
30
+ readonly windowMs?: number | undefined;
32
31
  } | undefined;
32
+ readonly notBefore?: number | undefined;
33
33
  }) => Promise<Readonly<{
34
- kind: "completed";
34
+ baseMs: number;
35
+ maxMs: number;
36
+ limit: Readonly<{
37
+ maxAttempts: number;
38
+ }> | Readonly<{
39
+ deadlineAt: number;
40
+ }>;
35
41
  }>>;
42
+ execute: (job: {
43
+ readonly lane: string;
44
+ readonly state: "running";
45
+ readonly queue: string;
46
+ readonly priority: number;
47
+ readonly payload: unknown;
48
+ readonly jobId: string;
49
+ readonly recovery?: {
50
+ readonly maxRecoveries: number;
51
+ readonly windowMs?: number | undefined;
52
+ } | undefined;
53
+ readonly notBefore?: number | undefined;
54
+ }, signal: AbortSignal, attempt: Readonly<{
55
+ count: number;
56
+ status: "admitted" | "exhausted";
57
+ final: boolean;
58
+ }> | undefined) => Promise<{
59
+ readonly kind: "retry";
60
+ } | {
61
+ readonly kind: "completed";
62
+ } | {
63
+ readonly kind: "failed";
64
+ readonly reason?: string | undefined;
65
+ } | {
66
+ readonly kind: "cancelled";
67
+ } | {
68
+ readonly kind: "outcome_unknown";
69
+ }>;
36
70
  };
37
71
  };
38
- hostWork: {
39
- pending: () => {
40
- due: boolean;
41
- nextWakeAt: number | null;
42
- };
43
- run: () => Promise<void>;
44
- }[];
45
72
  };
46
73
  deliver: (value: Parameters<AgentMail["send"]>[0]) => Promise<import("@fungi.computer/shiitake").DelegationReceipt>;
47
74
  };
@@ -12,18 +12,10 @@ export function agentMail(options) {
12
12
  throw new Error("Agent Post is not open");
13
13
  return post;
14
14
  };
15
- const recover = async () => {
16
- let cursor;
17
- do {
18
- cursor = await runtime().enqueueDue(64, cursor);
19
- } while (cursor !== undefined);
20
- };
21
15
  const drain = async () => {
22
- await recover();
23
16
  if (tick === undefined)
24
17
  throw new Error("Agent Post lane is not open");
25
18
  await tick();
26
- await mail.stageUndeliverableReplies();
27
19
  };
28
20
  const mail = new AgentMail({ ...options, post: runtime, drain });
29
21
  const host = {
@@ -35,26 +27,20 @@ export function agentMail(options) {
35
27
  routes,
36
28
  owner: options.storage,
37
29
  transactional: owner.transactional,
38
- readJob: owner.readJob,
39
30
  now: Date.now,
40
31
  scheduleWake: options.wake,
41
32
  });
42
33
  tick = owner.tickConcurrent;
43
- return { execute: (job) => runtime().execute(job) };
34
+ return {
35
+ retryPolicy: (job) => runtime().retryPolicy(job),
36
+ execute: async (job, signal, attempt) => {
37
+ const decision = await runtime().execute(job, attempt, signal);
38
+ await mail.stageUndeliverableReplies();
39
+ return decision;
40
+ },
41
+ };
44
42
  },
45
43
  },
46
- hostWork: [
47
- {
48
- pending: () => {
49
- const nextWakeAt = runtime().nextWake();
50
- return {
51
- due: nextWakeAt !== null && nextWakeAt <= Date.now(),
52
- nextWakeAt,
53
- };
54
- },
55
- run: drain,
56
- },
57
- ],
58
44
  };
59
45
  return {
60
46
  host,
@@ -210,6 +210,7 @@ export declare abstract class StandaloneAgentBase<Env extends StandaloneAgentEnv
210
210
  private readComputerSnapshot;
211
211
  private ui;
212
212
  protected hostFetch(request: Request): Promise<Response> | undefined;
213
+ private readAgentModels;
213
214
  protected closeShiitake(): Promise<void>;
214
215
  private controlDirectory;
215
216
  private delegationOwner;
@@ -46,6 +46,8 @@ import { createAssistantMessageEventStream } from "@earendil-works/pi-ai/utils/e
46
46
  import { agentModelChoice, agentModelChoiceSchema, AgentModelRefused, selectAgentModel, } from "./agent-model-choice.js";
47
47
  import { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, createAiBindingFetch, } from "@earendil-works/pi-ai/api/cloudflare-ai-binding";
48
48
  import { cloudflareWorkersAIProvider } from "@earendil-works/pi-ai/providers/cloudflare-workers-ai";
49
+ import { getSupportedThinkingLevels } from "@earendil-works/pi-ai/models";
50
+ import { agentModelListSchema } from "@fungi.computer/shiitake/model-list";
49
51
  import * as Schema from "effect/Schema";
50
52
  import { z } from "zod";
51
53
  import {} from "../cloudflare.js";
@@ -544,6 +546,8 @@ export class StandaloneAgentBase extends ShiitakeDO {
544
546
  }
545
547
  hostFetch(request) {
546
548
  const pathname = new URL(request.url).pathname;
549
+ if (pathname === "/models" && request.method === "GET")
550
+ return this.readAgentModels();
547
551
  if (pathname.startsWith("/cloud-browser/"))
548
552
  return standaloneBrowserLiveView(this.env.BROWSER, () => ({
549
553
  teamId: this.env.OYSTER_ORIGIN,
@@ -559,6 +563,31 @@ export class StandaloneAgentBase extends ShiitakeDO {
559
563
  return this.preparedComputerSnapshot().then(() => this.runtimeOwner().fetch(request));
560
564
  return undefined;
561
565
  }
566
+ async readAgentModels() {
567
+ const pin = await this.policyDirectory();
568
+ const agentId = this.ctx.id.name;
569
+ if (pin === null ||
570
+ agentId === undefined ||
571
+ !(await this.env.AGENT_DIRECTORY.getByName(pin.directoryName).has(agentId)))
572
+ return new Response("Agent scope is unavailable", { status: 403 });
573
+ const choice = await this.readModelChoice();
574
+ // The same owner checks the chosen source before reporting it as available.
575
+ await this.sourceFor(choice);
576
+ const model = await selectAgentModel(choice);
577
+ return Response.json(agentModelListSchema.parse([
578
+ {
579
+ providerId: choice.model.providerId,
580
+ providerName: choice.keySource === "byok"
581
+ ? "Your provider key"
582
+ : choice.keySource === "workers-ai"
583
+ ? "Workers AI"
584
+ : "Fungi Gateway",
585
+ id: choice.model.modelId,
586
+ name: model.name,
587
+ reasoning: getSupportedThinkingLevels(model).filter((level) => level !== "off"),
588
+ },
589
+ ]));
590
+ }
562
591
  async closeShiitake() {
563
592
  try {
564
593
  await (await this.ui()).close();
@@ -1075,11 +1104,7 @@ export class StandaloneAgentBase extends ShiitakeDO {
1075
1104
  this.archiveControl().assertOpen();
1076
1105
  },
1077
1106
  },
1078
- hostWork: [
1079
- ...this.mail().host.hostWork,
1080
- ...keeping.hostWork,
1081
- this.archiveControl().work,
1082
- ],
1107
+ hostWork: [...keeping.hostWork, this.archiveControl().work],
1083
1108
  };
1084
1109
  }
1085
1110
  /** Send an installation-admitted message through fleet Session operations. */
@@ -92,6 +92,12 @@ class TryError extends Error {
92
92
  this.next = next;
93
93
  }
94
94
  }
95
+ /** A desktop-only failure still permits sign-in for recovery. */
96
+ class DesktopSetupError extends Error {
97
+ constructor(cause) {
98
+ super("Tourtois preparation failed.", { cause });
99
+ }
100
+ }
95
101
  /**
96
102
  * Streaming logs and interactive progress cannot share a terminal, so
97
103
  * --verbose prints plain lines.
@@ -219,6 +225,20 @@ function captureOutput(child, log, verbose) {
219
225
  stream?.pipe(process.stderr, { end: false });
220
226
  }
221
227
  }
228
+ const npmFailureSchema = z.object({ error: z.object({ code: z.string() }) });
229
+ function npmFailureCode(output) {
230
+ try {
231
+ const parsed = npmFailureSchema.safeParse(JSON.parse(output));
232
+ return parsed.success ? parsed.data.error.code : undefined;
233
+ }
234
+ catch (cause) {
235
+ if (!(cause instanceof SyntaxError))
236
+ throw cause;
237
+ // Lifecycle scripts can mix text into npm's JSON. The complete log remains
238
+ // available; unstructured output must retain the ordinary install failure.
239
+ return undefined;
240
+ }
241
+ }
222
242
  async function runInstall(directory, manager, verbose, signal) {
223
243
  signal.throwIfAborted();
224
244
  await mkdir(join(directory, ".oyster"), { recursive: true });
@@ -233,7 +253,7 @@ async function runInstall(directory, manager, verbose, signal) {
233
253
  ]));
234
254
  const stop = () => awaitCleanup(beginStop());
235
255
  try {
236
- child = spawn(manager, ["install"], {
256
+ child = spawn(manager, manager === "npm" ? ["install", "--json"] : ["install"], {
237
257
  cwd: directory,
238
258
  detached: process.platform !== "win32",
239
259
  signal,
@@ -241,6 +261,17 @@ async function runInstall(directory, manager, verbose, signal) {
241
261
  shell: process.platform === "win32",
242
262
  });
243
263
  captureOutput(child, log, verbose);
264
+ // npm owns the diagnostic format. Bound this extra copy; the file receives
265
+ // all output even when lifecycle scripts exceed the diagnostic budget.
266
+ let diagnostic = "";
267
+ let diagnosticBytes = 0;
268
+ if (manager === "npm") {
269
+ child.stdout?.setEncoding("utf8");
270
+ child.stdout?.on("data", (chunk) => {
271
+ diagnosticBytes += new TextEncoder().encode(chunk).byteLength;
272
+ diagnostic = diagnosticBytes <= 64 * 1024 ? diagnostic + chunk : "";
273
+ });
274
+ }
244
275
  const closed = new Promise((done, fail) => {
245
276
  let failure;
246
277
  child?.once("error", (cause) => {
@@ -251,8 +282,10 @@ async function runInstall(directory, manager, verbose, signal) {
251
282
  fail(failure);
252
283
  else if (code === 0)
253
284
  done();
254
- else
255
- fail(new Error(`${manager} install failed (exit ${String(code)}).`));
285
+ else {
286
+ const errorCode = npmFailureCode(diagnostic);
287
+ fail(Object.assign(new Error(`${manager} install failed (${errorCode === undefined ? "" : `${errorCode}; `}exit ${String(code)}).`), { code: errorCode }));
288
+ }
256
289
  });
257
290
  });
258
291
  listener = addAbortListener(signal, () => {
@@ -531,7 +564,12 @@ export async function tryOyster(args, effects = realEffects, ui = createTryCli(a
531
564
  await task(`Installing dependencies with ${manager}`, () => effects.installDependencies(directory, manager, verbose, signal)).catch((cause) => {
532
565
  if (isTryCancellation(cause, signal))
533
566
  throw cause;
534
- throw new TryError(innermostError(cause).message, `Keep this project. Read ${join(directory, installLogFile)}, fix the reported cause, then run \`${retry}\`. Dependencies will be retried; your key and files stay in place.`);
567
+ const failure = innermostError(cause);
568
+ if (isNetworkFailure(failure))
569
+ throw new TryError(`${manager} could not reach its package registry (${failure.code}).`, `Keep this project. Check your connection and ${manager} registry/proxy settings; details are in ${join(directory, installLogFile)}. Then run \`${retry}\`. Dependencies will be retried; your key and files stay in place.`);
570
+ if ("code" in failure && failure.code === "ERESOLVE")
571
+ throw new TryError(`${manager} could not resolve this project's dependencies (ERESOLVE).`, `Keep this project. Check registry access and the dependency versions reported in ${join(directory, installLogFile)}, then run \`${retry}\`. Dependencies will be retried; your key and files stay in place.`);
572
+ throw new TryError(failure.message, `Keep this project. Read ${join(directory, installLogFile)}, fix the reported cause, then run \`${retry}\`. Dependencies will be retried; your key and files stay in place.`);
535
573
  });
536
574
  await rm(join(directory, pendingInstall));
537
575
  }
@@ -569,25 +607,74 @@ export async function tryOyster(args, effects = realEffects, ui = createTryCli(a
569
607
  return result;
570
608
  });
571
609
  };
572
- await setupTask("Installing the Hello App", async () => {
573
- const status = await effects.installHello({
610
+ const desktop = await setupTask(fresh
611
+ ? "Installing Hello and building Tourtois"
612
+ : "Installing Hello and checking Tourtois", async () => {
613
+ // The Apps have separate sources and installation identities. One
614
+ // progress display owns both; their cleanup must settle before the
615
+ // server can stop or sign-in can be offered.
616
+ const preparation = new AbortController();
617
+ const input = {
574
618
  directory,
575
619
  url,
576
620
  key,
577
- signal,
621
+ signal: AbortSignal.any([signal, preparation.signal]),
622
+ };
623
+ void watchedExit.then(() => {
624
+ preparation.abort();
578
625
  });
579
- if (status < 200 || status >= 300)
580
- throw new Error(`Hello App installation returned HTTP ${String(status)}.`);
626
+ const hello = async () => {
627
+ try {
628
+ input.signal.throwIfAborted();
629
+ const status = await effects.installHello(input);
630
+ if (status < 200 || status >= 300)
631
+ throw new Error(`Hello App installation returned HTTP ${String(status)}.`);
632
+ }
633
+ catch (cause) {
634
+ preparation.abort();
635
+ if (signal.aborted || cause instanceof CleanupError)
636
+ throw cause;
637
+ assertRunning();
638
+ throw new TryError(innermostError(cause).message, `Keep your Hello source. Run \`${retryWithLogs()}\` and report the install error if it repeats.`);
639
+ }
640
+ };
641
+ const tourtois = async () => {
642
+ try {
643
+ input.signal.throwIfAborted();
644
+ return await effects.installDesktop(input);
645
+ }
646
+ catch (cause) {
647
+ if (cause instanceof CleanupError)
648
+ preparation.abort();
649
+ throw cause;
650
+ }
651
+ };
652
+ const [helloResult, desktopResult] = await Promise.allSettled([
653
+ hello(),
654
+ tourtois(),
655
+ ]);
656
+ // Cleanup failure must not be hidden by its sibling's cancellation.
657
+ for (const result of [helloResult, desktopResult])
658
+ if (result.status === "rejected" &&
659
+ result.reason instanceof CleanupError)
660
+ throw result.reason;
661
+ for (const result of [helloResult, desktopResult])
662
+ if (signal.aborted &&
663
+ result.status === "rejected" &&
664
+ result.reason instanceof InstallationObservationError)
665
+ throw result.reason;
666
+ signal.throwIfAborted();
667
+ if (helloResult.status === "rejected")
668
+ throw helloResult.reason;
669
+ if (desktopResult.status === "rejected")
670
+ throw new DesktopSetupError(desktopResult.reason);
671
+ return desktopResult.value;
581
672
  }).catch((cause) => {
582
673
  if (signal.aborted || cause instanceof CleanupError)
583
674
  throw cause;
584
675
  assertRunning();
585
- throw new TryError(innermostError(cause).message, `Keep your Hello source. Run \`${retryWithLogs()}\` and report the install error if it repeats.`);
586
- });
587
- const desktop = await setupTask(fresh ? "Building Tourtois" : "Checking Tourtois", () => effects.installDesktop({ directory, url, key, signal })).catch((cause) => {
588
- if (signal.aborted || cause instanceof CleanupError)
676
+ if (!(cause instanceof DesktopSetupError))
589
677
  throw cause;
590
- assertRunning();
591
678
  ui.warn(`Tourtois, the desktop, could not be built (${innermostError(cause).message}). Oyster is available for recovery; the desktop is not ready.`, isNetworkFailure(innermostError(cause))
592
679
  ? `Check your connection, stop this trial with Ctrl-C, then run \`${retry}\` to retry the desktop.`
593
680
  : `Stop this trial with Ctrl-C, then run \`${retryWithLogs()}\` and report the desktop build error.`);
@@ -96,7 +96,7 @@ The configured provider answered with a failure or is unreachable.
96
96
  #### Extends
97
97
 
98
98
  - `YieldableError`\<`this`\> & `object` & `Readonly`\<\{ `op`: `string`;
99
- `status`: `number` \| `null`; `message`: `string`; \}\>
99
+ `status`: `number` \| `null`; `message`: `string`; `cause?`: `unknown`; \}\>
100
100
 
101
101
  #### Constructors
102
102
 
@@ -108,12 +108,13 @@ new CloudBrowserUpstreamError(args): CloudBrowserUpstreamError;
108
108
 
109
109
  ###### Parameters
110
110
 
111
- | Parameter | Type |
112
- | -------------- | ------------------------------------------------------------------------ |
113
- | `args` | \{ `op`: `string`; `status`: `number` \| `null`; `message`: `string`; \} |
114
- | `args.op` | `string` |
115
- | `args.status` | `number` \| `null` |
116
- | `args.message` | `string` |
111
+ | Parameter | Type | Description |
112
+ | -------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
113
+ | `args` | \{ `op`: `string`; `status`: `number` \| `null`; `message`: `string`; `cause?`: `unknown`; \} | - |
114
+ | `args.op` | `string` | - |
115
+ | `args.status` | `number` \| `null` | - |
116
+ | `args.message` | `string` | - |
117
+ | `args.cause?` | `unknown` | Original transport failure retained for host diagnostics. |
117
118
 
118
119
  ###### Returns
119
120
 
@@ -128,6 +129,8 @@ Data.TaggedError(
128
129
  readonly op: string;
129
130
  readonly status: number | null;
130
131
  readonly message: string;
132
+ / Original transport failure retained for host diagnostics. /
133
+ readonly cause?: unknown;
131
134
  }>.constructor
132
135
  ```
133
136
 
@@ -157,6 +160,20 @@ readonly status: number | null;
157
160
  Data.TaggedError("CloudBrowserUpstreamError").status;
158
161
  ```
159
162
 
163
+ ##### cause?
164
+
165
+ ```ts
166
+ optional cause?: unknown;
167
+ ```
168
+
169
+ Original transport failure retained for host diagnostics.
170
+
171
+ ###### Inherited from
172
+
173
+ ```ts
174
+ Data.TaggedError("CloudBrowserUpstreamError").cause;
175
+ ```
176
+
160
177
  ##### message
161
178
 
162
179
  ```ts
@@ -1019,7 +1019,7 @@ gill(
1019
1019
  title: string;
1020
1020
  state: "error";
1021
1021
  rows: readonly [];
1022
- reason?: "exec_isolation_required" | "params_required";
1022
+ reason?: "disabled" | "exec_isolation_required" | "params_required";
1023
1023
  error: string;
1024
1024
  recovery?: | {
1025
1025
  kind: "configure";
@@ -1078,7 +1078,7 @@ Invoke a Release-declared Gill in a fresh immutable frame.
1078
1078
  `Promise`\<[`InstanceResult`](host.md#instanceresult)\< \| \{ `viewId`:
1079
1079
  `string`; `title`: `string`; `state`: `"empty"`; `rows`: readonly \[\]; `next?`:
1080
1080
  `string`; \} \| \{ `viewId`: `string`; `title`: `string`; `state`: `"error"`;
1081
- `rows`: readonly \[\]; `reason?`: `"exec_isolation_required"` \|
1081
+ `rows`: readonly \[\]; `reason?`: `"disabled"` \| `"exec_isolation_required"` \|
1082
1082
  `"params_required"`; `error`: `string`; `recovery?`: \| \{ `kind`:
1083
1083
  `"configure"`; `param`: `string`; \} \| \{ `kind`: `"open"`; \}; \} \| \{
1084
1084
  `viewId`: `string`; `title`: `string`; `state`: `"full"`; `rows`: readonly
@@ -2050,7 +2050,7 @@ gill(
2050
2050
  title: string;
2051
2051
  state: "error";
2052
2052
  rows: readonly [];
2053
- reason?: "exec_isolation_required" | "params_required";
2053
+ reason?: "disabled" | "exec_isolation_required" | "params_required";
2054
2054
  error: string;
2055
2055
  recovery?: | {
2056
2056
  kind: "configure";
@@ -2109,7 +2109,7 @@ Invoke a Release-declared Gill in a fresh immutable frame.
2109
2109
  `Promise`\<[`InstanceResult`](host.md#instanceresult)\< \| \{ `viewId`:
2110
2110
  `string`; `title`: `string`; `state`: `"empty"`; `rows`: readonly \[\]; `next?`:
2111
2111
  `string`; \} \| \{ `viewId`: `string`; `title`: `string`; `state`: `"error"`;
2112
- `rows`: readonly \[\]; `reason?`: `"exec_isolation_required"` \|
2112
+ `rows`: readonly \[\]; `reason?`: `"disabled"` \| `"exec_isolation_required"` \|
2113
2113
  `"params_required"`; `error`: `string`; `recovery?`: \| \{ `kind`:
2114
2114
  `"configure"`; `param`: `string`; \} \| \{ `kind`: `"open"`; \}; \} \| \{
2115
2115
  `viewId`: `string`; `title`: `string`; `state`: `"full"`; `rows`: readonly