@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,21 +8,26 @@
8
8
  // npx @fungi.computer/oyster try [directory] [--port 8787] [--no-open] [--verbose]
9
9
  //
10
10
  // Output goes through Lantern, the shared Fungi terminal kit: a wordmark, one
11
- // spinner per real step, a success box and a next step for every failure. It
11
+ // progress log per real step, a success box and a next step for every failure. It
12
12
  // is quiet by default; install and server output go to files under .oyster/
13
13
  // and --verbose streams them instead. Piped output or CI gets plain lines.
14
- import { spawn, spawnSync } from "node:child_process";
14
+ import { spawn } from "node:child_process";
15
15
  import { randomBytes } from "node:crypto";
16
+ import { addAbortListener } from "node:events";
17
+ import { finished } from "node:stream/promises";
18
+ import { runGit } from "../build/local-build.js";
19
+ import { CleanupError, stopProcessGroup, awaitCleanup, } from "../build/process-group.js";
20
+ import { InstallationObservationError } from "../installation-client.js";
16
21
  import { createWriteStream } from "node:fs";
17
- import { copyFile, mkdir, readdir, readFile, stat, writeFile, } from "node:fs/promises";
22
+ import { copyFile, mkdir, mkdtemp, rename, readdir, rm, readFile, stat, writeFile, } from "node:fs/promises";
18
23
  import { createServer } from "node:net";
19
- import { basename, delimiter, join, resolve } from "node:path";
24
+ import { basename, dirname, delimiter, join, resolve } from "node:path";
20
25
  import process from "node:process";
21
26
  import { parseArgs } from "node:util";
22
27
  import { Cli } from "@fungi.computer/lantern";
23
28
  import * as z from "zod";
24
29
  import { installHelloApp } from "./hello-app.js";
25
- import { installLocalDesktop, isInstalled } from "./local-desktop.js";
30
+ import { installLocalDesktop, localDesktopState, } from "./local-desktop.js";
26
31
  import { startSignInLink } from "./sign-in-link.js";
27
32
  export const tryUsage = "Usage: oyster try [directory] [--port 8787] [--no-open] [--verbose] [--package <npm spec>]";
28
33
  const tryHelp = `${tryUsage}
@@ -49,6 +54,33 @@ const ownerKeyFile = ".oyster-owner";
49
54
  const logFile = join(".oyster", "wrangler.log");
50
55
  const installLogFile = join(".oyster", "install.log");
51
56
  const command = "npx @fungi.computer/oyster try";
57
+ const pendingInstall = join(".oyster", "install.pending");
58
+ const quote = (value) => "'" + value.replaceAll("'", "'\"'\"'") + "'";
59
+ const retryCommand = (directory, port) => `${command} ${quote(directory)} --port ${String(port)}`;
60
+ /** Lantern owns rendering; Oyster owns the measured phase and its lifetime. */
61
+ async function timedTask(ui, label, work) {
62
+ const started = performance.now();
63
+ const elapsed = () => `${((performance.now() - started) / 1000).toFixed(1)}s`;
64
+ try {
65
+ return await ui.task(label, async (update) => {
66
+ const timer = setInterval(() => {
67
+ update(`${label} · ${elapsed()} elapsed`);
68
+ }, 5000);
69
+ try {
70
+ const result = await work();
71
+ update(`${label} · done in ${elapsed()}`);
72
+ return result;
73
+ }
74
+ finally {
75
+ clearInterval(timer);
76
+ }
77
+ });
78
+ }
79
+ catch (cause) {
80
+ ui.step(`${label} · ${cause instanceof Error && cause.name === "AbortError" ? "stopped" : "failed"} after ${elapsed()}`);
81
+ throw cause;
82
+ }
83
+ }
52
84
  /** A failure that knows the exact next step; the command shows both. */
53
85
  class TryError extends Error {
54
86
  title;
@@ -60,9 +92,15 @@ class TryError extends Error {
60
92
  this.next = next;
61
93
  }
62
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
+ }
63
101
  /**
64
- * Streaming logs and a redrawing spinner cannot share a terminal, so
65
- * --verbose prints plain lines instead of spinners.
102
+ * Streaming logs and interactive progress cannot share a terminal, so
103
+ * --verbose prints plain lines.
66
104
  */
67
105
  export function createTryCli(args) {
68
106
  return args.includes("--verbose")
@@ -150,15 +188,34 @@ const pnpmWorkspace = `allowBuilds:
150
188
  async function exists(path) {
151
189
  return stat(path).then(() => true, () => false);
152
190
  }
