@neta-art/cohub-cli 10.14.1 → 10.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +3 -1
  2. package/dist/auth.d.ts +3 -1
  3. package/dist/auth.js +4 -0
  4. package/dist/board-export.d.ts +7 -0
  5. package/dist/board-export.js +3 -3
  6. package/dist/board-kernel.d.ts +1 -0
  7. package/dist/board-kernel.js +7605 -277
  8. package/dist/board-simulate.d.ts +53 -0
  9. package/dist/board-simulate.js +151 -0
  10. package/dist/bootstrap.js +5 -0
  11. package/dist/commands/auth.js +12 -1
  12. package/dist/commands/boards.js +68 -0
  13. package/dist/commands/host.d.ts +2 -0
  14. package/dist/commands/host.js +11 -0
  15. package/dist/commands/runtime.js +4 -16
  16. package/dist/commands/space-invitations.d.ts +3 -2
  17. package/dist/commands/space-invitations.js +29 -8
  18. package/dist/commands/spaces.js +55 -30
  19. package/dist/host/auth.d.ts +20 -0
  20. package/dist/host/auth.js +107 -0
  21. package/dist/host/login-env.d.ts +1 -0
  22. package/dist/host/login-env.js +31 -0
  23. package/dist/host/runtime.d.ts +25 -0
  24. package/dist/host/runtime.js +250 -0
  25. package/dist/host/runtimes.d.ts +9 -0
  26. package/dist/host/runtimes.js +42 -0
  27. package/dist/host/serve.d.ts +2 -0
  28. package/dist/host/serve.js +73 -0
  29. package/dist/index.js +2 -0
  30. package/dist/runtime/connection.d.ts +3 -0
  31. package/dist/runtime/connection.js +59 -3
  32. package/dist/runtime/harnesses/claude.js +8 -2
  33. package/dist/runtime/harnesses/index.d.ts +2 -0
  34. package/dist/runtime/harnesses/index.js +13 -0
  35. package/dist/runtime/harnesses/stream-json.d.ts +2 -2
  36. package/dist/runtime/harnesses/stream-json.js +5 -3
  37. package/dist/runtime/harnesses/types.d.ts +4 -2
  38. package/dist/runtime/harnesses/workbuddy.d.ts +8 -2
  39. package/dist/runtime/instance.d.ts +8 -1
  40. package/dist/runtime/instance.js +89 -9
  41. package/dist/runtime/launch.d.ts +1 -0
  42. package/dist/runtime/launch.js +6 -0
  43. package/dist/runtime/model-catalog.d.ts +1 -3
  44. package/dist/runtime/model-catalog.js +23 -7
  45. package/dist/runtime/supervisor.js +6 -4
  46. package/dist/space.d.ts +1 -0
  47. package/dist/space.js +1 -1
  48. package/package.json +3 -3
