@ouro.bot/cli 0.1.0-alpha.1431 → 0.1.0-alpha.1432

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 (30) hide show
  1. package/changelog.json +12 -1
  2. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
  3. package/deploy/unraid/sanctuary.xml +1 -1
  4. package/dist/eval/interview-guest-entry.js +17 -0
  5. package/dist/eval/interviews/allocation.js +64 -0
  6. package/dist/eval/interviews/guest/arms.js +173 -0
  7. package/dist/eval/interviews/guest/ax/ax-command.js +792 -0
  8. package/dist/eval/interviews/guest/ax/effects.js +51 -0
  9. package/dist/eval/interviews/guest/ax/exit-codes.js +51 -0
  10. package/dist/eval/interviews/guest/ax/help.js +181 -0
  11. package/dist/eval/interviews/guest/ax/mcp.js +246 -0
  12. package/dist/eval/interviews/guest/ax/outcome.js +211 -0
  13. package/dist/eval/interviews/guest/ax/output.js +53 -0
  14. package/dist/eval/interviews/guest/ax/precise-copy.js +200 -0
  15. package/dist/eval/interviews/guest/ax/problem.js +95 -0
  16. package/dist/eval/interviews/guest/ax/voice.js +83 -0
  17. package/dist/eval/interviews/guest/ax/wait.js +158 -0
  18. package/dist/eval/interviews/guest/books-core.js +54 -0
  19. package/dist/eval/interviews/guest/cli-shell.js +267 -0
  20. package/dist/eval/interviews/guest/loop.js +78 -0
  21. package/dist/eval/interviews/guest/operations.js +108 -0
  22. package/dist/eval/interviews/guest/run.js +62 -0
  23. package/dist/eval/interviews/latch.js +122 -0
  24. package/dist/eval/interviews/protocol.js +77 -0
  25. package/dist/eval/remote-entry.js +2 -0
  26. package/dist/eval/sandbox/docker.js +23 -6
  27. package/dist/eval/sandbox/remote.js +2 -2
  28. package/dist/nerves/coverage/file-completeness.js +3 -0
  29. package/npm-shrinkwrap.json +2 -2
  30. package/package.json +1 -1
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WAIT_VERSION = exports.WAIT_STATES = exports.WAIT_FLAGS = exports.DEFAULT_WAIT_EXITS = void 0;
4
+ exports.formatDuration = formatDuration;
5
+ exports.isWait = isWait;
6
+ exports.parseDuration = parseDuration;
7
+ exports.validateWait = validateWait;
8
+ exports.wait = wait;
9
+ exports.waitExit = waitExit;
10
+ exports.waitFor = waitFor;
11
+ exports.waitText = waitText;
12
+ /**
13
+ * A typed wait: the agent names a reference it already holds, the tool waits (polling, if it must, where the agent
14
+ * cannot see it) until something happens or the time limit passes, and returns what happened with the cursor that
15
+ * resumes the wait. The agent waits with one call instead of a polling loop of its own.
16
+ */
17
+ const WAIT_VERSION = "wait/1";
18
+ exports.WAIT_VERSION = WAIT_VERSION;
19
+ /**
20
+ * How a wait ended.
21
+ * - `satisfied`: it happened; `events` holds what happened.
22
+ * - `waiting`: still waiting (a stream's first line); keep reading or resume.
23
+ * - `timed-out`: nothing happened in time; `resume` waits again from the same cursor.
24
+ * - `gone`: what was awaited cannot happen any more (deleted, left, closed).
25
+ */
26
+ const WAIT_STATES = Object.freeze(["satisfied", "waiting", "timed-out", "gone"]);
27
+ exports.WAIT_STATES = WAIT_STATES;
28
+ /** Builds a wait; a `timed-out` or `waiting` wait needs `resume`, which {@link validateWait} checks. */
29
+ function wait(fields) {
30
+ const { for: what, state, since, target = null, until = null, cursor = null, events = [], fresh = null, resume = null, reason = null, callback = null, next = [] } = fields;
31
+ return { ax: WAIT_VERSION, for: what, target, state, since, until, cursor, events, fresh, resume, reason, callback, next };
32
+ }
33
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
34
+ const isText = (v) => typeof v === "string" && v.trim().length > 0;
35
+ const isStep = (v) => isRecord(v) && isText(v["command"]) && isText(v["why"]);
36
+ /** Whether a value is a wait of this version (its shape only). */
37
+ function isWait(v) {
38
+ return isRecord(v) && v["ax"] === WAIT_VERSION && WAIT_STATES.includes(v["state"]);
39
+ }
40
+ /** Checks a wait: one that can go on names how to resume it, and a satisfied one carries what happened. */
41
+ function validateWait(v) {
42
+ const errors = [];
43
+ const warnings = [];
44
+ if (!isWait(v))
45
+ return { ok: false, errors: [`not a ${WAIT_VERSION} envelope: ax must be "${WAIT_VERSION}" and state one of ${WAIT_STATES.join(", ")}`], warnings };
46
+ if (!isText(v.for))
47
+ errors.push("for is empty: say what is awaited");
48
+ if (!isText(v.since))
49
+ errors.push("since is empty");
50
+ if (!Array.isArray(v.events))
51
+ errors.push("events is a list");
52
+ else if (v.state === "satisfied" && v.events.length === 0)
53
+ errors.push("satisfied, but no event says what happened");
54
+ if ((v.state === "waiting" || v.state === "timed-out") && !isStep(v.resume))
55
+ errors.push(`${v.state} needs resume: the exact command that waits again from the cursor`);
56
+ else if (v.resume !== null && !isStep(v.resume))
57
+ errors.push("resume needs a command and a why");
58
+ if (v.state !== "gone" && v.cursor === null)
59
+ warnings.push("no cursor: a resumed wait may miss or repeat events");
60
+ if (v.fresh === null)
61
+ warnings.push("no freshness: nothing seen is not the same as nothing happened");
62
+ if (!Array.isArray(v.next) || !v.next.every(isStep))
63
+ errors.push("every next step needs a command and a why");
64
+ return { ok: errors.length === 0, errors, warnings };
65
+ }
66
+ /**
67
+ * The default: a satisfied or open wait exits `ok`; a wait that timed out or can no longer happen exits `error`.
68
+ *
69
+ * @claim "a wait that timed out or can no longer happen exits" registry/ouro/ax/wait.test.mts verify:testExists(registry/ouro/ax/wait.test.mts::waitExit and waitText)
70
+ */
71
+ const DEFAULT_WAIT_EXITS = Object.freeze({ satisfied: "ok", waiting: "ok", "timed-out": "error", gone: "error" });
72
+ exports.DEFAULT_WAIT_EXITS = DEFAULT_WAIT_EXITS;
73
+ /** The exit code a wait gives, by its state's name in the tool's table. */
74
+ function waitExit(w, exits, names = DEFAULT_WAIT_EXITS) {
75
+ return exits.code(names[w.state]);
76
+ }
77
+ /** The wait as text: what happened (one line per event), or that nothing did, then how to resume. */
78
+ function waitText(w) {
79
+ const head = { satisfied: `Happened: ${w.for}.`, waiting: `Waiting for ${w.for}.`, "timed-out": `Nothing yet: ${w.for}, waited until ${w.until ?? "the limit"}.`, gone: `It can't happen any more: ${w.for}${w.reason ? `: ${w.reason.replace(/[.\s]+$/, "")}` : ""}.` }[w.state];
80
+ const lines = [head, ...w.events.map((e) => `${e.at} ${e.by}: ${e.summary}`)];
81
+ if (w.fresh && w.fresh.state !== "live")
82
+ lines.push(`Freshness: ${w.fresh.state}${w.fresh.asOf ? ` as of ${w.fresh.asOf}` : ""}.`);
83
+ if (w.resume)
84
+ lines.push(`Resume: ${w.resume.command} (${w.resume.why})`);
85
+ for (const n of w.next)
86
+ lines.push(`Next: ${n.command} (${n.why})`);
87
+ return lines.join("\n");
88
+ }
89
+ const UNITS = Object.freeze({ ms: 1, s: 1000, m: 60_000, h: 3_600_000 });
90
+ /**
91
+ * "90s", "2m", "1h", "500ms" or a bare number of seconds, as milliseconds; null when it is none of these.
92
+ *
93
+ * @claim "or a bare number of seconds" registry/ouro/ax/wait.test.mts verify:testExists(registry/ouro/ax/wait.test.mts::parseDuration and formatDuration read and write the same durations)
94
+ */
95
+ function parseDuration(text) {
96
+ const m = /^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h)?\s*$/.exec(text);
97
+ if (!m)
98
+ return null;
99
+ return Math.round(Number(m[1]) * (UNITS[m[2] ?? "s"]));
100
+ }
101
+ /** Milliseconds as the shortest exact duration {@link parseDuration} reads back: "2m", "90s", "500ms". */
102
+ function formatDuration(ms) {
103
+ for (const unit of ["h", "m", "s"]) {
104
+ const size = UNITS[unit];
105
+ if (ms >= size && ms % size === 0)
106
+ return `${ms / size}${unit}`;
107
+ }
108
+ return `${ms}ms`;
109
+ }
110
+ /**
111
+ * The flags a wait command takes, shaped as `ax-command` flags: how long to wait and where to resume from. Spread them
112
+ * into a command's `flags`.
113
+ */
114
+ const WAIT_FLAGS = Object.freeze({
115
+ timeout: { type: "string", placeholder: "<duration>", description: 'How long to wait, such as "90s" or "5m"; then it exits with a resume command.' },
116
+ cursor: { type: "string", placeholder: "<cursor>", description: "Resume from this cursor (a wait's resume command gives it); without it, only what happens from now counts." },
117
+ });
118
+ exports.WAIT_FLAGS = WAIT_FLAGS;
119
+ const realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
120
+ /**
121
+ * Waits on a reference until a matching event, a time limit or the target is gone, reading the source as often as
122
+ * `intervalMs` allows, and returns the typed wait. Inside the tool, so the agent makes one call instead of a loop.
123
+ */
124
+ async function waitFor(options) {
125
+ const now = options.now ?? Date.now;
126
+ const sleep = options.sleep ?? realSleep;
127
+ const interval = Math.max(1, options.intervalMs ?? 1000);
128
+ const match = options.match ?? (() => true);
129
+ const started = now();
130
+ const deadline = started + Math.max(0, options.timeoutMs);
131
+ const base = { for: options.for, target: options.target, since: new Date(started).toISOString(), until: new Date(deadline).toISOString(), callback: options.callback ?? null };
132
+ let cursor = options.cursor ?? null;
133
+ let fresh = null;
134
+ if (cursor === null) {
135
+ const first = await options.read(null);
136
+ cursor = first.cursor;
137
+ fresh = first.fresh ?? null;
138
+ }
139
+ const stopped = () => wait({ ...base, state: "gone", cursor, fresh, reason: "stopped", next: [] });
140
+ for (;;) {
141
+ if (options.signal?.aborted)
142
+ return stopped();
143
+ const read = await options.read(cursor);
144
+ cursor = read.cursor ?? cursor;
145
+ fresh = read.fresh ?? fresh;
146
+ if (read.gone)
147
+ return wait({ ...base, state: "gone", cursor, fresh, reason: read.gone, next: options.next?.([]) ?? [] });
148
+ const events = read.events.filter(match);
149
+ if (events.length > 0)
150
+ return wait({ ...base, state: "satisfied", cursor, fresh, events, next: options.next?.(events) ?? [] });
151
+ const left = deadline - now();
152
+ if (left <= 0)
153
+ return wait({ ...base, state: "timed-out", cursor, fresh, resume: options.resume(cursor) });
154
+ await sleep(Math.min(interval, left));
155
+ if (options.signal?.aborted)
156
+ return stopped();
157
+ }
158
+ }
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.relativize = relativize;
4
+ exports.booksCore = booksCore;
5
+ exports.coreError = coreError;
6
+ /**
7
+ * The one books implementation under every X arm: the bundle's `books` command (in the eval, the books stub, run
8
+ * against the fake household), started with an argv and no shell, in its own folder. Paths in its answers are made
9
+ * relative to that folder, so no arm shows the production path (whose folder names carry brand words), and a relative
10
+ * path an arm passes back resolves to the same file.
11
+ */
12
+ const node_child_process_1 = require("node:child_process");
13
+ const runtime_1 = require("../../../nerves/runtime");
14
+ /* v8 ignore start -- process wiring: the core's handling of what the process printed is tested with an injected exec @preserve */
15
+ const nodeExecFile = (file, args, options) => new Promise((resolve) => {
16
+ (0, node_child_process_1.execFile)(file, args, { ...options, encoding: "utf8" }, (error, stdout, stderr) => {
17
+ const code = error ? (typeof error.code === "number" ? error.code : 1) : 0;
18
+ resolve({ code, stdout, stderr: stderr || (error && typeof error.code !== "number" ? error.message : "") });
19
+ });
20
+ });
21
+ /* v8 ignore stop */
22
+ /** `text` with every path under `home` made relative to it, and `home` itself as `.`. */
23
+ function relativize(text, home) {
24
+ const bare = home.replace(/\/+$/, "");
25
+ return text.split(`${bare}/`).join("").split(bare).join(".");
26
+ }
27
+ function booksCore(input) {
28
+ const exec = input.exec ?? nodeExecFile;
29
+ const command = input.command ?? `${input.home}/books`;
30
+ return async (argv) => {
31
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.interview_books_start", message: "running a books operation", meta: { words: argv.slice(0, 2).join(" ") } });
32
+ const run = await exec(command, argv, { cwd: input.home, timeout: input.timeoutMs ?? 180_000, maxBuffer: 8 * 1024 * 1024 });
33
+ const output = relativize(run.stdout.trim(), input.home);
34
+ let json = null;
35
+ try {
36
+ const parsed = JSON.parse(output);
37
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
38
+ json = parsed;
39
+ }
40
+ catch {
41
+ // Not JSON: the arm shows the command's output as it is.
42
+ }
43
+ if (json === null) {
44
+ (0, runtime_1.emitNervesEvent)({ component: "eval", level: "warn", event: "eval.interview_books_unparsed", message: "a books operation printed no JSON answer", meta: { code: run.code } });
45
+ return { code: run.code === 0 ? 1 : run.code, json: { ok: false, error: relativize(run.stderr.trim() || output || `the books command exited ${run.code} with no answer`, input.home) }, output };
46
+ }
47
+ return { code: run.code, json, output };
48
+ };
49
+ }
50
+ /** The core's error message when the operation failed outright (not a verdict such as a failed check). */
51
+ function coreError(result) {
52
+ const error = result.json?.error;
53
+ return result.json?.ok === false && typeof error === "string" ? error : null;
54
+ }
@@ -0,0 +1,267 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tokenize = tokenize;
4
+ exports.overviewHelp = overviewHelp;
5
+ exports.commandHelp = commandHelp;
6
+ exports.humanText = humanText;
7
+ exports.parseBooks = parseBooks;
8
+ exports.cliShellArm = cliShellArm;
9
+ /**
10
+ * The `cli-shell` X arm: a conventional `books` command line behind one `shell` tool, written to the Command Line
11
+ * Interface Guidelines (clig.dev): `--help` and `-h` on every command, a help overview with examples, output for a
12
+ * person by default and `--json` for a program, errors on stderr that say what to do next, exit status 0 on success,
13
+ * 1 on failure and 2 on a usage error.
14
+ *
15
+ * The shell runs one `books` command per call, with POSIX quoting. It has no other programs, pipes, redirection or
16
+ * chaining, so this arm reaches exactly the operations the other two arms do (a fidelity note every report carries).
17
+ */
18
+ const runtime_1 = require("../../../nerves/runtime");
19
+ const books_core_1 = require("./books-core");
20
+ const operations_1 = require("./operations");
21
+ /** The command's words, or why the shell will not run it. */
22
+ function tokenize(command) {
23
+ const words = [];
24
+ let word = null;
25
+ let i = 0;
26
+ const add = (text) => { word = (word ?? "") + text; };
27
+ while (i < command.length) {
28
+ const c = command[i];
29
+ if (c === "'") {
30
+ const end = command.indexOf("'", i + 1);
31
+ if (end < 0)
32
+ return { error: "unterminated quote" };
33
+ add(command.slice(i + 1, end));
34
+ i = end + 1;
35
+ }
36
+ else if (c === "\"") {
37
+ let j = i + 1;
38
+ let text = "";
39
+ while (j < command.length && command[j] !== "\"") {
40
+ if (command[j] === "\\" && j + 1 < command.length && "\"\\$`".includes(command[j + 1]))
41
+ j += 1;
42
+ else if (command[j] === "$" || command[j] === "`")
43
+ return { error: "substitution is not available in this shell" };
44
+ text += command[j];
45
+ j += 1;
46
+ }
47
+ if (j >= command.length)
48
+ return { error: "unterminated quote" };
49
+ add(text);
50
+ i = j + 1;
51
+ }
52
+ else if (c === "\\") {
53
+ add(command[i + 1] ?? "");
54
+ i += 2;
55
+ }
56
+ else if (/\s/.test(c)) {
57
+ if (word !== null)
58
+ words.push(word);
59
+ word = null;
60
+ i += 1;
61
+ }
62
+ else if ("|&;<>()`$".includes(c)) {
63
+ return { error: "pipes, redirection, chaining and substitution are not available in this shell; run one books command at a time" };
64
+ }
65
+ else {
66
+ add(c);
67
+ i += 1;
68
+ }
69
+ }
70
+ if (word !== null)
71
+ words.push(word);
72
+ return words;
73
+ }
74
+ const usageOf = (op) => {
75
+ const positional = op.params.filter((p) => p.positional).map((p) => p.kind === "list" ? `<${p.name.replace(/s$/, "")}>...` : `<${p.name}>`);
76
+ const flags = op.params.filter((p) => !p.positional).map((p) => p.kind === "flag" ? `[--${p.name}]` : `[--${p.name} <${p.kind === "number" ? "n" : "value"}>]`);
77
+ return ["books", ...op.words, ...positional, ...flags, "[--json]"].join(" ");
78
+ };
79
+ function overviewHelp() {
80
+ const width = Math.max(...operations_1.OPERATIONS.map((op) => op.words.join(" ").length));
81
+ return [
82
+ "Find, check, shelve and send the household's e-books.",
83
+ "",
84
+ "Usage: books <command> [arguments] [--json]",
85
+ "",
86
+ "Commands:",
87
+ ...operations_1.OPERATIONS.map((op) => ` ${op.words.join(" ").padEnd(width)} ${op.summary}`),
88
+ "",
89
+ "Examples:",
90
+ " books search \"The Harbour Almanac\"",
91
+ " books library find \"The Harbour Almanac\"",
92
+ " books check work/1700000000-ab12cd34/the-harbour-almanac.epub",
93
+ "",
94
+ "Run 'books <command> --help' for a command's arguments. Add --json to any command for machine-readable output.",
95
+ ].join("\n");
96
+ }
97
+ function commandHelp(op) {
98
+ const lines = [op.summary, "", `Usage: ${usageOf(op)}`];
99
+ const positional = op.params.filter((p) => p.positional);
100
+ const flags = op.params.filter((p) => !p.positional);
101
+ if (positional.length > 0)
102
+ lines.push("", "Arguments:", ...positional.map((p) => ` ${p.name} ${p.description}`));
103
+ lines.push("", "Options:", ...flags.map((p) => ` --${p.name}${p.kind === "flag" ? "" : " <value>"} ${p.description}`), " --json Print the answer as JSON.", " -h, --help Show this help.");
104
+ lines.push("", "Example:", ` books ${op.example}`);
105
+ return lines.join("\n");
106
+ }
107
+ function table(rows) {
108
+ const keys = [...new Set(rows.flatMap((row) => Object.keys(row).filter((key) => row[key] === null || typeof row[key] !== "object")))];
109
+ const cell = (value) => value === undefined || value === null ? "" : String(value);
110
+ const widths = keys.map((key) => Math.max(key.length, ...rows.map((row) => cell(row[key]).length)));
111
+ const line = (values) => values.map((value, i) => value.padEnd(widths[i])).join(" ").trimEnd();
112
+ const nested = rows.flatMap((row, i) => Object.entries(row).filter(([, value]) => value !== null && typeof value === "object").map(([key, value]) => ` row ${i + 1} ${key}: ${JSON.stringify(value)}`));
113
+ return [line(keys.map((key) => key.toUpperCase())), ...rows.map((row) => line(keys.map((key) => cell(row[key])))), ...nested];
114
+ }
115
+ /** The answer for a person: each field on its line, lists of records as a table. */
116
+ function humanText(value, indent = "") {
117
+ const lines = [];
118
+ for (const [key, field] of Object.entries(value)) {
119
+ if (key === "ok" && indent === "")
120
+ continue;
121
+ if (Array.isArray(field)) {
122
+ if (field.length === 0)
123
+ lines.push(`${indent}${key}: none`);
124
+ else if (field.every((item) => item !== null && typeof item === "object" && !Array.isArray(item)))
125
+ lines.push(`${indent}${key}:`, ...table(field).map((row) => `${indent} ${row}`));
126
+ else
127
+ lines.push(`${indent}${key}: ${field.map((item) => typeof item === "object" ? JSON.stringify(item) : String(item)).join(", ")}`);
128
+ }
129
+ else if (field !== null && typeof field === "object") {
130
+ lines.push(`${indent}${key}:`, humanText(field, `${indent} `));
131
+ }
132
+ else {
133
+ lines.push(`${indent}${key}: ${String(field)}`);
134
+ }
135
+ }
136
+ return lines.join("\n");
137
+ }
138
+ /** Reads `books` argv into an operation and its input, its help, or a usage error. */
139
+ function parseBooks(argv) {
140
+ const asksHelp = argv.includes("--help") || argv.includes("-h");
141
+ const rest = argv.filter((word) => word !== "--help" && word !== "-h");
142
+ if (rest.length === 0 || (rest.length === 1 && rest[0] === "help"))
143
+ return { help: overviewHelp() };
144
+ const op = [...operations_1.OPERATIONS].sort((a, b) => b.words.length - a.words.length).find((candidate) => candidate.words.every((word, i) => rest[i] === word));
145
+ if (!op) {
146
+ const near = operations_1.OPERATIONS.filter((candidate) => candidate.words[0] === rest[0] || candidate.words.join(" ").startsWith(rest[0].slice(0, 3))).map((candidate) => candidate.words.join(" "));
147
+ return { usage: `'${rest.slice(0, 2).join(" ")}' is not a books command.${near.length ? ` Did you mean: ${near.join(", ")}?` : ""} See 'books --help'.` };
148
+ }
149
+ if (asksHelp)
150
+ return { help: commandHelp(op) };
151
+ const input = {};
152
+ const positional = [];
153
+ let json = false;
154
+ const words = rest.slice(op.words.length);
155
+ for (let i = 0; i < words.length; i += 1) {
156
+ const word = words[i];
157
+ if (word === "--json") {
158
+ json = true;
159
+ continue;
160
+ }
161
+ if (!word.startsWith("--") || word === "--") {
162
+ positional.push(word);
163
+ continue;
164
+ }
165
+ const [name, inline] = word.slice(2).split(/=(.*)/s, 2);
166
+ const param = op.params.find((p) => !p.positional && p.name === name);
167
+ if (!param)
168
+ return { op, usage: `unknown option --${name}. Usage: ${usageOf(op)}` };
169
+ if (param.kind === "flag") {
170
+ input[param.name] = true;
171
+ continue;
172
+ }
173
+ const value = inline ?? words[i + 1];
174
+ if (value === undefined)
175
+ return { op, usage: `--${name} needs a value. Usage: ${usageOf(op)}` };
176
+ if (inline === undefined)
177
+ i += 1;
178
+ if (param.kind === "number" && !Number.isFinite(Number(value)))
179
+ return { op, usage: `--${name} must be a number, not '${value}'.` };
180
+ input[param.name] = param.kind === "number" ? Number(value) : value;
181
+ }
182
+ const slots = op.params.filter((p) => p.positional);
183
+ for (const [index, param] of slots.entries()) {
184
+ if (param.kind === "list") {
185
+ if (positional.length > index)
186
+ input[param.name] = positional.slice(index);
187
+ }
188
+ else if (positional[index] !== undefined) {
189
+ if (param.kind === "number" && !/^\d+$/.test(positional[index]))
190
+ return { op, usage: `<${param.name}> must be a whole number, not '${positional[index]}'.` };
191
+ input[param.name] = param.kind === "number" ? Number(positional[index]) : positional[index];
192
+ }
193
+ }
194
+ const extra = slots.some((p) => p.kind === "list") ? 0 : positional.length - slots.length;
195
+ if (extra > 0)
196
+ return { op, usage: `too many arguments: ${positional.slice(slots.length).join(" ")}. Usage: ${usageOf(op)}` };
197
+ const missing = op.params.find((p) => p.required && input[p.name] === undefined);
198
+ if (missing)
199
+ return { op, usage: `missing <${missing.name}>. Usage: ${usageOf(op)}` };
200
+ return { op, input, json };
201
+ }
202
+ const shellAnswer = (stdout, stderr, code) => {
203
+ const parts = [stdout, stderr].filter(Boolean);
204
+ if (code !== 0)
205
+ parts.push(`[exit status ${code}]`);
206
+ return { text: parts.join("\n"), isError: code !== 0 };
207
+ };
208
+ function cliShellArm(core) {
209
+ const commandOf = (args) => {
210
+ try {
211
+ const parsed = JSON.parse(args || "{}");
212
+ return typeof parsed.command === "string" ? parsed.command : null;
213
+ }
214
+ catch {
215
+ return null;
216
+ }
217
+ };
218
+ const parse = (args) => {
219
+ const command = commandOf(args);
220
+ if (command === null)
221
+ return { answer: shellAnswer("", "shell: give the command line to run as {\"command\": \"...\"}", 2) };
222
+ const words = tokenize(command);
223
+ if (!Array.isArray(words))
224
+ return { answer: shellAnswer("", `shell: ${words.error}`, 2) };
225
+ if (words.length === 0)
226
+ return { answer: shellAnswer("", "", 0) };
227
+ if (words[0] !== "books")
228
+ return { answer: shellAnswer("", `shell: ${words[0]}: command not found (this shell has one program: books; see 'books --help')`, 127) };
229
+ return { words: words.slice(1) };
230
+ };
231
+ return {
232
+ key: "cli-shell",
233
+ tools: [{
234
+ name: "shell",
235
+ description: "Run a command line in the household's shell and return its output and exit status. The shell has one program, `books`; run `books --help` to see its commands.",
236
+ parameters: { type: "object", properties: { command: { type: "string", description: "The command line to run, such as: books --help" } }, required: ["command"] },
237
+ }],
238
+ async call(name, args) {
239
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.interview_shell_call", message: "running a cli-shell call", meta: { tool: name } });
240
+ if (name !== "shell")
241
+ return shellAnswer("", `unknown tool ${name}; the only tool is shell`, 2);
242
+ const words = parse(args);
243
+ if ("answer" in words)
244
+ return words.answer;
245
+ const parsed = parseBooks(words.words);
246
+ if ("help" in parsed)
247
+ return shellAnswer(parsed.help, "", 0);
248
+ if ("usage" in parsed)
249
+ return shellAnswer("", `books: ${parsed.usage}`, 2);
250
+ const result = await core((0, operations_1.argvOf)(parsed.op, parsed.input));
251
+ const error = (0, books_core_1.coreError)(result);
252
+ if (error !== null)
253
+ return shellAnswer("", `books ${parsed.op.words.join(" ")}: ${error}`, result.code === 0 ? 1 : result.code);
254
+ const stdout = parsed.json ? JSON.stringify(result.json, null, 2) : humanText(result.json);
255
+ return shellAnswer(stdout, "", result.code);
256
+ },
257
+ operationOf(name, args) {
258
+ if (name !== "shell")
259
+ return null;
260
+ const words = parse(args);
261
+ if ("answer" in words)
262
+ return null;
263
+ const parsed = parseBooks(words.words);
264
+ return "input" in parsed ? { op: parsed.op, input: parsed.input } : null;
265
+ },
266
+ };
267
+ }
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NO_CALLBACKS = void 0;
4
+ exports.messageOf = messageOf;
5
+ exports.withoutThinking = withoutThinking;
6
+ exports.runConversation = runConversation;
7
+ const runtime_1 = require("../../../nerves/runtime");
8
+ const protocol_1 = require("../protocol");
9
+ const mcp_tools_1 = require("../../../repertoire/mcp-tools");
10
+ /** The loop streams nothing to anyone: every callback does nothing. */
11
+ exports.NO_CALLBACKS = {
12
+ onModelStart: () => undefined, onModelStreamStart: () => undefined, onTextChunk: () => undefined, onReasoningChunk: () => undefined,
13
+ onToolStart: () => undefined, onToolEnd: () => undefined, onError: () => undefined,
14
+ };
15
+ /** A caught value's message. */
16
+ function messageOf(error) {
17
+ return error instanceof Error ? error.message : String(error);
18
+ }
19
+ /** Assistant text without the reasoning some models put inline. */
20
+ function withoutThinking(text) {
21
+ return text.replace(/<think>[\s\S]*?(<\/think>|$)/g, "").trim();
22
+ }
23
+ async function runConversation(input) {
24
+ const scrub = (text) => (0, protocol_1.scrubBrands)(text, input.product);
25
+ const scrubbed = input.arm.tools.map((tool) => ({ name: scrub(tool.name), description: scrub(tool.description), inputSchema: JSON.parse(scrub(JSON.stringify(tool.parameters))) }));
26
+ // Each arm's tools are the study's interfaces under test, not the harness's own, so they go to the model the way a
27
+ // connected MCP server's tools do: `mcpToolSchema`, the census's passthrough (ax/census.config.json). A tool named
28
+ // as its own server keeps its name, and every arm's tools have a description, so nothing is added to either.
29
+ const activeTools = scrubbed.map((tool) => (0, mcp_tools_1.mcpToolSchema)({ server: tool.name }, tool));
30
+ const messages = [{ role: "system", content: scrub(input.system) }, ...input.prefix];
31
+ const timeline = [];
32
+ const turns = [];
33
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.interview_conversation_start", message: "starting a neutral-loop conversation", meta: { arm: input.arm.key, turns: input.userTexts.length } });
34
+ for (const text of input.userTexts) {
35
+ const turn = { start: timeline.length, finalReply: "", outcome: "settled", calls: 0 };
36
+ turns.push(turn);
37
+ messages.push({ role: "user", content: text });
38
+ input.runtime.resetTurnState(messages);
39
+ for (;;) {
40
+ let result;
41
+ try {
42
+ turn.calls += 1;
43
+ result = await input.runtime.streamTurn({ messages, activeTools, callbacks: exports.NO_CALLBACKS });
44
+ }
45
+ catch (error) {
46
+ turn.outcome = `provider-error: ${messageOf(error)}`;
47
+ (0, runtime_1.emitNervesEvent)({ component: "eval", level: "warn", event: "eval.interview_conversation_ended", message: "a provider error ended the conversation", meta: { arm: input.arm.key, calls: turn.calls } });
48
+ return { timeline, turns };
49
+ }
50
+ const content = withoutThinking(result.content);
51
+ const assistant = { role: "assistant", ...(content ? { content } : {}) };
52
+ if (result.toolCalls.length > 0)
53
+ assistant.tool_calls = result.toolCalls.map((call) => ({ id: call.id, type: "function", function: { name: call.name, arguments: call.arguments } }));
54
+ messages.push(assistant);
55
+ if (result.toolCalls.length === 0) {
56
+ turn.finalReply = content;
57
+ timeline.push({ kind: "reply", text: content });
58
+ break;
59
+ }
60
+ for (const call of result.toolCalls) {
61
+ let answer;
62
+ try {
63
+ const reply = await input.arm.call(call.name, call.arguments);
64
+ // A failed call is marked the same way in every arm, as an MCP client shows `isError`.
65
+ answer = scrub(reply.isError ? `Error: ${reply.text}` : reply.text);
66
+ }
67
+ catch (error) {
68
+ answer = scrub(`error: ${messageOf(error)}`);
69
+ }
70
+ timeline.push({ kind: "call", name: call.name, args: call.arguments, result: answer });
71
+ messages.push({ role: "tool", tool_call_id: call.id, content: answer });
72
+ input.runtime.appendToolOutput(call.id, answer);
73
+ }
74
+ }
75
+ }
76
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.interview_conversation_end", message: "finished a neutral-loop conversation", meta: { arm: input.arm.key, turns: turns.length } });
77
+ return { timeline, turns };
78
+ }