@fungi.computer/oyster 0.13.0 → 0.14.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 (52) hide show
  1. package/README.md +30 -15
  2. package/dist/agents.js +2 -1
  3. package/dist/approval-home.js +4 -2
  4. package/dist/boot-host-script.js +1 -1
  5. package/dist/browser/cdp-client.d.ts +1 -1
  6. package/dist/browser/cdp-client.js +73 -37
  7. package/dist/browser/errors.d.ts +2 -0
  8. package/dist/browser/lease-registry.d.ts +5 -1
  9. package/dist/browser/lease-registry.js +2 -6
  10. package/dist/build/candidate-cli.mjs +267 -246
  11. package/dist/build/definition-emission.js +17 -3
  12. package/dist/build/local-build.d.ts +6 -0
  13. package/dist/build/local-build.js +104 -91
  14. package/dist/build/process-group.d.ts +6 -0
  15. package/dist/build/process-group.js +92 -0
  16. package/dist/build.d.ts +1 -1
  17. package/dist/build.js +1 -1
  18. package/dist/embed-metafiles.js +2 -2
  19. package/dist/embed-scripts.js +1 -1
  20. package/dist/git-journal.js +12 -9
  21. package/dist/hello-app-script.js +1 -1
  22. package/dist/host-page-assets.js +1 -1
  23. package/dist/host-page.d.ts +6 -1
  24. package/dist/host-page.js +40 -0
  25. package/dist/host.js +24 -9
  26. package/dist/installation-operations.js +1 -1
  27. package/dist/machine-link/host.js +18 -13
  28. package/dist/pack.d.ts +3 -1
  29. package/dist/pack.js +28 -7
  30. package/dist/page/app-permissions.js +3 -13
  31. package/dist/page-script.js +2 -2
  32. package/dist/standalone/agent-mail.d.ts +38 -11
  33. package/dist/standalone/agent-mail.js +8 -22
  34. package/dist/standalone/agents.d.ts +1 -0
  35. package/dist/standalone/agents.js +30 -5
  36. package/dist/standalone/hello-app.d.ts +4 -1
  37. package/dist/standalone/hello-app.js +67 -22
  38. package/dist/standalone/hello-lesson.d.ts +2 -0
  39. package/dist/standalone/hello-lesson.js +36 -0
  40. package/dist/standalone/local-desktop.d.ts +6 -4
  41. package/dist/standalone/local-desktop.js +39 -20
  42. package/dist/standalone/sign-in-link.d.ts +2 -1
  43. package/dist/standalone/sign-in-link.js +58 -17
  44. package/dist/standalone/try-cli.d.ts +12 -9
  45. package/dist/standalone/try-cli.js +490 -138
  46. package/docs/api/browser.md +24 -7
  47. package/docs/api/pack.md +3 -2
  48. package/docs/api/workers-git.md +2 -2
  49. package/docs/api/workers.md +2 -2
  50. package/docs/site/agent-quickstart.mdx +109 -354
  51. package/examples/standalone/wrangler.jsonc +1 -1
  52. package/package.json +24 -24
