@neta-art/cohub-cli 10.14.1 → 10.16.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 (48) hide show
  1. package/README.md +3 -1
  2. package/dist/auth.d.ts +3 -1
  3. package/dist/auth.js +4 -0
  4. package/dist/board-export.d.ts +7 -0
  5. package/dist/board-export.js +3 -3
  6. package/dist/board-kernel.d.ts +1 -0
  7. package/dist/board-kernel.js +7605 -277
  8. package/dist/board-simulate.d.ts +53 -0
  9. package/dist/board-simulate.js +151 -0
  10. package/dist/bootstrap.js +5 -0
  11. package/dist/commands/auth.js +12 -1
  12. package/dist/commands/boards.js +68 -0
  13. package/dist/commands/host.d.ts +2 -0
  14. package/dist/commands/host.js +11 -0
  15. package/dist/commands/runtime.js +4 -16
  16. package/dist/commands/space-invitations.d.ts +3 -2
  17. package/dist/commands/space-invitations.js +29 -8
  18. package/dist/commands/spaces.js +55 -30
  19. package/dist/host/auth.d.ts +20 -0
  20. package/dist/host/auth.js +107 -0
  21. package/dist/host/login-env.d.ts +1 -0
  22. package/dist/host/login-env.js +31 -0
  23. package/dist/host/runtime.d.ts +25 -0
  24. package/dist/host/runtime.js +250 -0
  25. package/dist/host/runtimes.d.ts +9 -0
  26. package/dist/host/runtimes.js +42 -0
  27. package/dist/host/serve.d.ts +2 -0
  28. package/dist/host/serve.js +73 -0
  29. package/dist/index.js +2 -0
  30. package/dist/runtime/connection.d.ts +3 -0
  31. package/dist/runtime/connection.js +59 -3
  32. package/dist/runtime/harnesses/claude.js +8 -2
  33. package/dist/runtime/harnesses/index.d.ts +2 -0
  34. package/dist/runtime/harnesses/index.js +13 -0
  35. package/dist/runtime/harnesses/stream-json.d.ts +2 -2
  36. package/dist/runtime/harnesses/stream-json.js +5 -3
  37. package/dist/runtime/harnesses/types.d.ts +4 -2
  38. package/dist/runtime/harnesses/workbuddy.d.ts +8 -2
  39. package/dist/runtime/instance.d.ts +8 -1
  40. package/dist/runtime/instance.js +89 -9
  41. package/dist/runtime/launch.d.ts +1 -0
  42. package/dist/runtime/launch.js +6 -0
  43. package/dist/runtime/model-catalog.d.ts +1 -3
  44. package/dist/runtime/model-catalog.js +23 -7
  45. package/dist/runtime/supervisor.js +6 -4
  46. package/dist/space.d.ts +1 -0
  47. package/dist/space.js +1 -1
  48. package/package.json +3 -3
@@ -1,6 +1,6 @@
1
1
  import { readdir, stat } from "node:fs/promises";
2
2
  import { basename, dirname, relative, resolve, sep } from "node:path";
3
- import { harnessSchema, readSentTurns, readSessionTurnOrigin, resolveCohubEnvironment } from "@neta-art/cohub";
3
+ import { harnessSchema, isModelThinkingLevel, MODEL_THINKING_LEVELS, readSentTurns, readSessionTurnOrigin, resolveCohubEnvironment } from "@neta-art/cohub";
4
4
  import { uploadAvatarAsset, uploadChatImageAsset } from "../avatar.js";
5
5
  import { createClient } from "../client.js";
6
6
  import { collectOption, readPromptContent } from "../command-input.js";
@@ -73,6 +73,15 @@ const parseAutoDestroy = (opts) => {
73
73
  return { mode: "idle", ttlSeconds };
74
74
  };
75
75
  const parseSandboxSpec = (value) => value ? parseChoice(value, "sandbox spec", SANDBOX_SPEC_IDS) : undefined;
