@fungi.computer/oyster 0.18.2 → 0.19.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.
@@ -21,13 +21,28 @@ export declare class AgentModelRefused extends Error {
21
21
  readonly reason: AgentModelRefusal;
22
22
  constructor(reason: AgentModelRefusal);
23
23
  }
24
+ /**
25
+ * An Agent with no saved choice runs on a model its host can reach, chosen when
26
+ * it runs: Workers AI where a Cloudflare account answers, then the Fungi
27
+ * gateway, then the first stored provider key's catalog default. A key added
28
+ * later just works; one removed moves the default on. Nothing is saved, so an
29
+ * Agent's own choice always wins.
30
+ */
31
+ export declare function resolveDefaultChoice(ready: Readonly<{
32
+ workersAi: boolean;
33
+ gateway: boolean;
34
+ keys: readonly Readonly<{
35
+ keyId: string;
36
+ provider: string;
37
+ }>[];
38
+ }>): Promise<AgentModelChoice>;
24
39
  /** Read the maintained Pi catalog; never accept a model from a different egress. */
25
40
  export declare function selectAgentModel(choice: AgentModelChoice): Promise<Model<Api>>;
26
41
  /** The Agent DO is the only durable owner. Absence is a new-format default, not an old-env reader. */
27
42
  export declare function agentModelChoice(storage: Readonly<{
28
43
  get<T = unknown>(key: string): Promise<T | undefined>;
29
44
  put(key: string, value: AgentModelChoice): Promise<void>;
30
- }>, admit: (choice: AgentModelChoice) => void | Promise<void>): {
45
+ }>, admit: (choice: AgentModelChoice) => void | Promise<void>, fallback?: () => Promise<AgentModelChoice>): {
31
46
  read(): Promise<AgentModelChoice>;
32
47
  set(input: AgentModelChoice): Promise<AgentModelChoice>;
33
48
  };
@@ -41,6 +41,38 @@ async function byokCatalog(provider) {
41
41
  .openrouterProvider()
42
42
  .getModels();
43
43
  }
44
+ /**
45
+ * An Agent with no saved choice runs on a model its host can reach, chosen when
46
+ * it runs: Workers AI where a Cloudflare account answers, then the Fungi
47
+ * gateway, then the first stored provider key's catalog default. A key added
48
+ * later just works; one removed moves the default on. Nothing is saved, so an
49
+ * Agent's own choice always wins.
50
+ */
51
+ export async function resolveDefaultChoice(ready) {
52
+ if (ready.workersAi)
53
+ return defaultChoice;
54
+ if (ready.gateway)
55
+ return {
56
+ keySource: "ai-gateway",
57
+ model: { providerId: "openai", modelId: "openai/gpt-6-luna" },
58
+ };
59
+ for (const { keyId, provider } of ready.keys) {
60
+ if (provider !== "anthropic" &&
61
+ provider !== "openai" &&
62
+ provider !== "openrouter")
63
+ continue;
64
+ const catalog = await byokCatalog(provider);
65
+ const model = catalog.find((entry) => "default" in entry && entry.default === true) ??
66
+ catalog[0];
67
+ if (model !== undefined)
68
+ return {
69
+ keySource: "byok",
70
+ keyId,
71
+ model: { providerId: provider, modelId: model.id },
72
+ };
73
+ }
74
+ return defaultChoice;
75
+ }
44
76
  /** Read the maintained Pi catalog; never accept a model from a different egress. */