@@ -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. */
@@ -1,4 +1,6 @@
1
- export declare const helloPage = "<!doctype html>\n<title>Hello</title>\n<h1>Hello from my first Oyster App</h1>\n<script type=\"module\" src=\"./main.js\"></script>\n";
1
+ export { helloPage } from "./hello-lesson.js";
2
+ /** A first commit, never mere .git existence, makes the editable source ready. */
3
+ export declare function prepareHelloSource(directory: string, signal: AbortSignal): Promise<string>;
2
4
  /** Pack the Hello App kept at `<directory>/hello-app` and install it as
3
5
  * `hello`; answers the HTTP status (201 new, 200 when already installed).
4
6
  * The first call writes and commits the source; later calls pack its current
@@ -7,4 +9,5 @@ export declare function installHelloApp(input: Readonly<{
7
9
  directory: string;
8
10
  url: string;
9
11
  key: string;
12
+ signal?: AbortSignal;
10
13
  }>): Promise<number>;
@@ -1,11 +1,13 @@
1
+ import { CleanupError } from "../build/process-group.js";
1
2
  // The starter Hello App for a local Oyster: a one-page bundled-html App,
2
3
  // committed to git, packed into a Release and installed as `hello`. The
3
4
  // quick start and `oyster try` install the same App through this module;
4
5
  // `try` keeps its source at `<project>/hello-app` for the person to edit.
5
- import { execFileSync } from "node:child_process";
6
- import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
6
+ import { GitCommandError, runGit } from "../build/local-build.js";
7
+ import { access, mkdir, mkdtemp, readdir, rename, rm, writeFile, } from "node:fs/promises";
7
8
  import { tmpdir } from "node:os";
8
9
  import { join } from "node:path";
10
+ import { helloPage, helloLayout } from "./hello-lesson.js";
9
11
  import { helloAppScript } from "#hello-app-script";
10
12
  import { installRelease, packRelease } from "../pack.js";
11
13
  const manifest = {
@@ -13,39 +15,78 @@ const manifest = {
13
15
  private: true,
14
16
  fungi: { app: { displayName: "Hello", icon: "fungi", capabilities: [] } },
15
17
  };
16
- // The script announces the page to Oyster; without it the window never opens.
17
- export const helloPage = '<!doctype html>\n<title>Hello</title>\n<h1>Hello from my first Oyster App</h1>\n<script type="module" src="./main.js"></script>\n';
18
+ export { helloPage } from "./hello-lesson.js";
18
19
  const exists = (path) => access(path).then(() => true, () => false);
19
- const git = (directory, args) => execFileSync("git", [
20
- "-C",
21
- directory,
20
+ const git = async (directory, args, signal) => new TextDecoder()
21
+ .decode(await runGit([
22
22
  "-c",
23
23
  "user.name=Oyster",
24
24
  "-c",
25
25
  "user.email=oyster@example.invalid",
26
26
  ...args,
27
- ], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
28
- // Write `hello-app/` under `directory` and commit it; answers the commit.
29
- async function writeHelloApp(directory) {
30
- const source = join(directory, "hello-app");
27
+ ], directory, signal, process.env))
28
+ .trim();
29
+ async function seedHello(source, signal) {
30
+ signal.throwIfAborted();
31
31
  await mkdir(join(source, "bundle"), { recursive: true });
32
- await writeFile(join(source, "package.json"), JSON.stringify(manifest, null, 2) + "\n");
33
- await writeFile(join(source, "bundle", "index.html"), helloPage);
34
- await writeFile(join(source, "bundle", "main.js"), helloAppScript);
35
- git(source, ["init", "-q"]);
36
- git(source, ["add", "."]);
37
- git(source, ["commit", "-qm", "Hello App"]);
38
- return git(source, ["rev-parse", "HEAD"]);
32
+ const { shellStyles, loginFontStyles } = await import("#page-script");
33
+ for (const [name, contents] of [
34
+ ["package.json", JSON.stringify(manifest, null, 2) + "\n"],
35
+ ["bundle/index.html", helloPage],
36
+ ["bundle/main.js", helloAppScript],
37
+ ["bundle/lesson.css", shellStyles + loginFontStyles + helloLayout],
38
+ ]) {
39
+ signal.throwIfAborted();
40
+ await writeFile(join(source, name), contents, { flag: "wx" }).catch((cause) => {
41
+ if (!(cause instanceof Error &&
42
+ "code" in cause &&
43
+ cause.code === "EEXIST"))
44
+ throw cause;
45
+ });
46
+ }
47
+ await git(source, ["init", "-q"], signal);
48
+ await git(source, ["add", "."], signal);
49
+ await git(source, ["commit", "-qm", "Hello App"], signal);
50
+ return git(source, ["rev-parse", "HEAD"], signal);
51
+ }
52
+ /** A first commit, never mere .git existence, makes the editable source ready. */
53
+ export async function prepareHelloSource(directory, signal) {
54
+ signal.throwIfAborted();
55
+ const source = join(directory, "hello-app");
56
+ if (await exists(join(source, ".git"))) {
57
+ try {
58
+ return await git(source, ["rev-parse", "--verify", "--quiet", "HEAD"], signal);
59
+ }
60
+ catch (cause) {
61
+ if (!(cause instanceof GitCommandError && cause.exitCode === 1))
62
+ throw cause;
63
+ return seedHello(source, signal);
64
+ }
65
+ }
66
+ if ((await exists(source)) && (await readdir(source)).length > 0)
67
+ throw new Error("hello-app already contains files without a Git repository; move that folder before creating the starter App.");
68
+ const stage = await mkdtemp(join(directory, ".hello-app-"));
69
+ try {
70
+ const commit = await seedHello(stage, signal);
71
+ signal.throwIfAborted();
72
+ await rename(stage, source);
73
+ return commit;
74
+ }
75
+ finally {
76
+ await rm(stage, { recursive: true, force: true }).catch((cause) => {
77
+ throw new CleanupError("Hello staging cleanup failed", { cause });
78
+ });
79
+ }
39
80
  }