153
- async function scaffold(directory, own, spec, manager) {
154
- await mkdir(directory, { recursive: true });
155
- const examples = join(import.meta.dirname, "../../examples/standalone");
156
- for (const name of ["worker.ts", "wrangler.jsonc"])
157
- await copyFile(join(examples, name), join(directory, name));
158
- await writeFile(join(directory, "package.json"), projectManifest(own, spec));
159
- if (manager === "pnpm")
160
- await writeFile(join(directory, "pnpm-workspace.yaml"), pnpmWorkspace);
161
- await writeFile(join(directory, ".gitignore"), ".oyster/\n.wrangler/\nnode_modules/\n.oyster-owner\n");
191
+ async function scaffold(directory, own, spec, manager, signal) {
192
+ signal.throwIfAborted();
193
+ await mkdir(dirname(directory), { recursive: true });
194
+ const stage = await mkdtemp(join(dirname(directory), ".oyster-try-"));
195
+ try {
196
+ const examples = join(import.meta.dirname, "../../examples/standalone");
197
+ for (const name of ["worker.ts", "wrangler.jsonc"]) {
198
+ signal.throwIfAborted();
199
+ await copyFile(join(examples, name), join(stage, name));
200
+ }
201
+ await writeFile(join(stage, "package.json"), projectManifest(own, spec));
202
+ if (manager === "pnpm")
203
+ await writeFile(join(stage, "pnpm-workspace.yaml"), pnpmWorkspace);
204
+ await writeFile(join(stage, ".gitignore"), ".oyster/\n.wrangler/\nnode_modules/\n.oyster-owner\n");
205
+ const key = Array.from(randomBytes(24), (byte) => byte.toString(16).padStart(2, "0")).join("");
206
+ await writeFile(join(stage, ownerKeyFile), key + "\n", {
207
+ mode: 0o600,
208
+ flag: "wx",
209
+ });
210
+ signal.throwIfAborted();
211
+ await rename(stage, directory);
212
+ return key;
213
+ }
214
+ finally {
215
+ await rm(stage, { recursive: true, force: true }).catch((cause) => {
216
+ throw new CleanupError("Project staging cleanup failed", { cause });
217
+ });
218
+ }
162
219
  }
163
220
  /** Write a child's output to a log file, and also to stderr when verbose. */
164
221
  function captureOutput(child, log, verbose) {
@@ -168,30 +225,84 @@ function captureOutput(child, log, verbose) {
168
225
  stream?.pipe(process.stderr, { end: false });
169
226
  }
170
227
  }
171
- async function runInstall(directory, manager, verbose) {
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
+ }
242
+ async function runInstall(directory, manager, verbose, signal) {
243
+ signal.throwIfAborted();
172
244
  await mkdir(join(directory, ".oyster"), { recursive: true });
245
+ signal.throwIfAborted();
173
246
  const log = createWriteStream(join(directory, installLogFile));
247
+ const logClosed = Promise.allSettled([finished(log)]);
248
+ let child;
249
+ let listener;
250
+ let stopping;
251
+ const beginStop = () => (stopping ??= Promise.allSettled([
252
+ child === undefined ? Promise.resolve() : stopProcessGroup(child),
253
+ ]));
254
+ const stop = () => awaitCleanup(beginStop());
174
255
  try {
175
- await new Promise((done, fail) => {
176
- const child = spawn(manager, ["install"], {
177
- cwd: directory,
178
- stdio: ["ignore", "pipe", "pipe"],
179
- shell: process.platform === "win32",
256
+ child = spawn(manager, manager === "npm" ? ["install", "--json"] : ["install"], {
257
+ cwd: directory,
258
+ detached: process.platform !== "win32",
259
+ signal,
260
+ stdio: ["ignore", "pipe", "pipe"],
261
+ shell: process.platform === "win32",
262
+ });
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 : "";
180
273
  });
181
- captureOutput(child, log, verbose);
182
- child.on("error", (cause) => {
183
- fail(new Error(`Could not run ${manager} install: ${cause.message}`));
274
+ }
275
+ const closed = new Promise((done, fail) => {
276
+ let failure;
277
+ child?.once("error", (cause) => {
278
+ failure = cause;
184
279
  });
185
- child.on("close", (code) => {
186
- if (code === 0)
280
+ child?.once("close", (code) => {
281
+ if (failure !== undefined)
282
+ fail(failure);
283
+ else if (code === 0)
187
284
  done();
188
- else
189
- 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
+ }
190
289
  });
191
290
  });
291
+ listener = addAbortListener(signal, () => {
292
+ void beginStop();
293
+ });
294
+ try {
295
+ await closed;
296
+ }
297
+ finally {
298
+ await stop();
299
+ }
300
+ signal.throwIfAborted();
192
301
  }
193
302
  finally {
303
+ listener?.[Symbol.dispose]();
194
304
  log.end();
305
+ await awaitCleanup(logClosed);
195
306
  }
196
307
  }
197
308
  function portFree(port) {
@@ -207,37 +318,34 @@ function portFree(port) {
207
318
  });
208
319
  });
209
320
  }
210
- async function waitUntilReady(url, child, timeoutMs) {
321
+ async function waitUntilReady(url, child, timeoutMs, signal) {
211
322
  const deadline = Date.now() + timeoutMs;
212
- while (Date.now() < deadline) {
213
- if (child.exitCode !== null)
214
- return false;
323
+ const stopped = () => child.exitCode !== null || child.signalCode !== null;
324
+ while (Date.now() < deadline && !signal.aborted) {
325
+ if (stopped())
326
+ return "exited";
215
327
  const answered = await fetch(`${url}/login`, {
216
- signal: AbortSignal.timeout(2_000),
328
+ signal: AbortSignal.any([signal, AbortSignal.timeout(2_000)]),
217
329
  }).then((response) => response.status < 500, () => false);
330
+ if (stopped())
331
+ return "exited";
218
332
  if (answered)
219
- return true;
333
+ return "ready";
220
334
  await new Promise((wake) => setTimeout(wake, 500));
221
335
  }
222
- return false;
223
- }
224
- async function tail(path) {
225
- try {
226
- const text = await readFile(path, "utf8");
227
- return text.trim().split("\n").slice(-15).join("\n");
228
- }
229
- catch {
230
- return "(no log was written)";
231
- }
336
+ return signal.aborted ? "exited" : "timeout";
232
337
  }
233
338
  function startWrangler(input) {
234
339
  return (async () => {
340
+ input.signal.throwIfAborted();
235
341
  const wrangler = join(input.directory, "node_modules", "wrangler", "bin", "wrangler.js");
236
342
  if (!(await exists(wrangler)))
237
- throw new TryError(`wrangler is not installed in ${input.directory}.`, `Run \`npm install\` there, then run \`${command}\` again.`);
343
+ throw new TryError(`wrangler is not installed in ${input.directory}.`, `Run \`npm install\` there, then run \`${retryCommand(input.directory, input.port)}\` again.`);
238
344
  await mkdir(join(input.directory, ".oyster"), { recursive: true });
239
345
  const log = join(input.directory, logFile);
346
+ input.signal.throwIfAborted();
240
347
  const logStream = createWriteStream(log);
348
+ const logClosed = Promise.allSettled([finished(logStream)]);
241
349
  const url = `http://127.0.0.1:${String(input.port)}`;
242
350
  const child = spawn(process.execPath, [
243
351
  wrangler,
@@ -258,52 +366,92 @@ function startWrangler(input) {
258
366
  "OYSTER_ORIGIN:https://oyster.test",
259
367
  ], {
260
368
  cwd: input.directory,
369
+ detached: process.platform !== "win32",
370
+ signal: input.signal,
261
371
  stdio: ["ignore", "pipe", "pipe"],
262
372
  env: { ...process.env, WRANGLER_SEND_METRICS: "false" },
263
373
  });
264
374
  captureOutput(child, logStream, input.verbose);
375
+ const lifetime = new AbortController();
376
+ const spawnError = new Promise((done) => {
377
+ child.once("error", () => {
378
+ done("spawn-error");
379
+ lifetime.abort();
380
+ });
381
+ });
265
382
  const exited = new Promise((done) => {
266
383
  child.on("close", (code) => {
267
- logStream.end();
384
+ lifetime.abort();
268
385
  done(code);
269
386
  });
270
387
  });
271
- const stop = async () => {
272
- if (child.exitCode === null)
273
- child.kill("SIGTERM");
274
- const forced = setTimeout(() => {
275
- child.kill("SIGKILL");
276
- }, 10_000);
277
- await exited;
278
- clearTimeout(forced);
279
- };
280
- if (!(await waitUntilReady(url, child, 120_000))) {
388
+ let stopping;
389
+ const beginStop = () => (stopping ??= Promise.allSettled([
390
+ (async () => {
391
+ try {
392
+ await stopProcessGroup(child);
393
+ await exited;
394
+ }
395
+ finally {
396
+ abortListener[Symbol.dispose]();
397
+ logStream.end();
398
+ await awaitCleanup(logClosed);
399
+ }
400
+ })(),
401
+ ]));
402
+ const stop = () => awaitCleanup(beginStop());
403
+ const abortListener = addAbortListener(input.signal, () => {
404
+ void beginStop();
405
+ });
406
+ try {
407
+ const readiness = await Promise.race([
408
+ waitUntilReady(url, child, 120_000, AbortSignal.any([lifetime.signal, input.signal])),
409
+ spawnError,
410
+ ]);
411
+ input.signal.throwIfAborted();
412
+ if (readiness !== "ready") {
413
+ const diagnostic = readiness === "spawn-error"
414
+ ? "Oyster could not launch its server process."
415
+ : readiness === "exited"
416
+ ? `Oyster stopped before readiness (${child.signalCode === null ? `exit ${String(child.exitCode)}` : `signal ${child.signalCode}`}).`
417
+ : "Oyster did not answer within 120 seconds.";
418
+ await stop();
419
+ throw new TryError(diagnostic, `Read ${log} for the server output.`);
420
+ }
421
+ return { stop, exited };
422
+ }
423
+ catch (cause) {
281
424
  await stop();
282
- throw new TryError("Oyster did not start.", `Read ${log}, or run \`${command} --verbose\` to watch it start. The last lines:\n${await tail(log)}`);
425
+ throw cause;
283
426
  }
284
- return { stop, exited };
285
427
  })();
286
428
  }
287
- function openBrowser(url) {
429
+ function openBrowser(url, failed) {
288
430
  const [command, args] = process.platform === "darwin"
289
431
  ? ["open", [url]]
290
432
  : process.platform === "win32"
291
433
  ? ["cmd", ["/c", "start", "", url]]
292
434
  : ["xdg-open", [url]];
293
435
  const child = spawn(command, args, { stdio: "ignore", detached: true });
294
- child.on("error", () => undefined);
436
+ let reported = false;
437
+ const reportFailure = () => {
438
+ if (reported)
439
+ return;
440
+ reported = true;
441
+ failed();
442
+ };
443
+ child.once("error", reportFailure);
444
+ child.once("close", (code) => {
445
+ if (code !== 0)
446
+ reportFailure();
447
+ });
295
448
  child.unref();
296
449
  }
297
- function untilInterrupted() {
298
- return new Promise((done) => {
299
- const once = () => {
300
- process.off("SIGINT", once);
301
- process.off("SIGTERM", once);
302
- done();
303
- };
304
- process.on("SIGINT", once);
305
- process.on("SIGTERM", once);
306
- });
450
+ function isTryCancellation(cause, signal) {
451
+ return (signal.aborted &&
452
+ (cause === signal.reason ||
453
+ (cause instanceof Error && cause.name === "AbortError") ||
454
+ cause instanceof InstallationObservationError));
307
455
  }
308
456
  const realEffects = {
309
457
  installDependencies: runInstall,
@@ -311,15 +459,18 @@ const realEffects = {
311
459
  installHello: installHelloApp,
312
460
  installDesktop: async ({ directory, ...input }) => {
313
461
  process.env.PATH = `${join(directory, "node_modules", ".bin")}${delimiter}${process.env.PATH ?? ""}`;
314
- if (!(await isInstalled({ ...input, installationId: "tourtois" })))
315
- await installLocalDesktop(input);
462
+ const saved = await localDesktopState(input);
463
+ if (saved !== "missing")
464
+ return saved;
465
+ await installLocalDesktop(input);
466
+ const installed = await localDesktopState(input);
467
+ return installed === "missing" ? "unavailable" : installed;
316
468
  },
317
469
  signInLink: startSignInLink,
318
470
  open: openBrowser,
319
- interrupted: untilInterrupted,
320
471
  portFree,
321
472
  };
322
- export async function tryOyster(args, effects = realEffects, ui = createTryCli(args)) {
473
+ export async function tryOyster(args, effects = realEffects, ui = createTryCli(args), callerSignal) {
323
474
  const { values, positionals } = parseArgs({
324
475
  args: [...args],
325
476
  allowPositionals: true,
@@ -340,66 +491,226 @@ export async function tryOyster(args, effects = realEffects, ui = createTryCli(a
340
491
  if (positionals.length > 1)
341
492
  throw new Error(tryUsage);
342
493
  ui.welcome("Oyster: your own Apps, running on this machine");
343
- const major = Number(process.versions.node.split(".")[0]);
344
- if (major < requiredNodeMajor)
345
- throw new TryError(`Oyster needs Node ${String(requiredNodeMajor)} or newer; this is Node ${process.versions.node}.`, `Install a current Node from https://nodejs.org, then run \`${command}\` again.`);
346
- if (!gitAvailable())
347
- throw new TryError("Oyster builds the Hello App from a git commit, so it needs Git.", `Install Git from https://git-scm.com, then run \`${command}\` again.`);
348
494
  const port = Number(values.port ?? "8787");
349
495
  if (!Number.isInteger(port) || port < 1 || port > 65_535)
350
496
  throw new TryError("--port must be a number from 1 to 65535.", `For example: \`${command} --port 8788\`.`);
351
- const directory = resolve(positionals[0] ??
352
- ((await exists(join(process.cwd(), ownerKeyFile))) ? "." : "my-oyster"));
353
- const keyPath = join(directory, ownerKeyFile);
354
- const fresh = !(await exists(keyPath));
355
- if (fresh) {
356
- const occupied = (await exists(directory))
357
- ? (await readdir(directory)).length > 0
358
- : false;
359
- if (occupied)
360
- throw new TryError(`${directory} already has files and is not an Oyster made by \`oyster try\`.`, `Choose a new directory: \`${command} <directory>\`.`);
361
- }
362
- if (!(await effects.portFree(port)))
363
- throw new TryError(`Port ${String(port)} on 127.0.0.1 is already in use.`, `Stop whatever is using it, or choose another port: \`${command} --port ${String(port + 1)}\`.`);
364
- let key;
365
- if (fresh) {
366
- const manager = detectManager(process.env.npm_config_user_agent);
367
- const own = await ownManifest();
368
- await ui.task(`Creating ${basename(directory)}`, () => scaffold(directory, own, values.package, manager));
369
- await ui
370
- .task(`Installing dependencies with ${manager} (a minute or two)`, () => effects.installDependencies(directory, manager, verbose))
371
- .catch((cause) => {
372
- throw new TryError(cause instanceof Error ? cause.message : String(cause), `Read ${join(directory, installLogFile)} (or add --verbose), delete ${directory}, and run \`${command}\` again.`);
373
- });
374
- key = Array.from(randomBytes(24), (byte) => byte.toString(16).padStart(2, "0")).join("");
375
- await writeFile(keyPath, key + "\n", { mode: 0o600 });
376
- }
377
- else {
378
- key = (await readFile(keyPath, "utf8")).trim();
379
- ui.info(`Restarting the Oyster in ${directory}`);
380
- }
381
- const url = `http://127.0.0.1:${String(port)}`;
382
- const server = await ui.task("Starting Oyster", () => effects.startServer({ directory, port, key, verbose }));
383
- let closeLink = () => undefined;
497
+ let directory = resolve(positionals[0] ?? "my-oyster");
498
+ const retryAtPort = (chosenPort) => retryCommand(directory, chosenPort) +
499
+ (values["no-open"] === true ? " --no-open" : "") +
500
+ (verbose ? " --verbose" : "") +
501
+ (values.package === undefined ? "" : ` --package ${quote(values.package)}`);
502
+ let retry = retryAtPort(port);
503
+ const retryWithLogs = () => retry + (verbose ? "" : " --verbose");
504
+ const cancellation = new AbortController();
505
+ const signal = callerSignal === undefined
506
+ ? cancellation.signal
507
+ : AbortSignal.any([cancellation.signal, callerSignal]);
508
+ const interrupt = () => {
509
+ cancellation.abort();
510
+ };
511
+ process.on("SIGINT", interrupt);
512
+ process.on("SIGTERM", interrupt);
513
+ let acquiredServer;
514
+ let closeLink;
384
515
  try {
385
- await ui.task("Installing the Hello App", () => effects.installHello({ directory, url, key }));
386
- await ui
387
- .task(fresh
388
- ? "Building Tourtois (about 2 min the first time)"
389
- : "Checking Tourtois", () => effects.installDesktop({ directory, url, key }))
390
- .catch((cause) => {
391
- ui.warn(`Tourtois, the desktop, could not be built (${innermostError(cause).message}). Continuing with the Hello App.`, isNetworkFailure(innermostError(cause))
392
- ? `Connect to the internet and run \`${command}\` again from ${directory} to try the desktop again.`
393
- : `Run \`${command} --verbose\` from ${directory} and report this.`);
516
+ if (positionals[0] === undefined &&
517
+ (await exists(join(process.cwd(), ownerKeyFile)))) {
518
+ directory = process.cwd();
519
+ retry = retryAtPort(port);
520
+ }
521
+ signal.throwIfAborted();
522
+ const major = Number(process.versions.node.split(".")[0]);
523
+ if (major < requiredNodeMajor)
524
+ throw new TryError(`Oyster needs Node ${String(requiredNodeMajor)} or newer; this is Node ${process.versions.node}.`, `Install a current Node from https://nodejs.org, then run \`${retry}\` again.`);
525
+ if (!(await gitAvailable(signal)))
526
+ throw new TryError("Oyster builds the Hello App from a git commit, so it needs Git.", `Install Git from https://git-scm.com, then run \`${retry}\` again.`);
527
+ const task = (label, work) => timedTask(ui, label, async () => {
528
+ signal.throwIfAborted();
529
+ const result = await work();
530
+ signal.throwIfAborted();
531
+ return result;
532
+ });
533
+ const keyPath = join(directory, ownerKeyFile);
534
+ const fresh = !(await exists(keyPath));
535
+ if (fresh) {
536
+ const occupied = (await exists(directory))
537
+ ? (await readdir(directory)).length > 0
538
+ : false;
539
+ if (occupied)
540
+ throw new TryError(`${directory} already has files and is not an Oyster made by \`oyster try\`.`, `Choose a new directory: \`${command} <directory>\`.`);
541
+ }
542
+ const available = await effects.portFree(port);
543
+ signal.throwIfAborted();
544
+ if (!available)
545
+ throw new TryError(`Port ${String(port)} on 127.0.0.1 is already in use.`, `Leave that listener running. Choose another port: \`${retryAtPort(port === 65535 ? 8787 : port + 1)}\`.`);
546
+ let key;
547
+ if (fresh) {
548
+ const manager = detectManager(process.env.npm_config_user_agent);
549
+ const own = await ownManifest();
550
+ key = await task(`Creating ${basename(directory)}`, () => scaffold(directory, own, values.package, manager, signal));
551
+ }
552
+ else {
553
+ key = (await readFile(keyPath, "utf8")).trim();
554
+ ui.info(`Restarting the Oyster in ${directory}`);
555
+ }
556
+ if (fresh ||
557
+ (await exists(join(directory, pendingInstall))) ||
558
+ !(await exists(join(directory, "node_modules/wrangler/bin/wrangler.js")))) {
559
+ const manager = (await exists(join(directory, "pnpm-workspace.yaml")))
560
+ ? "pnpm"
561
+ : "npm";
562
+ await mkdir(join(directory, ".oyster"), { recursive: true });
563
+ await writeFile(join(directory, pendingInstall), "Dependencies have not finished installing.\n");
564
+ await task(`Installing dependencies with ${manager}`, () => effects.installDependencies(directory, manager, verbose, signal)).catch((cause) => {
565
+ if (isTryCancellation(cause, signal))
566
+ throw cause;
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.`);
573
+ });
574
+ await rm(join(directory, pendingInstall));
575
+ }
576
+ const url = `http://127.0.0.1:${String(port)}`;
577
+ const server = await task("Starting Oyster", () => (async () => {
578
+ const resource = await effects.startServer({
579
+ directory,
580
+ port,
581
+ key,
582
+ verbose,
583
+ signal,
584
+ });
585
+ acquiredServer = resource;
586
+ return resource;
587
+ })()).catch((cause) => {
588
+ if (isTryCancellation(cause, signal))
589
+ throw cause;
590
+ throw new TryError(cause instanceof TryError ? cause.title : innermostError(cause).message, `Read ${join(directory, logFile)}, then run \`${retryWithLogs()}\`.`);
394
591
  });
395
- const link = await ui.task("Opening your desktop", async () => {
396
- const made = await effects.signInLink({ oysterUrl: url, key });
592
+ let serverExited = false;
593
+ const watchedExit = server.exited.then((code) => {
594
+ serverExited = true;
595
+ return code;
596
+ });
597
+ const assertRunning = () => {
598
+ signal.throwIfAborted();
599
+ if (serverExited)
600
+ throw new TryError("Oyster stopped unexpectedly during setup.", `Read ${join(directory, logFile)}, then run \`${retryWithLogs()}\`.`);
601
+ };
602
+ const setupTask = (label, work) => {
603
+ assertRunning();
604
+ return task(label, async () => {
605
+ const result = await work();
606
+ assertRunning();
607
+ return result;
608
+ });
609
+ };
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 = {
618
+ directory,
619
+ url,
620
+ key,
621
+ signal: AbortSignal.any([signal, preparation.signal]),
622
+ };
623
+ void watchedExit.then(() => {
624
+ preparation.abort();
625
+ });
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;
672
+ }).catch((cause) => {
673
+ if (signal.aborted || cause instanceof CleanupError)
674
+ throw cause;
675
+ assertRunning();
676
+ if (!(cause instanceof DesktopSetupError))
677
+ throw cause;
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))
679
+ ? `Check your connection, stop this trial with Ctrl-C, then run \`${retry}\` to retry the desktop.`
680
+ : `Stop this trial with Ctrl-C, then run \`${retryWithLogs()}\` and report the desktop build error.`);
681
+ return "failed";
682
+ });
683
+ const desktopReady = desktop === "ready";
684
+ const accessUrl = new URL("/api/installations/tourtois/grants", url).href;
685
+ if (desktop !== "ready" && desktop !== "failed")
686
+ ui.warn(desktop === "approval-required"
687
+ ? "Tourtois needs Shell approval."
688
+ : desktop === "disabled"
689
+ ? "Tourtois is disabled."
690
+ : desktop === "deleted"
691
+ ? "Tourtois was removed."
692
+ : "Tourtois is unavailable; its shell entry did not become ready.", desktop === "deleted"
693
+ ? `Sign in at ${url}/login, then open your Hello App at ${url}/apps/hello/. The desktop was not reinstalled.`
694
+ : `Sign in, then review App access at ${accessUrl}. Your saved installation and approvals were not changed.`);
695
+ const link = await setupTask(desktopReady ? "Preparing desktop sign-in" : "Preparing recovery sign-in", async () => {
696
+ const made = await effects.signInLink({ oysterUrl: url, key, signal });
397
697
  closeLink = made.close;
698
+ signal.throwIfAborted();
398
699
  if (values["no-open"] !== true && process.stdout.isTTY)
399
- effects.open(made.url);
700
+ effects.open(made.url, () => {
701
+ if (signal.aborted)
702
+ return;
703
+ ui.warn("The browser did not open.", "Use the sign-in link printed here to open Oyster.");
704
+ });
400
705
  return made;
706
+ }).catch((cause) => {
707
+ if (signal.aborted || cause instanceof CleanupError)
708
+ throw cause;
709
+ assertRunning();
710
+ throw new TryError(innermostError(cause).message, `Sign-in could not be prepared. Run \`${retryWithLogs()}\` again; your saved project is unchanged.`);
401
711
  });
402
- ui.note("Oyster is running", [
712
+ assertRunning();
713
+ ui.note(desktopReady ? "Oyster is running" : "Oyster needs desktop repair", [
403
714
  `Open (works once): ${link.url}`,
404
715
  `Oyster: ${url}`,
405
716
  `Owner key saved in: ${keyPath}`,
@@ -407,21 +718,62 @@ export async function tryOyster(args, effects = realEffects, ui = createTryCli(a
407
718
  `Sign in later by pasting that key at ${url}/login.`,
408
719
  "Press Ctrl-C to stop.",
409
720
  ]);
410
- const outcome = await Promise.race([
411
- effects.interrupted().then(() => "interrupted"),
412
- server.exited.then(() => "exited"),
413
- ]);
414
- if (outcome === "exited")
415
- throw new TryError("Oyster stopped unexpectedly.", `Read ${join(directory, logFile)}, then run \`${command}\` again.`);
721
+ let stopListener;
722
+ try {
723
+ const requested = new Promise((done) => {
724
+ stopListener = addAbortListener(signal, () => {
725
+ done();
726
+ });
727
+ });
728
+ const outcome = await Promise.race([
729
+ requested.then(() => "interrupted"),
730
+ watchedExit.then(() => "exited"),
731
+ ]);
732
+ if (outcome === "exited")
733
+ throw new TryError("Oyster stopped unexpectedly.", `Read ${join(directory, logFile)}, then run \`${retry}\` again.`);
734
+ }
735
+ finally {
736
+ stopListener?.[Symbol.dispose]();
737
+ }
738
+ }
739
+ catch (cause) {
740
+ if (!isTryCancellation(cause, signal))
741
+ throw cause;
742
+ if (cause instanceof InstallationObservationError)
743
+ ui.info(cause.message);
416
744
  }
417
745
  finally {
418
- closeLink();
419
- ui.step("Stopping Oyster");
420
- await server.stop();
746
+ try {
747
+ const cleanup = async () => {
748
+ const outcomes = await Promise.allSettled([
749
+ Promise.resolve().then(() => closeLink?.()),
750
+ Promise.resolve().then(() => acquiredServer?.stop()),
751
+ ]);
752
+ if (outcomes.some((result) => result.status === "rejected"))
753
+ throw new TryError("Oyster cleanup did not complete.", `Check ${join(directory, logFile)} and the local listener before running \`${retry}\` again.`);
754
+ };
755
+ if (acquiredServer !== undefined || closeLink !== undefined)
756
+ await timedTask(ui, "Stopping Oyster", cleanup);
757
+ else
758
+ await cleanup();
759
+ }
760
+ finally {
761
+ process.off("SIGINT", interrupt);
762
+ process.off("SIGTERM", interrupt);
763
+ }
421
764
  }
422
- ui.outro("Stopped. Run the same command again to start it again.");
765
+ ui.outro(`Stopped. Restart with \`${retry}\`.`);
423
766
  }
424
767
  /** Whether `git` is available; Hello App packing reads its commit. */
425
- function gitAvailable() {
426
- return spawnSync("git", ["--version"], { stdio: "ignore" }).status === 0;
768
+ async function gitAvailable(signal) {
769
+ try {
770
+ await runGit(["--version"], process.cwd(), signal, process.env);
771
+ return true;
772
+ }
773
+ catch (cause) {
774
+ if (cause instanceof CleanupError)
775
+ throw cause;
776
+ signal.throwIfAborted();
777
+ return false;
778
+ }
427
779
  }