@@ -0,0 +1,42 @@
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
+ import { withRuntimeSpaceBindingsLock } from "../runtime/space-binding.js";
6
+ export const hostRuntimesPath = () => join(homedir(), ".local", "state", "cohub", "host", "runtimes.json");
7
+ // Only a missing file is empty; an unreadable one throws, so it is never overwritten.
8
+ async function read(path) {
9
+ let text;
10
+ try {
11
+ text = await readFile(path, "utf8");
12
+ }
13
+ catch (error) {
14
+ if (error.code === "ENOENT")
15
+ return [];
16
+ throw error;
17
+ }
18
+ const file = JSON.parse(text);
19
+ if (file.version !== 1 || !Array.isArray(file.runtimes))
20
+ throw new Error(`Unsupported desktop Runtime state: ${path}`);
21
+ return file.runtimes.filter((item) => typeof item?.key === "string" && typeof item.spaceId === "string" && typeof item.root === "string");
22
+ }
23
+ async function update(path, change) {
24
+ await withRuntimeSpaceBindingsLock(async () => {
25
+ const before = await read(path);
26
+ const after = change(before);
27
+ if (JSON.stringify(after) === JSON.stringify(before))
28
+ return;
29
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
30
+ const temporary = `${path}.${randomUUID()}.tmp`;
31
+ try {
32
+ await writeFile(temporary, `${JSON.stringify({ version: 1, runtimes: after }, null, 2)}\n`, { mode: 0o600, flag: "wx" });
33
+ await rename(temporary, path);
34
+ }
35
+ finally {
36
+ await rm(temporary, { force: true });
37
+ }
38
+ }, { path });
39
+ }
40
+ export const hostRuntimes = (key, path = hostRuntimesPath()) => read(path).then((runtimes) => runtimes.filter((item) => item.key === key));
41
+ export const rememberHostRuntime = (runtime, path = hostRuntimesPath()) => update(path, (runtimes) => [...runtimes.filter((item) => item.key !== runtime.key || item.spaceId !== runtime.spaceId), runtime]);
42
+ export const forgetHostRuntime = (key, spaceId, path = hostRuntimesPath()) => update(path, (runtimes) => runtimes.filter((item) => item.key !== key || item.spaceId !== spaceId));
@@ -0,0 +1,2 @@
1
+ export type HostEmit = (name: string, payload?: unknown) => void;
2
+ export declare function serveHost(entry?: string): Promise<void>;
@@ -0,0 +1,73 @@
1
+ import { createInterface } from "node:readline";
2
+ import { fileURLToPath } from "node:url";
3
+ import { HOST_BRIDGE_ERROR, HOST_BRIDGE_METHODS, HOST_SERVICE_VERSION, hostBridgeRequestSchema, } from "@neta-art/cohub/host-bridge";
4
+ import { currentIdentityKey } from "../space.js";
5
+ import { HostAuth } from "./auth.js";
6
+ import { loginShellEnv } from "./login-env.js";
7
+ import { DeviceRuntimeHost } from "./runtime.js";
8
+ const CAPABILITIES = ["auth.token", "auth.signIn", "auth.session", "runtime"];
9
+ const MAX_LINE = 1024 * 1024;
10
+ const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
11
+ export async function serveHost(entry = fileURLToPath(new URL("../../bin/cohub.js", import.meta.url))) {
12
+ const emit = (name, payload) => write({ type: "event", name, ...(payload === undefined ? {} : { payload }) });
13
+ let environment = null;
14
+ const runtime = new DeviceRuntimeHost(emit, {
15
+ cli: entry,
16
+ env: () => (environment ??= loginShellEnv()),
17
+ account: currentIdentityKey,
18
+ });
19
+ const auth = new HostAuth(emit, () => {
20
+ runtime.changed();
21
+ void runtime.restore();
22
+ });
23
+ const handlers = {
24
+ "auth.getAccessToken": (params) => auth.accessToken(params.forceRefresh === true),
25
+ "auth.getSessionVersion": () => auth.sessionVersion(),
26
+ "auth.getSession": () => auth.session(),
27
+ "auth.signIn": (params) => auth.signIn(typeof params.redirectPath === "string" ? params.redirectPath : undefined),
28
+ "auth.signOut": () => auth.signOut(),
29
+ "runtime.list": () => runtime.list(),
30
+ "runtime.browse": (params) => runtime.browse(typeof params.path === "string" ? params.path : undefined),
31
+ "runtime.start": (params) => runtime.connect(String(params.spaceId), String(params.root)),
32
+ "runtime.stop": (params) => runtime.disconnect(String(params.spaceId)),
33
+ };
34
+ const methods = Object.keys(handlers);
35
+ const answer = async (line) => {
36
+ let raw;
37
+ try {
38
+ raw = JSON.parse(line);
39
+ }
40
+ catch {
41
+ return;
42
+ }
43
+ const request = hostBridgeRequestSchema.safeParse(raw);
44
+ if (!request.success)
45
+ return;
46
+ const { id, method } = request.data;
47
+ 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
+ const name = method;
51
+ const shape = HOST_BRIDGE_METHODS[name];
52
+ const params = shape.params.safeParse(request.data.params);
53
+ if (!params.success)
54
+ return fail(HOST_BRIDGE_ERROR.failed, `Invalid params for ${method}`);
55
+ try {
56
+ const result = await handlers[name]((params.data ?? {}));
57
+ write({ type: "response", id, result: shape.result.parse(result) });
58
+ }
59
+ catch (error) {
60
+ fail(HOST_BRIDGE_ERROR.failed, error instanceof Error ? error.message : String(error));
61
+ }
62
+ };
63
+ const hello = { type: "hello", version: HOST_SERVICE_VERSION, capabilities: [...CAPABILITIES], methods };
64
+ write(hello);
65
+ auth.watch();
66
+ runtime.watch();
67
+ const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
68
+ input.on("line", (line) => { if (line.length <= MAX_LINE)
69
+ void answer(line); });
70
+ await new Promise((resolve) => input.once("close", resolve));
71
+ auth.close();
72
+ runtime.close();
73
+ }
package/dist/index.js CHANGED
@@ -22,6 +22,7 @@ import { maybeHandleRunCommand, printRunHelp } from "./commands/run.js";
22
22
  import { registerRuntime } from "./commands/runtime.js";
23
23
  import { registerTasks } from "./commands/tasks.js";
24
24
  import { registerDesktop, registerLegacyUi } from "./commands/desktop.js";
25
+ import { registerHost } from "./commands/host.js";
25
26
  import { registerApps } from "./commands/apps.js";