40
81
  /** Pack the Hello App kept at `<directory>/hello-app` and install it as
41
82
  * `hello`; answers the HTTP status (201 new, 200 when already installed).
42
83
  * The first call writes and commits the source; later calls pack its current
43
84
  * `HEAD`, so a committed edit followed by `oyster try` shows the change. */
44
85
  export async function installHelloApp(input) {
86
+ const signal = input.signal ?? new AbortController().signal;
45
87
  const source = join(input.directory, "hello-app");
46
- const commit = (await exists(join(source, ".git")))
47
- ? git(source, ["rev-parse", "HEAD"])
48
- : await writeHelloApp(input.directory);
88
+ const commit = await prepareHelloSource(input.directory, signal);
89
+ signal.throwIfAborted();
49
90
  const scratch = await mkdtemp(join(tmpdir(), "oyster-hello-"));
50
91
  try {
51
92
  await packRelease({
@@ -66,16 +107,20 @@ export async function installHelloApp(input) {
66
107
  maxOutputBytes: 4_194_304,
67
108
  },
68
109
  outDirectory: join(scratch, "release"),
110
+ signal,
69
111
  });
70
112
  const response = await installRelease({
71
113
  directory: join(scratch, "release"),
72
114
  url: input.url,
73
115
  key: input.key,
74
116
  installationId: "hello",
117
+ signal,
75
118
  });
76
119
  return response.status;
77
120
  }
78
121
  finally {
79
- await rm(scratch, { recursive: true, force: true });
122
+ await rm(scratch, { recursive: true, force: true }).catch((cause) => {
123
+ throw new CleanupError("App scratch cleanup failed", { cause });
124
+ });
80
125
  }
81
126
  }
