@neta-art/cohub-cli 10.17.1 → 10.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +6 -0
  2. package/dist/board-export-resources.d.ts +2 -0
  3. package/dist/board-export-resources.js +1 -0
  4. package/dist/board-export.d.ts +11 -2
  5. package/dist/board-export.js +181 -62
  6. package/dist/board-gpu/index.d.ts +32 -0
  7. package/dist/board-gpu/index.js +188 -0
  8. package/dist/board-gpu/page.js +70384 -0
  9. package/dist/board-gpu/protocol.d.ts +38 -0
  10. package/dist/board-gpu/protocol.js +1 -0
  11. package/dist/board-kernel/{getPo2TextureFromSource.js → FilterPipe.js} +251 -1
  12. package/dist/board-kernel/browserAll.js +1 -1
  13. package/dist/board-kernel/init.js +1 -251
  14. package/dist/board-kernel/webworkerAll.js +1 -1
  15. package/dist/board-kernel.d.ts +3 -3
  16. package/dist/board-kernel.js +6501 -414
  17. package/dist/board-media-export.d.ts +16 -0
  18. package/dist/board-media-export.js +147 -0
  19. package/dist/board-media.d.ts +2 -1
  20. package/dist/board-media.js +23 -0
  21. package/dist/board-simulate.d.ts +4 -0
  22. package/dist/board-simulate.js +34 -4
  23. package/dist/client.d.ts +1 -0
  24. package/dist/client.js +4 -1
  25. package/dist/commands/apps.js +25 -3
  26. package/dist/commands/boards/authoring.js +45 -3
  27. package/dist/commands/boards/examples.js +21 -5
  28. package/dist/commands/boards.js +10 -2
  29. package/dist/commands/space-displays.d.ts +1 -1
  30. package/dist/commands/space-displays.js +356 -85
  31. package/dist/commands/spaces.js +11 -2
  32. package/dist/host/runtime.d.ts +12 -2
  33. package/dist/host/runtime.js +155 -10
  34. package/dist/host/serve.js +49 -11
  35. package/dist/host/workspaces.d.ts +2 -0
  36. package/dist/host/workspaces.js +18 -0
  37. package/dist/index.js +1 -0
  38. package/dist/output.d.ts +1 -0
  39. package/dist/output.js +3 -0
  40. package/dist/runtime/cli-path.d.ts +5 -0
  41. package/dist/runtime/cli-path.js +27 -0
  42. package/dist/runtime/connection.d.ts +22 -4
  43. package/dist/runtime/connection.js +13 -3
  44. package/dist/runtime/harnesses/claude-approval.d.ts +31 -0
  45. package/dist/runtime/harnesses/claude-approval.js +119 -0
  46. package/dist/runtime/harnesses/claude.js +42 -3
  47. package/dist/runtime/harnesses/codex-approval.d.ts +25 -0
  48. package/dist/runtime/harnesses/codex-approval.js +69 -0
  49. package/dist/runtime/harnesses/codex.js +36 -5
  50. package/dist/runtime/harnesses/index.js +12 -3
  51. package/dist/runtime/harnesses/stream-json.d.ts +16 -2
  52. package/dist/runtime/harnesses/stream-json.js +26 -6
  53. package/dist/runtime/harnesses/types.d.ts +3 -1
  54. package/dist/runtime/instance.d.ts +1 -0
  55. package/dist/runtime/instance.js +1 -0
  56. package/dist/runtime/launch.js +2 -4
  57. package/dist/runtime/local-workspace.d.ts +15 -0
  58. package/dist/runtime/local-workspace.js +52 -0
  59. package/dist/runtime/model-catalog.js +7 -4
  60. package/dist/runtime/native/approvals.d.ts +18 -0
  61. package/dist/runtime/native/approvals.js +54 -0
  62. package/dist/runtime/native/codex-link.d.ts +7 -0
  63. package/dist/runtime/native/codex-link.js +40 -5
  64. package/dist/runtime/native/daemon.d.ts +5 -1
  65. package/dist/runtime/native/daemon.js +6 -1
  66. package/dist/runtime/native/execution.d.ts +2 -0
  67. package/dist/runtime/preferences.d.ts +7 -0
  68. package/dist/runtime/preferences.js +22 -0
  69. package/dist/runtime/presentation.d.ts +3 -0
  70. package/dist/runtime/presentation.js +2 -1
  71. package/dist/runtime/supervisor.js +92 -9
  72. package/dist/safe-remote-image.d.ts +4 -0
  73. package/dist/safe-remote-image.js +8 -0
  74. package/dist/space-files/transfer.js +3 -2
  75. package/dist/space-files/upload.d.ts +5 -2
  76. package/dist/space-files/upload.js +41 -1
  77. package/package.json +2 -2
