@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
@@ -0,0 +1,52 @@
1
+ import { Agent, request } from "node:http";
2
+ import { Readable } from "node:stream";
3
+ import { loopbackWorkspace } from "@neta-art/cohub";
4
+ import { currentIdentityKey } from "../space.js";
5
+ import { controlRuntimeInstance, runtimeInstanceDirectory } from "./instance.js";
6
+ const DISCOVERY_TIMEOUT_MS = 1_500;
7
+ const NULL_BODY_STATUS = new Set([204, 304]);
8
+ /** Its own agent keeps requests off the proxy `--use-env-proxy` gives global fetch and http: they carry the Runtime's token. */
9
+ const direct = new Agent({ keepAlive: true });
10
+ const loopbackFetch = (input, init = {}) => new Promise((resolve, reject) => {
11
+ const client = request(String(input), { agent: direct, method: init.method ?? "GET", headers: Object.fromEntries(new Headers(init.headers)), signal: init.signal ?? undefined }, (response) => {
12
+ const headers = new Headers(Object.entries(response.headers).flatMap(([name, value]) => [value ?? []].flat().map((item) => [name, item])));
13
+ const status = response.statusCode ?? 502;
14
+ resolve(new Response(NULL_BODY_STATUS.has(status) ? null : Readable.toWeb(response), { status, headers }));
15
+ });
16
+ client.on("error", (cause) => reject(new TypeError("fetch failed", { cause })));
17
+ const { body } = init;
18
+ if (body instanceof Blob)
19
+ Readable.from(body.stream()).on("error", (error) => client.destroy(error)).pipe(client);
20
+ else
21
+ client.end(typeof body === "string" ? body : undefined);
22
+ });
23
+ export const connectLocalWorkspace = (endpoint) => loopbackWorkspace(endpoint, loopbackFetch);
24
+ const isEndpoint = (value) => {
25
+ const endpoint = value;
26
+ return typeof endpoint?.token === "string" && typeof endpoint.url === "string" && /^http:\/\/127\.0\.0\.1:\d+$/.test(endpoint.url);
27
+ };
28
+ export async function findLocalWorkspace(spaceId) {
29
+ const identity = currentIdentityKey();
30
+ if (!identity)
31
+ return null;
32
+ const response = await controlRuntimeInstance(runtimeInstanceDirectory(identity, spaceId), "workspace", {}, DISCOVERY_TIMEOUT_MS).catch(() => null);
33
+ return isEndpoint(response?.result) ? response.result : null;
34
+ }
35
+ const found = new Map();
36
+ /**
37
+ * Files and displays of a Space this machine serves go straight to its Runtime,
38
+ * looked up once per account and process. Only the signed-in owner goes direct: a scoped
39
+ * execution token stays on the API that enforces its scope, as does
40
+ * `COHUB_NO_DIRECT=1`.
41
+ */
42
+ export const resolveLocalWorkspace = (spaceId) => {
43
+ if (process.env.COHUB_NO_DIRECT === "1" || process.env.COHUB_EXECUTION_TOKEN?.trim())
44
+ return null;
45
+ const key = `${currentIdentityKey()}\0${spaceId}`;
46
+ let workspace = found.get(key);
47
+ if (!workspace) {
48
+ workspace = findLocalWorkspace(spaceId).then((endpoint) => (endpoint ? connectLocalWorkspace(endpoint) : null));
49
+ found.set(key, workspace);
50
+ }
51
+ return workspace;
52
+ };
@@ -1,4 +1,4 @@
1
- import { isModelThinkingLevel, MODEL_THINKING_LEVELS as thinkingLevels, RUNTIME_MAX_SERVICE_TIERS, runtimeServiceTierSchema, thinkingLevelMapFor } from "@neta-art/cohub";
1
+ import { isModelThinkingLevel, MODEL_THINKING_LEVELS as thinkingLevels, RUNTIME_MAX_SERVICE_TIERS, runtimeServiceTierSchema, STANDARD_SERVICE_TIER, thinkingLevelMapFor } from "@neta-art/cohub";
2
2
  import { record } from "./json-rpc.js";
3
3
  const thinkingLevel = (value) => isModelThinkingLevel(value) ? value : undefined;
4
4
  /**
@@ -46,7 +46,7 @@ function codexThinking(model, configuredEffort) {
46
46
  };
47
47
  }
48
48
  /** `serviceTiers` supersedes the deprecated `additionalSpeedTiers`, which only names tier ids. */