@@ -0,0 +1,2 @@
1
+ export declare const helloPage: string;
2
+ export declare const helloLayout = "\nhtml { --font-sans: \"Nunito\", sans-serif; --font-mono: \"Maple Mono\", monospace; --font-display: var(--font-sans); }\nbody { margin: 0; font-family: var(--font-sans); color: var(--color-base-content); background: var(--color-base-100); }\nmain { max-width: 760px; margin: auto; padding: clamp(20px, 5vw, 56px); }\nh1 { font-size: clamp(28px, 5vw, 44px); line-height: 1.15; margin: 12px 0; overflow-wrap: anywhere; }\nh2 { font-size: 18px; margin: 0 0 6px; }\np { line-height: 1.6; }\nol { list-style: decimal; padding-inline-start: 24px; display: grid; gap: 20px; }\nli p { margin: 0; }\npre { overflow: auto; padding: 12px 0; font-family: var(--font-mono); }\nnav { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 24px; }\nnav a { text-decoration: underline; padding-block: 10px; }\n.eyebrow { font-family: var(--font-mono); font-size: 12px; }\n.intro { font-size: 18px; margin-bottom: 28px; }\n.note { margin-top: 16px; font-size: 14px; }\n";
@@ -0,0 +1,36 @@
1
+ import { createElement as h } from "react";
2
+ import { renderToStaticMarkup } from "react-dom/server";
3
+ import { Card, CardContent } from "@fungi.computer/caps/components/card";
4
+ const docs = "https://docs.fungi.computer";
5
+ const step = (title, ...content) => h("li", null, h("h2", null, title), ...content.map((text) => h("p", null, text)));
6
+ // This is an ordinary installed App. Keep the readiness script when editing it.
7
+ export const helloPage = "<!doctype html>" +
8
+ renderToStaticMarkup(h("html", { lang: "en", "data-theme": "latte" }, h("head", null, h("meta", { charSet: "utf-8" }), h("meta", {
9
+ name: "viewport",
10
+ content: "width=device-width, initial-scale=1",
11
+ }), h("title", null, "Hello · Your first Oyster App"), h("link", { rel: "stylesheet", href: "./lesson.css" })), h("body", null, h("main", null, h("p", { className: "eyebrow" }, "Oyster · Your first App"), h("h1", null, "Hello from my first Oyster App"), h("p", { className: "intro" }, "You have a working App on your own computer. Make one small change and see it here."), h(Card, null, h(CardContent, null, h("ol", null, step("Open the source", "In your Oyster project, open hello-app/bundle/index.html in your editor. This page is yours to change."), step("Make it yours", "Change the heading above to something you wrote. Keep the main.js script at the bottom: it tells Oyster this App is ready."), step("Commit your edit", "Save the file, then commit it in the hello-app Git repository. Oyster builds committed source; unsaved or uncommitted edits will not appear."), step("Restart and open Hello", "Press Ctrl-C in the terminal running your trial. From your Oyster project folder, run the command below. Open the new sign-in link and choose Hello again.")), h("pre", null, h("code", null, "npx @fungi.computer/oyster try .")))), h("nav", { "aria-label": "Next steps" }, h("a", {
12
+ href: docs + "/agents/build-an-app.md",
13
+ target: "_blank",
14
+ rel: "noreferrer",
15
+ }, "Get the exact edit commands"), h("a", {
16
+ href: docs + "/guides/run-your-own-oyster/#deploy-it",
17
+ target: "_blank",
18
+ rel: "noreferrer",
19
+ }, "Read the hosting guide")), h("p", { className: "note" }, "This local trial needs no account or payment. Cloud hosting needs your own account and paid resources; the guide explains those before you deploy.")), h("script", { type: "module", src: "./main.js" }))));
20
+ // Layout and typography only. Caps owns the Card styles.
21
+ export const helloLayout = `
22
+ html { --font-sans: "Nunito", sans-serif; --font-mono: "Maple Mono", monospace; --font-display: var(--font-sans); }
23
+ body { margin: 0; font-family: var(--font-sans); color: var(--color-base-content); background: var(--color-base-100); }
24
+ main { max-width: 760px; margin: auto; padding: clamp(20px, 5vw, 56px); }
25
+ h1 { font-size: clamp(28px, 5vw, 44px); line-height: 1.15; margin: 12px 0; overflow-wrap: anywhere; }
26
+ h2 { font-size: 18px; margin: 0 0 6px; }
27
+ p { line-height: 1.6; }
28
+ ol { list-style: decimal; padding-inline-start: 24px; display: grid; gap: 20px; }
29
+ li p { margin: 0; }
30
+ pre { overflow: auto; padding: 12px 0; font-family: var(--font-mono); }
31
+ nav { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 24px; }
32
+ nav a { text-decoration: underline; padding-block: 10px; }
33
+ .eyebrow { font-family: var(--font-mono); font-size: 12px; }
34
+ .intro { font-size: 18px; margin-bottom: 28px; }
35
+ .note { margin-top: 16px; font-size: 14px; }
36
+ `;
@@ -1,11 +1,13 @@
1
- /** Whether the Oyster already has an installation with this id. */
2
- export declare function isInstalled(input: Readonly<{
1
+ export type DesktopReadiness = "ready" | "approval-required" | "disabled" | "deleted" | "unavailable";
2
+ /** The host-owned entry decides whether the saved desktop may run. Read-only. */
3
+ export declare function localDesktopState(input: Readonly<{
3
4
  url: string;
4
5
  key: string;
5
- installationId: string;
6
- }>): Promise<boolean>;
6
+ signal?: AbortSignal;
7
+ }>): Promise<DesktopReadiness | "missing">;
7
8
  /** Build Tourtois from source on this machine and install it as `tourtois`. */
