@neta-art/cohub-cli 10.14.0 → 10.15.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/dist/board-export.d.ts +7 -0
- package/dist/board-export.js +3 -3
- package/dist/board-kernel.d.ts +1 -0
- package/dist/board-kernel.js +7605 -277
- package/dist/board-simulate.d.ts +53 -0
- package/dist/board-simulate.js +151 -0
- package/dist/commands/boards.js +68 -0
- package/dist/commands/spaces.js +13 -13
- package/dist/runtime/connection.d.ts +3 -0
- package/dist/runtime/connection.js +59 -3
- package/dist/runtime/harnesses/claude.js +8 -2
- package/dist/runtime/harnesses/index.d.ts +2 -0
- package/dist/runtime/harnesses/index.js +13 -0
- package/dist/runtime/harnesses/stream-json.d.ts +2 -2
- package/dist/runtime/harnesses/stream-json.js +5 -3
- package/dist/runtime/harnesses/types.d.ts +4 -2
- package/dist/runtime/harnesses/workbuddy.d.ts +8 -2
- package/dist/runtime/model-catalog.d.ts +1 -3
- package/dist/runtime/model-catalog.js +23 -7
- package/dist/runtime/supervisor.js +2 -1
- package/package.json +3 -3
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { BoardExportRegion, BoardThemeId } from "@neta-art/cohub/board";
|
|
2
|
+
import type { BoardNodeExportFormat } from "@neta-art/cohub/board/export/node";
|
|
3
|
+
import type { BoardScriptHarnessPointer } from "@neta-art/cohub/board/testing";
|
|
4
|
+
declare const TOOLS: readonly ["select", "hand", "text", "shape", "draw", "arrow", "frame"];
|
|
5
|
+
type Point = {
|
|
6
|
+
x: number;
|
|
7
|
+
y: number;
|
|
8
|
+
};
|
|
9
|
+
export type BoardSimulationStep = {
|
|
10
|
+
wait: number;
|
|
11
|
+
} | {
|
|
12
|
+
tool: (typeof TOOLS)[number];
|
|
13
|
+
} | {
|
|
14
|
+
tap: Point;
|
|
15
|
+
input: BoardScriptHarnessPointer;
|
|
16
|
+
} | {
|
|
17
|
+
drag: Point[];
|
|
18
|
+
input: BoardScriptHarnessPointer;
|
|
19
|
+
} | {
|
|
20
|
+
pointer: "down" | "move" | "up";
|
|
21
|
+
at: Point;
|
|
22
|
+
input: BoardScriptHarnessPointer;
|
|
23
|
+
} | {
|
|
24
|
+
key: string;
|
|
25
|
+
} | {
|
|
26
|
+
select: string[];
|
|
27
|
+
};
|
|
28
|
+
export declare function parseBoardSimulationSteps(value: unknown): BoardSimulationStep[];
|
|
29
|
+
export type BoardSimulationResult = {
|
|
30
|
+
time: number;
|
|
31
|
+
commits: number;
|
|
32
|
+
changes: Record<string, unknown>;
|
|
33
|
+
errors: Record<string, string>;
|
|
34
|
+
image?: {
|
|
35
|
+
bytes: Uint8Array;
|
|
36
|
+
width: number;
|
|
37
|
+
height: number;
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
export declare function runBoardSimulation(options: {
|
|
41
|
+
spaceId: string;
|
|
42
|
+
target: string;
|
|
43
|
+
steps: readonly BoardSimulationStep[];
|
|
44
|
+
leader: boolean;
|
|
45
|
+
image?: {
|
|
46
|
+
region: BoardExportRegion;
|
|
47
|
+
scale: number;
|
|
48
|
+
theme: BoardThemeId;
|
|
49
|
+
format: BoardNodeExportFormat;
|
|
50
|
+
withImages: boolean;
|
|
51
|
+
};
|
|
52
|
+
}): Promise<BoardSimulationResult>;
|
|
53
|
+
export {};
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { diffMergePatch } from "@neta-art/cohub/board";
|
|
2
|
+
import { loadBoardDocument, readSpaceFileBytes, resolveBundledFonts, runBoardExport } from "./board-export.js";
|
|
3
|
+
import { createBoardScriptHarness, createNodeBoardRenderer } from "./board-kernel.js";
|
|
4
|
+
import { settleBoardDocument } from "./board-media.js";
|
|
5
|
+
import { parseBoardTime } from "./board-time.js";
|
|
6
|
+
import { createClient } from "./client.js";
|
|
7
|
+
const TOOLS = ["select", "hand", "text", "shape", "draw", "arrow", "frame"];
|
|
8
|
+
const POINTER_TYPES = ["mouse", "pen", "touch"];
|
|
9
|
+
const MAX_STEPS = 10_000;
|
|
10
|
+
const MAX_TIME_MS = 600_000;
|
|
11
|
+
const FRAME_MS = 1000 / 60;
|
|
12
|
+
function point(value, name) {
|
|
13
|
+
if (!Array.isArray(value) || value.length !== 2 || !value.every((n) => typeof n === "number" && Number.isFinite(n)))
|
|
14
|
+
throw new Error(`${name} must be [x, y]`);
|
|
15
|
+
return { x: value[0], y: value[1] };
|
|
16
|
+
}
|
|
17
|
+
function pointerInput(step, name) {
|
|
18
|
+
const pointerType = step.pointerType ?? "mouse";
|
|
19
|
+
if (!POINTER_TYPES.includes(pointerType))
|
|
20
|
+
throw new Error(`${name}.pointerType must be one of ${POINTER_TYPES.join(", ")}`);
|
|
21
|
+
const input = { pointerType: pointerType };
|
|
22
|
+
for (const key of ["shiftKey", "altKey", "ctrlKey", "metaKey"]) {
|
|
23
|
+
if (step[key] === undefined)
|
|
24
|
+
continue;
|
|
25
|
+
if (typeof step[key] !== "boolean")
|
|
26
|
+
throw new Error(`${name}.${key} must be a boolean`);
|
|
27
|
+
input[key] = step[key];
|
|
28
|
+
}
|
|
29
|
+
return input;
|
|
30
|
+
}
|
|
31
|
+
export function parseBoardSimulationSteps(value) {
|
|
32
|
+
if (!Array.isArray(value))
|
|
33
|
+
throw new Error("steps must be an array");
|
|
34
|
+
if (value.length > MAX_STEPS)
|
|
35
|
+
throw new Error(`steps exceed the limit of ${MAX_STEPS}`);
|
|
36
|
+
const steps = value.map(parseStep);
|
|
37
|
+
const elapsed = steps.reduce((total, step) => total + ("wait" in step ? step.wait : "tap" in step ? 2 * FRAME_MS : "drag" in step ? (step.drag.length + 1) * FRAME_MS : "pointer" in step ? FRAME_MS : 0), 0);
|
|
38
|
+
if (elapsed > MAX_TIME_MS)
|
|
39
|
+
throw new Error(`steps exceed ${MAX_TIME_MS / 60_000} minutes of simulated time`);
|
|
40
|
+
return steps;
|
|
41
|
+
}
|
|
42
|
+
function parseStep(entry, index) {
|
|
43
|
+
const name = `steps[${index}]`;
|
|
44
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
45
|
+
throw new Error(`${name} must be an object`);
|
|
46
|
+
const step = entry;
|
|
47
|
+
if ("wait" in step) {
|
|
48
|
+
const wait = typeof step.wait === "number" ? step.wait : parseBoardTime(String(step.wait), `${name}.wait`);
|
|
49
|
+
if (!Number.isFinite(wait) || wait < 0)
|
|
50
|
+
throw new Error(`${name}.wait must not be negative`);
|
|
51
|
+
return { wait };
|
|
52
|
+
}
|
|
53
|
+
if ("tool" in step) {
|
|
54
|
+
if (!TOOLS.includes(step.tool))
|
|
55
|
+
throw new Error(`${name}.tool must be one of ${TOOLS.join(", ")}`);
|
|
56
|
+
return { tool: step.tool };
|
|
57
|
+
}
|
|
58
|
+
if ("tap" in step)
|
|
59
|
+
return { tap: point(step.tap, `${name}.tap`), input: pointerInput(step, name) };
|
|
60
|
+
if ("drag" in step) {
|
|
61
|
+
if (!Array.isArray(step.drag) || step.drag.length < 2)
|
|
62
|
+
throw new Error(`${name}.drag must list at least two points`);
|
|
63
|
+
return { drag: step.drag.map((entry, at) => point(entry, `${name}.drag[${at}]`)), input: pointerInput(step, name) };
|
|
64
|
+
}
|
|
65
|
+
if ("pointer" in step) {
|
|
66
|
+
if (step.pointer !== "down" && step.pointer !== "move" && step.pointer !== "up")
|
|
67
|
+
throw new Error(`${name}.pointer must be down, move or up`);
|
|
68
|
+
return { pointer: step.pointer, at: point(step.at, `${name}.at`), input: pointerInput(step, name) };
|
|
69
|
+
}
|
|
70
|
+
if ("key" in step) {
|
|
71
|
+
if (typeof step.key !== "string" || !step.key)
|
|
72
|
+
throw new Error(`${name}.key must be a key name`);
|
|
73
|
+
return { key: step.key };
|
|
74
|
+
}
|
|
75
|
+
if ("select" in step) {
|
|
76
|
+
if (!Array.isArray(step.select) || !step.select.every((id) => typeof id === "string"))
|
|
77
|
+
throw new Error(`${name}.select must list item ids`);
|
|
78
|
+
return { select: step.select };
|
|
79
|
+
}
|
|
80
|
+
throw new Error(`${name} must be one of wait, tool, tap, drag, pointer, key or select`);
|
|
81
|
+
}
|
|
82
|
+
async function run(harness, steps) {
|
|
83
|
+
for (const step of steps) {
|
|
84
|
+
if ("wait" in step)
|
|
85
|
+
await harness.advance(step.wait);
|
|
86
|
+
else if ("tool" in step)
|
|
87
|
+
harness.tool = step.tool;
|
|
88
|
+
else if ("tap" in step)
|
|
89
|
+
await harness.tap(step.tap, step.input);
|
|
90
|
+
else if ("drag" in step)
|
|
91
|
+
await harness.drag(step.drag, step.input);
|
|
92
|
+
else if ("pointer" in step)
|
|
93
|
+
await harness.pointer(step.pointer, step.at, step.input);
|
|
94
|
+
else if ("key" in step) {
|
|
95
|
+
await harness.key("keydown", step.key);
|
|
96
|
+
await harness.key("keyup", step.key);
|
|
97
|
+
}
|
|
98
|
+
else
|
|
99
|
+
await harness.select(step.select);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
export async function runBoardSimulation(options) {
|
|
103
|
+
const client = createClient();
|
|
104
|
+
const document = await settleBoardDocument(options.spaceId, (await loadBoardDocument(options.spaceId, options.target)).document);
|
|
105
|
+
const renderer = await createNodeBoardRenderer({ fonts: resolveBundledFonts() });
|
|
106
|
+
const harness = await createBoardScriptHarness({
|
|
107
|
+
document,
|
|
108
|
+
renderer,
|
|
109
|
+
leader: options.leader,
|
|
110
|
+
readModule: async (path) => new TextDecoder().decode((await readSpaceFileBytes(client, options.spaceId, path)).bytes),
|
|
111
|
+
});
|
|
112
|
+
try {
|
|
113
|
+
await run(harness, options.steps);
|
|
114
|
+
await harness.flush();
|
|
115
|
+
const shown = options.image ? await harness.shown(options.image.scale) : null;
|
|
116
|
+
const errors = {};
|
|
117
|
+
for (const [id, item] of Object.entries(harness.document.items)) {
|
|
118
|
+
const message = item.script?.enabled ? harness.error(id) : null;
|
|
119
|
+
if (message)
|
|
120
|
+
errors[id] = message;
|
|
121
|
+
}
|
|
122
|
+
const result = {
|
|
123
|
+
time: Math.round(harness.time),
|
|
124
|
+
commits: harness.commits.length,
|
|
125
|
+
changes: diffMergePatch(document, harness.document) ?? {},
|
|
126
|
+
errors,
|
|
127
|
+
};
|
|
128
|
+
if (options.image && shown) {
|
|
129
|
+
const exported = await runBoardExport({
|
|
130
|
+
spaceId: options.spaceId,
|
|
131
|
+
target: options.target,
|
|
132
|
+
document: shown.document,
|
|
133
|
+
...(shown.scripts ? { scripts: shown.scripts } : {}),
|
|
134
|
+
region: options.image.region,
|
|
135
|
+
scale: options.image.scale,
|
|
136
|
+
theme: options.image.theme,
|
|
137
|
+
background: "paper",
|
|
138
|
+
format: options.image.format,
|
|
139
|
+
withImages: options.image.withImages,
|
|
140
|
+
});
|
|
141
|
+
const frame = exported?.frames[0];
|
|
142
|
+
if (frame)
|
|
143
|
+
result.image = { bytes: frame.bytes, width: frame.width, height: frame.height };
|
|
144
|
+
}
|
|
145
|
+
return result;
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
harness.destroy();
|
|
149
|
+
renderer.destroy();
|
|
150
|
+
}
|
|
151
|
+
}
|
package/dist/commands/boards.js
CHANGED
|
@@ -298,6 +298,73 @@ Examples:
|
|
|
298
298
|
}
|
|
299
299
|
});
|
|
300
300
|
}
|
|
301
|
+
function registerSimulateCommand(boards) {
|
|
302
|
+
withJson(boards.command("simulate <board> [steps]")
|
|
303
|
+
.description("Run a Board's scripts locally through input steps; nothing is saved")
|
|
304
|
+
.option("-i, --input <file>", "Steps JSON; - for stdin")
|
|
305
|
+
.option("-o, --out <file>", "Also render the result, screen UI included; the extension picks the format")
|
|
306
|
+
.option("--follower", "Simulate an editor that does not write autonomous commits")
|
|
307
|
+
.option("--frame <item-id>", "Render one frame")
|
|
308
|
+
.option("--items <ids>", "Render comma-separated item ids")
|
|
309
|
+
.option("--rect <rect>", "Render a world rect as x,y,width,height")
|
|
310
|
+
.option("--scale <factor>", "Output pixels per board unit", "2")
|
|
311
|
+
.option("--theme <name>", `Cohub theme: ${BOARD_THEME_IDS.join(", ")}`, "dark")
|
|
312
|
+
.option("--no-images", "Draw placeholders instead of downloading images")
|
|
313
|
+
.option("--force", "Replace an existing output file"))
|
|
314
|
+
.addHelpText("after", `
|
|
315
|
+
Steps are {"steps": [...]}, points in board coordinates, run on a virtual clock:
|
|
316
|
+
{"wait": "500ms"} {"tool": "draw"} {"tap": [x, y]} {"drag": [[x, y], ...], "pointerType": "pen"}
|
|
317
|
+
{"pointer": "down", "at": [x, y]} {"key": "Enter"} {"select": ["id"]}
|
|
318
|
+
|
|
319
|
+
Examples:
|
|
320
|
+
cohub boards simulate farm.board '{"steps":[{"wait":"2s"}]}' -o farm.png
|
|
321
|
+
cohub boards simulate farm.board -i steps.json --json`)
|
|
322
|
+
.action(async (target, inline, options) => {
|
|
323
|
+
try {
|
|
324
|
+
if (inline !== undefined && options.input !== undefined)
|
|
325
|
+
throw new Error("Pass steps inline or with --input, not both.");
|
|
326
|
+
const input = inline !== undefined
|
|
327
|
+
? parseBoardJsonObject(inline, "steps")
|
|
328
|
+
: options.input !== undefined ? await readBoardJsonObject(options.input) : { steps: [] };
|
|
329
|
+
const { parseBoardSimulationSteps, runBoardSimulation } = await import("../board-simulate.js");
|
|
330
|
+
const steps = parseBoardSimulationSteps(input.steps);
|
|
331
|
+
const out = options.out;
|
|
332
|
+
if (out && !options.force && existsSync(out))
|
|
333
|
+
throw new Error(`${out} already exists; use --force to replace it.`);
|
|
334
|
+
const result = await runBoardSimulation({
|
|
335
|
+
spaceId: await resolveSpace(boards),
|
|
336
|
+
target,
|
|
337
|
+
steps,
|
|
338
|
+
leader: !options.follower,
|
|
339
|
+
...(out ? { image: {
|
|
340
|
+
region: parseExportRegion(options),
|
|
341
|
+
scale: parseNumber(options.scale ?? "2", "--scale", { min: 0.01, max: 16 }),
|
|
342
|
+
theme: parseChoice(options.theme, "--theme", BOARD_THEME_IDS),
|
|
343
|
+
format: parseExportFormat(options, out),
|
|
344
|
+
withImages: options.images !== false,
|
|
345
|
+
} } : {}),
|
|
346
|
+
});
|
|
347
|
+
if (out && result.image) {
|
|
348
|
+
await mkdir(dirname(out), { recursive: true });
|
|
349
|
+
await writeBoardOutput(out, result.image.bytes, Boolean(options.force));
|
|
350
|
+
}
|
|
351
|
+
const { image, ...summary } = result;
|
|
352
|
+
if (jsonRequested(options))
|
|
353
|
+
return outJson({ ...summary, ...(out && image ? { file: out, width: image.width, height: image.height } : {}) });
|
|
354
|
+
const changed = Object.keys(result.changes.items ?? {}).length;
|
|
355
|
+
ok(`Simulated ${formatBoardTime(result.time)}: ${result.commits} commit${result.commits === 1 ? "" : "s"}, ${changed} item${changed === 1 ? "" : "s"} changed (not saved)`);
|
|
356
|
+
for (const [id, message] of Object.entries(result.errors))
|
|
357
|
+
console.log(` ! ${id}: ${message.split("\n")[0]}`);
|
|
358
|
+
if (out && image)
|
|
359
|
+
console.log(` Rendered ${image.width}×${image.height} to ${out}`);
|
|
360
|
+
else if (out)
|
|
361
|
+
console.log(" ! Nothing to render: the region contains no items.");
|
|
362
|
+
}
|
|
363
|
+
catch (cause) {
|
|
364
|
+
handleHttp(cause);
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
}
|
|
301
368
|
// ─── Commands ────────────────────────────────────────────────────────────────
|
|
302
369
|
export function registerBoards(program) {
|
|
303
370
|
const boards = program
|
|
@@ -535,6 +602,7 @@ Presets: ${BOARD_PRESET_NAMES.join(", ")}
|
|
|
535
602
|
});
|
|
536
603
|
registerBoardExampleCommands(boards);
|
|
537
604
|
registerExportCommand(boards);
|
|
605
|
+
registerSimulateCommand(boards);
|
|
538
606
|
registerBoardAuthoringCommands(boards);
|
|
539
607
|
registerPlaybackCommands(boards);
|
|
540
608
|
withJson(boards.command("watch <board>")
|
package/dist/commands/spaces.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readdir, stat } from "node:fs/promises";
|
|
2
2
|
import { basename, dirname, relative, resolve, sep } from "node:path";
|
|
3
|
-
import { harnessSchema, readSentTurns, readSessionTurnOrigin, resolveCohubEnvironment } from "@neta-art/cohub";
|
|
3
|
+
import { harnessSchema, isModelThinkingLevel, MODEL_THINKING_LEVELS, readSentTurns, readSessionTurnOrigin, resolveCohubEnvironment } from "@neta-art/cohub";
|
|
4
4
|
import { uploadAvatarAsset, uploadChatImageAsset } from "../avatar.js";
|
|
5
5
|
import { createClient } from "../client.js";
|
|
6
6
|
import { collectOption, readPromptContent } from "../command-input.js";
|
|
@@ -198,10 +198,10 @@ async function sendPrompt(command, words, opts) {
|
|
|
198
198
|
if (agentOnly.length)
|
|
199
199
|
return error("Conflicting options", `--note cannot be combined with ${agentOnly.join(", ")}`);
|
|
200
200
|
}
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
return error("Invalid thinking level",
|
|
201
|
+
const requestedThinkingLevel = opts.thinkingLevel?.trim() || undefined;
|
|
202
|
+
const thinkingLevel = isModelThinkingLevel(requestedThinkingLevel) ? requestedThinkingLevel : undefined;
|
|
203
|
+
if (requestedThinkingLevel && !thinkingLevel) {
|
|
204
|
+
return error("Invalid thinking level", `Use ${MODEL_THINKING_LEVELS.join("|")}`);
|
|
205
205
|
}
|
|
206
206
|
const spaceId = await resolveSpace(command, { home: true });
|
|
207
207
|
const client = createClient();
|
|
@@ -249,7 +249,7 @@ async function sendPrompt(command, words, opts) {
|
|
|
249
249
|
model: opts.model,
|
|
250
250
|
provider: opts.provider,
|
|
251
251
|
harness: opts.harness,
|
|
252
|
-
thinkingLevel
|
|
252
|
+
thinkingLevel,
|
|
253
253
|
accessMode: opts.readOnly ? "read_only" : "full_access",
|
|
254
254
|
intent: opts.steer ? "steer" : undefined,
|
|
255
255
|
env: parseEnvOptions(opts.env),
|
|
@@ -291,10 +291,10 @@ async function runCompletionCommand(command, words, opts) {
|
|
|
291
291
|
if (maxTokens !== undefined && (!Number.isFinite(maxTokens) || maxTokens <= 0)) {
|
|
292
292
|
return error("Invalid max tokens", "--max-tokens must be a positive number");
|
|
293
293
|
}
|
|
294
|
-
const
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
return error("Invalid thinking level",
|
|
294
|
+
const requestedThinkingLevel = opts.thinkingLevel?.trim() || undefined;
|
|
295
|
+
const thinkingLevel = isModelThinkingLevel(requestedThinkingLevel) ? requestedThinkingLevel : undefined;
|
|
296
|
+
if (requestedThinkingLevel && !thinkingLevel) {
|
|
297
|
+
return error("Invalid thinking level", `Use ${MODEL_THINKING_LEVELS.join("|")}`);
|
|
298
298
|
}
|
|
299
299
|
const client = createClient();
|
|
300
300
|
const input = {
|
|
@@ -304,7 +304,7 @@ async function runCompletionCommand(command, words, opts) {
|
|
|
304
304
|
messages: [{ role: "user", content: [{ type: "text", text }] }],
|
|
305
305
|
temperature,
|
|
306
306
|
maxTokens,
|
|
307
|
-
thinkingLevel
|
|
307
|
+
thinkingLevel,
|
|
308
308
|
};
|
|
309
309
|
try {
|
|
310
310
|
if (opts.stream) {
|
|
@@ -356,7 +356,7 @@ export function registerPrompt(program) {
|
|
|
356
356
|
.option("-m, --model <model>", "Model name")
|
|
357
357
|
.option("-p, --provider <provider>", "Provider name")
|
|
358
358
|
.option("--harness <harness>", `Harness: ${harnessSchema.options.join(", ")}`, "cohub")
|
|
359
|
-
.option("--thinking-level <level>",
|
|
359
|
+
.option("--thinking-level <level>", `Thinking level: ${MODEL_THINKING_LEVELS.join("|")}`)
|
|
360
360
|
.option("--read-only", "Use read-only tools")
|
|
361
361
|
.option("--steer", "Interrupt the current turn and run immediately")
|
|
362
362
|
.option("--delay-ms <ms>", "Delay sending by milliseconds")
|
|
@@ -720,7 +720,7 @@ export function registerSpaces(program) {
|
|
|
720
720
|
.option("--title <title>", "Title for a newly created session or schedule")
|
|
721
721
|
.option("-m, --model <model>", "Model name")
|
|
722
722
|
.option("-p, --provider <provider>", "Provider name")
|
|
723
|
-
.option("--thinking-level <level>",
|
|
723
|
+
.option("--thinking-level <level>", `Thinking level: ${MODEL_THINKING_LEVELS.join("|")}`)
|
|
724
724
|
.option("--read-only", "Use read-only tools")
|
|
725
725
|
.option("--steer", "Interrupt the current turn and run immediately")
|
|
726
726
|
.option("--delay-ms <ms>", "Delay sending by milliseconds")
|
|
@@ -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 {
|
|
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:
|
|
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.
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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,6 +1,5 @@
|
|
|
1
|
-
import type
|
|
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 {};
|