@@ -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, isModelThinkingLevel, MODEL_THINKING_LEVELS, readSentTurns, readSessionTurnOrigin, resolveCohubEnvironment } from "@neta-art/cohub";
3
+ import { APPROVAL_MODES, harnessSchema, isApprovalMode, 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";
@@ -202,7 +202,8 @@ async function sendPrompt(command, words, opts) {
202
202
  if (opts.note) {
203
203
  const agentOnly = Object.entries({
204
204
  "--delay-ms": opts.delayMs, "--at": opts.at, "--cron": opts.cron, "--model": opts.model, "--provider": opts.provider,
205
- "--thinking-level": opts.thinkingLevel, "--read-only": opts.readOnly, "--steer": opts.steer, "--env": opts.env?.length,
205
+ "--thinking-level": opts.thinkingLevel, "--approval-mode": opts.approvalMode, "--service-tier": opts.serviceTier,
206
+ "--read-only": opts.readOnly, "--steer": opts.steer, "--env": opts.env?.length,
206
207
  }).flatMap(([flag, value]) => value ? [flag] : []);
207
208
  if (agentOnly.length)
208
209
  return error("Conflicting options", `--note cannot be combined with ${agentOnly.join(", ")}`);
@@ -215,6 +216,8 @@ async function sendPrompt(command, words, opts) {
215
216
  if (requestedThinkingLevel && !thinkingLevel) {
216
217
  return error("Invalid thinking level", `Use ${MODEL_THINKING_LEVELS.join("|")}`);
217
218
  }
219
+ if (opts.approvalMode !== undefined && !isApprovalMode(opts.approvalMode))
220
+ return error("Invalid approval mode", `Use ${APPROVAL_MODES.join("|")}`);
218
221
  const spaceId = await resolveSpace(command, { home: true });
219
222
  const client = createClient();
220
223
  try {
@@ -262,6 +265,8 @@ async function sendPrompt(command, words, opts) {
262
265
  provider: opts.provider,
263
266
  harness: opts.harness,
264
267
  thinkingLevel,
268
+ ...(isApprovalMode(opts.approvalMode) ? { approvalMode: opts.approvalMode } : {}),
269
+ ...(opts.serviceTier ? { serviceTier: opts.serviceTier } : {}),
265
270
  accessMode: opts.readOnly ? "read_only" : "full_access",
266
271
  intent: opts.steer ? "steer" : undefined,
267
272
  env: parseEnvOptions(opts.env),
@@ -372,6 +377,8 @@ export function registerPrompt(program) {
372
377
  .option("-p, --provider <provider>", "Provider name")
373
378
  .option("--harness <harness>", `Harness: ${harnessSchema.options.join(", ")}`, "cohub")
374
379
  .option("--thinking-level <level>", `Thinking level: ${MODEL_THINKING_LEVELS.join("|")}`)
380
+ .option("--approval-mode <mode>", `Local Harness approval mode: ${APPROVAL_MODES.join("|")}`)
381
+ .option("--service-tier <tier>", "Local Harness service tier, e.g. priority for Codex Fast")
375
382
  .option("--read-only", "Use read-only tools")
376
383
  .option("--steer", "Interrupt the current turn and run immediately")
377
384
  .option("--delay-ms <ms>", "Delay sending by milliseconds")
@@ -747,6 +754,8 @@ export function registerSpaces(program) {
747
754
  .option("-m, --model <model>", "Model name")
748
755
  .option("-p, --provider <provider>", "Provider name")
749
756
  .option("--thinking-level <level>", `Thinking level: ${MODEL_THINKING_LEVELS.join("|")}`)
757
+ .option("--approval-mode <mode>", `Local Harness approval mode: ${APPROVAL_MODES.join("|")}`)
758
+ .option("--service-tier <tier>", "Local Harness service tier, e.g. priority for Codex Fast")
750
759
  .option("--read-only", "Use read-only tools")
751
760
  .option("--steer", "Interrupt the current turn and run immediately")
752
761
  .option("--delay-ms <ms>", "Delay sending by milliseconds")
@@ -1,6 +1,7 @@
1
- import type { DEVICE_RUNTIME_REFUSALS, DeviceFolderListing, DeviceRuntime } from "@neta-art/cohub/host-bridge";
1
+ import type { DEVICE_RUNTIME_REFUSALS, DEVICE_RUNTIME_STOP_REFUSALS, DeviceDisplayStatus, DeviceFolderListing, DeviceRuntime } from "@neta-art/cohub/host-bridge";
2
2
  import type { HostEmit } from "./serve.js";
3
3
  type Refusal = (typeof DEVICE_RUNTIME_REFUSALS)[number];
4
+ type StopRefusal = (typeof DEVICE_RUNTIME_STOP_REFUSALS)[number];
4
5
  export type DeviceRuntimeHostOptions = {
5
6
  cli: string;
6
7
  env: () => Promise<NodeJS.ProcessEnv>;
@@ -19,7 +20,16 @@ export declare class DeviceRuntimeHost {
19
20
  connect(spaceId: string, root: string): Promise<DeviceRuntime & {
20
21
  refused: Refusal | null;
21
22
  }>;
22
- disconnect(spaceId: string): Promise<DeviceRuntime>;
23
+ disconnect(spaceId: string, force?: boolean): Promise<DeviceRuntime & {
24
+ refused: StopRefusal | null;
25
+ }>;
26
+ stopAccount(): Promise<void>;
27
+ accountChanged(): void;
28
+ displayStatus(): Promise<DeviceDisplayStatus>;
29
+ share(spaceId: string): Promise<DeviceDisplayStatus>;
30
+ stopSharing(): Promise<DeviceDisplayStatus>;
31
+ stopOwnSharing(): Promise<void>;
32
+ keepAwake(enabled?: boolean): Promise<boolean>;
23
33
  restore(): Promise<void>;
24
34
  }
25
35
  export {};
@@ -1,16 +1,21 @@
1
1
  import { spawn } from "node:child_process";
2
- import { mkdirSync, watch } from "node:fs";
3
- import { readdir, realpath, stat } from "node:fs/promises";
2
+ import { existsSync, mkdirSync, watch } from "node:fs";
3
+ import { opendir, readdir, realpath, stat } from "node:fs/promises";
4
4
  import { homedir } from "node:os";
5
5
  import { basename, dirname, join, relative, sep } from "node:path";
6
6
  import { EXPECTED_IDENTITY_ENV } from "../runtime/launch.js";
7
- import { requestRuntimeInstance, runtimeInstanceDirectory, runtimeInstancesRoot, stopRuntimeInstance, watchRuntimeInstance } from "../runtime/instance.js";
7
+ import { controlRuntimeInstance, requestRuntimeInstance, runtimeInstanceDirectory, runtimeInstancesRoot, stopRuntimeInstance, UNCONFIRMED_WORK, watchRuntimeInstance } from "../runtime/instance.js";
8
+ import { readRuntimePreferences, writeRuntimePreferences } from "../runtime/preferences.js";
8
9
  import { readRuntimeSpaceBindings, runtimeSpaceBindingsPath } from "../runtime/space-binding.js";
9
10
  import { forgetHostRuntime, hostRuntimes, rememberHostRuntime } from "./runtimes.js";
10
11
  const MAX_INSTANCES = 256;
11
12
  const MAX_FOLDERS = 10_000;
12
13
  const MAX_VOLUMES = 16;
13
- const isRunning = (instance) => instance?.state === "connecting" || instance?.state === "ready";
14
+ const DISPLAY_CONTROL_MS = 15_000;
15
+ const SHARED_SCREEN = "auto";
16
+ const NO_SCREEN = "";
17
+ const isRunningState = (state) => state === "connecting" || state === "ready";
18
+ const isRunning = (instance) => isRunningState(instance?.state);
14
19
  const samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
15
20
  function deviceState(status) {
16
21
  if (!status || status.state === "stopping")
@@ -19,6 +24,23 @@ function deviceState(status) {
19
24
  return "ready";
20
25
  return status.state === "attention" ? "error" : "connecting";
21
26
  }
27
+ const isDenied = (error) => ["EPERM", "EACCES"].includes(error.code ?? "");
28
+ function launchFailure(message) {
29
+ if (/non-elevated/.test(message))
30
+ return "elevated";
31
+ if (/EPERM|EACCES|permission denied|operation not permitted/i.test(message))
32
+ return "folder_denied";
33
+ if (/fetch failed|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|Download of \S+ (failed|timed out)/.test(message))
34
+ return "offline";
35
+ return "failed";
36
+ }
37
+ function hasWindowsShell(env = process.env) {
38
+ if (env.COHUB_BASH)
39
+ return true;
40
+ const roots = [env.ProgramFiles, env["ProgramFiles(x86)"], env.LOCALAPPDATA && join(env.LOCALAPPDATA, "Programs")];
41
+ const directories = (env.PATH ?? env.Path ?? "").split(";").filter((entry) => /[\\/]git[\\/]/i.test(entry));
42
+ return [...roots.flatMap((root) => root ? [join(root, "Git", "bin", "bash.exe")] : []), ...directories.map((entry) => join(entry, "bash.exe")), ...directories.map((entry) => join(dirname(entry), "bin", "bash.exe"))].some((path) => existsSync(path));
43
+ }
22
44
  function displayPath(path, home = homedir()) {
23
45
  if (process.platform === "win32")
24
46
  return path;
@@ -59,6 +81,11 @@ export class DeviceRuntimeHost {
59
81
  #published = "";
60
82
  #restoring = Promise.resolve();
61
83
  #unwatchable = new Set();
84
+ #transient = new Map();
85
+ #screen = { sharedWith: null, control: false, error: null };
86
+ #publishedScreen = "";
87
+ #shared = new Set();
88
+ #screenWork = Promise.resolve();
62
89
  constructor(emit, options) {
63
90
  this.emit = emit;
64
91
  this.options = options;
@@ -112,19 +139,37 @@ export class DeviceRuntimeHost {
112
139
  roots.delete(binding.spaceId);
113
140
  roots.set(binding.spaceId, binding.root);
114
141
  }
142
+ for (const [spaceId, { root }] of this.#transient)
143
+ if (!roots.has(spaceId))
144
+ roots.set(spaceId, root);
145
+ let screen = { sharedWith: null, control: false, error: null };
146
+ const shared = new Set();
147
+ const hasShell = process.platform !== "win32" || hasWindowsShell();
115
148
  const instances = await Promise.all([...roots].slice(-MAX_INSTANCES).map(async ([spaceId, root]) => {
116
149
  const directory = runtimeInstanceDirectory(key, spaceId);
150
+ const transient = this.#transient.get(spaceId);
117
151
  try {
118
152
  const status = await requestRuntimeInstance(directory);
153
+ if (!status && transient)
154
+ return { spaceId, ...transient, label: displayPath(transient.root) };
119
155
  if (status)
120
156
  this.#subscribe(directory, status.pid);
157
+ if (status?.display) {
158
+ const needs = status.displayNeeds ?? [];
159
+ if (status.displayOnRequest)
160
+ shared.add(spaceId);
161
+ screen = { sharedWith: spaceId, control: !needs.includes("accessibility"), error: needs.includes("screenRecording") ? "screen_recording" : null };
162
+ }
121
163
  const path = status?.root ?? root;
122
- return { spaceId, root: path, label: displayPath(path), state: deviceState(status), error: status?.state === "attention" ? "attention" : null };
164
+ const state = deviceState(status);
165
+ return { spaceId, root: path, label: displayPath(path), state, error: status?.state === "attention" ? "attention" : isRunningState(state) && !hasShell ? "no_shell" : null };
123
166
  }
124
167
  catch {
125
168
  return { spaceId, root, label: displayPath(root), state: "error", error: "unreachable" };
126
169
  }
127
170
  }));
171
+ this.#screen = screen;
172
+ this.#shared = shared;
128
173
  return { instances };
129
174
  }
130
175
  async browse(path) {
@@ -167,17 +212,112 @@ export class DeviceRuntimeHost {
167
212
  return { ...current, refused: samePath(serving.root, folder) ? null : "space_in_use" };
168
213
  if (current.instances.some((instance) => isRunning(instance) && samePath(instance.root, folder)))
169
214
  return { ...current, refused: "folder_in_use" };
170
- await this.#launch(key, spaceId, folder);
171
- await rememberHostRuntime({ key, spaceId, root: folder });
215
+ const denied = await opendir(folder).then((directory) => directory.close().then(() => false), isDenied);
216
+ if (denied)
217
+ return { ...current, refused: "folder_denied" };
218
+ this.#transient.set(spaceId, { root: folder, state: "connecting", error: null });
219
+ void this.#publish().catch(() => undefined);
220
+ try {
221
+ await this.#launch(key, spaceId, folder);
222
+ await rememberHostRuntime({ key, spaceId, root: folder });
223
+ this.#transient.delete(spaceId);
224
+ }
225
+ catch (error) {
226
+ const message = error instanceof Error ? error.message : String(error);
227
+ process.stderr.write(`Could not connect ${folder}: ${message}\n`);
228
+ this.#transient.set(spaceId, { root: folder, state: "error", error: launchFailure(message) });
229
+ }
172
230
  return { ...await this.#publish(), refused: null };
173
231
  }
174
- async disconnect(spaceId) {
232
+ async disconnect(spaceId, force = false) {
175
233
  const key = this.options.account();
176
234
  if (!key)
177
235
  throw new Error("Sign in first");
178
- await stopRuntimeInstance(runtimeInstanceDirectory(key, spaceId));
236
+ this.#transient.delete(spaceId);
237
+ try {
238
+ await stopRuntimeInstance(runtimeInstanceDirectory(key, spaceId), force);
239
+ }
240
+ catch (error) {
241
+ if (error instanceof Error && error.message.startsWith(UNCONFIRMED_WORK))
242
+ return { ...await this.list(), refused: "unconfirmed_work" };
243
+ throw error;
244
+ }
179
245
  await forgetHostRuntime(key, spaceId);
180
- return this.#publish();
246
+ return { ...await this.#publish(), refused: null };
247
+ }
248
+ async stopAccount() {
249
+ const key = this.options.account();
250
+ if (!key)
251
+ return;
252
+ const { instances } = await this.list();
253
+ await Promise.allSettled(instances.filter(isRunning).map((instance) => stopRuntimeInstance(runtimeInstanceDirectory(key, instance.spaceId), true)));
254
+ this.accountChanged();
255
+ }
256
+ accountChanged() {
257
+ this.#transient.clear();
258
+ }
259
+ async displayStatus() {
260
+ await this.list();
261
+ return this.#screen;
262
+ }
263
+ #serialScreen(work) {
264
+ const run = this.#screenWork.then(work);
265
+ this.#screenWork = run.catch(() => undefined);
266
+ return run;
267
+ }
268
+ share(spaceId) {
269
+ return this.#serialScreen(async () => {
270
+ const key = this.options.account();
271
+ if (!key)
272
+ throw new Error("Sign in first");
273
+ const { instances } = await this.list();
274
+ if (!isRunning(instances.find((instance) => instance.spaceId === spaceId)))
275
+ throw new Error("This device does not serve that Space");
276
+ const previous = this.#screen.sharedWith;
277
+ if (previous && previous !== spaceId)
278
+ await this.#setScreen(key, previous, NO_SCREEN);
279
+ await this.#setScreen(key, spaceId, SHARED_SCREEN);
280
+ await this.#publish();
281
+ return this.#screen;
282
+ });
283
+ }
284
+ stopSharing() {
285
+ return this.#serialScreen(async () => {
286
+ const key = this.options.account();
287
+ if (!key)
288
+ throw new Error("Sign in first");
289
+ await this.list();
290
+ if (this.#screen.sharedWith)
291
+ await this.#setScreen(key, this.#screen.sharedWith, NO_SCREEN);
292
+ await this.#publish();
293
+ return this.#screen;
294
+ });
295
+ }
296
+ stopOwnSharing() {
297
+ return this.#serialScreen(async () => {
298
+ const key = this.options.account();
299
+ if (!key)
300
+ return;
301
+ await this.list();
302
+ const results = await Promise.allSettled([...this.#shared].map((spaceId) => this.#setScreen(key, spaceId, NO_SCREEN)));
303
+ for (const result of results)
304
+ if (result.status === "rejected")
305
+ process.stderr.write(`Could not stop sharing the screen: ${String(result.reason)}\n`);
306
+ });
307
+ }
308
+ async keepAwake(enabled) {
309
+ if (enabled === undefined)
310
+ return (await readRuntimePreferences()).keepAwake;
311
+ await writeRuntimePreferences({ keepAwake: enabled });
312
+ const key = this.options.account();
313
+ if (key) {
314
+ const { instances } = await this.list();
315
+ await Promise.allSettled(instances.filter(isRunning).map((instance) => controlRuntimeInstance(runtimeInstanceDirectory(key, instance.spaceId), "keepAwake")));
316
+ }
317
+ return enabled;
318
+ }
319
+ async #setScreen(key, spaceId, spec) {
320
+ await controlRuntimeInstance(runtimeInstanceDirectory(key, spaceId), "display", { spec }, DISPLAY_CONTROL_MS);
181
321
  }
182
322
  restore() {
183
323
  this.#restoring = this.#restoring.then(async () => {
@@ -211,6 +351,11 @@ export class DeviceRuntimeHost {
211
351
  this.#published = serialized;
212
352
  this.emit("runtime.changed", runtime);
213
353
  }
354
+ const screen = JSON.stringify(this.#screen);
355
+ if (screen !== this.#publishedScreen) {
356
+ this.#publishedScreen = screen;
357
+ this.emit("display.changed", this.#screen);
358
+ }
214
359
  return runtime;
215
360
  }
216
361
  #subscribe(directory, pid) {
@@ -1,12 +1,17 @@
1
1
  import { createInterface } from "node:readline";
2
2
  import { fileURLToPath } from "node:url";
3
- import { HOST_BRIDGE_ERROR, HOST_BRIDGE_METHODS, HOST_SERVICE_VERSION, hostBridgeRequestSchema, } from "@neta-art/cohub/host-bridge";
3
+ import { HOST_BRIDGE_ERROR, HOST_BRIDGE_METHODS, HOST_SERVICE_VERSION, HOST_SERVICE_WORKSPACE_ENDPOINT, HostBridgeErrorClass, hostBridgeRequestSchema, } from "@neta-art/cohub/host-bridge";
4
+ import { findLocalWorkspace } from "../runtime/local-workspace.js";
4
5
  import { currentIdentityKey } from "../space.js";
5
6
  import { HostAuth } from "./auth.js";
6
7
  import { loginShellEnv } from "./login-env.js";
7
8
  import { DeviceRuntimeHost } from "./runtime.js";
8
- const CAPABILITIES = ["auth.token", "auth.signIn", "auth.session", "runtime"];
9
- const MAX_LINE = 1024 * 1024;
9
+ import { callLocalWorkspace } from "./workspaces.js";
10
+ const SCREEN_PLATFORMS = ["darwin", "win32"];
11
+ const CAPABILITIES = ["auth.token", "auth.signIn", "auth.session", "runtime", "runtime.keepAwake", "workspace", ...(SCREEN_PLATFORMS.includes(process.platform) ? ["display"] : [])];
12
+ const SPACE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13
+ // Shells re-encode requests, and may escape what the page sized as one byte into six.
14
+ const MAX_LINE = 8 * 1024 * 1024;
10
15
  const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
11
16
  export async function serveHost(entry = fileURLToPath(new URL("../../bin/cohub.js", import.meta.url))) {
12
17
  const emit = (name, payload) => write({ type: "event", name, ...(payload === undefined ? {} : { payload }) });
@@ -17,6 +22,7 @@ export async function serveHost(entry = fileURLToPath(new URL("../../bin/cohub.j
17
22
  account: currentIdentityKey,
18
23
  });
19
24
  const auth = new HostAuth(emit, () => {
25
+ runtime.accountChanged();
20
26
  runtime.changed();
21
27
  void runtime.restore();
22
28
  });
@@ -25,13 +31,31 @@ export async function serveHost(entry = fileURLToPath(new URL("../../bin/cohub.j
25
31
  "auth.getSessionVersion": () => auth.sessionVersion(),
26
32
  "auth.getSession": () => auth.session(),
27
33
  "auth.signIn": (params) => auth.signIn(typeof params.redirectPath === "string" ? params.redirectPath : undefined),
28
- "auth.signOut": () => auth.signOut(),
34
+ "auth.signOut": async () => {
35
+ await runtime.stopAccount().catch((error) => process.stderr.write(`Could not stop Runtimes before signing out: ${error instanceof Error ? error.message : String(error)}\n`));
36
+ return auth.signOut();
37
+ },
29
38
  "runtime.list": () => runtime.list(),
30
39
  "runtime.browse": (params) => runtime.browse(typeof params.path === "string" ? params.path : undefined),
31
40
  "runtime.start": (params) => runtime.connect(String(params.spaceId), String(params.root)),
32
- "runtime.stop": (params) => runtime.disconnect(String(params.spaceId)),
41
+ "runtime.stop": (params) => runtime.disconnect(String(params.spaceId), params.force === true),
42
+ "runtime.keepAwake": (params) => runtime.keepAwake(typeof params.enabled === "boolean" ? params.enabled : undefined),
43
+ ...(CAPABILITIES.includes("display") ? {
44
+ "display.status": () => runtime.displayStatus(),
45
+ "display.share": (params) => runtime.share(String(params.spaceId)),
46
+ "display.stop": () => runtime.stopSharing(),
47
+ } : {}),
48
+ "workspace.call": (params) => callLocalWorkspace(String(params.spaceId), String(params.method), params.params),
49
+ };
50
+ // Asked by the shell itself to proxy file URLs; absent from hello, so a page can never reach it.
51
+ const shellHandlers = {
52
+ [HOST_SERVICE_WORKSPACE_ENDPOINT]: (params) => {
53
+ const spaceId = String(params.spaceId ?? "");
54
+ if (!SPACE_ID.test(spaceId))
55
+ throw new Error("A Space id is required");
56
+ return findLocalWorkspace(spaceId);
57
+ },
33
58
  };
34
- const methods = Object.keys(handlers);
35
59
  const answer = async (line) => {
36
60
  let raw;
37
61
  try {
@@ -45,22 +69,35 @@ export async function serveHost(entry = fileURLToPath(new URL("../../bin/cohub.j
45
69
  return;
46
70
  const { id, method } = request.data;
47
71
  const fail = (code, message) => write({ type: "response", id, error: { code, message: message.slice(0, 2_000) || "Host call failed" } });
48
- if (!(method in handlers))
49
- return fail(HOST_BRIDGE_ERROR.unsupported, `Unsupported method: ${method}`);
50
72
  const name = method;
73
+ const shellHandler = Object.hasOwn(shellHandlers, method) ? shellHandlers[method] : undefined;
74
+ if (shellHandler) {
75
+ try {
76
+ write({ type: "response", id, result: await shellHandler((request.data.params ?? {})) ?? null });
77
+ }
78
+ catch (error) {
79
+ fail(HOST_BRIDGE_ERROR.failed, error instanceof Error ? error.message : String(error));
80
+ }
81
+ return;
82
+ }
83
+ const handler = handlers[name];
84
+ if (!handler)
85
+ return fail(HOST_BRIDGE_ERROR.unsupported, `Unsupported method: ${method}`);
51
86
  const shape = HOST_BRIDGE_METHODS[name];
52
87
  const params = shape.params.safeParse(request.data.params);
53
88
  if (!params.success)
54
89
  return fail(HOST_BRIDGE_ERROR.failed, `Invalid params for ${method}`);
55
90
  try {
56
- const result = await handlers[name]((params.data ?? {}));
91
+ const result = await handler((params.data ?? {}));
57
92
  write({ type: "response", id, result: shape.result.parse(result) });
58
93
  }
59
94
  catch (error) {
60
- fail(HOST_BRIDGE_ERROR.failed, error instanceof Error ? error.message : String(error));
95
+ const denied = ["EPERM", "EACCES"].includes(error.code ?? "");
96
+ const code = error instanceof HostBridgeErrorClass ? error.code : denied ? HOST_BRIDGE_ERROR.denied : HOST_BRIDGE_ERROR.failed;
97
+ fail(code, error instanceof Error ? error.message : String(error));
61
98
  }
62
99
  };
63
- const hello = { type: "hello", version: HOST_SERVICE_VERSION, capabilities: [...CAPABILITIES], methods };
100
+ const hello = { type: "hello", version: HOST_SERVICE_VERSION, capabilities: [...CAPABILITIES], methods: Object.keys(handlers) };
64
101
  write(hello);
65
102
  auth.watch();
66
103
  runtime.watch();
@@ -69,5 +106,6 @@ export async function serveHost(entry = fileURLToPath(new URL("../../bin/cohub.j
69
106
  void answer(line); });
70
107
  await new Promise((resolve) => input.once("close", resolve));
71
108
  auth.close();
109
+ await runtime.stopOwnSharing();
72
110
  runtime.close();
73
111
  }
@@ -0,0 +1,2 @@
1
+ import { type HostWorkspaceCallResult } from "@neta-art/cohub/host-bridge";
2
+ export declare function callLocalWorkspace(spaceId: string, method: string, params: unknown): Promise<HostWorkspaceCallResult>;
@@ -0,0 +1,18 @@
1
+ import { HOST_BRIDGE_ERROR, HostBridgeErrorClass } from "@neta-art/cohub/host-bridge";
2
+ import { LocalWorkspaceRpcError, LocalWorkspaceUnavailableError } from "@neta-art/cohub";
3
+ import { connectLocalWorkspace, findLocalWorkspace } from "../runtime/local-workspace.js";
4
+ export async function callLocalWorkspace(spaceId, method, params) {
5
+ const endpoint = await findLocalWorkspace(spaceId);
6
+ if (endpoint) {
7
+ try {
8
+ return { result: await connectLocalWorkspace(endpoint).call(method, params ?? {}) };
9
+ }
10
+ catch (error) {
11
+ if (error instanceof LocalWorkspaceRpcError)
12
+ return { error: { code: error.rpcErrorCode, message: error.message.slice(0, 4_000) } };
13
+ if (!(error instanceof LocalWorkspaceUnavailableError))
14
+ throw error;
15
+ }
16
+ }
17
+ throw new HostBridgeErrorClass(HOST_BRIDGE_ERROR.unavailable, "This device does not serve that Space");
18
+ }
package/dist/index.js CHANGED
@@ -87,6 +87,7 @@ Environment:
87
87
  COHUB_BASE_URL Override the API base URL
88
88
  COHUB_WS_URL Override the realtime WebSocket URL
89
89
  COHUB_WEB_URL Override the web URL used in links
90
+ COHUB_NO_DIRECT=1 Send files and screens through the API even when this machine serves the Space
90
91
  ENV=dev Use the development Cohub environment
91
92
  HTTPS_PROXY Honored for API and uploads (also HTTP_PROXY, NO_PROXY)
92
93
  Runtime logs ~/.local/state/cohub/runtime/<space-id>/diagnostics
package/dist/output.d.ts CHANGED
@@ -36,6 +36,7 @@ export declare function jsonRequested(opts?: {
36
36
  json?: boolean;
37
37
  }): boolean;
38
38
  export declare function ok(msg: string): void;
39
+ export declare function warn(msg: string): void;
39
40
  export declare function error(msg: string, detail?: string): never;
40
41
  export declare function handleHttp(e: unknown): never;
41
42
  export declare function spinner(): {
package/dist/output.js CHANGED
@@ -95,6 +95,9 @@ export function jsonRequested(opts) {
95
95
  export function ok(msg) {
96
96
  console.log(`\n ✓ ${msg}\n`);
97
97
  }
98
+ export function warn(msg) {
99
+ console.log(`\n ⚠ ${msg}\n`);
100
+ }
98
101
  export function error(msg, detail) {
99
102
  process.stderr.write(`\n ✗ ${msg}\n`);
100
103
  if (detail)
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Puts this Runtime's own `cohub` last on PATH, so what it runs can always call the CLI while a
3
+ * `cohub` already on PATH (a global install that updates itself) still comes first.
4
+ */
5
+ export declare function appendCliToPath(env?: NodeJS.ProcessEnv, node?: string, entry?: string): string;
@@ -0,0 +1,27 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, renameSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ const ENTRY = fileURLToPath(new URL("../../bin/cohub.js", import.meta.url));
7
+ /**
8
+ * Puts this Runtime's own `cohub` last on PATH, so what it runs can always call the CLI while a
9
+ * `cohub` already on PATH (a global install that updates itself) still comes first.
10
+ */
11
+ export function appendCliToPath(env = process.env, node = process.execPath, entry = ENTRY) {
12
+ const dir = join(homedir(), ".cache", "cohub", "cli", createHash("sha256").update(`${node}\0${entry}`).digest("hex").slice(0, 12));
13
+ const windows = process.platform === "win32";
14
+ const script = windows
15
+ ? `@"${node}" "${entry}" %*\r\n`
16
+ : `#!/bin/sh\nexec ${quote(node)} ${quote(entry)} "$@"\n`;
17
+ mkdirSync(dir, { recursive: true });
18
+ const file = join(dir, windows ? "cohub.cmd" : "cohub");
19
+ const temporary = `${file}.${process.pid}`;
20
+ writeFileSync(temporary, script, { mode: 0o755 });
21
+ renameSync(temporary, file);
22
+ const path = env.PATH?.split(delimiter).filter(Boolean) ?? [];
23
+ if (!path.includes(dir))
24
+ env.PATH = [...path, dir].join(delimiter);
25
+ return dir;
26
+ }
27
+ const quote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
@@ -1,6 +1,20 @@
1
- import { type RuntimeNativeStop, type RuntimeCapabilities, type NativeRuntimeEvent } from "@neta-art/cohub";
2
- import { type Executor } from "./native/execution.js";
3
- import { type RuntimeDiagnostics } from "./diagnostics.js";
1
+ import { type RuntimeNativeStop, type RuntimeApprovalDecision, type RuntimeCapabilities, type LocalHarness, type NativeRuntimeEvent } from "@neta-art/cohub";
2
+ import { type Executor, type HarnessResult } from "./native/execution.js";
3
+ import { type RuntimeDiagnosticContext, type RuntimeDiagnostics } from "./diagnostics.js";
4
+ export type Execution = {
5
+ controller: AbortController;
6
+ promise: Promise<void>;
7
+ sessionId: string;
8
+ turnId: string;
9
+ harness: LocalHarness;
10
+ requestId?: string | null;
11
+ traceContext?: RuntimeDiagnosticContext["traceContext"];
12
+ result?: HarnessResult;
13
+ /** Started on a transport that has since closed; it keeps running and replays on a later one. */
14
+ detached?: boolean;
15
+ /** Only replays a saved result for its connection; it does no local work and ends with that connection. */
16
+ recovery?: boolean;
17
+ };
4
18
  export type RuntimeConnectionOptions = {
5
19
  spaceId: string;
6
20
  cwd: string;
@@ -17,8 +31,12 @@ export type RuntimeConnectionOptions = {
17
31
  runtimeId?: string;
18
32
  diagnostics?: RuntimeDiagnostics;
19
33
  leaseConflictTimeoutMs?: number;
20
- onNativeChannel?: (send: (event: NativeRuntimeEvent) => Promise<unknown>) => void;
34
+ onNativeChannel?: (send: (event: NativeRuntimeEvent) => Promise<unknown>, features: {
35
+ approvals: boolean;
36
+ }) => void;
21
37
  /** The web asked to stop a Turn; one running in a native client is stopped there. */
22
38
  onNativeStop?: (stop: RuntimeNativeStop) => void;
39
+ onApprovalDecision?: (decision: RuntimeApprovalDecision) => void;
40
+ executions?: Map<string, Execution>;
23
41
  };
24
42
  export declare function serveRuntime(options: RuntimeConnectionOptions): Promise<void>;
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { setTimeout as delay } from "node:timers/promises";
3
3
  import { isDeepStrictEqual } from "node:util";
4
- import { RUNTIME_MAX_FRAME_BYTES, RUNTIME_PROTOCOL_VERSION, runtimeCapabilitiesSchema, runtimeCommandSchema, runtimeHelloCapabilities, runtimeReadySchema, runtimeNativeStopSchema, } from "@neta-art/cohub";
4
+ import { RUNTIME_MAX_FRAME_BYTES, RUNTIME_PROTOCOL_VERSION, runtimeCapabilitiesSchema, runtimeCommandSchema, runtimeHelloCapabilities, runtimeReadySchema, runtimeNativeStopSchema, runtimeApprovalDecisionSchema, } from "@neta-art/cohub";
5
5
  import { describeError } from "../network-error.js";
6
6
  import { executeTurn } from "./native/execution.js";
7
7
  import { ContextRequiredError } from "./native/results.js";
@@ -15,7 +15,7 @@ export async function serveRuntime(options) {
15
15
  let conflictSince = null;
16
16
  // Executions outlive a single transport so a dropped socket reconnects immediately
17
17
  // instead of waiting for in-flight turns to finish.
18
- const executions = new Map();
18
+ const executions = options.executions ?? new Map();
19
19
  const seen = new Set();
20
20
  const announce = { current: null };
21
21
  const catalog = { current: options.capabilities, publish: null };
@@ -448,7 +448,7 @@ async function connect(options) {
448
448
  }, { connectionId });
449
449
  nativeChannelReady = true;
450
450
  capabilitiesFrame = frame.features?.includes("capabilities") === true;
451
- options.onNativeChannel?.(sendNative);
451
+ options.onNativeChannel?.(sendNative, { approvals: frame.features?.includes("approvals") === true });
452
452
  options.onReady();
453
453
  options.announce.current = announceHere;
454
454
  options.catalog.publish = publishCatalog;
@@ -479,6 +479,16 @@ async function connect(options) {
479
479
  options.onNativeStop?.(stop.data);
480
480
  return;
481
481
  }
482
+ if (raw.type === "runtime.approval.decision") {
483
+ const decision = runtimeApprovalDecisionSchema.safeParse(raw);
484
+ if (!decision.success) {
485
+ log("warn", "runtime.protocol.invalid_approval_decision", { error: decision.error.message }, { connectionId });
486
+ return;
487
+ }
488
+ if (decision.data.spaceId === options.spaceId)
489
+ options.onApprovalDecision?.(decision.data);
490
+ return;
491
+ }
482
492
  if (raw.type === "runtime.native.result") {
483
493
  const result = raw;
484
494
  const pending = result.requestId ? nativePending.get(result.requestId) : null;
@@ -0,0 +1,31 @@
1
+ import { type ApprovalMode, type RuntimeTurnInput } from "@neta-art/cohub";
2
+ import { type JsonRecord } from "../json-rpc.js";
3
+ import type { ApprovalBroker, ApprovalRequest } from "../native/approvals.js";
4
+ /** Cards answer Claude Code's permission prompts, so without `--permission-prompt-tool stdio` no mode is offered. */
5
+ export declare function claudeApprovalModes(help: string): ApprovalMode[];
6
+ /** The platform's read-only access always wins; `null` keeps `acceptEdits`. */
7
+ export declare function claudeApprovalMode(input: RuntimeTurnInput, modes: readonly ApprovalMode[]): ApprovalMode | null;
8
+ export declare const claudePermissionMode: (mode: Exclude<ApprovalMode, "read_only"> | null) => string | null;
9
+ /**
10
+ * A `can_use_tool` request shown on a card, and what Allow for this chat remembers; other tools are denied.
11
+ * Claude Code reports no working directory: its shell keeps the last `cd`, so none is guessed.
12
+ */
13
+ export declare function claudeApprovalRequest(request: JsonRecord): {
14
+ card: ApprovalRequest;
15
+ grants: string[];
16
+ } | null;
17
+ /**
18
+ * Allow for this chat, kept by the Runtime per Cohub Session: each Turn starts a new Claude Code
19
+ * process, and Claude's own settings are never written. Bounded and forgotten after a day unused.
20
+ */
21
+ export declare class SessionGrants {
22
+ private readonly now;
23
+ private readonly sessions;
24
+ constructor(now?: () => number);
25
+ covers(sessionId: string, keys: string[]): boolean;
26
+ add(sessionId: string, keys: string[]): void;
27
+ private live;
28
+ private touch;
29
+ }
30
+ /** The `can_use_tool` answer: a card for Bash and file edits, a denial for anything else or without a card. */
31
+ export declare function answerClaudeApproval(request: JsonRecord, input: RuntimeTurnInput, approvals: ApprovalBroker, grants: SessionGrants, signal: AbortSignal): Promise<JsonRecord>;