49
- function codexServiceTiers(model) {
49
+ function codexServiceTiers(model, configuredTier) {
50
50
  const candidates = Array.isArray(model.serviceTiers)
51
51
  ? model.serviceTiers.map((entry) => {
52
52
  const tier = record(entry);
@@ -58,7 +58,10 @@ function codexServiceTiers(model) {
58
58
  const parsed = runtimeServiceTierSchema.safeParse(tier);
59
59
  return parsed.success ? [parsed.data] : [];
60
60
  }).slice(0, RUNTIME_MAX_SERVICE_TIERS);
61
- const defaultServiceTier = typeof model.defaultServiceTier === "string" && tiers.some((tier) => tier.id === model.defaultServiceTier) ? model.defaultServiceTier : undefined;
61
+ // A configured `service_tier` replaces the catalog default; `fast` is its legacy name for `priority`.
62
+ const configured = configuredTier === "fast" ? "priority" : configuredTier;
63
+ const preferred = configured === STANDARD_SERVICE_TIER ? undefined : typeof configured === "string" && configured ? configured : model.defaultServiceTier;
64
+ const defaultServiceTier = typeof preferred === "string" && tiers.some((tier) => tier.id === preferred) ? preferred : undefined;
62
65
  return { ...(tiers.length ? { serviceTiers: tiers } : {}), ...(defaultServiceTier ? { defaultServiceTier } : {}) };
63
66
  }
64
67
  /** Use Codex's picker-visible model/list for every provider, including custom providers. */
@@ -73,7 +76,7 @@ export function codexModelCatalog(configResponse, entries) {
73
76
  return [];
74
77
  // A configured model replaces the catalog's own default.
75
78
  const isDefault = configuredModel ? id === configuredModel : model.isDefault === true;
76
- return [{ harness: "codex", provider, id, name: typeof model.displayName === "string" ? model.displayName : id, ...(isDefault ? { isDefault } : {}), ...codexThinking(model, config.model_reasoning_effort), ...codexServiceTiers(model) }];
79
+ return [{ harness: "codex", provider, id, name: typeof model.displayName === "string" ? model.displayName : id, ...(isDefault ? { isDefault } : {}), ...codexThinking(model, config.model_reasoning_effort), ...codexServiceTiers(model, config.service_tier) }];
77
80
  });
78
81
  if (configuredModel && !models.some((model) => model.id === configuredModel))
79
82
  models.unshift({ harness: "codex", provider, id: configuredModel, name: configuredModel, isDefault: true });
@@ -0,0 +1,18 @@
1
+ import type { ApprovalDecision, NativeRuntimeEvent, RuntimeApproval, RuntimeApprovalDecision } from "@neta-art/cohub";
2
+ /** How long a card waits for a person; unanswered, the request is declined. */
3
+ export declare const APPROVAL_TIMEOUT_MS: number;
4
+ type Send = (event: NativeRuntimeEvent) => Promise<unknown>;
5
+ export type ApprovalRequest = Omit<RuntimeApproval, "id" | "requestedAt" | "expiresAt">;
6
+ /** Asks the web for a decision over the control connection; without one, it declines. */
7
+ export declare class ApprovalBroker {
8
+ private readonly timeoutMs;
9
+ private send;
10
+ private readonly pending;
11
+ constructor(timeoutMs?: number);
12
+ /** `null` when the Gateway cannot relay decisions; open cards are then declined. */
13
+ connect(send: Send | null): void;
14
+ get available(): boolean;
15
+ request(sessionId: string, turnId: string, request: ApprovalRequest, signal: AbortSignal): Promise<ApprovalDecision>;
16
+ decide(input: Pick<RuntimeApprovalDecision, "sessionId" | "turnId" | "approvalId" | "decision">): void;
17
+ }
18
+ export {};
@@ -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
- await initialize(channel);
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
- async function initialize(channel) {
147
- await channel.request("initialize", { clientInfo: { name: "cohub-runtime", title: "Cohub", version: "1" }, capabilities: { experimentalApi: true } });
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
- connect(send: ((event: NativeRuntimeEvent) => Promise<unknown>) | null): void;
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
- connect(send) {
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("Unconfirmed executions remain. Use down --yes to stop; results and files are retained");
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) => native.control(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: config.display ?? "", ...(controlPipe ? { COHUB_RUNTIME_CONTROL_PIPE: controlPipe.path } : {}) },
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
- onNativeChannel: (send) => {
320
- native.connect(send);
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;
@@ -29,4 +29,8 @@ export declare function downloadPublicAudio(input: string, options?: RemoteImage
29
29
  bytes: Uint8Array;
30
30
  mimeType: string;
31
31
  }>;
32
+ export declare function downloadPublicVideo(input: string, options?: RemoteImageDownloadOptions): Promise<{
33
+ bytes: Uint8Array;
34
+ mimeType: string;
35
+ }>;
32
36
  export {};
@@ -18,6 +18,7 @@ const AUDIO_MIME_TYPES = new Set([
18
18
  "audio/wav", "audio/x-wav", "audio/wave", "audio/flac", "audio/x-flac",
19
19
  "audio/webm", "audio/opus", "application/ogg",
20
20
  ]);
21
+ const VIDEO_MIME_TYPES = new Set(["video/mp4", "video/webm", "video/quicktime", "video/ogg", "video/x-matroska"]);
21
22
  const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
22
23
  async function defaultLookup(hostname) {
23
24
  const records = await dns.lookup(hostname, { all: true, verbatim: true });
@@ -145,6 +146,13 @@ export function downloadPublicAudio(input, options = {}) {
145
146
  ...options,
146
147
  });
147
148
  }
149
+ export function downloadPublicVideo(input, options = {}) {
150
+ return downloadPublicMedia(input, VIDEO_MIME_TYPES, {
151
+ maxBytes: 512 * 1024 * 1024,
152
+ timeoutMs: 120_000,
153
+ ...options,
154
+ });
155
+ }
148
156
  async function downloadPublicMedia(input, mimeTypes, options) {
149
157
  const lookup = options.lookup ?? defaultLookup;
150
158
  const requester = options.requester ?? requestPinned;