@neta-art/cohub-cli 10.17.1 → 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 +6624 -1462
- 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 +2 -2
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
/** How long a card waits for a person; unanswered, the request is declined. */
|
|
3
|
+
export const APPROVAL_TIMEOUT_MS = 30 * 60_000;
|
|
4
|
+
/** Asks the web for a decision over the control connection; without one, it declines. */
|
|
5
|
+
export class ApprovalBroker {
|
|
6
|
+
timeoutMs;
|
|
7
|
+
send = null;
|
|
8
|
+
pending = new Map();
|
|
9
|
+
constructor(timeoutMs = APPROVAL_TIMEOUT_MS) {
|
|
10
|
+
this.timeoutMs = timeoutMs;
|
|
11
|
+
}
|
|
12
|
+
/** `null` when the Gateway cannot relay decisions; open cards are then declined. */
|
|
13
|
+
connect(send) {
|
|
14
|
+
this.send = send;
|
|
15
|
+
if (!send)
|
|
16
|
+
for (const entry of this.pending.values())
|
|
17
|
+
entry.resolve("decline");
|
|
18
|
+
}
|
|
19
|
+
get available() { return this.send !== null; }
|
|
20
|
+
async request(sessionId, turnId, request, signal) {
|
|
21
|
+
const send = this.send;
|
|
22
|
+
if (!send || signal.aborted)
|
|
23
|
+
return "decline";
|
|
24
|
+
const id = randomUUID();
|
|
25
|
+
const now = Date.now();
|
|
26
|
+
let timer;
|
|
27
|
+
let onAbort = () => { };
|
|
28
|
+
const decided = new Promise((resolve) => {
|
|
29
|
+
this.pending.set(id, { sessionId, turnId, resolve });
|
|
30
|
+
timer = setTimeout(() => resolve("decline"), this.timeoutMs);
|
|
31
|
+
onAbort = () => resolve("decline");
|
|
32
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
33
|
+
});
|
|
34
|
+
try {
|
|
35
|
+
await send({ type: "approval", sessionId, turnId, approval: { ...request, id, requestedAt: new Date(now).toISOString(), expiresAt: new Date(now + this.timeoutMs).toISOString() } });
|
|
36
|
+
return await decided;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// A server that cannot show the card cannot answer it either.
|
|
40
|
+
return "decline";
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
signal.removeEventListener("abort", onAbort);
|
|
45
|
+
this.pending.delete(id);
|
|
46
|
+
void this.send?.({ type: "approval.closed", sessionId, turnId, approvalId: id }).catch(() => undefined);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
decide(input) {
|
|
50
|
+
const entry = this.pending.get(input.approvalId);
|
|
51
|
+
if (entry && entry.sessionId === input.sessionId && entry.turnId === input.turnId)
|
|
52
|
+
entry.resolve(input.decision);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -15,6 +15,7 @@ export type CodexEvent = {
|
|
|
15
15
|
export interface CodexChannel {
|
|
16
16
|
request(method: string, params?: JsonRecord, timeoutMs?: number): Promise<JsonRecord>;
|
|
17
17
|
refuse(id: string | number, message: string): void;
|
|
18
|
+
respond(id: string | number, result: JsonRecord): void;
|
|
18
19
|
onEvent(listener: (event: CodexEvent & {
|
|
19
20
|
id?: string | number;
|
|
20
21
|
}) => void): () => void;
|
|
@@ -22,10 +23,14 @@ export interface CodexChannel {
|
|
|
22
23
|
close(): Promise<void>;
|
|
23
24
|
readonly shared: boolean;
|
|
24
25
|
readonly closed: boolean;
|
|
26
|
+
/** The app-server's own version, which may differ from the binary on PATH. */
|
|
27
|
+
readonly version: Version | null;
|
|
25
28
|
}
|
|
26
29
|
/** Codex's shared server listens on an AF_UNIX socket, which Node cannot reach on Windows. */
|
|
27
30
|
export declare const sharedServerAvailable: boolean;
|
|
28
31
|
export declare const supportsSharedServer: (version: Version | null) => boolean;
|
|
32
|
+
/** Version of a shared app-server already running, which Cohub's Turns would use instead of the binary. */
|
|
33
|
+
export declare function runningSharedVersion(): Promise<Version | null>;
|
|
29
34
|
/** A private app-server over stdio, used when no shared one is available; it lives for one Turn. */
|
|
30
35
|
export declare function openPrivateServer(rpc: JsonRpcProcess): Promise<CodexChannel>;
|
|
31
36
|
/** The Runtime's connection to the shared app-server. */
|
|
@@ -49,5 +54,7 @@ export declare class CodexShared {
|
|
|
49
54
|
interrupt(threadId: string, turnId: string): Promise<boolean>;
|
|
50
55
|
close(): Promise<void>;
|
|
51
56
|
}
|
|
57
|
+
/** `userAgent` starts with `<client name>/<server version>`. */
|
|
58
|
+
export declare function userAgentVersion(userAgent: unknown): Version | null;
|
|
52
59
|
/** Resume a thread for a Cohub Turn, waiting out an unload in progress. */
|
|
53
60
|
export declare function resumeThread(channel: CodexChannel, params: JsonRecord): Promise<JsonRecord>;
|
|
@@ -8,6 +8,8 @@ import { atLeast, harnessVersion } from "./version.js";
|
|
|
8
8
|
/** First Codex release whose terminal client attaches to a shared app-server by default. */
|
|
9
9
|
export const CODEX_SHARED_MIN_VERSION = [0, 156, 0];
|
|
10
10
|
const REQUEST_TIMEOUT_MS = 60_000;
|
|
11
|
+
/** An optional probe of a running shared server must not hold up Runtime startup. */
|
|
12
|
+
const PROBE_TIMEOUT_MS = 3_000;
|
|
11
13
|
const JOIN_ATTEMPTS = 20;
|
|
12
14
|
const JOIN_RETRY_MS = 100;
|
|
13
15
|
const CLOSING_ATTEMPTS = 100;
|
|
@@ -48,6 +50,19 @@ async function ensureSharedServer(binary, cwd) {
|
|
|
48
50
|
return false;
|
|
49
51
|
}
|
|
50
52
|
}
|
|
53
|
+
/** Version of a shared app-server already running, which Cohub's Turns would use instead of the binary. */
|
|
54
|
+
export async function runningSharedVersion() {
|
|
55
|
+
if (!sharedServerAvailable || !existsSync(codexControlSocket()))
|
|
56
|
+
return null;
|
|
57
|
+
try {
|
|
58
|
+
const channel = await openShared(PROBE_TIMEOUT_MS);
|
|
59
|
+
await channel.close();
|
|
60
|
+
return channel.version;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
51
66
|
async function probe() {
|
|
52
67
|
try {
|
|
53
68
|
const channel = await openShared();
|
|
@@ -58,14 +73,20 @@ async function probe() {
|
|
|
58
73
|
return false;
|
|
59
74
|
}
|
|
60
75
|
}
|
|
61
|
-
async function openShared() {
|
|
62
|
-
const socket = new WebSocket(`ws+unix://${codexControlSocket()}
|
|
76
|
+
async function openShared(timeoutMs) {
|
|
77
|
+
const socket = new WebSocket(`ws+unix://${codexControlSocket()}:/`, timeoutMs ? { handshakeTimeout: timeoutMs } : {});
|
|
63
78
|
await new Promise((resolve, reject) => {
|
|
64
79
|
socket.once("open", () => resolve());
|
|
65
80
|
socket.once("error", reject);
|
|
66
81
|
});
|
|
67
82
|
const channel = new SocketChannel(socket);
|
|
68
|
-
|
|
83
|
+
try {
|
|
84
|
+
await initialize(channel, timeoutMs);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
await channel.close();
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
69
90
|
return channel;
|
|
70
91
|
}
|
|
71
92
|
/** A private app-server over stdio, used when no shared one is available; it lives for one Turn. */
|
|
@@ -143,14 +164,21 @@ export class CodexShared {
|
|
|
143
164
|
this.channel = null;
|
|
144
165
|
}
|
|
145
166
|
}
|
|
146
|
-
|
|
147
|
-
|
|
167
|
+
/** `userAgent` starts with `<client name>/<server version>`. */
|
|
168
|
+
export function userAgentVersion(userAgent) {
|
|
169
|
+
const match = typeof userAgent === "string" ? /^[^/\s]+\/(\d+)\.(\d+)\.(\d+)/.exec(userAgent) : null;
|
|
170
|
+
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
|
|
171
|
+
}
|
|
172
|
+
async function initialize(channel, timeoutMs) {
|
|
173
|
+
const result = await channel.request("initialize", { clientInfo: { name: "cohub-runtime", title: "Cohub", version: "1" }, capabilities: { experimentalApi: true } }, timeoutMs);
|
|
174
|
+
channel.version = userAgentVersion(result.userAgent);
|
|
148
175
|
// The notification completes the handshake; responses are not expected.
|
|
149
176
|
channel.notify("initialized");
|
|
150
177
|
}
|
|
151
178
|
class SocketChannel {
|
|
152
179
|
socket;
|
|
153
180
|
shared = true;
|
|
181
|
+
version = null;
|
|
154
182
|
pending = new Map();
|
|
155
183
|
listeners = new Set();
|
|
156
184
|
closeListeners = new Set();
|
|
@@ -215,6 +243,8 @@ class SocketChannel {
|
|
|
215
243
|
notify(method, params = {}) { this.socket.send(JSON.stringify({ method, params })); }
|
|
216
244
|
refuse(id, message) { if (!this.closedError)
|
|
217
245
|
this.socket.send(JSON.stringify({ id, error: { code: -32000, message } })); }
|
|
246
|
+
respond(id, result) { if (!this.closedError)
|
|
247
|
+
this.socket.send(JSON.stringify({ id, result })); }
|
|
218
248
|
onEvent(listener) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
|
|
219
249
|
onClose(listener) {
|
|
220
250
|
if (this.closedError) {
|
|
@@ -230,6 +260,7 @@ class SocketChannel {
|
|
|
230
260
|
class StdioChannel {
|
|
231
261
|
rpc;
|
|
232
262
|
shared = false;
|
|
263
|
+
version = null;
|
|
233
264
|
failed = false;
|
|
234
265
|
constructor(rpc) {
|
|
235
266
|
this.rpc = rpc;
|
|
@@ -242,6 +273,10 @@ class StdioChannel {
|
|
|
242
273
|
this.rpc.write({ id, error: { code: -32000, message } });
|
|
243
274
|
}
|
|
244
275
|
catch { /* The process is gone. */ } }
|
|
276
|
+
respond(id, result) { try {
|
|
277
|
+
this.rpc.write({ id, result });
|
|
278
|
+
}
|
|
279
|
+
catch { /* The process is gone. */ } }
|
|
245
280
|
onClose(listener) { return this.rpc.onFailure(listener); }
|
|
246
281
|
onEvent(listener) {
|
|
247
282
|
return this.rpc.onEvent((event) => {
|
|
@@ -41,6 +41,7 @@ export declare class NativeRuntime {
|
|
|
41
41
|
private readonly watched;
|
|
42
42
|
private readonly active;
|
|
43
43
|
private send;
|
|
44
|
+
private readonly approvals;
|
|
44
45
|
private extension;
|
|
45
46
|
constructor(options: {
|
|
46
47
|
spaceId: string;
|
|
@@ -56,7 +57,10 @@ export declare class NativeRuntime {
|
|
|
56
57
|
});
|
|
57
58
|
private get synced();
|
|
58
59
|
start(signal: AbortSignal): Promise<void>;
|
|
59
|
-
|
|
60
|
+
/** `approvals`: the Gateway relays approval decisions back. */
|
|
61
|
+
connect(send: ((event: NativeRuntimeEvent) => Promise<unknown>) | null, features?: {
|
|
62
|
+
approvals?: boolean;
|
|
63
|
+
}): void;
|
|
60
64
|
stop(sessionId: string, turnId: string): boolean;
|
|
61
65
|
status(): NativeStatus;
|
|
62
66
|
control(action: string, message: Record<string, unknown>): Promise<unknown>;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { serializeDiagnosticError } from "../diagnostics.js";
|
|
2
2
|
import { record } from "../json-rpc.js";
|
|
3
3
|
import { readTranscript } from "./adapters.js";
|
|
4
|
+
import { ApprovalBroker } from "./approvals.js";
|
|
4
5
|
import { CodexShared } from "./codex-link.js";
|
|
5
6
|
import { readNativeConfig } from "./config.js";
|
|
6
7
|
import { DEFAULT_IMPORT_CONCURRENCY, NativeIngest } from "./ingest.js";
|
|
@@ -35,6 +36,7 @@ export class NativeRuntime {
|
|
|
35
36
|
watched = new Map();
|
|
36
37
|
active = new Set();
|
|
37
38
|
send = null;
|
|
39
|
+
approvals = new ApprovalBroker();
|
|
38
40
|
extension = "missing";
|
|
39
41
|
constructor(options) {
|
|
40
42
|
this.options = options;
|
|
@@ -101,6 +103,7 @@ export class NativeRuntime {
|
|
|
101
103
|
archives: options.archives,
|
|
102
104
|
pi: this.pi,
|
|
103
105
|
codex: this.codex,
|
|
106
|
+
approvals: this.approvals,
|
|
104
107
|
piExtension: piExtensionSource(),
|
|
105
108
|
diagnostics: options.diagnostics,
|
|
106
109
|
};
|
|
@@ -129,9 +132,11 @@ export class NativeRuntime {
|
|
|
129
132
|
if (this.codex.enabled)
|
|
130
133
|
void this.codex.get();
|
|
131
134
|
}
|
|
132
|
-
|
|
135
|
+
/** `approvals`: the Gateway relays approval decisions back. */
|
|
136
|
+
connect(send, features = {}) {
|
|
133
137
|
this.send = send;
|
|
134
138
|
this.ingest.connect(send ? nativeWebSocketTransport(send) : null);
|
|
139
|
+
this.approvals.connect(send && features.approvals ? send : null);
|
|
135
140
|
}
|
|
136
141
|
stop(sessionId, turnId) {
|
|
137
142
|
return this.ingest.stop(sessionId, turnId);
|
|
@@ -2,6 +2,7 @@ import { type RuntimeTurnInput } from "@neta-art/cohub";
|
|
|
2
2
|
import type { RuntimeArchiveStore } from "../archive-store.js";
|
|
3
3
|
import { type RuntimeDiagnosticContext, type RuntimeDiagnostics } from "../diagnostics.js";
|
|
4
4
|
import type { HarnessExecutables, HarnessResult, HarnessTurn } from "../harnesses/types.js";
|
|
5
|
+
import type { ApprovalBroker } from "./approvals.js";
|
|
5
6
|
import type { CodexShared } from "./codex-link.js";
|
|
6
7
|
import type { NativeIngest } from "./ingest.js";
|
|
7
8
|
import type { PiLink } from "./pi-link.js";
|
|
@@ -17,6 +18,7 @@ export type Executor = {
|
|
|
17
18
|
archives: RuntimeArchiveStore;
|
|
18
19
|
pi: PiLink;
|
|
19
20
|
codex: CodexShared;
|
|
21
|
+
approvals: ApprovalBroker;
|
|
20
22
|
piExtension: string;
|
|
21
23
|
diagnostics?: RuntimeDiagnostics;
|
|
22
24
|
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
type RuntimePreferences = {
|
|
2
|
+
keepAwake: boolean;
|
|
3
|
+
};
|
|
4
|
+
export declare const runtimePreferencesPath: () => string;
|
|
5
|
+
export declare function readRuntimePreferences(path?: string): Promise<RuntimePreferences>;
|
|
6
|
+
export declare function writeRuntimePreferences(preferences: RuntimePreferences, path?: string): Promise<void>;
|
|
7
|
+
export {};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
const DEFAULTS = { keepAwake: true };
|
|
6
|
+
export const runtimePreferencesPath = () => join(homedir(), ".config", "cohub", "runtime-preferences.json");
|
|
7
|
+
export async function readRuntimePreferences(path = runtimePreferencesPath()) {
|
|
8
|
+
const stored = await readFile(path, "utf8").then(JSON.parse).catch(() => null);
|
|
9
|
+
const keepAwake = stored?.keepAwake;
|
|
10
|
+
return { keepAwake: typeof keepAwake === "boolean" ? keepAwake : DEFAULTS.keepAwake };
|
|
11
|
+
}
|
|
12
|
+
export async function writeRuntimePreferences(preferences, path = runtimePreferencesPath()) {
|
|
13
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
14
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
15
|
+
try {
|
|
16
|
+
await writeFile(temporary, `${JSON.stringify(preferences, null, 2)}\n`, { mode: 0o600, flag: "wx" });
|
|
17
|
+
await rename(temporary, path);
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
await rm(temporary, { force: true });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -19,6 +19,9 @@ export type RuntimeSummary = {
|
|
|
19
19
|
diagnosticsPath: string;
|
|
20
20
|
background: boolean;
|
|
21
21
|
display?: string;
|
|
22
|
+
displayOnRequest?: boolean;
|
|
23
|
+
displayNeeds?: string[];
|
|
24
|
+
direct?: boolean;
|
|
22
25
|
native?: NativeStatus;
|
|
23
26
|
};
|
|
24
27
|
export declare function printRuntimeSummary(summary: RuntimeSummary, json?: boolean, reused?: boolean): void;
|
|
@@ -68,9 +68,10 @@ export function printRuntimeSummary(summary, json = false, reused = false) {
|
|
|
68
68
|
["Space", summary.spaceId],
|
|
69
69
|
["URL", value.url],
|
|
70
70
|
["Directory", summary.root],
|
|
71
|
-
["Harness", summary.harnesses.join(" · ")],
|
|
71
|
+
["Harness", summary.harnesses.join(" · ") || "Cohub"],
|
|
72
72
|
["Mode", summary.background ? "Background" : "Foreground"],
|
|
73
73
|
...(summary.display ? [["Screen", summary.display === "auto" ? "This computer" : summary.display]] : []),
|
|
74
|
+
...(summary.direct ? [["Direct", "Files and screens on this machine skip the network"]] : []),
|
|
74
75
|
["PID", String(summary.pid)],
|
|
75
76
|
["Logs", summary.diagnosticsPath],
|
|
76
77
|
];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
3
3
|
import { createServer } from "node:net";
|
|
4
4
|
import { createInterface } from "node:readline";
|
|
5
5
|
import { setTimeout as delay } from "node:timers/promises";
|
|
@@ -12,12 +12,16 @@ import { ensureSandboxdBinary } from "../commands/sandboxd-binary.js";
|
|
|
12
12
|
import { serveRuntime } from "./connection.js";
|
|
13
13
|
import { discoverHarnesses, refreshHarnesses } from "./harnesses/index.js";
|
|
14
14
|
import { RuntimeDiagnostics, serializeDiagnosticError } from "./diagnostics.js";
|
|
15
|
-
import { ownRuntimeInstance, runtimeInstanceDirectory } from "./instance.js";
|
|
15
|
+
import { ownRuntimeInstance, runtimeInstanceDirectory, UNCONFIRMED_WORK } from "./instance.js";
|
|
16
|
+
import { readRuntimePreferences } from "./preferences.js";
|
|
16
17
|
import { createDiagnosticConsole } from "./presentation.js";
|
|
17
18
|
import { join } from "node:path";
|
|
18
19
|
import { RuntimeArchiveStore } from "./archive-store.js";
|
|
20
|
+
import { appendCliToPath } from "./cli-path.js";
|
|
19
21
|
import { readNativeConfig, runtimeStateRoot } from "./native/config.js";
|
|
20
22
|
import { NativeRuntime } from "./native/daemon.js";
|
|
23
|
+
const DISPLAY_ANSWER_MS = 10_000;
|
|
24
|
+
const ACTIVITY_MS = 60_000;
|
|
21
25
|
export function sandboxOutputLevel(value, stream) {
|
|
22
26
|
const level = typeof value === "string" ? value.toLowerCase() : "";
|
|
23
27
|
if (["debug", "info", "warn", "error"].includes(level))
|
|
@@ -48,6 +52,7 @@ export async function runRuntime(config, onState, externalSignal, onDiagnostic)
|
|
|
48
52
|
const stop = () => controller.abort();
|
|
49
53
|
process.once("SIGINT", stop);
|
|
50
54
|
process.once("SIGTERM", stop);
|
|
55
|
+
appendCliToPath();
|
|
51
56
|
const client = createClient();
|
|
52
57
|
const space = client.space(config.spaceId);
|
|
53
58
|
const stateRoot = runtimeStateRoot(config.spaceId);
|
|
@@ -94,6 +99,51 @@ export async function runRuntime(config, onState, externalSignal, onDiagnostic)
|
|
|
94
99
|
let retryDisconnectedBridge;
|
|
95
100
|
let nativeStarted = false;
|
|
96
101
|
let tokenInFlight = null;
|
|
102
|
+
const executions = new Map();
|
|
103
|
+
let bridgeControl = null;
|
|
104
|
+
let workspace = null;
|
|
105
|
+
let displayAnswer = null;
|
|
106
|
+
const applyKeepAwake = async () => {
|
|
107
|
+
if (bridgeControl?.features.includes("keepAwake"))
|
|
108
|
+
bridgeControl.send({ type: "keepAwake", enabled: (await readRuntimePreferences()).keepAwake });
|
|
109
|
+
};
|
|
110
|
+
const setDisplay = async (spec) => {
|
|
111
|
+
if (bridgeControl && !bridgeControl.features.includes("display"))
|
|
112
|
+
throw new Error("This Runtime cannot change its screen while running; reconnect it");
|
|
113
|
+
if (!spec)
|
|
114
|
+
update({ display: undefined, displayOnRequest: undefined, displayNeeds: undefined });
|
|
115
|
+
if (!bridgeControl) {
|
|
116
|
+
if (!spec)
|
|
117
|
+
return summary();
|
|
118
|
+
throw new Error("The file bridge is restarting; try again");
|
|
119
|
+
}
|
|
120
|
+
const { send } = bridgeControl;
|
|
121
|
+
const before = status.displayOnRequest;
|
|
122
|
+
if (spec)
|
|
123
|
+
update({ displayOnRequest: true });
|
|
124
|
+
const frame = await new Promise((resolve, reject) => {
|
|
125
|
+
const timer = setTimeout(() => {
|
|
126
|
+
displayAnswer = null;
|
|
127
|
+
if (spec)
|
|
128
|
+
send({ type: "display", spec: "" });
|
|
129
|
+
update({ display: undefined, displayOnRequest: undefined, displayNeeds: undefined });
|
|
130
|
+
reject(new Error("The file bridge did not answer"));
|
|
131
|
+
}, DISPLAY_ANSWER_MS);
|
|
132
|
+
displayAnswer = (answer) => {
|
|
133
|
+
if (!answer.error && answer.spec !== spec)
|
|
134
|
+
return;
|
|
135
|
+
clearTimeout(timer);
|
|
136
|
+
displayAnswer = null;
|
|
137
|
+
resolve(answer);
|
|
138
|
+
};
|
|
139
|
+
send({ type: "display", spec });
|
|
140
|
+
});
|
|
141
|
+
if (frame.error) {
|
|
142
|
+
update({ displayOnRequest: before });
|
|
143
|
+
throw new Error(frame.error);
|
|
144
|
+
}
|
|
145
|
+
return summary();
|
|
146
|
+
};
|
|
97
147
|
const token = (forceRefresh = false) => {
|
|
98
148
|
tokenInFlight ??= (async () => {
|
|
99
149
|
if (currentIdentityKey() !== config.identity)
|
|
@@ -112,11 +162,19 @@ export async function runRuntime(config, onState, externalSignal, onDiagnostic)
|
|
|
112
162
|
if (!force)
|
|
113
163
|
for await (const batch of native.executor.results.pendingBatches()) {
|
|
114
164
|
if (batch.length)
|
|
115
|
-
throw new Error(
|
|
165
|
+
throw new Error(`${UNCONFIRMED_WORK}. Use down --yes to stop; results and files are retained`);
|
|
116
166
|
}
|
|
117
167
|
update({ state: "stopping" });
|
|
118
168
|
setTimeout(stop, 30);
|
|
119
|
-
}, (action, message) =>
|
|
169
|
+
}, (action, message) => {
|
|
170
|
+
if (action === "display")
|
|
171
|
+
return setDisplay(String(message.spec ?? ""));
|
|
172
|
+
if (action === "keepAwake")
|
|
173
|
+
return applyKeepAwake();
|
|
174
|
+
if (action === "workspace")
|
|
175
|
+
return Promise.resolve(status.state === "ready" ? workspace : null);
|
|
176
|
+
return native.control(action, message);
|
|
177
|
+
});
|
|
120
178
|
onState({ ...status });
|
|
121
179
|
diagnostics.log("info", "runtime.cli_started", { platform: process.platform, node: process.versions.node, harnesses: config.harnesses });
|
|
122
180
|
const [binary, capabilities] = await Promise.all([
|
|
@@ -150,10 +208,12 @@ export async function runRuntime(config, onState, externalSignal, onDiagnostic)
|
|
|
150
208
|
signal.throwIfAborted();
|
|
151
209
|
if (process.platform === "win32")
|
|
152
210
|
controlPipe = await listenWindowsControlPipe();
|
|
211
|
+
const spawnedScreen = status.display ?? "";
|
|
212
|
+
const localToken = randomBytes(32).toString("base64url");
|
|
153
213
|
const bridge = spawn(binary, ["--local", "--space", config.spaceId, "--root", config.root, "--relay", process.env.COHUB_RELAY_URL?.trim() || relay.toString()], {
|
|
154
214
|
stdio: controlPipe ? ["pipe", "pipe", "pipe"] : ["pipe", "pipe", "pipe", "pipe"],
|
|
155
215
|
windowsHide: true,
|
|
156
|
-
env: { ...process.env, COHUB_RELAY_TOKEN: initialToken, COHUB_RUNTIME_ID: status.runtimeId, COHUB_LOG_FORMAT: "json", COHUB_RUNTIME_MANAGED: "1", COHUB_DISPLAY:
|
|
216
|
+
env: { ...process.env, COHUB_RELAY_TOKEN: initialToken, COHUB_LOCAL_TOKEN: localToken, COHUB_RUNTIME_ID: status.runtimeId, COHUB_LOG_FORMAT: "json", COHUB_RUNTIME_MANAGED: "1", COHUB_DISPLAY: spawnedScreen, ...(controlPipe ? { COHUB_RUNTIME_CONTROL_PIPE: controlPipe.path } : {}) },
|
|
157
217
|
});
|
|
158
218
|
bridge.stdin?.on("error", () => undefined);
|
|
159
219
|
const closed = new Promise((resolve) => {
|
|
@@ -203,6 +263,20 @@ export async function runRuntime(config, onState, externalSignal, onDiagnostic)
|
|
|
203
263
|
const event = JSON.parse(line);
|
|
204
264
|
if (event.type === "hello")
|
|
205
265
|
managed = true;
|
|
266
|
+
if (event.type === "features") {
|
|
267
|
+
bridgeControl = { features: event.features, send: (frame) => bridge.stdin?.write(`${JSON.stringify(frame)}\n`) };
|
|
268
|
+
void applyKeepAwake().catch(() => undefined);
|
|
269
|
+
if ((status.display ?? "") !== spawnedScreen)
|
|
270
|
+
bridgeControl.send({ type: "display", spec: status.display ?? "" });
|
|
271
|
+
}
|
|
272
|
+
if (event.type === "local" && Number.isInteger(event.port)) {
|
|
273
|
+
workspace = { url: `http://127.0.0.1:${event.port}`, token: localToken };
|
|
274
|
+
update({ direct: true });
|
|
275
|
+
}
|
|
276
|
+
if (event.type === "display") {
|
|
277
|
+
update({ display: event.spec || undefined, displayNeeds: event.needs?.length ? event.needs : undefined });
|
|
278
|
+
displayAnswer?.(event);
|
|
279
|
+
}
|
|
206
280
|
if (event.type === "connected" || event.type === "disconnected") {
|
|
207
281
|
const connected = event.type === "connected";
|
|
208
282
|
bridgeDisconnected = !connected;
|
|
@@ -292,12 +366,14 @@ export async function runRuntime(config, onState, externalSignal, onDiagnostic)
|
|
|
292
366
|
}
|
|
293
367
|
finally {
|
|
294
368
|
retryDisconnectedBridge = undefined;
|
|
369
|
+
bridgeControl = null;
|
|
370
|
+
workspace = null;
|
|
295
371
|
childStopped = true;
|
|
296
372
|
controlPipe?.close();
|
|
297
373
|
clearTimeout(refreshTimer);
|
|
298
374
|
clearTimeout(probeTimer);
|
|
299
375
|
clearTimeout(recoveryTimer);
|
|
300
|
-
update({ workspaceConnected: false });
|
|
376
|
+
update({ workspaceConnected: false, direct: undefined });
|
|
301
377
|
}
|
|
302
378
|
if (Date.now() - startedAt > 60_000)
|
|
303
379
|
attempts = 0;
|
|
@@ -306,18 +382,25 @@ export async function runRuntime(config, onState, externalSignal, onDiagnostic)
|
|
|
306
382
|
}
|
|
307
383
|
};
|
|
308
384
|
bridgeTask = runBridge();
|
|
385
|
+
const activity = setInterval(() => {
|
|
386
|
+
if (executions.size || native.status().running)
|
|
387
|
+
bridgeControl?.send({ type: "activity" });
|
|
388
|
+
}, ACTIVITY_MS);
|
|
389
|
+
activity.unref();
|
|
390
|
+
signal.addEventListener("abort", () => clearInterval(activity), { once: true });
|
|
309
391
|
await native.start(signal);
|
|
310
392
|
nativeStarted = true;
|
|
311
393
|
let importRequested = Boolean(config.importHistory);
|
|
312
394
|
await serveRuntime({
|
|
313
395
|
spaceId: config.spaceId, cwd: config.root, url: url.toString(), capabilities,
|
|
314
396
|
refreshCapabilities: (current) => refreshHarnesses(current, config.executables, config.root, (harness, error) => diagnostics.log("warn", "runtime.harness_catalog_failed", { harness, error: serializeDiagnosticError(error) })),
|
|
315
|
-
runtimeId: status.runtimeId, diagnostics, token, signal, executor: native.executor,
|
|
397
|
+
runtimeId: status.runtimeId, diagnostics, token, signal, executor: native.executor, executions,
|
|
316
398
|
onReady: () => { update({ harnessConnected: true }); retryDisconnectedBridge?.(); },
|
|
317
399
|
onDisconnected: () => { native.connect(null); update({ harnessConnected: false }); retryDisconnectedBridge?.(); },
|
|
318
400
|
onNativeStop: (stop) => { native.stop(stop.sessionId, stop.turnId); },
|
|
319
|
-
|
|
320
|
-
|
|
401
|
+
onApprovalDecision: (decision) => { native.executor.approvals.decide(decision); },
|
|
402
|
+
onNativeChannel: (send, features) => {
|
|
403
|
+
native.connect(send, features);
|
|
321
404
|
if (!importRequested)
|
|
322
405
|
return;
|
|
323
406
|
importRequested = false;
|
|
@@ -6,7 +6,7 @@ import { Readable } from "node:stream";
|
|
|
6
6
|
import { pipeline } from "node:stream/promises";
|
|
7
7
|
import { UPLOAD_MAX_FILE_BYTES } from "@neta-art/cohub";
|
|
8
8
|
import { createLimiter } from "./limit.js";
|
|
9
|
-
import { uploadLocalFiles } from "./upload.js";
|
|
9
|
+
import { uploadLocalFiles, uploadsDirectly } from "./upload.js";
|
|
10
10
|
export class CopyAbortError extends Error {
|
|
11
11
|
name = "CopyAbortError";
|
|
12
12
|
}
|
|
@@ -106,6 +106,7 @@ export async function uploadToSpace(input) {
|
|
|
106
106
|
for (const entry of node.tree.entries)
|
|
107
107
|
existing.set(entry.path, entry.type);
|
|
108
108
|
})));
|
|
109
|
+
const maxFileBytes = await uploadsDirectly(files) ? Number.POSITIVE_INFINITY : UPLOAD_MAX_FILE_BYTES;
|
|
109
110
|
const upload = entries.filter((entry) => {
|
|
110
111
|
const current = existing.get(entry.relativePath);
|
|
111
112
|
if (current === "dir") {
|
|
@@ -120,7 +121,7 @@ export async function uploadToSpace(input) {
|
|
|
120
121
|
fail(entry.relativePath, "name_invalid", `cannot upload '${entry.localPath}': unsupported file name`);
|
|
121
122
|
return false;
|
|
122
123
|
}
|
|
123
|
-
if (entry.size >
|
|
124
|
+
if (entry.size > maxFileBytes) {
|
|
124
125
|
fail(entry.relativePath, "file_too_large", `cannot upload '${entry.localPath}': file exceeds the upload size limit`);
|
|
125
126
|
return false;
|
|
126
127
|
}
|
|
@@ -5,10 +5,13 @@ export type LocalUploadEntry = {
|
|
|
5
5
|
relativePath: string;
|
|
6
6
|
size: number;
|
|
7
7
|
};
|
|
8
|
-
|
|
8
|
+
type UploadOptions = {
|
|
9
9
|
targetDir?: string;
|
|
10
10
|
onUploaded?: (entry: LocalUploadEntry) => void;
|
|
11
|
-
}
|
|
11
|
+
};
|
|
12
|
+
export declare const uploadsDirectly: (files: SpaceFiles) => Promise<boolean>;
|
|
13
|
+
export declare function uploadLocalFiles(files: SpaceFiles, entries: LocalUploadEntry[], options?: UploadOptions): Promise<{
|
|
12
14
|
uploaded: SpaceFsUploadEntry[];
|
|
13
15
|
uploadIds: string[];
|
|
14
16
|
}>;
|
|
17
|
+
export {};
|
|
@@ -1,9 +1,49 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import {
|
|
2
|
+
import { openAsBlob } from "node:fs";
|
|
3
|
+
import { posix } from "node:path";
|
|
4
|
+
import { batchUploadEntries, LocalWorkspaceUnavailableError, localWorkspaceHttpError, mimeTypeForPath, } from "@neta-art/cohub";
|
|
3
5
|
import { putLocalFile } from "../http-put.js";
|
|
4
6
|
import { createLimiter } from "./limit.js";
|
|
5
7
|
const PUT_CONCURRENCY = 4;
|
|
8
|
+
export const uploadsDirectly = async (files) => Boolean((await files.workspace())?.put);
|
|
6
9
|
export async function uploadLocalFiles(files, entries, options = {}) {
|
|
10
|
+
const workspace = await files.workspace();
|
|
11
|
+
if (!workspace?.put)
|
|
12
|
+
return uploadThroughApi(files, entries, options);
|
|
13
|
+
const { uploaded, remaining } = await putLocalFiles(workspace, workspace.put, entries, options);
|
|
14
|
+
if (!remaining.length)
|
|
15
|
+
return { uploaded, uploadIds: [] };
|
|
16
|
+
const rest = await uploadThroughApi(files, remaining, options);
|
|
17
|
+
return { uploaded: [...uploaded, ...rest.uploaded], uploadIds: rest.uploadIds };
|
|
18
|
+
}
|
|
19
|
+
async function putLocalFiles(workspace, put, entries, options) {
|
|
20
|
+
const limit = createLimiter(PUT_CONCURRENCY);
|
|
21
|
+
const uploaded = [];
|
|
22
|
+
const remaining = [];
|
|
23
|
+
const failures = [];
|
|
24
|
+
await Promise.all(entries.map((entry) => limit(async () => {
|
|
25
|
+
const path = options.targetDir ? posix.join(options.targetDir, entry.relativePath) : entry.relativePath;
|
|
26
|
+
try {
|
|
27
|
+
// As the API's uploads do: a file edited meanwhile is a conflict, never overwritten.
|
|
28
|
+
const version = await workspace.fs.statVersion(path);
|
|
29
|
+
const expected = version.exists ? { expected: { size: version.size, mtimeMs: version.mtimeMs } } : { exclusive: true };
|
|
30
|
+
const result = await put(path, await openAsBlob(entry.localPath), expected);
|
|
31
|
+
const name = posix.basename(path);
|
|
32
|
+
uploaded.push({ path, name, size: result.bytesWritten, mimeType: mimeTypeForPath(name), mtimeMs: result.mtimeMs ?? Date.now(), created: result.created });
|
|
33
|
+
options.onUploaded?.(entry);
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error instanceof LocalWorkspaceUnavailableError)
|
|
37
|
+
remaining.push(entry);
|
|
38
|
+
else
|
|
39
|
+
failures.push(error);
|
|
40
|
+
}
|
|
41
|
+
})));
|
|
42
|
+
if (failures.length)
|
|
43
|
+
throw localWorkspaceHttpError(failures[0]);
|
|
44
|
+
return { uploaded, remaining };
|
|
45
|
+
}
|
|
46
|
+
async function uploadThroughApi(files, entries, options) {
|
|
7
47
|
const uploaded = [];
|
|
8
48
|
const uploadIds = [];
|
|
9
49
|
const limit = createLimiter(PUT_CONCURRENCY);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@neta-art/cohub-cli",
|
|
3
|
-
"version": "10.
|
|
3
|
+
"version": "10.18.0",
|
|
4
4
|
"description": "CLI for Cohub — spaces, sessions, and agent collaboration.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"NOTICE"
|
|
19
19
|
],
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@neta-art/cohub": "13.
|
|
21
|
+
"@neta-art/cohub": "13.9.0",
|
|
22
22
|
"@neta-art/generation": "0.2.15",
|
|
23
23
|
"commander": "^15.0.0",
|
|
24
24
|
"sharp": "^0.35.4",
|