76
+ async function resolveGuestApp(client, spaceId, value) {
77
+ if (value === "none")
78
+ return null;
79
+ const { apps } = await client.apps.listBySpace(spaceId);
80
+ const app = apps.find((item) => item.id === value || item.slug === value);
81
+ if (!app)
82
+ return error("App not found", `No App "${value}" in this Space`);
83
+ return { appId: app.id };
84
+ }
76
85
  export function buildSpaceCreateInput(opts) {
77
86
  const autoDestroy = parseAutoDestroy(opts);
78
87
  const spec = parseSandboxSpec(opts.spec);
@@ -198,10 +207,13 @@ async function sendPrompt(command, words, opts) {
198
207
  if (agentOnly.length)
199
208
  return error("Conflicting options", `--note cannot be combined with ${agentOnly.join(", ")}`);
200
209
  }
201
- const thinkingLevel = opts.thinkingLevel?.trim() || undefined;
202
- if (thinkingLevel
203
- && !new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]).has(thinkingLevel)) {
204
- return error("Invalid thinking level", "Use off|minimal|low|medium|high|xhigh|max");
210
+ if (opts.reply && (opts.note || scheduleFlags.length)) {
211
+ return error("Conflicting options", "--reply cannot be combined with --note or scheduling");
212
+ }
213
+ const requestedThinkingLevel = opts.thinkingLevel?.trim() || undefined;
214
+ const thinkingLevel = isModelThinkingLevel(requestedThinkingLevel) ? requestedThinkingLevel : undefined;
215
+ if (requestedThinkingLevel && !thinkingLevel) {
216
+ return error("Invalid thinking level", `Use ${MODEL_THINKING_LEVELS.join("|")}`);
205
217
  }
206
218
  const spaceId = await resolveSpace(command, { home: true });
207
219
  const client = createClient();
@@ -249,17 +261,20 @@ async function sendPrompt(command, words, opts) {
249
261
  model: opts.model,
250
262
  provider: opts.provider,
251
263
  harness: opts.harness,
252
- thinkingLevel: thinkingLevel,
264
+ thinkingLevel,
253
265
  accessMode: opts.readOnly ? "read_only" : "full_access",
254
266
  intent: opts.steer ? "steer" : undefined,
255
267
  env: parseEnvOptions(opts.env),
256
268
  schedule,
257
269
  labelRefs: opts.label?.length ? opts.label : undefined,
270
+ ...(opts.reply ? { reply: "prompt" } : {}),
258
271
  });
259
272
  if (jsonRequested(opts))
260
273
  return outJson(result);
261
- if (result.mode === "immediate")
262
- return ok(`${opts.note ? "Note recorded" : "Prompt sent"} — sessionId: ${result.session.id}, turnId: ${result.turn.id}`);
274
+ if (result.mode === "immediate") {
275
+ const label = opts.note ? "Note recorded" : opts.reply ? "Prompt sent; the reply will come back to this Chat" : "Prompt sent";
276
+ return ok(`${label} — sessionId: ${result.session.id}, turnId: ${result.turn.id}`);
277
+ }
263
278
  if (result.mode === "repeat")
264
279
  return ok(`Prompt scheduled — cronJobId: ${result.cronJobId}, nextRunAt: ${result.nextRunAt}`);
265
280
  return ok(`Prompt scheduled — taskRunId: ${result.taskRunId}, scheduledAt: ${result.scheduledAt}`);