45
77
  export async function selectAgentModel(choice) {
46
78
  const { providerId, modelId, reasoning } = choice.model;
@@ -72,12 +104,12 @@ export async function selectAgentModel(choice) {
72
104
  return model;
73
105
  }
74
106
  /** The Agent DO is the only durable owner. Absence is a new-format default, not an old-env reader. */
75
- export function agentModelChoice(storage, admit) {
107
+ export function agentModelChoice(storage, admit, fallback = () => Promise.resolve(defaultChoice)) {
76
108
  return {
77
109
  async read() {
78
110
  const stored = await storage.get(key);
79
111
  return stored === undefined
80
- ? defaultChoice
112
+ ? fallback()
81
113
  : Schema.decodeUnknownSync(agentModelChoiceSchema, {
82
114
  onExcessProperty: "error",
83
115
  })(stored);
@@ -43,7 +43,7 @@ import { standaloneBrowserLiveView, standaloneBrowserSource, } from "./browser.j
43
43
  import { standaloneWebSource } from "./web.js";
44
44
  import { configuredProviderEgress, providerFetch, } from "@fungi.computer/veil/gatekeeper";
45
45
  import { createAssistantMessageEventStream } from "@earendil-works/pi-ai/utils/event-stream";
46
- import { agentModelChoice, agentModelChoiceSchema, AgentModelRefused, selectAgentModel, } from "./agent-model-choice.js";
46
+ import { agentModelChoice, agentModelChoiceSchema, AgentModelRefused, resolveDefaultChoice, 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 { cloudflareAccountReady } from "./cloudflare-account.js";
49
49
  import { cloudflareWorkersAIProvider } from "@earendil-works/pi-ai/providers/cloudflare-workers-ai";
@@ -877,6 +877,15 @@ export class StandaloneAgentBase extends ShiitakeDO {
877
877
  throw new AgentModelRefused("key_not_connected");
878
878
  if (choice.keySource === "workers-ai" && this.env.AI === undefined)
879
879
  throw new AgentModelRefused("key_not_connected");
880
+ }, async () => {
881
+ const pin = await this.policyDirectory();
882
+ return resolveDefaultChoice({
883
+ workersAi: this.env.AI !== undefined && cloudflareAccountReady(this.env),
884
+ gateway: configuredProviderEgress(this.env).baseUrl("ai-gateway") !== null,
885
+ keys: pin === null
886
+ ? []
887
+ : await this.env.AGENT_DIRECTORY.getByName(pin.directoryName).listModelKeys(),
888
+ });
880
889
  });
881
890
  }
882
891
  /** Secret-free default of this Agent; stored separately from Session history. */
@@ -5,6 +5,8 @@ export type StarterApp = Readonly<{
5
5
  /** Selecting this configured dashboard approves its declared shell authority only. */
6
6
  dashboard?: true;
7
7
  installationId: string;
8
+ /** The name the desktop shows for it while it is being set up. */
9
+ displayName: string;
8
10
  appId: string;
9
11
  /** The App's directory in a Botanical checkout; its recipe is rooted there. */
10
12
  directory: string;
@@ -15,6 +15,7 @@ import { installOnOyster, InstallationObservationError, } from "../installation-
15
15
  export const standaloneAppSet = [
16
16
  {
17
17
  installationId: "tourtois",
18
+ displayName: "Tourtois",
18
19
  dashboard: true,
19
20
  directory: "apps/tourtois",
20
21
  repository: "tourtois",
@@ -23,6 +24,7 @@ export const standaloneAppSet = [
23
24
  },
24
25
  {
25
26
  installationId: "bonsai",
27
+ displayName: "Bonsai",
26
28
  directory: "apps/bonsai",
27
29
  repository: "bonsai",
28
30
  appId: "app_bonsai",
@@ -30,6 +32,7 @@ export const standaloneAppSet = [
30
32
  },
31
33
  {
32
34
  installationId: "shed",
35
+ displayName: "Shed",
33
36
  directory: "apps/shed",
34
37
  repository: "shed",
35
38
  appId: "app_shed",
@@ -37,6 +40,7 @@ export const standaloneAppSet = [
37
40
  },
38
41
  {
39
42
  installationId: "inkcap",
43
+ displayName: "Inkcap",
40
44
  directory: "apps/inkcap",
41
45
  repository: "inkcap",
42
46
  appId: "app_inkcap",
@@ -44,6 +48,7 @@ export const standaloneAppSet = [
44
48
  },
45
49
  {
46
50
  installationId: "trellis",
51
+ displayName: "Trellis",
47
52
  directory: "apps/trellis",
48
53
  repository: "trellis",
49
54
  appId: "app_trellis",
@@ -51,6 +56,7 @@ export const standaloneAppSet = [
51
56
  },
52
57
  {
53
58
  installationId: "prints",
59
+ displayName: "Prints",
54
60
  directory: "apps/prints",
55
61
  repository: "prints",
56
62
  appId: "app_prints",
@@ -58,6 +64,7 @@ export const standaloneAppSet = [
58
64
  },
59
65
  {
60
66
  installationId: "grove",
67
+ displayName: "Grove",
61
68
  directory: "apps/grove",
62
69
  repository: "grove",
63
70
  appId: "app_grove",
@@ -11,6 +11,7 @@ export declare function starterCloneArguments(app: StarterApp, tag: string, dest
11
11
  export declare const desktopApp: Readonly<{
12
12
  dashboard?: true;
13
13
  installationId: string;
14
+ displayName: string;
14
15
  appId: string;
15
16
  directory: string;
16
17
  repository: string;
@@ -0,0 +1,13 @@
1
+ import type { InstallingApp } from "@fungi.computer/nacre/workbench-directory";
2
+ /** The owner-key request `oyster try` makes to the Oyster it started. */
3
+ export type TrialRequest = Readonly<{
4
+ url: string;
5
+ key: string;
6
+ signal?: AbortSignal;
7
+ }>;
8
+ /** Tell the running Oyster which starter Apps are installing, failed or need a runtime. */
9
+ export declare function reportTrialStarters(input: TrialRequest & {
10
+ installing: readonly InstallingApp[];
11
+ }): Promise<void>;
12
+ /** Take the Apps the desktop asked to retry; each ask is handed out once. */
13
+ export declare function takeTrialRetries(input: TrialRequest): Promise<readonly string[]>;
@@ -0,0 +1,33 @@
1
+ import * as z from "zod";
2
+ import { trialStartersBodySchema } from "./trial-starters.js";
3
+ const retriesSchema = z.strictObject({
4
+ retries: z.array(z.string().min(1).max(64)).max(16),
5
+ });
6
+ const headers = (key) => ({
7
+ Authorization: `Bearer ${key}`,
8
+ Accept: "application/json",
9
+ });
10
+ /** Tell the running Oyster which starter Apps are installing, failed or need a runtime. */
11
+ export async function reportTrialStarters(input) {
12
+ const body = trialStartersBodySchema.parse({ installing: input.installing });
13
+ const init = {
14
+ method: "PUT",
15
+ headers: { ...headers(input.key), "Content-Type": "application/json" },
16
+ body: JSON.stringify(body),
17
+ };
18
+ if (input.signal)
19
+ init.signal = input.signal;
20
+ const response = await fetch(new URL("/api/trial/starters", input.url), init);
21
+ if (response.status !== 204)
22
+ throw new Error(`Starter state was not accepted (HTTP ${String(response.status)}).`);
23
+ }
24
+ /** Take the Apps the desktop asked to retry; each ask is handed out once. */
25
+ export async function takeTrialRetries(input) {
26
+ const init = { method: "POST", headers: headers(input.key) };
27
+ if (input.signal)
28
+ init.signal = input.signal;
29
+ const response = await fetch(new URL("/api/trial/starters/retries", input.url), init);
30
+ if (!response.ok)
31
+ throw new Error(`Retry asks were not readable (HTTP ${String(response.status)}).`);
32
+ return retriesSchema.parse(await response.json()).retries;
33
+ }
@@ -2,6 +2,7 @@ import { Cli } from "@fungi.computer/lantern";
2
2
  import { type DesktopReadiness } from "./local-desktop.js";
3
3
  import { type StarterApp } from "./app-set.js";
4
4
  import { type SignInLink } from "./sign-in-link.js";
5
+ import type { InstallingApp } from "@fungi.computer/nacre/workbench-directory";
5
6
  export declare const tryUsage = "Usage: oyster try [directory] [--port 8787] [--no-open] [--verbose] [--package <npm spec>]";
6
7
  /**
7
8
  * Streaming logs and interactive progress cannot share a terminal, so
@@ -45,6 +46,18 @@ export type TryEffects = Readonly<{
45
46
  key: string;
46
47
  signal: AbortSignal;
47
48
  }) => Promise<"installed" | "already-installed">;
49
+ /** Tell the Oyster which starter Apps are not ready yet. */
50
+ reportStarters: (input: {
51
+ url: string;
52
+ key: string;
53
+ signal: AbortSignal;
54
+ }, installing: readonly InstallingApp[]) => Promise<void>;
55
+ /** The Apps the desktop asked to retry; each ask is handed out once. */
56
+ takeRetries: (input: {
57
+ url: string;
58
+ key: string;
59
+ signal: AbortSignal;
60
+ }) => Promise<readonly string[]>;
48
61
  /** Whether a model is connected, so the start message can say what to do. */
49
62
  modelSetup: (input: {
50
63
  url: string;
@@ -30,6 +30,8 @@ import { installHelloApp } from "./hello-app.js";
30
30
  import { desktopApp, installLocalStarter, localDesktopState, localStarterInstalled, localModelSetup, } from "./local-desktop.js";
31
31
  import { standaloneAppSet, trialStarterOrder, } from "./app-set.js";
32
32
  import { startSignInLink } from "./sign-in-link.js";
33
+ import { reportTrialStarters, takeTrialRetries, } from "./trial-starters-client.js";
34
+ import { setTimeout as sleep } from "node:timers/promises";
33
35
  export const tryUsage = "Usage: oyster try [directory] [--port 8787] [--no-open] [--verbose] [--package <npm spec>]";
34
36
  const tryHelp = `${tryUsage}
35
37
 
@@ -332,6 +334,7 @@ async function runInstall(directory, manager, verbose, signal) {
332
334
  await awaitCleanup(logClosed);
333
335
  }
334
336
  }
337
+ const retryPollMs = 3_000;
335
338
  const originFile = join(".oyster", "origin");
336
339
  /**
337
340
  * Local data belongs to the origin it was seeded for. A project made for
@@ -523,6 +526,8 @@ const realEffects = {
523
526
  await installLocalStarter(app, input);
524
527
  return "installed";
525
528
  },
529
+ reportStarters: (input, installing) => reportTrialStarters({ ...input, installing }),
530
+ takeRetries: takeTrialRetries,
526
531
  modelSetup: localModelSetup,
527
532
  signInLink: startSignInLink,
528
533
  open: openBrowser,
@@ -796,29 +801,90 @@ export async function tryOyster(args, effects = realEffects, ui = createTryCli(a
796
801
  trialAbort.abort();
797
802
  });
798
803
  const stopped = () => trialSignal.aborted;
799
- // A stop interrupts the build in flight; that is not a failure to report.
800
- const reportStarterFailure = (name, cause) => {
804
+ // What the desktop shows for each starter App that is not ready yet.
805
+ const pending = new Map();
806
+ const trial = { url, key, signal: trialSignal };
807
+ const publish = () => effects
808
+ .reportStarters(trial, [...pending.values()])
809
+ .then(undefined, (cause) => {
801
810
  if (!stopped())
802
- ui.warn(`${name} couldn't be installed: ${innermostError(cause).message}`, `Run \`${retry}\` again to retry it.`);
811
+ ui.warn(`The desktop could not be told which Apps are installing (${innermostError(cause).message}).`, "Installs continue; the desktop will not show their progress.");
812
+ });
813
+ const failureReason = (cause) => {
814
+ const failure = innermostError(cause);
815
+ return {
816
+ code: isNetworkFailure(failure)
817
+ ? "network"
818
+ : "build_failed",
819
+ message: failure.message.slice(0, 200) || "The build failed.",
820
+ };
821
+ };
822
+ const installOne = async (app) => {
823
+ const name = app.installationId;
824
+ pending.set(name, {
825
+ installationId: name,
826
+ displayName: app.displayName,
827
+ state: "installing",
828
+ });
829
+ await publish();
830
+ const settled = await effects.installStarter(app, trial).then((result) => ({ kind: "done", result }), (cause) => ({ kind: "failed", cause }));
831
+ if (stopped())
832
+ return;
833
+ if (settled.kind === "failed") {
834
+ pending.set(name, {
835
+ installationId: name,
836
+ displayName: app.displayName,
837
+ state: "failed",
838
+ reason: failureReason(settled.cause),
839
+ });
840
+ ui.warn(`${name} couldn't be installed: ${innermostError(settled.cause).message}`, `Retry it from the desktop, or run \`${retry}\` again.`);
841
+ }
842
+ else if (app.trial === "needs-runtime") {
843
+ pending.set(name, {
844
+ installationId: name,
845
+ displayName: app.displayName,
846
+ state: "needs-runtime",
847
+ });
848
+ ui.info(`${name} installed: needs a Computer runtime (see ${name})`);
849
+ }
850
+ else {
851
+ pending.delete(name);
852
+ ui.info(settled.result === "already-installed"
853
+ ? `${name} already installed`
854
+ : `${name} ready`);
855
+ }
856
+ await publish();
803
857
  };
804
858
  const background = desktopReady
805
859
  ? (async () => {
806
860
  ui.info(`Getting ${String(starters.length)} more Apps ready in the background.`);
861
+ // Every starter shows as getting ready from the start, so the
862
+ // launcher does not grow tile by tile.
863
+ for (const app of starters)
864
+ pending.set(app.installationId, {
865
+ installationId: app.installationId,
866
+ displayName: app.displayName,
867
+ state: "installing",
868
+ });
869
+ await publish();
807
870
  for (const app of starters) {
808
871
  if (stopped())
809
872
  return;
810
- const name = app.installationId;
811
- const settled = await effects
812
- .installStarter(app, { url, key, signal: trialSignal })
813
- .then((result) => ({ kind: "done", result }), (cause) => ({ kind: "failed", cause }));
814
- if (settled.kind === "failed")
815
- reportStarterFailure(name, settled.cause);
816
- else
817
- ui.info(app.trial === "needs-runtime"
818
- ? `${name} installed: needs a Computer runtime (see ${name})`
819
- : settled.result === "already-installed"
820
- ? `${name} already installed`
821
- : `${name} ready`);
873
+ await installOne(app);
874
+ }
875
+ // Then answer the desktop's retry asks until the trial stops.
876
+ while (!stopped()) {
877
+ const waited = await sleep(retryPollMs, undefined, {
878
+ signal: trialSignal,
879
+ }).then(() => true, () => false);
880
+ if (!waited)
881
+ return;
882
+ const asked = await effects.takeRetries(trial).then((ids) => ids, () => []);
883
+ for (const id of asked) {
884
+ const app = starters.find((item) => item.installationId === id);
885
+ if (app !== undefined && !stopped())
886
+ await installOne(app);
887
+ }
822
888
  }
823
889
  })()
824
890
  : Promise.resolve();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/oyster",
3
- "version": "0.18.2",
3
+ "version": "0.19.0",
4
4
  "author": "Levi <levi@technomancy.dev>",
5
5
  "description": "Run your own Apps on Cloudflare Workers or celld: installable App Releases, each with its own Durable Object, SQLite database and declared bindings",
6
6
  "type": "module",