8
9
  export declare function installLocalDesktop(input: Readonly<{
9
10
  url: string;
10
11
  key: string;
12
+ signal?: AbortSignal;
11
13
  }>): Promise<void>;
@@ -1,9 +1,10 @@
1
+ import { CleanupError } from "../build/process-group.js";
1
2
  // The Tourtois desktop for a local Oyster. The standalone Oyster builds its
2
3
  // starter Apps on its own Computer, which a laptop does not have, so `oyster
3
4
  // try` builds Tourtois here from its public source with the ordinary local
4
5
  // packer and installs it as the home installation, approving its shell the
5
6
  // same way `install-apps` does.
6
- import { execFileSync } from "node:child_process";
7
+ import { runGit } from "../build/local-build.js";
7
8
  import { mkdtemp, realpath, rm } from "node:fs/promises";
8
9
  import { tmpdir } from "node:os";
9
10
  import { join } from "node:path";
@@ -11,45 +12,60 @@ import * as Schema from "effect/Schema";
11
12
  import * as z from "zod";
12
13
  import { installRelease, packRelease } from "../pack.js";
13
14
  import { appBuildRecipe, readBuildManifest } from "../build/workspace-build.js";
15
+ import { installationSchema } from "../apps/installation.js";
14
16
  import { approveChosenDashboard } from "./dashboard-approval.js";
15
17
  const tourtoisRepository = "https://github.com/fungi-computer/tourtois.git";