26
27
  import { registerRooms } from "./commands/rooms.js";
27
28
  import { formatUnknownCommandError, resolveHelpPath } from "./help-path.js";
@@ -113,6 +114,7 @@ registerRooms(program);
113
114
  registerFeedback(program);
114
115
  registerDesktop(program);
115
116
  registerLegacyUi(program);
117
+ registerHost(program);
116
118
  const argv = process.argv.slice(2);
117
119
  const help = resolveHelpPath(program, argv);
118
120
  if (help.kind === "help") {
@@ -6,6 +6,9 @@ export type RuntimeConnectionOptions = {
6
6
  cwd: string;
7
7
  url: string;
8
8
  capabilities: RuntimeCapabilities;
9
+ /** Rediscovers the catalog; a change is published to the registration without restarting. */
10
+ refreshCapabilities?: (current: RuntimeCapabilities) => Promise<RuntimeCapabilities>;
11
+ capabilitiesRefreshMs?: number;
9
12
  token: (forceRefresh?: boolean) => Promise<string>;
10
13
  signal: AbortSignal;
11
14
  executor: Executor;
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { setTimeout as delay } from "node:timers/promises";
3
- import { RUNTIME_MAX_FRAME_BYTES, RUNTIME_PROTOCOL_VERSION, runtimeCommandSchema, runtimeReadySchema, runtimeNativeStopSchema, } from "@neta-art/cohub";
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
5
  import { describeError } from "../network-error.js";
5
6
  import { executeTurn } from "./native/execution.js";
6
7
  import { ContextRequiredError } from "./native/results.js";
@@ -17,6 +18,7 @@ export async function serveRuntime(options) {
17
18
  const executions = new Map();
18
19
  const seen = new Set();
19
20
  const announce = { current: null };
21
+ const catalog = { current: options.capabilities, publish: null };
20
22
  const uploads = new AbortController();
21
23
  const uploadSignal = AbortSignal.any([options.signal, uploads.signal]);
22
24
  const log = (level, event, data, context) => options.diagnostics?.log(level, event, data, context);
@@ -29,6 +31,29 @@ export async function serveRuntime(options) {
29
31
  const timer = setInterval(() => {
30
32
  void flush();
31
33
  }, 10_000);
34
+ let refreshing = false;
35
+ const refreshCatalog = async () => {
36
+ if (!options.refreshCapabilities || refreshing || options.signal.aborted)
37
+ return;
38
+ refreshing = true;
39
+ try {
40
+ const next = await options.refreshCapabilities(catalog.current);
41
+ // The Gateway closes a Runtime that sends an invalid frame; an invalid catalog stays local.
42
+ runtimeCapabilitiesSchema.parse(next);
43
+ if (options.signal.aborted || isDeepStrictEqual(next, catalog.current))
44
+ return;
45
+ catalog.current = next;
46
+ log("info", "runtime.catalog_changed", { harnesses: next.harnesses, modelCount: next.models.length });
47
+ catalog.publish?.();
48
+ }
49
+ catch (error) {
50
+ log("warn", "runtime.catalog_refresh_failed", { error: serializeDiagnosticError(error) });
51
+ }
52
+ finally {
53
+ refreshing = false;
54
+ }
55
+ };
56
+ const catalogTimer = options.refreshCapabilities ? setInterval(() => { void refreshCatalog(); }, options.capabilitiesRefreshMs ?? 60 * 60_000) : undefined;
32
57
  void flush();
33
58
  log("info", "runtime.started", {
34
59
  runtimeId,
@@ -49,6 +74,7 @@ export async function serveRuntime(options) {
49
74
  executions,
50
75
  seen,
51
76
  announce,
77
+ catalog,
52
78
  onReady: () => {
53
79
  readyAt = Date.now();
54
80
  conflictSince = null;
@@ -91,6 +117,7 @@ export async function serveRuntime(options) {
91
117
  }
92
118
  }
93
119
  finally {
120
+ clearInterval(catalogTimer);
94
121
  for (const execution of executions.values())
95
122
  execution.controller.abort();
96
123
  await Promise.allSettled([...executions.values()].map((entry) => entry.promise));
@@ -179,6 +206,29 @@ async function connect(options) {
179
206
  socket.send(data);
180
207
  };
181
208
  const closeTransport = () => socket.close();
209
+ /** What the Gateway holds for this connection. */
210
+ let registered = null;
211
+ let capabilitiesFrame = false;
212
+ // A Gateway without the update frame learns a changed catalog from the next hello.
213
+ const publishCatalog = () => {
214
+ const current = options.catalog.current;
215
+ if (!connectionId || isDeepStrictEqual(registered, capabilitiesFrame ? current : runtimeHelloCapabilities(current)))
216
+ return;
217
+ if (!capabilitiesFrame) {
218
+ log("info", "runtime.catalog_reconnect", undefined, { connectionId });
219
+ closeTransport();
220
+ return;
221
+ }
222
+ try {
223
+ send({ type: "runtime.capabilities", capabilities: current });
224
+ registered = current;
225
+ log("info", "runtime.catalog_published", { modelCount: current.models.length }, { connectionId });
226
+ }
227
+ catch (error) {
228
+ log("warn", "runtime.catalog_publish_failed", { error: serializeDiagnosticError(error) }, { connectionId });
229
+ closeTransport();
230
+ }
231
+ };
182
232
  const shutdown = () => {
183
233
  for (const execution of active.values())
184
234
  execution.controller.abort();
@@ -311,6 +361,8 @@ async function connect(options) {
311
361
  const executionMustStop = options.signal.aborted || fatal || conflict;
312
362
  if (options.announce.current === announceHere)
313
363
  options.announce.current = null;
364
+ if (options.catalog.publish === publishCatalog)
365
+ options.catalog.publish = null;
314
366
  for (const [requestId, execution] of active) {
315
367
  if (executionMustStop) {
316
368
  log("error", "runtime.execution_transport_invalidated", { code: event.code, reason: event.reason }, executionContext(connectionId, execution));
@@ -354,12 +406,13 @@ async function connect(options) {
354
406
  attempt: options.attempt,
355
407
  durationMs: Date.now() - connectedAt,
356
408
  });
409
+ registered = runtimeHelloCapabilities(options.catalog.current);
357
410
  send({
358
411
  type: "runtime.hello",
359
412
  version: RUNTIME_PROTOCOL_VERSION,
360
413
  spaceId: options.spaceId,
361
414
  token: currentToken,
362
- capabilities: options.capabilities,
415
+ capabilities: registered,
363
416
  });
364
417
  }
365
418
  catch (error) {
@@ -394,9 +447,12 @@ async function connect(options) {
394
447
  detachedExecutions: [...active.values()].filter((entry) => entry.detached).length,
395
448
  }, { connectionId });
396
449
  nativeChannelReady = true;
450
+ capabilitiesFrame = frame.features?.includes("capabilities") === true;
397
451
  options.onNativeChannel?.(sendNative);
398
452
  options.onReady();
399
453
  options.announce.current = announceHere;
454
+ options.catalog.publish = publishCatalog;
455
+ publishCatalog();
400
456
  let recoveryBatch = 0;
401
457
  for await (const executions of options.executor.results.pendingBatches()) {
402
458
  recoveryBatch += 1;
@@ -548,7 +604,7 @@ async function connect(options) {
548
604
  })();
549
605
  return;
550
606
  }
551
- if (frame.input.spaceId !== options.spaceId || !options.capabilities.harnesses.includes(frame.input.harness))
607
+ if (frame.input.spaceId !== options.spaceId || !options.catalog.current.harnesses.includes(frame.input.harness))
552
608
  throw new Error("Invalid Runtime target");
553
609
  const context = executionContext(connectionId, frame.input);
554
610
  log("info", "runtime.turn_received", {
@@ -109,14 +109,20 @@ function claudeModelCatalog(entries, baseUrl) {
109
109
  export const claudeHarness = {
110
110
  id: "claude",
111
111
  binary: profile.binary,
112
- async models(executable, cwd) {
112
+ async models(executable, cwd, options) {
113
113
  await streamJsonHelp(profile, executable, cwd);
114
114
  try {
115
115
  const models = claudeModelCatalog(array((await claudeInitialize(executable, cwd)).models), process.env.ANTHROPIC_BASE_URL);
116
116
  if (models.some((model) => model.isDefault))
117
117
  return models;
118
+ if (options?.strict)
119
+ throw new Error("Claude Code initialize lists no default model");
120
+ }
121
+ catch (error) {
122
+ // A CLI without the initialize model list keeps the account aliases.
123
+ if (options?.strict)
124
+ throw error;
118
125
  }
119
- catch { /* A CLI without the initialize model list keeps the account aliases. */ }
120
126
  // Aliases follow the signed-in account; Haiku takes no effort level.
121
127
  return [
122
128
  streamJsonModel(profile, DEFAULT_MODEL, "Default", { reasoning: true, isDefault: true }),
@@ -12,3 +12,5 @@ export declare function installedHarnesses(cwd: string, executables: HarnessExec
12
12
  * and left out instead, so auto-discovery still starts with the ones that work.
13
13
  */
14
14
  export declare function discoverHarnesses(harnesses: LocalHarness[], executables: HarnessExecutables, cwd: string, onUnavailable?: (harness: LocalHarness, error: unknown) => void): Promise<RuntimeCapabilities>;
15
+ /** Rediscover the running harnesses' models; a harness that fails keeps its previous models. */
16
+ export declare function refreshHarnesses(current: RuntimeCapabilities, executables: HarnessExecutables, cwd: string, onUnavailable: (harness: LocalHarness, error: unknown) => void): Promise<RuntimeCapabilities>;
@@ -49,3 +49,16 @@ export async function discoverHarnesses(harnesses, executables, cwd, onUnavailab
49
49
  const available = catalogs.filter((catalog) => catalog !== null);
50
50
  return { harnesses: available.map((catalog) => catalog.harness), models: available.flatMap((catalog) => catalog.models) };
51
51
  }
52
+ /** Rediscover the running harnesses' models; a harness that fails keeps its previous models. */
53
+ export async function refreshHarnesses(current, executables, cwd, onUnavailable) {
54
+ const catalogs = await Promise.all(current.harnesses.map(async (harness) => {
55
+ try {
56
+ return await adapters()[harness].models(harnessExecutable(harness, executables), cwd, { strict: true });
57
+ }
58
+ catch (error) {
59
+ onUnavailable(harness, error);
60
+ return current.models.filter((model) => model.harness === harness);
61
+ }
62
+ }));
63
+ return { harnesses: current.harnesses, models: catalogs.flat() };
64
+ }
@@ -1,4 +1,4 @@
1
- import type { ContentBlock, RuntimeMessage, RuntimeTurnInput } from "@neta-art/cohub";
1
+ import { type ContentBlock, type RuntimeMessage, type RuntimeTurnInput } from "@neta-art/cohub";
2
2
  import type { Executor } from "../native/execution.js";
3
3
  import type { HarnessModel, HarnessRun, HarnessTurn } from "./types.js";
4
4
  /** Runs without `--model`, so the CLI's own configuration and account default apply. */
@@ -12,7 +12,7 @@ export type StreamJsonProfile = {
12
12
  /** Root holding `projects/<project>/<session>.jsonl`. */
13
13
  dataRoot(): string;
14
14
  projectDirectory(cwd: string): string;
15
- /** Thinking levels accepted by `--effort`. */
15
+ /** Thinking levels offered when the CLI does not list a model's own. */
16
16
  effortLevels: readonly string[];
17
17
  /** The CLI keeps a stream-json prompt's `uuid` as its record id, so the file names the Cohub Turn. */
18
18
  promptUuid: boolean;
@@ -4,6 +4,7 @@ import { createReadStream } from "node:fs";
4
4
  import { access, readdir } from "node:fs/promises";
5
5
  import { join } from "node:path";
6
6
  import { promisify } from "node:util";
7
+ import { isModelThinkingLevel, thinkingLevelMapFor } from "@neta-art/cohub";
7
8
  import { JsonRpcProcess, record } from "../json-rpc.js";
8
9
  import { describeError } from "../../network-error.js";
9
10
  import { array, closeHost, harnessCommand, identifiable, inlineImage, missing, text, turnEnvironment, watchHost } from "./process.js";
@@ -18,7 +19,6 @@ const FLUSH_TIMEOUT_MS = 10_000;
18
19
  const READ_ONLY_TOOLS = "Read,Glob,Grep";
19
20
  /** Flags every Turn relies on; an executable whose help lacks one is an older or unrelated CLI. */
20
21
  const REQUIRED_FLAGS = ["--input-format", "--output-format", "--include-partial-messages", "--session-id", "--resume", "--permission-mode", "--tools", "--strict-mcp-config", "--model", "--effort"];
21
- const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
22
22
  /** Runs without `--model`, so the CLI's own configuration and account default apply. */
23
23
  export const DEFAULT_MODEL = "default";
24
24
  /** The CLI's help, after checking it offers every flag a Turn uses. */
@@ -34,7 +34,8 @@ export function streamJsonModel(profile, id, name, options) {
34
34
  return {
35
35
  harness: profile.harness, provider: options.provider ?? profile.provider, id, name,
36
36
  ...(options.isDefault ? { isDefault: true } : {}),
37
- ...(options.reasoning ? { reasoning: true, thinkingLevelMap: Object.fromEntries(THINKING_LEVELS.map((level) => [level, effortLevels.includes(level) ? level : null])) } : {}),
37
+ // An explicit `reasoning: false` lets Cohub fit any requested level to `off`, so no `--effort` is sent.
38
+ ...(options.reasoning ? { reasoning: true, thinkingLevelMap: thinkingLevelMapFor((level) => effortLevels.includes(level) ? level : null) } : { reasoning: false }),
38
39
  };
39
40
  }
40
41
  /** A session's file is found by id; the project directory naming is only the fast path. */
@@ -219,7 +220,8 @@ export async function runStreamJson(profile, executor, turn) {
219
220
  if (profile.promptUuid && prepared.resume === "native" && await holdsPrompt(prepared.session.path, input.turnId, signal))
220
221
  prepared = await prepare(() => false);
221
222
  let session = prepared.session;
222
- const effort = input.thinkingLevel && profile.effortLevels.includes(input.thinkingLevel) ? input.thinkingLevel : null;
223
+ // Cohub has already fitted the level to the levels the model declares; these CLIs have no `off` effort.
224
+ const effort = isModelThinkingLevel(input.thinkingLevel) && input.thinkingLevel !== "off" ? input.thinkingLevel : null;
223
225
  const args = [
224
226
  "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages",
225
227
  ...(prepared.resume === "new" ? ["--session-id", session.nativeSessionId] : ["--resume", session.nativeSessionId]),
@@ -104,8 +104,10 @@ export type LocalHarnessAdapter = {
104
104
  id: LocalHarness;
105
105
  /** Executable looked up on PATH unless overridden. */
106
106
  binary: string;
107
- /** Fails when the harness cannot run. */
108
- models(executable: string, cwd: string): Promise<HarnessModel[]>;
107
+ /** Fails when the harness cannot run; with `strict`, also instead of falling back to a reduced catalog. */
108
+ models(executable: string, cwd: string, options?: {
109
+ strict?: boolean;
110
+ }): Promise<HarnessModel[]>;
109
111
  run(executor: Executor, turn: HarnessTurn): Promise<HarnessRun>;
110
112
  session: NativeSessionFormat;
111
113
  /** Every harness reads its own transcripts, so terminal conversations sync to the Space. */
@@ -9,7 +9,13 @@ export declare function workbuddyModels(help: string): {
9
9
  name: string;
10
10
  isDefault?: boolean | undefined;
11
11
  reasoning?: boolean | undefined;
12
- defaultThinkingLevel?: "high" | "low" | "max" | "medium" | "minimal" | "off" | "xhigh" | undefined;
13
- thinkingLevelMap?: Partial<Record<"high" | "low" | "max" | "medium" | "minimal" | "off" | "xhigh", string | null>> | undefined;
12
+ defaultThinkingLevel?: "high" | "low" | "max" | "medium" | "minimal" | "off" | "ultra" | "xhigh" | undefined;
13
+ thinkingLevelMap?: Partial<Record<"high" | "low" | "max" | "medium" | "minimal" | "off" | "ultra" | "xhigh", string | null>> | undefined;
14
+ serviceTiers?: {
15
+ id: string;
16
+ name: string;
17
+ description?: string | undefined;
18
+ }[] | undefined;
19
+ defaultServiceTier?: string | undefined;
14
20
  }[];
15
21
  export declare const workbuddyHarness: LocalHarnessAdapter;
@@ -1,4 +1,5 @@
1
1
  import type { RuntimeSummary } from "./presentation.js";
2
+ export declare function runtimeInstancesRoot(): string;
2
3
  export declare function runtimeInstanceDirectory(identity: string, spaceId: string): string;
3
4
  type Response = {
4
5
  status: RuntimeSummary;
@@ -7,6 +8,12 @@ type Response = {
7
8
  export declare function requestRuntimeInstance(directory: string, action?: "status" | "stop", force?: boolean): Promise<RuntimeSummary | null>;
8
9
  /** Send a control action to the running Runtime; `null` when none runs. */
9
10
  export declare function controlRuntimeInstance(directory: string, action: string, payload?: Record<string, unknown>, timeoutMs?: number): Promise<Response | null>;
11
+ export declare function stopRuntimeInstance(directory: string, force?: boolean): Promise<RuntimeSummary | null>;
12
+ export declare function watchRuntimeInstance(directory: string, onStatus: (status: RuntimeSummary) => void, signal?: AbortSignal): Promise<boolean>;
13
+ export type RuntimeInstanceHandle = {
14
+ changed(): void;
15
+ close(): Promise<void>;
16
+ };
10
17
  /** Private local IPC is both the single-instance guard and the control surface. */
11
- export declare function ownRuntimeInstance(directory: string, status: () => RuntimeSummary, stop: (force: boolean) => Promise<void>, control?: (action: string, message: Record<string, unknown>) => Promise<unknown>): Promise<() => Promise<void>>;
18
+ export declare function ownRuntimeInstance(directory: string, status: () => RuntimeSummary, stop: (force: boolean) => Promise<void>, control?: (action: string, message: Record<string, unknown>) => Promise<unknown>): Promise<RuntimeInstanceHandle>;
12
19
  export {};
@@ -3,10 +3,15 @@ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"
3
3
  import { createConnection, createServer } from "node:net";
4
4
  import { homedir } from "node:os";
5
5
  import { join } from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
6
7
  import { withRuntimeSpaceBindingsLock } from "./space-binding.js";
8
+ const MAX_WATCHERS = 16;
9
+ export function runtimeInstancesRoot() {
10
+ return join(homedir(), ".local", "state", "cohub", "instances");
11
+ }
7
12
  export function runtimeInstanceDirectory(identity, spaceId) {
8
13
  const key = createHash("sha256").update(`${identity}\0${spaceId}`).digest("hex").slice(0, 24);
9
- return join(homedir(), ".local", "state", "cohub", "instances", key);
14
+ return join(runtimeInstancesRoot(), key);
10
15
  }
11
16
  function alive(pid) {
12
17
  if (!Number.isSafeInteger(pid) || pid <= 0)
@@ -94,6 +99,61 @@ export async function controlRuntimeInstance(directory, action, payload = {}, ti
94
99
  throw error;
95
100
  }
96
101
  }
102
+ export async function stopRuntimeInstance(directory, force = false) {
103
+ const local = await requestRuntimeInstance(directory, "stop", force);
104
+ const until = Date.now() + 15_000;
105
+ let running = Boolean(local);
106
+ while (running && Date.now() < until) {
107
+ await delay(250);
108
+ try {
109
+ running = Boolean(await requestRuntimeInstance(directory));
110
+ }
111
+ catch {
112
+ running = true;
113
+ } // An unreachable control socket does not prove the process stopped.
114
+ }
115
+ if (running)
116
+ throw new Error("Runtime is still stopping; inspect logs");
117
+ return local;
118
+ }
119
+ export async function watchRuntimeInstance(directory, onStatus, signal) {
120
+ const record = await readRecord(directory).catch(() => null);
121
+ if (!record || !alive(record.pid) || signal?.aborted)
122
+ return false;
123
+ let streamed = false;
124
+ await new Promise((resolve) => {
125
+ const socket = createConnection(record.socket);
126
+ const abort = () => socket.destroy();
127
+ let buffer = "";
128
+ signal?.addEventListener("abort", abort, { once: true });
129
+ socket.on("connect", () => socket.write(`${JSON.stringify({ action: "watch", nonce: record.nonce })}\n`));
130
+ socket.on("data", (chunk) => {
131
+ buffer += chunk.toString();
132
+ for (let end = buffer.indexOf("\n"); end >= 0; end = buffer.indexOf("\n")) {
133
+ const line = buffer.slice(0, end);
134
+ buffer = buffer.slice(end + 1);
135
+ try {
136
+ const response = JSON.parse(line);
137
+ if (response.nonce !== record.nonce || response.status?.pid !== record.pid) {
138
+ socket.destroy();
139
+ return;
140
+ }
141
+ streamed = true;
142
+ onStatus(response.status);
143
+ }
144
+ catch {
145
+ socket.destroy();
146
+ return;
147
+ }
148
+ }
149
+ if (buffer.length > 64 * 1024)
150
+ socket.destroy();
151
+ });
152
+ socket.on("error", () => socket.destroy());
153
+ socket.on("close", () => { signal?.removeEventListener("abort", abort); resolve(); });
154
+ });
155
+ return streamed;
156
+ }
97
157
  /** Private local IPC is both the single-instance guard and the control surface. */
98
158
  export async function ownRuntimeInstance(directory, status, stop, control = async () => { throw new Error("Unknown Runtime control request"); }) {
99
159
  await mkdir(directory, { recursive: true, mode: 0o700 });
@@ -107,11 +167,13 @@ export async function ownRuntimeInstance(directory, status, stop, control = asyn
107
167
  await rm(socketPath, { force: true });
108
168
  const record = { pid: process.pid, nonce: randomUUID(), socket: socketPath };
109
169
  const clients = new Set();
170
+ const watchers = new Set();
171
+ const statusLine = () => `${JSON.stringify({ nonce: record.nonce, status: status() })}\n`;
110
172
  const server = createServer((socket) => {
111
173
  clients.add(socket);
112
174
  socket.setTimeout(3000, () => socket.destroy());
113
175
  socket.on("error", () => socket.destroy());
114
- socket.on("close", () => clients.delete(socket));
176
+ socket.on("close", () => { clients.delete(socket); watchers.delete(socket); });
115
177
  let input = "";
116
178
  socket.on("data", (chunk) => {
117
179
  input += chunk.toString();
@@ -130,6 +192,15 @@ export async function ownRuntimeInstance(directory, status, stop, control = asyn
130
192
  socket.destroy();
131
193
  return;
132
194
  }
195
+ if (message.action === "watch") {
196
+ if (watchers.size >= MAX_WATCHERS) {
197
+ socket.destroy();
198
+ return;
199
+ }
200
+ watchers.add(socket);
201
+ socket.write(statusLine());
202
+ return;
203
+ }
133
204
  let result;
134
205
  if (message.action === "stop")
135
206
  await stop(message.force === true);
@@ -154,13 +225,22 @@ export async function ownRuntimeInstance(directory, status, stop, control = asyn
154
225
  server.close();
155
226
  throw error;
156
227
  }
157
- return async () => {
158
- for (const client of clients)
159
- client.destroy();
160
- await new Promise((resolve) => server.close(() => resolve()));
161
- // Never remove a replacement owner's files.
162
- if ((await readRecord(directory))?.nonce === record.nonce)
163
- await rm(join(directory, "owner.json"));
228
+ return {
229
+ changed: () => {
230
+ if (!watchers.size)
231
+ return;
232
+ const line = statusLine();
233
+ for (const watcher of watchers)
234
+ watcher.write(line);
235
+ },
236
+ close: async () => {
237
+ for (const client of clients)
238
+ client.destroy();
239
+ await new Promise((resolve) => server.close(() => resolve()));
240
+ // Never remove a replacement owner's files.
241
+ if ((await readRecord(directory))?.nonce === record.nonce)
242
+ await rm(join(directory, "owner.json"));
243
+ },
164
244
  };
165
245
  }, { path: join(directory, "owner.json") });
166
246
  }
@@ -3,6 +3,7 @@ import { type HarnessExecutables } from "./harnesses/index.js";
3
3
  import type { Command } from "commander";
4
4
  import { type RuntimeSummary } from "./presentation.js";
5
5
  import { type RuntimeLaunch } from "./supervisor.js";
6
+ export declare const EXPECTED_IDENTITY_ENV = "COHUB_RUNTIME_EXPECTED_IDENTITY";
6
7
  export type RuntimeUpOptions = HarnessExecutables & {
7
8
  space?: string;
8
9
  new?: boolean;
@@ -15,6 +15,7 @@ import { ensureNativeSync, repairIntegrations } from "./native/attach.js";
15
15
  import { serializeDiagnosticError } from "./diagnostics.js";
16
16
  import { createDiagnosticConsole, printRuntimeSummary, runtimeWebUrl } from "./presentation.js";
17
17
  import { runRuntime } from "./supervisor.js";
18
+ export const EXPECTED_IDENTITY_ENV = "COHUB_RUNTIME_EXPECTED_IDENTITY";
18
19
  /** Executable overrides come from the per-harness `--<harness> <path>` options. */
19
20
  export const runtimeExecutables = (options) => Object.fromEntries(LOCAL_HARNESSES.flatMap((harness) => options[harness] ? [[harness, options[harness]]] : []));
20
21
  export const resolveLocalSpaceName = (root, name) => name?.trim() || basename(root) || "local-space";
@@ -123,6 +124,11 @@ export async function runtimeUp(program, dir, options) {
123
124
  await requireAccessToken();
124
125
  throw new Error("Cannot identify the signed-in account");
125
126
  }
127
+ // Consumed here, so the Runtime and the tools it runs never inherit it.
128
+ const expected = process.env[EXPECTED_IDENTITY_ENV];
129
+ delete process.env[EXPECTED_IDENTITY_ENV];
130
+ if (expected && expected !== identity)
131
+ throw new Error("The signed-in account changed");
126
132
  const binding = await getRuntimeSpaceBinding(root, identity);
127
133
  const existingId = requested || binding?.spaceId;
128
134
  let harnesses = parseRuntimeHarnesses(options.harness);
@@ -1,6 +1,5 @@
1
- import type { RuntimeCapabilities } from "@neta-art/cohub";
1
+ import { type RuntimeModel as Model } from "@neta-art/cohub";
2
2
  import { type JsonRecord } from "./json-rpc.js";
3
- type Model = RuntimeCapabilities["models"][number];
4
3
  /**
5
4
  * Publish only picker metadata, never provider credentials or request configuration.
6
5
  * `state` is a fresh Pi's `get_state`: its model is what Pi runs when Cohub requests
@@ -11,4 +10,3 @@ type Model = RuntimeCapabilities["models"][number];
11
10
  export declare function piModelCatalog(entries: unknown[], state: JsonRecord): Model[];
12
11
  /** Use Codex's picker-visible model/list for every provider, including custom providers. */
13
12
  export declare function codexModelCatalog(configResponse: JsonRecord, entries: unknown[]): Model[];
14
- export {};