@@ -291,10 +306,10 @@ async function runCompletionCommand(command, words, opts) {
291
306
  if (maxTokens !== undefined && (!Number.isFinite(maxTokens) || maxTokens <= 0)) {
292
307
  return error("Invalid max tokens", "--max-tokens must be a positive number");
293
308
  }
294
- const thinkingLevel = opts.thinkingLevel?.trim() || undefined;
295
- if (thinkingLevel
296
- && !new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]).has(thinkingLevel)) {
297
- return error("Invalid thinking level", "Use off|minimal|low|medium|high|xhigh|max");
309
+ const requestedThinkingLevel = opts.thinkingLevel?.trim() || undefined;
310
+ const thinkingLevel = isModelThinkingLevel(requestedThinkingLevel) ? requestedThinkingLevel : undefined;
311
+ if (requestedThinkingLevel && !thinkingLevel) {
312
+ return error("Invalid thinking level", `Use ${MODEL_THINKING_LEVELS.join("|")}`);
298
313
  }
299
314
  const client = createClient();
300
315
  const input = {
@@ -304,7 +319,7 @@ async function runCompletionCommand(command, words, opts) {
304
319
  messages: [{ role: "user", content: [{ type: "text", text }] }],
305
320
  temperature,
306
321
  maxTokens,
307
- thinkingLevel: thinkingLevel,
322
+ thinkingLevel,
308
323
  };
309
324
  try {
310
325
  if (opts.stream) {
@@ -356,7 +371,7 @@ export function registerPrompt(program) {
356
371
  .option("-m, --model <model>", "Model name")
357
372
  .option("-p, --provider <provider>", "Provider name")
358
373
  .option("--harness <harness>", `Harness: ${harnessSchema.options.join(", ")}`, "cohub")
359
- .option("--thinking-level <level>", "Thinking level: off|minimal|low|medium|high|xhigh|max")
374
+ .option("--thinking-level <level>", `Thinking level: ${MODEL_THINKING_LEVELS.join("|")}`)
360
375
  .option("--read-only", "Use read-only tools")
361
376
  .option("--steer", "Interrupt the current turn and run immediately")
362
377
  .option("--delay-ms <ms>", "Delay sending by milliseconds")
@@ -367,6 +382,7 @@ export function registerPrompt(program) {
367
382
  .option("--env <key=value>", "Set an environment variable for this turn", collectOption, [])
368
383
  .option("--image <path>", "Attach an image", collectOption, [])
369
384
  .option("--note", "Record the message without an AI reply")
385
+ .option("--reply", "Send the final reply back to the calling Chat and run its Agent")
370
386
  .option("--json", "Output as JSON")
371
387
  .action((words, opts) => sendPrompt(program, words, opts));
372
388
  program
@@ -674,6 +690,7 @@ export function registerSpaces(program) {
674
690
  .option("--idle-ttl <seconds>", "Idle auto destroy TTL in seconds, max 2592000 (30d)")
675
691
  .option("--spec <spec>", "Sandbox spec: standard, boost, ultra, or auto")
676
692
  .option("--image <image>", "Sandbox image: default, game, or auto")
693
+ .option("--guest-app <app>", "Published public App shown to visitors without access: id, slug, or none")
677
694
  .option("--json", "Output as JSON")
678
695
  .action(async (id, opts) => {
679
696
  const client = createClient();
@@ -681,8 +698,13 @@ export function registerSpaces(program) {
681
698
  const autoDestroy = parseAutoDestroy(opts);
682
699
  const spec = opts.spec === "auto" ? null : parseSandboxSpec(opts.spec);
683
700
  const image = opts.image === "auto" ? null : opts.image ? parseChoice(opts.image, "sandbox image", ["default", "game"]) : undefined;
684
- if (autoDestroy || spec !== undefined || image !== undefined) {
685
- const result = await client.space(id).updateConfig({ sandbox: { ...(autoDestroy ? { autoDestroy } : {}), ...(spec !== undefined ? { spec } : {}), ...(image !== undefined ? { image } : {}) } });
701
+ const guest = opts.guestApp === undefined ? undefined : await resolveGuestApp(client, id, opts.guestApp);
702
+ const sandboxChanged = Boolean(autoDestroy) || spec !== undefined || image !== undefined;
703
+ if (sandboxChanged || guest !== undefined) {
704
+ const result = await client.space(id).updateConfig({
705
+ ...(sandboxChanged ? { sandbox: { ...(autoDestroy ? { autoDestroy } : {}), ...(spec !== undefined ? { spec } : {}), ...(image !== undefined ? { image } : {}) } } : {}),
706
+ ...(guest !== undefined ? { guest } : {}),
707
+ });
686
708
  if (jsonRequested(opts))
687
709
  return outJson(result);
688
710
  ok(`Space config updated${autoDestroy ? ` — sandbox auto destroy: ${formatAutoDestroy(autoDestroy)}` : ""}${spec ? ` — sandbox spec: ${spec}` : ""}${result.sandbox?.pendingRestart ? " — restart the sandbox to apply" : ""}`);
@@ -701,6 +723,7 @@ export function registerSpaces(program) {
701
723
  { key: "sandbox.spec", value: result.config.sandbox.spec ?? "standard" },
702
724
  { key: "sandbox.appliedSpec", value: result.config.sandbox.appliedSpec ?? "—" },
703
725
  { key: "sandbox.allowedSpec", value: result.config.sandbox.allowedSpec ?? "standard" },
726
+ { key: "guest.appId", value: result.config.guest?.appId ?? "default" },
704
727
  ], [
705
728
  { key: "key", label: "Key" },
706
729
  { key: "value", label: "Value" },
@@ -720,7 +743,7 @@ export function registerSpaces(program) {
720
743
  .option("--title <title>", "Title for a newly created session or schedule")
721
744
  .option("-m, --model <model>", "Model name")
722
745
  .option("-p, --provider <provider>", "Provider name")
723
- .option("--thinking-level <level>", "Thinking level: off|minimal|low|medium|high|xhigh|max")
746
+ .option("--thinking-level <level>", `Thinking level: ${MODEL_THINKING_LEVELS.join("|")}`)
724
747
  .option("--read-only", "Use read-only tools")
725
748
  .option("--steer", "Interrupt the current turn and run immediately")
726
749
  .option("--delay-ms <ms>", "Delay sending by milliseconds")
@@ -731,6 +754,7 @@ export function registerSpaces(program) {
731
754
  .option("--env <key=value>", "Set an environment variable for this turn", collectOption, [])
732
755
  .option("--image <path>", "Attach an image", collectOption, [])
733
756
  .option("--note", "Record the message without an AI reply")
757
+ .option("--reply", "Send the final reply back to the calling Chat and run its Agent")
734
758
  .option("--json", "Output as JSON")
735
759
  .action((words, opts) => sendPrompt(spacesCmd, words, opts));
736
760
  // ── spaces completion ──
@@ -1873,6 +1897,10 @@ function registerMembers(spacesCmd) {
1873
1897
  });
1874
1898
  }
1875
1899
  // ── Access control ──
1900
+ const ACCESS_COLUMNS = [
1901
+ { key: "signed_in_user", label: "Signed-in" },
1902
+ { key: "anonymous_user", label: "Anonymous" },
1903
+ ];
1876
1904
  function registerAccess(spacesCmd) {
1877
1905
  const accCmd = spacesCmd
1878
1906
  .command("access")
@@ -1889,10 +1917,7 @@ function registerAccess(spacesCmd) {
1889
1917
  const policy = await client.space(spaceId).access.get();
1890
1918
  if (jsonRequested(opts))
1891
1919
  return outJson(policy);
1892
- table([policy], [
1893
- { key: "signed_in_user", label: "Signed-in" },
1894
- { key: "anonymous_user", label: "Anonymous" },
1895
- ]);
1920
+ table([policy], ACCESS_COLUMNS);
1896
1921
  }
1897
1922
  catch (e) {
1898
1923
  handleHttp(e);
@@ -1900,25 +1925,25 @@ function registerAccess(spacesCmd) {
1900
1925
  });
1901
1926
  accCmd
1902
1927
  .command("set")
1903
- .description("Set access policy")
1904
- .option("--signed-in <role>", "Role for signed-in users (host|builder|guest|null)")
1905
- .option("--anonymous <role>", "Role for anonymous users (host|builder|guest|null)")
1928
+ .description("Set access policy; omitted options stay unchanged")
1929
+ .option("--signed-in <role>", "Role for signed-in users (builder|guest|null)")
1930
+ .option("--anonymous <role>", "Role for anonymous users (guest|null)")
1906
1931
  .option("--json", "Output as JSON")
1907
1932
  .action(async (opts) => {
1908
1933
  const spaceId = await resolveSpace(spacesCmd);
1909
1934
  const client = createClient();
1935
+ if (opts.signedIn === undefined && opts.anonymous === undefined) {
1936
+ return error("Nothing to update", "Pass --signed-in or --anonymous");
1937
+ }
1910
1938
  try {
1911
1939
  const policy = await client.space(spaceId).access.set({
1912
- signed_in_user: parseNullableRole(opts.signedIn, "signed-in role"),
1913
- anonymous_user: parseNullableRole(opts.anonymous, "anonymous role"),
1940
+ ...(opts.signedIn !== undefined ? { signed_in_user: parseNullableRole(opts.signedIn, "signed-in role") } : {}),
1941
+ ...(opts.anonymous !== undefined ? { anonymous_user: parseNullableRole(opts.anonymous, "anonymous role") } : {}),
1914
1942
  });
1915
1943
  if (jsonRequested(opts))
1916
1944
  return outJson(policy);
1917
1945
  ok("Access policy updated");
1918
- table([policy], [
1919
- { key: "signed_in_user", label: "Signed-in" },
1920
- { key: "anonymous_user", label: "Anonymous" },
1921
- ]);
1946
+ table([policy], ACCESS_COLUMNS);
1922
1947
  }
1923
1948
  catch (e) {
1924
1949
  handleHttp(e);
@@ -0,0 +1,20 @@
1
+ import type { HostEmit } from "./serve.js";
2
+ export declare class HostAuth {
3
+ #private;
4
+ private readonly emit;
5
+ private readonly onAccountChanged;
6
+ constructor(emit: HostEmit, onAccountChanged: () => void);
7
+ watch(): void;
8
+ close(): void;
9
+ get subject(): string | null;
10
+ accessToken(forceRefresh?: boolean): Promise<string | null>;
11
+ sessionVersion(): number;
12
+ session(): {
13
+ authenticated: boolean;
14
+ userUuid: null;
15
+ subject: string | null;
16
+ email: null;
17
+ };
18
+ signIn(redirectPath?: string): Promise<boolean>;
19
+ signOut(): Promise<boolean>;
20
+ }
@@ -0,0 +1,107 @@
1
+ import { mkdirSync, watch } from "node:fs";
2
+ import { basename, dirname } from "node:path";
3
+ import { HOST_SERVICE_SHELL_EVENTS, hostAuthChangedSchema, hostShellOpenSchema } from "@neta-art/cohub/host-bridge";
4
+ import { AuthRequiredError, authSessionPath, pollDeviceCode, readAuthSession, requestDeviceCode, resolveAccessToken, revokeAndClearAuthSession, } from "../auth.js";
5
+ import { clearHomeSpaceCache, jwtClaim } from "../space.js";
6
+ function snapshot() {
7
+ const session = readAuthSession();
8
+ if (!session)
9
+ return { subject: null, revision: null };
10
+ return {
11
+ subject: jwtClaim(session.idToken, "sub") ?? jwtClaim(session.accessToken, "sub"),
12
+ revision: `${session.updatedAt}:${session.refreshToken}`,
13
+ };
14
+ }
15
+ export class HostAuth {
16
+ emit;
17
+ onAccountChanged;
18
+ #current = snapshot();
19
+ #version = 0;
20
+ #watcher = null;
21
+ #debounce;
22
+ #rewatch;
23
+ #pending = null;
24
+ constructor(emit, onAccountChanged) {
25
+ this.emit = emit;
26
+ this.onAccountChanged = onAccountChanged;
27
+ }
28
+ watch() {
29
+ const path = authSessionPath();
30
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
31
+ this.#watcher = watch(dirname(path), (_event, name) => {
32
+ if (name && name !== basename(path))
33
+ return;
34
+ clearTimeout(this.#debounce);
35
+ this.#debounce = setTimeout(() => this.#sync(), 50);
36
+ });
37
+ this.#watcher.once("error", () => {
38
+ this.#watcher?.close();
39
+ this.#rewatch = setTimeout(() => this.watch(), 1_000).unref();
40
+ });
41
+ }
42
+ close() {
43
+ clearTimeout(this.#debounce);
44
+ clearTimeout(this.#rewatch);
45
+ this.#watcher?.close();
46
+ }
47
+ get subject() {
48
+ return this.#current.subject;
49
+ }
50
+ async accessToken(forceRefresh = false) {
51
+ try {
52
+ return await resolveAccessToken({ forceRefresh });
53
+ }
54
+ catch (error) {
55
+ if (error instanceof AuthRequiredError)
56
+ return null;
57
+ throw error;
58
+ }
59
+ }
60
+ sessionVersion() {
61
+ return this.#version;
62
+ }
63
+ session() {
64
+ const { subject } = snapshot();
65
+ return { authenticated: subject !== null, userUuid: null, subject, email: null };
66
+ }
67
+ async signIn(redirectPath) {
68
+ const destination = hostAuthChangedSchema.shape.redirectPath.safeParse(redirectPath).data;
69
+ if (this.#pending && this.#pending.expiresAt > Date.now()) {
70
+ this.#pending.redirectPath = destination;
71
+ this.#open(this.#pending.url);
72
+ return true;
73
+ }
74
+ const code = await requestDeviceCode();
75
+ const pending = { url: code.verificationUriComplete, expiresAt: code.expiresAt, redirectPath: destination };
76
+ this.#pending = pending;
77
+ this.#open(pending.url);
78
+ void pollDeviceCode(code)
79
+ .then(() => this.#sync({ redirectPath: pending.redirectPath, signedIn: true }))
80
+ .catch((error) => process.stderr.write(`Sign-in did not complete: ${error instanceof Error ? error.message : String(error)}\n`))
81
+ .finally(() => { if (this.#pending === pending)
82
+ this.#pending = null; });
83
+ return true;
84
+ }
85
+ async signOut() {
86
+ await revokeAndClearAuthSession();
87
+ clearHomeSpaceCache();
88
+ this.#sync();
89
+ this.emit("auth.signedOut");
90
+ return true;
91
+ }
92
+ #open(url) {
93
+ this.emit(HOST_SERVICE_SHELL_EVENTS.open, hostShellOpenSchema.parse({ url }));
94
+ }
95
+ #sync({ redirectPath, signedIn = false } = {}) {
96
+ const next = snapshot();
97
+ const accountChanged = next.subject !== this.#current.subject;
98
+ if (next.revision !== this.#current.revision || accountChanged)
99
+ this.#version += 1;
100
+ this.#current = next;
101
+ if (accountChanged)
102
+ this.onAccountChanged();
103
+ if (!accountChanged && !signedIn)
104
+ return;
105
+ this.emit("auth.changed", hostAuthChangedSchema.parse({ authenticated: next.subject !== null, ...(redirectPath ? { redirectPath } : {}) }));
106
+ }
107
+ }
@@ -0,0 +1 @@
1
+ export declare function loginShellEnv(base?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): Promise<NodeJS.ProcessEnv>;
@@ -0,0 +1,31 @@
1
+ import { execFile } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ const TIMEOUT_MS = 10_000;
4
+ // Cohub settings come from the host, never from the user's shell.
5
+ const SCOPED = /^(COHUB_.*|ENV)$/;
6
+ const quote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
7
+ export async function loginShellEnv(base = process.env, platform = process.platform) {
8
+ const scoped = Object.fromEntries(Object.entries(base).filter(([key]) => SCOPED.test(key)));
9
+ if (platform === "win32")
10
+ return base;
11
+ const shell = base.SHELL || (platform === "darwin" ? "/bin/zsh" : "/bin/sh");
12
+ const mark = randomUUID();
13
+ const print = `${quote(process.execPath)} -e ${quote("process.stdout.write(JSON.stringify(process.env))")}`;
14
+ const output = await new Promise((resolve) => {
15
+ execFile(shell, ["-l", "-i", "-c", `printf %s ${mark}; ${print}; printf %s ${mark}`], {
16
+ encoding: "utf8", timeout: TIMEOUT_MS, maxBuffer: 4 * 1024 * 1024,
17
+ env: base,
18
+ }, (_error, stdout) => resolve(typeof stdout === "string" ? stdout : null));
19
+ });
20
+ const json = output?.split(mark)[1];
21
+ if (!json)
22
+ return base;
23
+ try {
24
+ const shellEnv = JSON.parse(json);
25
+ const inherited = Object.fromEntries(Object.entries(shellEnv).filter(([key]) => !SCOPED.test(key)));
26
+ return { ...inherited, ...scoped };
27
+ }
28
+ catch {
29
+ return base;
30
+ }
31
+ }
@@ -0,0 +1,25 @@
1
+ import type { DEVICE_RUNTIME_REFUSALS, DeviceFolderListing, DeviceRuntime } from "@neta-art/cohub/host-bridge";
2
+ import type { HostEmit } from "./serve.js";
3
+ type Refusal = (typeof DEVICE_RUNTIME_REFUSALS)[number];
4
+ export type DeviceRuntimeHostOptions = {
5
+ cli: string;
6
+ env: () => Promise<NodeJS.ProcessEnv>;
7
+ account: () => string | null;
8
+ };
9
+ export declare class DeviceRuntimeHost {
10
+ #private;
11
+ private readonly emit;
12
+ private readonly options;
13
+ constructor(emit: HostEmit, options: DeviceRuntimeHostOptions);
14
+ watch(): void;
15
+ close(): void;
16
+ changed(): void;
17
+ list(): Promise<DeviceRuntime>;
18
+ browse(path?: string): Promise<DeviceFolderListing>;
19
+ connect(spaceId: string, root: string): Promise<DeviceRuntime & {
20
+ refused: Refusal | null;
21
+ }>;
22
+ disconnect(spaceId: string): Promise<DeviceRuntime>;
23
+ restore(): Promise<void>;
24
+ }
25
+ export {};
@@ -0,0 +1,250 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdirSync, watch } from "node:fs";
3
+ import { readdir, realpath, stat } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { basename, dirname, join, relative, sep } from "node:path";
6
+ import { EXPECTED_IDENTITY_ENV } from "../runtime/launch.js";
7
+ import { requestRuntimeInstance, runtimeInstanceDirectory, runtimeInstancesRoot, stopRuntimeInstance, watchRuntimeInstance } from "../runtime/instance.js";
8
+ import { readRuntimeSpaceBindings, runtimeSpaceBindingsPath } from "../runtime/space-binding.js";
9
+ import { forgetHostRuntime, hostRuntimes, rememberHostRuntime } from "./runtimes.js";
10
+ const MAX_INSTANCES = 256;
11
+ const MAX_FOLDERS = 10_000;
12
+ const MAX_VOLUMES = 16;
13
+ const isRunning = (instance) => instance?.state === "connecting" || instance?.state === "ready";
14
+ const samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
15
+ function deviceState(status) {
16
+ if (!status || status.state === "stopping")
17
+ return "stopped";
18
+ if (status.state === "ready")
19
+ return "ready";
20
+ return status.state === "attention" ? "error" : "connecting";
21
+ }
22
+ function displayPath(path, home = homedir()) {
23
+ if (process.platform === "win32")
24
+ return path;
25
+ const inside = relative(home, path);
26
+ if (!inside)
27
+ return "~";
28
+ return inside.startsWith("..") || inside.startsWith(sep) ? path : `~/${inside}`;
29
+ }
30
+ async function isDirectory(path) {
31
+ return stat(path).then((info) => info.isDirectory(), () => false);
32
+ }
33
+ async function volumes() {
34
+ const home = homedir();
35
+ const homeVolume = { path: home, label: basename(home) || home };
36
+ if (process.platform === "win32") {
37
+ const drives = await Promise.all([..."CDEFGHIJKLMNOPQRSTUVWXYZ"].map(async (letter) => {
38
+ const path = `${letter}:\\`;
39
+ return await isDirectory(path) ? { path, label: `${letter}:` } : null;
40
+ }));
41
+ return [homeVolume, ...drives.filter((drive) => drive !== null)].slice(0, MAX_VOLUMES);
42
+ }
43
+ if (process.platform === "darwin") {
44
+ const mounted = await readdir("/Volumes").catch(() => []);
45
+ const resolved = await Promise.all(mounted.map(async (name) => {
46
+ const path = await realpath(join("/Volumes", name)).catch(() => null);
47
+ return path ? { path, label: name } : null;
48
+ }));
49
+ return [homeVolume, ...resolved.filter((volume) => volume !== null)].slice(0, MAX_VOLUMES);
50
+ }
51
+ return [homeVolume, { path: "/", label: "/" }];
52
+ }
53
+ export class DeviceRuntimeHost {
54
+ emit;
55
+ options;
56
+ #watchers = [];
57
+ #subscriptions = new Map();
58
+ #debounce;
59
+ #published = "";
60
+ #restoring = Promise.resolve();
61
+ #unwatchable = new Set();
62
+ constructor(emit, options) {
63
+ this.emit = emit;
64
+ this.options = options;
65
+ }
66
+ watch() {
67
+ this.#watch();
68
+ void this.restore();
69
+ }
70
+ close() {
71
+ clearTimeout(this.#debounce);
72
+ for (const watcher of this.#watchers)
73
+ watcher.close();
74
+ for (const subscription of this.#subscriptions.values())
75
+ subscription.abort();
76
+ }
77
+ #watch() {
78
+ const bindings = runtimeSpaceBindingsPath();
79
+ const instances = runtimeInstancesRoot();
80
+ mkdirSync(dirname(bindings), { recursive: true, mode: 0o700 });
81
+ mkdirSync(instances, { recursive: true, mode: 0o700 });
82
+ const watchers = [
83
+ watch(dirname(bindings), (_event, name) => { if (!name || name === basename(bindings))
84
+ this.changed(); }),
85
+ watch(instances, { recursive: true }, () => this.changed()),
86
+ ];
87
+ this.#watchers = watchers;
88
+ const rewatch = () => {
89
+ if (this.#watchers !== watchers)
90
+ return;
91
+ this.#watchers = [];
92
+ for (const watcher of watchers)
93
+ watcher.close();
94
+ setTimeout(() => { this.#watch(); this.changed(); }, 1_000).unref();
95
+ };
96
+ for (const watcher of watchers)
97
+ watcher.on("error", rewatch);
98
+ }
99
+ changed() {
100
+ clearTimeout(this.#debounce);
101
+ this.#debounce = setTimeout(() => void this.#publish().catch(() => undefined), 100);
102
+ }
103
+ async list() {
104
+ const key = this.options.account();
105
+ if (!key)
106
+ return { instances: [] };
107
+ const bindings = (await readRuntimeSpaceBindings().catch(() => ({ bindings: [] }))).bindings;
108
+ const roots = new Map();
109
+ for (const binding of bindings) {
110
+ if (binding.key !== key)
111
+ continue;
112
+ roots.delete(binding.spaceId);
113
+ roots.set(binding.spaceId, binding.root);
114
+ }
115
+ const instances = await Promise.all([...roots].slice(-MAX_INSTANCES).map(async ([spaceId, root]) => {
116
+ const directory = runtimeInstanceDirectory(key, spaceId);
117
+ try {
118
+ const status = await requestRuntimeInstance(directory);
119
+ if (status)
120
+ this.#subscribe(directory, status.pid);
121
+ const path = status?.root ?? root;
122
+ return { spaceId, root: path, label: displayPath(path), state: deviceState(status), error: status?.state === "attention" ? "attention" : null };
123
+ }
124
+ catch {
125
+ return { spaceId, root, label: displayPath(root), state: "error", error: "unreachable" };
126
+ }
127
+ }));
128
+ return { instances };
129
+ }
130
+ async browse(path) {
131
+ const target = await realpath(path ?? homedir());
132
+ if (!await isDirectory(target))
133
+ throw new Error("Not a folder");
134
+ const entries = await readdir(target, { withFileTypes: true });
135
+ const folders = (await Promise.all(entries.map(async (entry) => {
136
+ if (entry.name.startsWith("."))
137
+ return null;
138
+ const folder = join(target, entry.name);
139
+ const directory = entry.isDirectory() || (entry.isSymbolicLink() && await isDirectory(folder));
140
+ return directory ? { name: entry.name, path: folder } : null;
141
+ })))
142
+ .filter((folder) => folder !== null)
143
+ .sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }))
144
+ .slice(0, MAX_FOLDERS);
145
+ const key = this.options.account();
146
+ const bindings = key ? (await readRuntimeSpaceBindings().catch(() => ({ bindings: [] }))).bindings : [];
147
+ const parent = dirname(target);
148
+ return {
149
+ path: target,
150
+ label: displayPath(target),
151
+ parent: parent === target ? null : parent,
152
+ spaceId: bindings.filter((binding) => binding.key === key && samePath(binding.root, target)).at(-1)?.spaceId ?? null,
153
+ folders,
154
+ volumes: await volumes(),
155
+ };
156
+ }
157
+ async connect(spaceId, root) {
158
+ const key = this.options.account();
159
+ if (!key)
160
+ throw new Error("Sign in first");
161
+ const folder = await realpath(root).catch(() => null);
162
+ const current = await this.list();
163
+ if (!folder || !await isDirectory(folder))
164
+ return { ...current, refused: "folder_unavailable" };
165
+ const serving = current.instances.find((instance) => instance.spaceId === spaceId);
166
+ if (isRunning(serving))
167
+ return { ...current, refused: samePath(serving.root, folder) ? null : "space_in_use" };
168
+ if (current.instances.some((instance) => isRunning(instance) && samePath(instance.root, folder)))
169
+ return { ...current, refused: "folder_in_use" };
170
+ await this.#launch(key, spaceId, folder);
171
+ await rememberHostRuntime({ key, spaceId, root: folder });
172
+ return { ...await this.#publish(), refused: null };
173
+ }
174
+ async disconnect(spaceId) {
175
+ const key = this.options.account();
176
+ if (!key)
177
+ throw new Error("Sign in first");
178
+ await stopRuntimeInstance(runtimeInstanceDirectory(key, spaceId));
179
+ await forgetHostRuntime(key, spaceId);
180
+ return this.#publish();
181
+ }
182
+ restore() {
183
+ this.#restoring = this.#restoring.then(async () => {
184
+ const key = this.options.account();
185
+ if (!key)
186
+ return;
187
+ // A failed read skips this restore; nothing is forgotten.
188
+ const { bindings } = await readRuntimeSpaceBindings();
189
+ for (const item of await hostRuntimes(key)) {
190
+ const bound = bindings.filter((binding) => binding.key === key && binding.spaceId === item.spaceId).at(-1);
191
+ if (!bound || !samePath(bound.root, item.root)) {
192
+ await forgetHostRuntime(key, item.spaceId);
193
+ continue;
194
+ }
195
+ const running = await requestRuntimeInstance(runtimeInstanceDirectory(key, item.spaceId)).catch(() => true);
196
+ if (running || !await isDirectory(item.root))
197
+ continue;
198
+ await this.#launch(key, item.spaceId, item.root).catch((error) => {
199
+ process.stderr.write(`Could not reconnect ${item.root}: ${error instanceof Error ? error.message : String(error)}\n`);
200
+ });
201
+ }
202
+ }).catch((error) => {
203
+ process.stderr.write(`Could not restore connected folders: ${error instanceof Error ? error.message : String(error)}\n`);
204
+ }).finally(() => this.changed());
205
+ return this.#restoring;
206
+ }
207
+ async #publish() {
208
+ const runtime = await this.list();
209
+ const serialized = JSON.stringify(runtime);
210
+ if (serialized !== this.#published) {
211
+ this.#published = serialized;
212
+ this.emit("runtime.changed", runtime);
213
+ }
214
+ return runtime;
215
+ }
216
+ #subscribe(directory, pid) {
217
+ const instance = `${directory}:${pid}`;
218
+ if (this.#subscriptions.has(directory) || this.#unwatchable.has(instance))
219
+ return;
220
+ const controller = new AbortController();
221
+ this.#subscriptions.set(directory, controller);
222
+ void watchRuntimeInstance(directory, () => this.changed(), controller.signal).then((streamed) => {
223
+ if (!streamed)
224
+ this.#unwatchable.add(instance);
225
+ }, () => undefined).finally(() => {
226
+ if (this.#subscriptions.get(directory) === controller)
227
+ this.#subscriptions.delete(directory);
228
+ if (!controller.signal.aborted)
229
+ this.changed();
230
+ });
231
+ }
232
+ async #launch(key, spaceId, root) {
233
+ const env = await this.options.env();
234
+ if (this.options.account() !== key)
235
+ throw new Error("The signed-in account changed");
236
+ const child = spawn(process.execPath, [this.options.cli, "runtime", "up", root, "--space", spaceId, "--detach", "--yes", "--no-display", "--json"], {
237
+ env: { ...env, [EXPECTED_IDENTITY_ENV]: key }, stdio: ["ignore", "ignore", "pipe"], windowsHide: true,
238
+ });
239
+ let stderr = "";
240
+ child.stderr.setEncoding("utf8").on("data", (chunk) => { stderr = `${stderr}${chunk}`.slice(-8_192); });
241
+ const code = await new Promise((resolve, reject) => {
242
+ child.once("error", reject);
243
+ child.once("close", resolve);
244
+ });
245
+ if (code === 0 || code === 2)
246
+ return;
247
+ const reason = stderr.trim().split("\n").at(-1)?.replace(/^Runtime failed: /, "");
248
+ throw new Error(reason || `Runtime exited (${code})`);
249
+ }
250
+ }
@@ -0,0 +1,9 @@
1
+ export type HostRuntime = {
2
+ key: string;
3
+ spaceId: string;
4
+ root: string;
5
+ };
6
+ export declare const hostRuntimesPath: () => string;
7
+ export declare const hostRuntimes: (key: string, path?: string) => Promise<HostRuntime[]>;
8
+ export declare const rememberHostRuntime: (runtime: HostRuntime, path?: string) => Promise<void>;
9
+ export declare const forgetHostRuntime: (key: string, spaceId: string, path?: string) => Promise<void>;