16
- const installationRowsSchema = z.array(z.object({ installationId: z.string() }).loose());
17
- const git = (cwd, args) => execFileSync("git", [...args], {
18
- cwd,
19
- encoding: "utf8",
20
- stdio: ["ignore", "pipe", "pipe"],
21
- }).trim();
22
- /** Whether the Oyster already has an installation with this id. */
23
- export async function isInstalled(input) {
24
- const response = await fetch(new URL("/api/installations", input.url), {
18
+ const installationRowsSchema = z.array(installationSchema);
19
+ const git = async (cwd, args, signal) => new TextDecoder().decode(await runGit(args, cwd, signal, process.env)).trim();
20
+ /** The host-owned entry decides whether the saved desktop may run. Read-only. */
21
+ export async function localDesktopState(input) {
22
+ const request = {
25
23
  headers: { Authorization: `Bearer ${input.key}` },
26
- });
24
+ };
25
+ if (input.signal !== undefined)
26
+ request.signal = input.signal;
27
+ const response = await fetch(new URL("/api/installations", input.url), request);
27
28
  if (!response.ok)
28
- return false;
29
+ throw new Error(`Desktop installation read failed (HTTP ${String(response.status)}).`);
29
30
  const rows = installationRowsSchema.parse(await response.json());
30
- return rows.some((row) => row.installationId === input.installationId);
31
+ const installed = rows.find((row) => row.installationId === "tourtois");
32
+ if (installed === undefined)
33
+ return "missing";
34
+ if (installed.status === "disabled")
35
+ return "disabled";
36
+ if (installed.status === "deleted")
37
+ return "deleted";
38
+ const entry = await fetch(new URL(`/ui-entry/tourtois/${encodeURIComponent(installed.release.releaseId)}/shell.js`, input.url), input.signal === undefined ? undefined : { signal: input.signal });
39
+ if (entry.ok)
40
+ return "ready";
41
+ return entry.status === 403 ? "approval-required" : "unavailable";
31
42
  }
32
43
  /** Build Tourtois from source on this machine and install it as `tourtois`. */
33
44
  export async function installLocalDesktop(input) {
34
- const scratch = await realpath(await mkdtemp(join(tmpdir(), "oyster-tourtois-")));
45
+ const signal = input.signal ?? new AbortController().signal;
46
+ signal.throwIfAborted();
47
+ const scratch = await mkdtemp(join(tmpdir(), "oyster-tourtois-"));
35
48
  try {
36
- const source = join(scratch, "tourtois");
37
- git(scratch, ["clone", "--quiet", "--depth=1", tourtoisRepository, source]);
38
- const commit = git(source, ["rev-parse", "HEAD"]);
49
+ const canonical = await realpath(scratch);
50
+ signal.throwIfAborted();
51
+ const source = join(canonical, "tourtois");
52
+ await git(canonical, ["clone", "--quiet", "--depth=1", tourtoisRepository, source], signal);
53
+ const commit = await git(source, ["rev-parse", "HEAD"], signal);
39
54
  const release = join(scratch, "release");
40
55
  await packRelease({
41
56
  appId: "app_tourtois",
42
57
  sourceDirectory: source,
43
58
  sourceRevision: `git:${commit}`,
44
- recipe: appBuildRecipe(readBuildManifest(git(source, ["show", `${commit}:package.json`])), ""),
59
+ recipe: appBuildRecipe(readBuildManifest(await git(source, ["show", `${commit}:package.json`], signal)), ""),
45
60
  outDirectory: release,
61
+ signal,
46
62
  });
47
63
  const owner = (method, path, body) => {
48
64
  const headers = new Headers({
49
65
  Authorization: `Bearer ${input.key}`,
50
66
  Accept: "application/json",
51
67
  });
52
- const init = { method, headers };
68
+ const init = { method, headers, signal };
53
69
  if (body !== undefined) {
54
70
  headers.set("Content-Type", "application/json");
55
71
  init.body = JSON.stringify(body);
@@ -61,6 +77,7 @@ export async function installLocalDesktop(input) {
61
77
  url: input.url,
62
78
  key: input.key,
63
79
  installationId: "tourtois",
80
+ signal,
64
81
  onCompleted: async (operation) => {
65
82
  if (operation.state === "succeeded")
66
83
  await approveChosenDashboard(operation, owner);
@@ -70,6 +87,8 @@ export async function installLocalDesktop(input) {
70
87
  throw new Error(`Tourtois install failed (${String(response.status)})`);
71
88
  }
72
89
  finally {
73
- await rm(scratch, { recursive: true, force: true });
90
+ await rm(scratch, { recursive: true, force: true }).catch((cause) => {
91
+ throw new CleanupError("App scratch cleanup failed", { cause });
92
+ });
74
93
  }
75
94
  }
@@ -1,9 +1,10 @@
1
1
  export type SignInLink = Readonly<{
2
2
  url: string;
3
- close: () => void;
3
+ close: () => Promise<void>;
4
4
  }>;
5
5
  /** Serve one single-use page that signs the owner in to `oysterUrl`. */
6
6
  export declare function startSignInLink(input: Readonly<{
7
7
  oysterUrl: string;
8
8
  key: string;
9
+ signal?: AbortSignal;
9
10
  }>): Promise<SignInLink>;
@@ -1,7 +1,9 @@
1
1
  // A one-time sign-in link for `oyster try`. The owner key never goes in a URL:
2
2
  // the link opens a page served by this process that posts the key to the local
3
3
  // Oyster's own /login form, then the server forgets the link.
4
+ import { awaitCleanup } from "../build/process-group.js";
4
5
  import { createHash, randomBytes } from "node:crypto";
6
+ import { addAbortListener } from "node:events";
5
7
  import { createServer } from "node:http";
6
8
  import * as z from "zod";
7
9
  import { hostPage } from "../host-page.js";
@@ -10,6 +12,8 @@ const addressSchema = z.object({ port: z.number() });
10
12
  const lifetimeMs = 10 * 60_000;
11
13
  /** Serve one single-use page that signs the owner in to `oysterUrl`. */
12
14
  export async function startSignInLink(input) {
15
+ const signal = input.signal ?? new AbortController().signal;
16
+ signal.throwIfAborted();
13
17
  const nonce = Array.from(randomBytes(18), (byte) => byte.toString(16).padStart(2, "0")).join("");
14
18
  let used = false;
15
19
  const sources = await loadPageAssets();
@@ -30,6 +34,8 @@ export async function startSignInLink(input) {
30
34
  })).text();
31
35
  const expired = await (await hostPage({ ...pageOptions, state: "link-expired", status: 404 })).text();
32
36
  const notFound = await (await hostPage({ ...pageOptions, state: "not-found", status: 404 })).text();
37
+ signal.throwIfAborted();
38
+ const timers = new Set();
33
39
  const server = createServer((request, response) => {
34
40
  const headers = {
35
41
  "Content-Type": "text/html; charset=utf-8",
@@ -49,22 +55,57 @@ export async function startSignInLink(input) {
49
55
  used = true;
50
56
  response.writeHead(200, headers).end(page);
51
57
  page = "";
52
- setTimeout(() => {
53
- server.close();
54
- }, 1_000).unref();
58
+ scheduleClose(1_000);
55
59
  });
56
- await new Promise((done, fail) => {
57
- server.once("error", fail);
58
- server.listen(0, "127.0.0.1", done);
59
- });
60
- setTimeout(() => {
61
- server.close();
62
- }, lifetimeMs).unref();
63
- const { port } = addressSchema.parse(server.address());
64
- return {
65
- url: `http://127.0.0.1:${String(port)}/${nonce}`,
66
- close: () => {
67
- server.close();
68
- },
69
- };
60
+ let closing;
61
+ let abortListener;
62
+ const beginClose = () => (closing ??= Promise.allSettled([
63
+ (async () => {
64
+ for (const timer of timers)
65
+ clearTimeout(timer);
66
+ timers.clear();
67
+ page = "";
68
+ abortListener?.[Symbol.dispose]();
69
+ await new Promise((resolve, reject) => {
70
+ server.close((cause) => {
71
+ if (cause &&
72
+ !("code" in cause && cause.code === "ERR_SERVER_NOT_RUNNING"))
73
+ reject(cause);
74
+ else
75
+ resolve();
76
+ });
77
+ server.closeAllConnections();
78
+ });
79
+ })(),
80
+ ]));
81
+ const close = () => awaitCleanup(beginClose());
82
+ function scheduleClose(ms) {
83
+ const timer = setTimeout(() => {
84
+ void beginClose();
85
+ }, ms);
86
+ timer.unref();
87
+ timers.add(timer);
88
+ }
89
+ try {
90
+ await new Promise((done, fail) => {
91
+ server.once("error", fail);
92
+ // listen is called synchronously before yielding ownership; cancellation
93
+ // joins the acquired listener even when it wins before the listen event.
94
+ server.listen(0, "127.0.0.1", () => {
95
+ server.off("error", fail);
96
+ done();
97
+ });
98
+ });
99
+ signal.throwIfAborted();
100
+ abortListener = addAbortListener(signal, () => {
101
+ void beginClose();
102
+ });
103
+ scheduleClose(lifetimeMs);
104
+ const { port } = addressSchema.parse(server.address());
105
+ return { url: `http://127.0.0.1:${String(port)}/${nonce}`, close };
106
+ }
107
+ catch (cause) {
108
+ await close();
109
+ throw cause;
110
+ }
70
111
  }