@neta-art/cohub-cli 10.17.0 → 10.18.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.
- package/README.md +6 -0
- package/dist/board-export-resources.d.ts +2 -0
- package/dist/board-export-resources.js +1 -0
- package/dist/board-export.d.ts +4 -1
- package/dist/board-export.js +109 -23
- package/dist/board-gpu/index.d.ts +32 -0
- package/dist/board-gpu/index.js +188 -0
- package/dist/board-gpu/page.js +70178 -0
- package/dist/board-gpu/protocol.d.ts +37 -0
- package/dist/board-gpu/protocol.js +1 -0
- package/dist/board-kernel/{getPo2TextureFromSource.js → FilterPipe.js} +251 -1
- package/dist/board-kernel/browserAll.js +1 -1
- package/dist/board-kernel/init.js +1 -251
- package/dist/board-kernel/webworkerAll.js +1 -1
- package/dist/board-kernel.d.ts +3 -3
- package/dist/board-kernel.js +6642 -1466
- package/dist/board-simulate.d.ts +4 -0
- package/dist/board-simulate.js +34 -4
- package/dist/client.d.ts +1 -0
- package/dist/client.js +4 -1
- package/dist/commands/apps.js +25 -3
- package/dist/commands/boards/examples.js +21 -5
- package/dist/commands/boards.js +10 -2
- package/dist/commands/space-displays.js +301 -82
- package/dist/commands/spaces.js +11 -2
- package/dist/host/runtime.d.ts +12 -2
- package/dist/host/runtime.js +155 -10
- package/dist/host/serve.js +49 -11
- package/dist/host/workspaces.d.ts +2 -0
- package/dist/host/workspaces.js +18 -0
- package/dist/index.js +1 -0
- package/dist/runtime/cli-path.d.ts +5 -0
- package/dist/runtime/cli-path.js +27 -0
- package/dist/runtime/connection.d.ts +22 -4
- package/dist/runtime/connection.js +13 -3
- package/dist/runtime/harnesses/claude-approval.d.ts +31 -0
- package/dist/runtime/harnesses/claude-approval.js +119 -0
- package/dist/runtime/harnesses/claude.js +42 -3
- package/dist/runtime/harnesses/codex-approval.d.ts +25 -0
- package/dist/runtime/harnesses/codex-approval.js +69 -0
- package/dist/runtime/harnesses/codex.js +36 -5
- package/dist/runtime/harnesses/index.js +12 -3
- package/dist/runtime/harnesses/stream-json.d.ts +16 -2
- package/dist/runtime/harnesses/stream-json.js +26 -6
- package/dist/runtime/harnesses/types.d.ts +3 -1
- package/dist/runtime/instance.d.ts +1 -0
- package/dist/runtime/instance.js +1 -0
- package/dist/runtime/launch.js +2 -4
- package/dist/runtime/local-workspace.d.ts +15 -0
- package/dist/runtime/local-workspace.js +52 -0
- package/dist/runtime/model-catalog.js +7 -4
- package/dist/runtime/native/approvals.d.ts +18 -0
- package/dist/runtime/native/approvals.js +54 -0
- package/dist/runtime/native/codex-link.d.ts +7 -0
- package/dist/runtime/native/codex-link.js +40 -5
- package/dist/runtime/native/daemon.d.ts +5 -1
- package/dist/runtime/native/daemon.js +6 -1
- package/dist/runtime/native/execution.d.ts +2 -0
- package/dist/runtime/preferences.d.ts +7 -0
- package/dist/runtime/preferences.js +22 -0
- package/dist/runtime/presentation.d.ts +3 -0
- package/dist/runtime/presentation.js +2 -1
- package/dist/runtime/supervisor.js +92 -9
- package/dist/space-files/transfer.js +3 -2
- package/dist/space-files/upload.d.ts +5 -2
- package/dist/space-files/upload.js +41 -1
- package/package.json +3 -3
package/dist/host/runtime.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
|
171
|
-
|
|
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
|
-
|
|
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) {
|
package/dist/host/serve.js
CHANGED
|
@@ -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
|
-
|
|
9
|
-
const
|
|
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": () =>
|
|
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
|
|
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
|
-
|
|
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,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
|
|
@@ -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
|
|
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>;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { APPROVAL_DECISIONS, APPROVAL_MODES } from "@neta-art/cohub";
|
|
2
|
+
import { record } from "../json-rpc.js";
|
|
3
|
+
import { text } from "./process.js";
|
|
4
|
+
const PERMISSION_MODES = { inherit: null, auto: "auto", full_access: "bypassPermissions", read_only: "plan" };
|
|
5
|
+
const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
|
|
6
|
+
/** Cards answer Claude Code's permission prompts, so without `--permission-prompt-tool stdio` no mode is offered. */
|
|
7
|
+
export function claudeApprovalModes(help) {
|
|
8
|
+
const start = help.search(/--permission-mode\b/);
|
|
9
|
+
const option = start < 0 ? "" : help.slice(start).split(/\n\s*-/)[0] ?? "";
|
|
10
|
+
const choices = new Set([...(/\(choices:([^)]*)\)/.exec(option)?.[1] ?? "").matchAll(/"([^"]+)"/g)].map((match) => match[1]));
|
|
11
|
+
return APPROVAL_MODES.filter((mode) => mode === "inherit" || choices.has(PERMISSION_MODES[mode] ?? ""));
|
|
12
|
+
}
|
|
13
|
+
/** The platform's read-only access always wins; `null` keeps `acceptEdits`. */
|
|
14
|
+
export function claudeApprovalMode(input, modes) {
|
|
15
|
+
if (input.accessMode === "read_only" && input.approvalMode && input.approvalMode !== "read_only") {
|
|
16
|
+
throw new Error("The approval mode conflicts with read-only access");
|
|
17
|
+
}
|
|
18
|
+
if (input.accessMode === "read_only")
|
|
19
|
+
return "read_only";
|
|
20
|
+
if (!input.approvalMode || modes.includes(input.approvalMode))
|
|
21
|
+
return input.approvalMode ?? null;
|
|
22
|
+
throw new Error(`This Claude Code does not support the ${input.approvalMode} approval mode; update Claude Code and restart the Runtime`);
|
|
23
|
+
}
|
|
24
|
+
export const claudePermissionMode = (mode) => mode ? PERMISSION_MODES[mode] : "acceptEdits";
|
|
25
|
+
const clip = (value, max) => typeof value === "string" && value ? value.slice(0, max) : undefined;
|
|
26
|
+
/** What a card cannot show in full is not shown at all: a person approves exactly what runs. */
|
|
27
|
+
const whole = (value, max) => typeof value === "string" && value.length > max ? null : text(value) || undefined;
|
|
28
|
+
/**
|
|
29
|
+
* A `can_use_tool` request shown on a card, and what Allow for this chat remembers; other tools are denied.
|
|
30
|
+
* Claude Code reports no working directory: its shell keeps the last `cd`, so none is guessed.
|
|
31
|
+
*/
|
|
32
|
+
export function claudeApprovalRequest(request) {
|
|
33
|
+
const tool = text(request.tool_name), input = record(request.input);
|
|
34
|
+
const reason = clip(tool === "Bash" ? text(input.description) || request.decision_reason : request.decision_reason, 4096);
|
|
35
|
+
const card = (kind, grants, fields) => ({
|
|
36
|
+
grants,
|
|
37
|
+
card: { kind, decisions: APPROVAL_DECISIONS.filter((decision) => decision !== "accept_for_session" || grants.length > 0), ...fields, ...(reason ? { reason } : {}) },
|
|
38
|
+
});
|
|
39
|
+
if (tool === "Bash") {
|
|
40
|
+
const command = whole(input.command, 16_384);
|
|
41
|
+
return command === null ? null : card("command", command ? [`command:${command}`] : [], command ? { command } : {});
|
|
42
|
+
}
|
|
43
|
+
if (!EDIT_TOOLS.has(tool))
|
|
44
|
+
return null;
|
|
45
|
+
const path = whole(input.file_path ?? input.notebook_path, 4096);
|
|
46
|
+
return path === null ? null : card("file_change", path ? [`file:${path}`] : [], path ? { paths: [path] } : {});
|
|
47
|
+
}
|
|
48
|
+
const MAX_SESSIONS = 200;
|
|
49
|
+
const MAX_GRANTS = 200;
|
|
50
|
+
const GRANT_IDLE_MS = 24 * 60 * 60_000;
|
|
51
|
+
/**
|
|
52
|
+
* Allow for this chat, kept by the Runtime per Cohub Session: each Turn starts a new Claude Code
|
|
53
|
+
* process, and Claude's own settings are never written. Bounded and forgotten after a day unused.
|
|
54
|
+
*/
|
|
55
|
+
export class SessionGrants {
|
|
56
|
+
now;
|
|
57
|
+
sessions = new Map();
|
|
58
|
+
constructor(now = Date.now) {
|
|
59
|
+
this.now = now;
|
|
60
|
+
}
|
|
61
|
+
covers(sessionId, keys) {
|
|
62
|
+
const entry = this.live(sessionId);
|
|
63
|
+
if (!entry || !keys.length || !keys.every((key) => entry.keys.has(key)))
|
|
64
|
+
return false;
|
|
65
|
+
this.touch(sessionId, entry);
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
add(sessionId, keys) {
|
|
69
|
+
if (!keys.length)
|
|
70
|
+
return;
|
|
71
|
+
const entry = this.live(sessionId) ?? { keys: new Set(), usedAt: 0 };
|
|
72
|
+
for (const key of keys) {
|
|
73
|
+
entry.keys.delete(key);
|
|
74
|
+
entry.keys.add(key);
|
|
75
|
+
}
|
|
76
|
+
for (const key of entry.keys) {
|
|
77
|
+
if (entry.keys.size <= MAX_GRANTS)
|
|
78
|
+
break;
|
|
79
|
+
entry.keys.delete(key);
|
|
80
|
+
}
|
|
81
|
+
this.touch(sessionId, entry);
|
|
82
|
+
for (const oldest of this.sessions.keys()) {
|
|
83
|
+
if (this.sessions.size <= MAX_SESSIONS)
|
|
84
|
+
break;
|
|
85
|
+
this.sessions.delete(oldest);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
live(sessionId) {
|
|
89
|
+
const entry = this.sessions.get(sessionId);
|
|
90
|
+
if (entry && this.now() - entry.usedAt > GRANT_IDLE_MS)
|
|
91
|
+
this.sessions.delete(sessionId);
|
|
92
|
+
return this.sessions.get(sessionId);
|
|
93
|
+
}
|
|
94
|
+
touch(sessionId, entry) {
|
|
95
|
+
entry.usedAt = this.now();
|
|
96
|
+
this.sessions.delete(sessionId);
|
|
97
|
+
this.sessions.set(sessionId, entry);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const DENIED = "Approval requires an interactive local client";
|
|
101
|
+
/** The `can_use_tool` answer: a card for Bash and file edits, a denial for anything else or without a card. */
|
|
102
|
+
export async function answerClaudeApproval(request, input, approvals, grants, signal) {
|
|
103
|
+
const allow = { behavior: "allow", updatedInput: record(request.input) };
|
|
104
|
+
const asked = claudeApprovalRequest(request);
|
|
105
|
+
// A platform read-only Turn is never widened, whoever approves.
|
|
106
|
+
if (!asked || input.accessMode === "read_only" || !approvals.available || signal.aborted)
|
|
107
|
+
return { behavior: "deny", message: DENIED };
|
|
108
|
+
if (grants.covers(input.sessionId, asked.grants))
|
|
109
|
+
return allow;
|
|
110
|
+
const decision = await approvals.request(input.sessionId, input.turnId, asked.card, signal);
|
|
111
|
+
// A Turn that ended meanwhile grants nothing, not even to later Turns.
|
|
112
|
+
if (signal.aborted)
|
|
113
|
+
return { behavior: "deny", message: DENIED };
|
|
114
|
+
if (decision === "decline")
|
|
115
|
+
return { behavior: "deny", message: "The user declined this tool use" };
|
|
116
|
+
if (decision === "accept_for_session")
|
|
117
|
+
grants.add(input.sessionId, asked.grants);
|
|
118
|
+
return allow;
|
|
119
|
+
}
|