@ouro.bot/cli 0.1.0-alpha.1503 → 0.1.0-alpha.1505

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/changelog.json CHANGED
@@ -1,6 +1,19 @@
1
1
  {
2
2
  "_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1505",
6
+ "changes": [
7
+ "Slugger's eval projection replaces each household name, handle or email it finds in a kept file with a fixed placeholder (\"Member A\", \"member-a@example.invalid\") instead of refusing the run, and reports only how many it replaced. Leak patterns now match whole words only (a name next to digits still matches), in the redaction and the leak lint alike; a file that isn't UTF-8 text is never rewritten, and is refused if it holds a pattern."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1504",
12
+ "changes": [
13
+ "The H interview guest has a `codex` arm: OpenAI Codex CLI at the commit pre-registration v2 pins, running its own agent loop against the H wire as its only provider. The Butler's persona and the label line are codex's developer instructions, and the bundle's skills are installed as codex skills. The job is `codex exec`, and each follow-up resumes the same thread. The config turns off retries, image viewing, sub-agents, web search, plugins, apps, bundled skills, analytics and telemetry. Codex runs in a home under the agent container's writable `/tmp` with no brand word in its path, with the bundle linked under it, and each run is killed before the host's guest deadline. `deploy/eval/build-codex.sh` builds codex from source in a throwaway container, and `deploy/eval/codex.Dockerfile` adds the binary to the eval's agent image.",
14
+ "The H interview guest has a model endpoint for the other harnesses: a Responses-API server on the agent container's loopback that codex is pointed at as a custom provider. Each request is turned into the harness's own request and sent through the host's runtime, so the host still rewrites, scans, gates and meters every call. The trace comes from the same traffic, so the case's assertions read each call with the output the harness sent back for it. The case's earlier conversation goes before the harness's first user message. Anything the server can't carry faithfully (another tool type, a custom tool call, an image) is refused by name and never sent. Every failure is answered with a 400, which codex doesn't retry, so no call is metered twice, and every request gets an answer."
15
+ ]
16
+ },
4
17
  {
5
18
  "version": "0.1.0-alpha.1503",
6
19
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1503",
2
+ "runtimeVersion": "0.1.0-alpha.1505",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1503</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1505</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CODEX_HOME_DIR = void 0;
7
+ exports.codexConfig = codexConfig;
8
+ exports.installSkills = installSkills;
9
+ exports.threadIdOf = threadIdOf;
10
+ exports.codexArm = codexArm;
11
+ /**
12
+ * H's `codex` arm (pre-registration v2 product H): OpenAI Codex CLI at `227fa4e805d4`, its own agent loop unchanged,
13
+ * pointed at the H wire on the container's loopback as a custom Responses provider. Every call it makes goes through
14
+ * the wire to the host's runtime, so the host still rewrites, scans, gates and meters it.
15
+ *
16
+ * What stays the same as in every arm: the Butler's persona and the label line (here codex's developer instructions,
17
+ * which it sends after its own), the case's conversation (put before the job by the wire), the bundle's skills
18
+ * (installed as codex skills, each described by its own when-line), the books command line and the household.
19
+ *
20
+ * What the config changes, and why (each is a fidelity flag in the H kit):
21
+ * - no retries, unbounded connection retries included: a retried call would be metered twice, and the wire answers
22
+ * every failure with a 400 anyway;
23
+ * - no `view_image`: its output is an image, which the wire can't carry;
24
+ * - no sub-agents: their tools are a namespace, not functions, which the wire can't carry;
25
+ * - no web search, plugins, apps, bundled skills, analytics or telemetry: the container has no route out, and the
26
+ * bundled skills are about codex itself, not the household.
27
+ * Codex doesn't know the model's name, so it runs as it does for any model it doesn't know: its generic prompt, no
28
+ * `apply_patch` tool, and a 10,000-byte cut on tool output.
29
+ *
30
+ * Codex runs in a neutral home with the bundle linked at a neutral path, so no path it shows the model carries a
31
+ * brand word, and a path the model writes back still resolves. The job is `codex exec`; each follow-up is
32
+ * `codex exec resume` on the same thread, as the owner's next message.
33
+ */
34
+ const node_child_process_1 = require("node:child_process");
35
+ const node_fs_1 = __importDefault(require("node:fs"));
36
+ const node_path_1 = __importDefault(require("node:path"));
37
+ const runtime_1 = require("../../../../nerves/runtime");
38
+ const skill_summaries_1 = require("../../../../repertoire/skill-summaries");
39
+ const loop_1 = require("../loop");
40
+ const run_1 = require("../run");
41
+ const wire_1 = require("./wire");
42
+ /** The whole conversation's time, inside the host's 600-second guest deadline, so a stuck codex is this arm's failure. */
43
+ const CONVERSATION_MS = 540_000;
44
+ /**
45
+ * Codex's home: a path with no brand word, on the agent container's writable `/tmp` (the container is read-only
46
+ * otherwise, and its own home's path carries a brand word).
47
+ */
48
+ exports.CODEX_HOME_DIR = "/tmp/agent";
49
+ /** The model name codex sends; the wire ignores it, and the host's runtime decides the model. */
50
+ const MODEL = "model";
51
+ /** A TOML basic string: JSON's escapes, plus the two TOML also forbids raw (DEL, and a lone surrogate's escape). */
52
+ const toml = (text) => JSON.stringify(text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�"))
53
+ .replace(/\u007f/g, "\\u007F");
54
+ /** Codex's config.toml for one conversation: the wire as its only provider, and nothing the wire can't carry. */
55
+ function codexConfig(input) {
56
+ return [
57
+ `model = ${toml(MODEL)}`,
58
+ "model_provider = \"eval\"",
59
+ "approval_policy = \"never\"",
60
+ "sandbox_mode = \"danger-full-access\"",
61
+ "web_search = \"disabled\"",
62
+ "check_for_update_on_startup = false",
63
+ `developer_instructions = ${toml(input.developerInstructions)}`,
64
+ "",
65
+ "[model_providers.eval]",
66
+ "name = \"eval\"",
67
+ `base_url = ${toml(input.baseUrl)}`,
68
+ "wire_api = \"responses\"",
69
+ "request_max_retries = 0",
70
+ "stream_max_retries = 0",
71
+ "stream_idle_timeout_ms = 300000",
72
+ "",
73
+ "[features]",
74
+ "view_image = false",
75
+ "multi_agent = false",
76
+ "unbounded_connection_retries = false",
77
+ "plugins = false",
78
+ "apps = false",
79
+ "",
80
+ "[agents]",
81
+ "enabled = false",
82
+ "",
83
+ "[skills.bundled]",
84
+ "enabled = false",
85
+ "",
86
+ "[analytics]",
87
+ "enabled = false",
88
+ "",
89
+ "[otel]",
90
+ "exporter = \"none\"",
91
+ "trace_exporter = \"none\"",
92
+ "metrics_exporter = \"none\"",
93
+ "",
94
+ ].join("\n");
95
+ }
96
+ /**
97
+ * Installs each of the bundle's skills (`skills/<name>.md`) as a codex user skill (`.agents/skills/<name>/SKILL.md`),
98
+ * named for its file and described by the when-line the harness shows beside it. Returns the names installed.
99
+ */
100
+ function installSkills(bundle, home) {
101
+ const dir = node_path_1.default.join(bundle, "skills");
102
+ if (!node_fs_1.default.existsSync(dir))
103
+ return [];
104
+ const names = node_fs_1.default.readdirSync(dir).filter((file) => file.endsWith(".md")).sort().map((file) => node_path_1.default.basename(file, ".md"));
105
+ for (const name of names) {
106
+ const markdown = node_fs_1.default.readFileSync(node_path_1.default.join(dir, `${name}.md`), "utf8");
107
+ const lines = markdown.split("\n");
108
+ const end = lines[0]?.trim() === "---" ? lines.indexOf("---", 1) : -1;
109
+ const body = end > 0 ? lines.slice(end + 1).join("\n") : markdown;
110
+ const description = (0, skill_summaries_1.whenLine)(markdown) ?? `The ${name} skill.`;
111
+ node_fs_1.default.mkdirSync(node_path_1.default.join(home, ".agents", "skills", name), { recursive: true });
112
+ node_fs_1.default.writeFileSync(node_path_1.default.join(home, ".agents", "skills", name, "SKILL.md"), `---\nname: ${JSON.stringify(name)}\ndescription: ${JSON.stringify(description)}\n---\n${body}`);
113
+ }
114
+ return names;
115
+ }
116
+ /** The thread codex started, from its `--json` lines; null when it named none. */
117
+ function threadIdOf(stdout) {
118
+ for (const line of stdout.split("\n")) {
119
+ try {
120
+ const event = JSON.parse(line);
121
+ if (event.type === "thread.started" && typeof event.thread_id === "string")
122
+ return event.thread_id;
123
+ }
124
+ catch {
125
+ // Not an event line.
126
+ }
127
+ }
128
+ return null;
129
+ }
130
+ /* v8 ignore start -- process wiring: what the arm does with codex's exit and output is tested with an injected run @preserve */
131
+ const spawnCodex = (args, options) => new Promise((resolve) => {
132
+ const child = (0, node_child_process_1.spawn)("codex", args, { cwd: options.cwd, env: options.env, stdio: ["ignore", "pipe", "pipe"] });
133
+ let stdout = "";
134
+ let stderr = "";
135
+ child.stdout.on("data", (chunk) => { stdout += chunk.toString("utf8"); });
136
+ child.stderr.on("data", (chunk) => { stderr += chunk.toString("utf8"); });
137
+ const timer = setTimeout(() => child.kill("SIGKILL"), Math.max(options.timeoutMs, 0));
138
+ child.on("error", (error) => { clearTimeout(timer); resolve({ code: 127, stdout, stderr: `${stderr}${error.message}\n` }); });
139
+ child.on("close", (code) => { clearTimeout(timer); resolve({ code: code ?? 137, stdout, stderr }); });
140
+ });
141
+ /* v8 ignore stop */
142
+ const lastLine = (text) => text.trim().split("\n").at(-1).trim();
143
+ function codexArm(options = {}) {
144
+ const run = options.run ?? spawnCodex;
145
+ const home = options.home ?? exports.CODEX_HOME_DIR;
146
+ const workdir = options.workdir ?? node_path_1.default.join(home, "AgentBundles", "sanctuary.agent");
147
+ return async ({ turn, bundle, providerRuntime }) => {
148
+ const deadline = Date.now() + CONVERSATION_MS;
149
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(workdir), { recursive: true });
150
+ if (!node_fs_1.default.existsSync(workdir))
151
+ node_fs_1.default.symlinkSync(bundle, workdir);
152
+ installSkills(bundle, home);
153
+ const wire = (0, wire_1.createWire)({ runtime: providerRuntime, prefix: turn.prefix });
154
+ const served = await (0, wire_1.serveWire)(wire);
155
+ try {
156
+ // Codex's state folder, with a neutral name: the model can see it in the shell's environment.
157
+ const codexHome = node_path_1.default.join(home, ".state");
158
+ node_fs_1.default.mkdirSync(codexHome, { recursive: true });
159
+ node_fs_1.default.writeFileSync(node_path_1.default.join(codexHome, "config.toml"), codexConfig({ baseUrl: served.url, developerInstructions: `${(0, run_1.personaPrompt)(bundle)}\n\n${turn.labelLine}` }));
160
+ const env = { HOME: home, CODEX_HOME: codexHome, PATH: process.env.PATH };
161
+ // `-C` keeps the neutral path as codex's cwd; without it codex resolves the link to the bundle's real path. The
162
+ // flags are `exec`'s, so they go before `resume`, which doesn't take `-C`.
163
+ const flags = ["--json", "--skip-git-repo-check", "--dangerously-bypass-approvals-and-sandbox", "-m", MODEL, "-C", workdir];
164
+ const turns = [];
165
+ let thread = null;
166
+ for (const [index, text] of [turn.userText, ...turn.followUps].entries()) {
167
+ const record = { start: wire.timeline().length, finalReply: "", outcome: "settled", calls: 0 };
168
+ turns.push(record);
169
+ if (index > 0 && thread === null) {
170
+ record.outcome = "harness-error: codex named no thread to resume";
171
+ break;
172
+ }
173
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.h_codex_turn_start", message: "codex is taking a turn", meta: { index } });
174
+ const callsBefore = wire.calls();
175
+ const ran = await run(index === 0 ? ["exec", ...flags, "--", text] : ["exec", ...flags, "resume", thread, "--", text], { cwd: workdir, env, timeoutMs: deadline - Date.now() });
176
+ if (index === 0)
177
+ thread = threadIdOf(ran.stdout);
178
+ record.calls = wire.calls() - callsBefore;
179
+ const reply = wire.timeline().slice(record.start).filter((entry) => entry.kind === "reply").at(-1);
180
+ if (reply)
181
+ record.finalReply = (0, loop_1.withoutThinking)(reply.text);
182
+ // A failed call ends the conversation, so any failure the wire remembers is this turn's.
183
+ const failure = wire.error();
184
+ if (failure !== null)
185
+ record.outcome = `provider-error: ${failure}`;
186
+ else if (ran.code !== 0)
187
+ record.outcome = `harness-error: codex exited ${ran.code}${ran.stderr.trim() ? `: ${lastLine(ran.stderr)}` : ""}`;
188
+ else if (!reply)
189
+ record.outcome = "harness-error: codex ended the turn with no reply";
190
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.h_codex_turn_end", message: "codex ended a turn", meta: { index, outcome: record.outcome, calls: record.calls } });
191
+ if (record.outcome !== "settled")
192
+ break;
193
+ }
194
+ const timeline = wire.timeline().map((entry) => entry.kind === "reply" ? { kind: "reply", text: (0, loop_1.withoutThinking)(entry.text) } : entry);
195
+ return { timeline, finalReply: turns[0].finalReply, outcome: turns[0].outcome, steps: wire.calls(), turns };
196
+ }
197
+ finally {
198
+ await served.close();
199
+ }
200
+ };
201
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ /**
3
+ * How each H arm departs from the harness as shipped, with the reason, for the report's `fidelity` (keyed
4
+ * `H:<arm>`). Every setting an arm turns off is here: the codex arm's test checks each `false` or `disabled` in its
5
+ * config against these notes by key name.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.H_CODEX_FIDELITY = exports.H_OURO_FIDELITY = void 0;
9
+ /** Departures every H arm shares, and where the `ouro` arm still differs from the others. */
10
+ exports.H_OURO_FIDELITY = [
11
+ "no provider retries, as in every arm: each error from the host's runtime is marked not retryable, so a retry is never a second metered call",
12
+ "offers web_search and fetch_url, which fail in the sandbox (no route off the host); the other arms don't offer web search at all, since their hosted search tools can't reach the host's runtime",
13
+ "the bundle sits at its production path, so the working folder the model sees differs from the other arms' neutral path",
14
+ "skills aren't listed in the prompt: a skill reaches the model only when the agent reads its file, while the other arms list each skill's name and when-line",
15
+ ];
16
+ exports.H_CODEX_FIDELITY = [
17
+ "request_max_retries, stream_max_retries and unbounded_connection_retries are off: a retry would be a second metered call, and the H wire answers every failure with a 400 codex never retries",
18
+ "view_image is off: its output is an image, which the H wire can't carry",
19
+ "multi_agent (sub-agents) is off, through both the deprecated [features] multi_agent and [agents] enabled = false: its tools are a namespace, not functions, which the H wire can't carry",
20
+ "the goal tools (get_goal, create_goal, update_goal) stay on: codex's goals feature is stable and on by default at this commit",
21
+ "request_user_input is offered, as stock codex offers it, though its description says it works only in Plan mode, which the arm never uses",
22
+ "web_search is disabled: it is a hosted tool the host's runtime can't run, and the sandbox has no route off the host",
23
+ "plugins and apps are off, and with them tool suggestions: the sandbox has no route off the host",
24
+ "bundled skills are off ([skills.bundled] enabled = false): they are about codex itself, not the household",
25
+ "analytics, the otel exporters (exporter, trace_exporter and metrics_exporter) and check_for_update_on_startup are off: the sandbox has no route off the host; the model sees no difference",
26
+ "the request's own settings (tool_choice, parallel_tool_calls, reasoning, include, store, prompt_cache_key and the like) are not passed on: the host's runtime sets the model's settings, as it does for the ouro arm",
27
+ "codex's leading developer messages become one system message, joined with a blank line, and a message's text parts are joined with a newline, since the harness's messages carry one string each",
28
+ "codex doesn't know the model's name, so it runs as for any unknown model: its generic base prompt, no apply_patch tool, and output of each tool call cut at 10,000 bytes",
29
+ "the brand words in codex's base prompt are replaced before the call reaches the model",
30
+ "the shell can still show the brand through the names of the variables codex sets (CODEX_HOME, CODEX_THREAD_ID, CODEX_SESSION_ID, CODEX_CI), none of which is in the prompt; codex adds no helper folder to PATH, since it refuses to create one under /tmp",
31
+ "codex runs from a neutral home under /tmp (the agent container is read-only elsewhere), with the bundle linked at /tmp/agent/AgentBundles/sanctuary.agent",
32
+ "codex is killed at 540 seconds, inside the host's 600-second guest deadline, and the turn reports that it exited 137; commands it started stop when the host removes the container at the guest's end",
33
+ "built from source at the pinned commit for x86_64 gnu (on the x86_64 sandbox host, which runs every session), not codex's released musl build, without the release's version stamp",
34
+ ];
@@ -20,6 +20,7 @@ const node_fs_1 = __importDefault(require("node:fs"));
20
20
  const runtime_1 = require("../../../../nerves/runtime");
21
21
  const provider_proxy_1 = require("../../../transport/provider-proxy");
22
22
  const telegram_turn_1 = require("../../../transport/telegram-turn");
23
+ const codex_1 = require("./codex");
23
24
  /** The ouro arm: the harness's own turn, unchanged but for the label line and the later message. */
24
25
  function ouroArm(runTurn = telegram_turn_1.runTelegramTurn) {
25
26
  return ({ turn, bundle, providerRuntime }) => runTurn({
@@ -27,7 +28,7 @@ function ouroArm(runTurn = telegram_turn_1.runTelegramTurn) {
27
28
  });
28
29
  }
29
30
  /** The H arms this guest runs. */
30
- exports.H_ARMS = { ouro: ouroArm() };
31
+ exports.H_ARMS = { ouro: ouroArm(), codex: (0, codex_1.codexArm)() };
31
32
  function readTurnFile(file) {
32
33
  const value = JSON.parse(node_fs_1.default.readFileSync(file, "utf8"));
33
34
  if (value.product !== "H" || typeof value.arm !== "string" || typeof value.labelLine !== "string" || !Array.isArray(value.prefix)
@@ -0,0 +1,296 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.checkToolFields = checkToolFields;
7
+ exports.responsesRequest = responsesRequest;
8
+ exports.responsesEvents = responsesEvents;
9
+ exports.sse = sse;
10
+ exports.createWire = createWire;
11
+ exports.serveWire = serveWire;
12
+ /**
13
+ * The H arms' model endpoint inside the agent container: an OpenAI-wire server on the container's loopback that the
14
+ * other harnesses (codex, openhands) are pointed at as a custom provider. Each request is turned into the harness's
15
+ * own request and sent through the host's runtime, as every interview call is, so the host still rewrites, scans,
16
+ * gates and meters it; the answer goes back in the wire's own shape. Nothing reaches a model any other way: the
17
+ * container has no route out.
18
+ *
19
+ * The wire is also where H's trace comes from: each call the model makes, with the output the harness sent back for
20
+ * it, and each reply, in order, as the case's assertions read them. The case's earlier conversation (its prefix) is
21
+ * put before the harness's first user message, since neither harness can be given a conversation to start from.
22
+ *
23
+ * Anything the wire can't carry faithfully (another tool type, a custom tool's call, an image) is refused by name and
24
+ * never sent, so a pilot finds it rather than a session being scored on a changed request.
25
+ */
26
+ const node_http_1 = __importDefault(require("node:http"));
27
+ const runtime_1 = require("../../../../nerves/runtime");
28
+ const mcp_tools_1 = require("../../../../repertoire/mcp-tools");
29
+ const loop_1 = require("../loop");
30
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
31
+ const typeOf = (value) => value === null ? "null" : isRecord(value) && typeof value.type === "string" ? value.type : typeof value;
32
+ const owner = (kind) => `${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind}'s`;
33
+ /** Refuses a field the wire would otherwise drop, naming it and whose it is. */
34
+ function checkFields(kind, value, allowed) {
35
+ for (const key of Object.keys(value))
36
+ if (!allowed.has(key))
37
+ throw new Error(`the H wire can't carry ${owner(kind)} ${key}`);
38
+ }
39
+ /** A field that must be a string, refused by name otherwise rather than sent as the text "undefined". */
40
+ function stringField(kind, value, key) {
41
+ const field = value[key];
42
+ if (typeof field !== "string")
43
+ throw new Error(`the H wire can't carry ${owner(kind)} ${key} of type ${field === null ? "null" : typeof field}`);
44
+ return field;
45
+ }
46
+ /** The fields of each input item the wire reads. An item's id and status are the client's own bookkeeping. */
47
+ const ITEM_FIELDS = {
48
+ message: new Set(["type", "id", "status", "role", "content"]),
49
+ function_call: new Set(["type", "id", "status", "call_id", "name", "arguments"]),
50
+ function_call_output: new Set(["type", "id", "status", "call_id", "output"]),
51
+ };
52
+ const PART_FIELDS = new Set(["type", "text"]);
53
+ /**
54
+ * The text of a message's or an output's content: a string, or text parts. Parts are joined with a newline, as the
55
+ * harness's messages carry one string each (a fidelity note for the arms).
56
+ */
57
+ function textOf(content) {
58
+ if (typeof content === "string")
59
+ return content;
60
+ if (!Array.isArray(content))
61
+ throw new Error(`the H wire can't carry content of type ${typeOf(content)}`);
62
+ return content.map((part) => {
63
+ if (isRecord(part) && ["input_text", "output_text", "text"].includes(String(part.type)) && typeof part.text === "string") {
64
+ checkFields(String(part.type), part, PART_FIELDS);
65
+ return part.text;
66
+ }
67
+ throw new Error(`the H wire can't carry content of type ${typeOf(part)}`);
68
+ }).join("\n");
69
+ }
70
+ /** The fields of an arm's function tool the wire carries; any other is refused, never dropped. */
71
+ const TOOL_FIELDS = new Set(["type", "name", "description", "parameters", "strict"]);
72
+ /** Refuses a tool with a field the wire would otherwise drop, or with no name. */
73
+ function checkToolFields(tool) {
74
+ checkFields("tool", tool, TOOL_FIELDS);
75
+ stringField("tool", tool, "name");
76
+ }
77
+ /**
78
+ * The arm's own tools, passed to the host's runtime as a connected MCP server's tools are: through `mcpToolSchema`,
79
+ * the census's passthrough (ax/census.config.json). They are the arm's doors, not the harness's: the arm runs each
80
+ * call to one, and nothing in the harness does. Each reaches the model exactly as the arm sent it. Named as its own
81
+ * server, a tool keeps its name, and its description and schema are the arm's objects. Where the arm sent no
82
+ * description or schema, the passthrough's fill-in is taken out again, and `strict` is carried as sent.
83
+ */
84
+ function wireTools(tools) {
85
+ const infos = tools.map((tool) => ({ name: tool.name, description: tool.description ?? "", inputSchema: tool.parameters ?? {} }));
86
+ return infos.map((info, index) => {
87
+ const schema = (0, mcp_tools_1.mcpToolSchema)({ server: info.name }, info);
88
+ const sent = tools[index];
89
+ if (sent.description === undefined)
90
+ delete schema.function.description;
91
+ else
92
+ schema.function.description = sent.description;
93
+ if (sent.parameters === undefined)
94
+ delete schema.function.parameters;
95
+ else
96
+ schema.function.parameters = sent.parameters;
97
+ if (sent.strict !== undefined)
98
+ schema.function.strict = sent.strict;
99
+ return schema;
100
+ });
101
+ }
102
+ /**
103
+ * The request fields codex 227fa4e sends. Its settings (model, reasoning and the rest) are left to the host's runtime,
104
+ * as for the ouro arm; any other field is refused rather than dropped. The wire always streams and always lets the
105
+ * model call the tools, so `stream` and `tool_choice` may only say so.
106
+ */
107
+ const RESPONSES_FIELDS = new Set([
108
+ "model", "input", "tools", "stream", "tool_choice", "parallel_tool_calls", "reasoning", "store", "include", "prompt_cache_key", "client_metadata",
109
+ ]);
110
+ /**
111
+ * A Responses body as the harness's request. The harness's instructions (its leading developer and system messages)
112
+ * become the one system message; the case's conversation goes before the first user message; a call joins the
113
+ * assistant message before it, and each output becomes its tool result. Reasoning items are not sent back.
114
+ */
115
+ function responsesRequest(body, prefix) {
116
+ if (!isRecord(body) || !Array.isArray(body.input))
117
+ throw new Error("a Responses body needs an input list");
118
+ checkFields("request", body, RESPONSES_FIELDS);
119
+ if (body.stream !== true)
120
+ throw new Error(`the H wire can't carry a request's stream of ${JSON.stringify(body.stream) ?? "undefined"}`);
121
+ if ("tool_choice" in body && body.tool_choice !== "auto")
122
+ throw new Error(`the H wire can't carry a request's tool_choice of ${JSON.stringify(body.tool_choice)}`);
123
+ if ("tools" in body && !Array.isArray(body.tools))
124
+ throw new Error(`the H wire can't carry a request's tools of type ${typeOf(body.tools)}`);
125
+ const leading = [];
126
+ const rest = [];
127
+ let prefixed = false;
128
+ for (const item of body.input) {
129
+ const type = typeOf(item);
130
+ const value = item;
131
+ if (type === "reasoning")
132
+ continue;
133
+ if (Object.hasOwn(ITEM_FIELDS, type))
134
+ checkFields(type, value, ITEM_FIELDS[type]);
135
+ if (type === "message") {
136
+ const role = String(value.role);
137
+ const text = textOf(value.content);
138
+ if (role === "developer" || role === "system") {
139
+ if (rest.length === 0)
140
+ leading.push(text);
141
+ else
142
+ rest.push({ role: "system", content: text });
143
+ }
144
+ else if (role === "user") {
145
+ if (!prefixed)
146
+ rest.push(...prefix);
147
+ prefixed = true;
148
+ rest.push({ role: "user", content: text });
149
+ }
150
+ else if (role === "assistant") {
151
+ rest.push({ role: "assistant", content: text });
152
+ }
153
+ else {
154
+ throw new Error(`the H wire can't carry a message from ${role}`);
155
+ }
156
+ }
157
+ else if (type === "function_call") {
158
+ const call = { id: stringField(type, value, "call_id"), type: "function", function: { name: stringField(type, value, "name"), arguments: stringField(type, value, "arguments") } };
159
+ const last = rest[rest.length - 1];
160
+ if (last?.role === "assistant") {
161
+ last.tool_calls = [...last.tool_calls ?? [], call];
162
+ }
163
+ else {
164
+ rest.push({ role: "assistant", content: null, tool_calls: [call] });
165
+ }
166
+ }
167
+ else if (type === "function_call_output") {
168
+ rest.push({ role: "tool", tool_call_id: stringField(type, value, "call_id"), content: textOf(value.output) });
169
+ }
170
+ else {
171
+ throw new Error(`the H wire can't carry an input item of type ${type}`);
172
+ }
173
+ }
174
+ const tools = (body.tools ?? []);
175
+ for (const tool of tools) {
176
+ if (typeOf(tool) !== "function")
177
+ throw new Error(`the H wire can't carry a tool of type ${typeOf(tool)}`);
178
+ checkToolFields(tool);
179
+ }
180
+ const activeTools = wireTools(tools);
181
+ return { messages: [...(leading.length > 0 ? [{ role: "system", content: leading.join("\n\n") }] : []), ...rest], activeTools };
182
+ }
183
+ /** The events a Responses client reads for one answer: created, each output item done, then completed with usage. */
184
+ function responsesEvents(result, id) {
185
+ const usage = result.usage;
186
+ return [
187
+ { type: "response.created", response: { id } },
188
+ ...(result.content ? [{ type: "response.output_item.done", item: { type: "message", role: "assistant", id: `${id}_msg`, content: [{ type: "output_text", text: result.content }] } }] : []),
189
+ ...result.toolCalls.map((call, index) => ({ type: "response.output_item.done", item: { type: "function_call", id: `${id}_fc_${index}`, call_id: call.id, name: call.name, arguments: call.arguments } })),
190
+ { type: "response.completed", response: { id, usage: {
191
+ input_tokens: usage?.input_tokens ?? 0, input_tokens_details: { cached_tokens: usage?.cached_input_tokens ?? 0 },
192
+ output_tokens: usage?.output_tokens ?? 0, output_tokens_details: { reasoning_tokens: usage?.reasoning_tokens ?? 0 },
193
+ total_tokens: usage?.total_tokens ?? 0,
194
+ } } },
195
+ ];
196
+ }
197
+ /** Server-sent events, one per object, named by its type. */
198
+ function sse(events) {
199
+ return events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join("");
200
+ }
201
+ const errorAnswer = (status, message) => ({ status, contentType: "application/json", body: JSON.stringify({ error: { message } }) });
202
+ function createWire(input) {
203
+ // The Anthropic provider rebuilds each tool and drops `strict` and schema combinators (oneOf, allOf, anyOf), so an
204
+ // arm's tools wouldn't reach the model as sent. The study's providers (Copilot and MiniMax) pass them through.
205
+ if (input.runtime.id === "anthropic")
206
+ throw new Error("the H wire can't carry an arm's tools to the anthropic provider");
207
+ const timeline = [];
208
+ const pending = new Map();
209
+ let calls = 0;
210
+ let failure = null;
211
+ let responses = 0;
212
+ return {
213
+ timeline: () => [...timeline],
214
+ calls: () => calls,
215
+ error: () => failure,
216
+ async handle(route, body) {
217
+ if (route !== "/v1/responses" && route !== "/responses")
218
+ return errorAnswer(404, `no route ${route}`);
219
+ let request;
220
+ try {
221
+ request = responsesRequest(body, input.prefix);
222
+ }
223
+ catch (error) {
224
+ failure = (0, loop_1.messageOf)(error);
225
+ (0, runtime_1.emitNervesEvent)({ component: "eval", level: "warn", event: "eval.h_wire_refused", message: "the H wire refused a request it can't carry", meta: { reason: failure } });
226
+ return errorAnswer(400, failure);
227
+ }
228
+ // The outputs the client sent back are the results of the calls it was given.
229
+ for (const message of request.messages) {
230
+ if (message.role !== "tool")
231
+ continue;
232
+ const call = pending.get(message.tool_call_id);
233
+ if (call) {
234
+ call.result = String(message.content);
235
+ pending.delete(message.tool_call_id);
236
+ }
237
+ }
238
+ calls += 1;
239
+ let result;
240
+ try {
241
+ input.runtime.resetTurnState(request.messages);
242
+ result = await input.runtime.streamTurn({ messages: request.messages, activeTools: request.activeTools, callbacks: loop_1.NO_CALLBACKS });
243
+ }
244
+ catch (error) {
245
+ failure = (0, loop_1.messageOf)(error);
246
+ (0, runtime_1.emitNervesEvent)({ component: "eval", level: "warn", event: "eval.h_wire_failed", message: "a call through the H wire failed", meta: { reason: failure } });
247
+ // 400, never 500: codex retries a server error, and every retry would be another metered call. A failed or
248
+ // refused call ends the conversation in every arm.
249
+ return errorAnswer(400, failure);
250
+ }
251
+ for (const call of result.toolCalls) {
252
+ const entry = { kind: "call", name: call.name, args: call.arguments, result: "" };
253
+ timeline.push(entry);
254
+ pending.set(call.id, entry);
255
+ }
256
+ if (result.toolCalls.length === 0)
257
+ timeline.push({ kind: "reply", text: result.content });
258
+ responses += 1;
259
+ return { status: 200, contentType: "text/event-stream", body: sse(responsesEvents(result, `resp_${responses}`)) };
260
+ },
261
+ };
262
+ }
263
+ /** Serves the wire on the container's loopback; `url` is the base a client's provider is given. */
264
+ async function serveWire(wire) {
265
+ const server = node_http_1.default.createServer((request, response) => {
266
+ const chunks = [];
267
+ request.on("data", (chunk) => chunks.push(chunk));
268
+ request.on("end", () => {
269
+ void (async () => {
270
+ let answer;
271
+ try {
272
+ let body;
273
+ try {
274
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
275
+ }
276
+ catch {
277
+ answer = errorAnswer(400, "the body is not JSON");
278
+ return;
279
+ }
280
+ answer = await wire.handle(new URL(request.url, "http://wire").pathname, body);
281
+ }
282
+ catch (error) {
283
+ // Anything else is answered too, so no request hangs and the guest never dies of one.
284
+ answer = errorAnswer(400, (0, loop_1.messageOf)(error));
285
+ }
286
+ finally {
287
+ response.writeHead(answer.status, { "content-type": answer.contentType }).end(answer.body);
288
+ }
289
+ })();
290
+ });
291
+ });
292
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
293
+ const { port } = server.address();
294
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.h_wire_listening", message: "the H wire is serving on the container's loopback", meta: { port } });
295
+ return { url: `http://127.0.0.1:${port}/v1`, close: () => new Promise((resolve) => server.close(() => resolve())) };
296
+ }
@@ -8,6 +8,8 @@ exports.archiveBundle = archiveBundle;
8
8
  exports.removeArchive = removeArchive;
9
9
  exports.projectAgentConfig = projectAgentConfig;
10
10
  exports.readLeakPatterns = readLeakPatterns;
11
+ exports.placeholder = placeholder;
12
+ exports.redact = redact;
11
13
  exports.leakLint = leakLint;
12
14
  exports.projectSlugger = projectSlugger;
13
15
  exports.sluggerProfile = sluggerProfile;
@@ -25,11 +27,17 @@ exports.sluggerProfile = sluggerProfile;
25
27
  * dot-file and dot-folder (`.git`, `.backup/`, ...) and every symbolic link.
26
28
  * - **Created empty:** every path Slugger's profile may write, so `books/` too, where the sandbox writes the books
27
29
  * CLI's synthetic settings.
28
- * - **Leak lint.** The household's names, handles, emails and addresses are kept in his private bundle at
30
+ * - **Leak patterns.** The household's names, handles, emails and addresses are kept in his private bundle at
29
31
  * `eval/leak-patterns.json` (`{ "literals": [...] }`) and never committed to the harness. They are read from the
30
- * same commit as the rest, so an older commit is checked against the list it had then. Each one is matched, in any
31
- * case, against every projected file's and folder's name, every file's contents and every gap before any model call.
32
- * A match, or no pattern file, stops the projection and removes it; the error gives counts only, never a match.
32
+ * same commit as the rest, so an older commit is checked against the list it had then. A pattern matches in any case
33
+ * and as a whole word only: not inside a longer run of letters (digits don't count, so `name99` matches). One with a
34
+ * letter outside basic Latin matches anywhere (see `wordPattern`).
35
+ * - **Redaction.** Every match in a copied file's contents is replaced with a placeholder fixed by the pattern's place
36
+ * in the list, the same in every file: "Member A", "Member B", ..., or "member-a@example.invalid" for a pattern
37
+ * holding `@`, or "@member-a" for a handle starting with it. Longer patterns are replaced first. A gap gives only how many strings and files were replaced.
38
+ * - **Leak lint.** After redaction the patterns are matched again against every projected file's and folder's name,
39
+ * every file's contents and every gap, before any model call. A match, or no pattern file, stops the projection and
40
+ * removes it; the error gives counts only, never a match.
33
41
  * `git archive` follows the bundle repository's `export-ignore` and `export-subst` attributes; a top-level entry left
34
42
  * out that way fails the archive's completeness check.
35
43
  * What differs from the live bundle comes back as `gaps`, which every report lists.
@@ -204,10 +212,85 @@ function readLeakPatterns(archiveDir) {
204
212
  }
205
213
  return literals.map((literal) => literal.trim().toLowerCase());
206
214
  }
215
+ /**
216
+ * A pattern in any case, as a whole word: not next to another letter, so a name inside a longer word is no match, but
217
+ * a handle next to digits (`name99`) is. Words in a pattern match across any run of spaces or line breaks. A pattern
218
+ * with a letter outside basic Latin matches anywhere, since scripts such as Japanese don't separate words and Hebrew
219
+ * joins prefixes to names.
220
+ */
221
+ function wordPattern(pattern) {
222
+ const body = pattern.split(/\s+/).map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\s+");
223
+ if (/[^\p{ASCII}]/u.test(pattern))
224
+ return new RegExp(body, "giu");
225
+ return new RegExp(`(?<![\\p{L}\\p{M}])${body}(?![\\p{L}\\p{M}])`, "giu");
226
+ }
227
+ const holdsAny = (text, patterns) => patterns.some((pattern) => wordPattern(pattern).test(text));
228
+ /**
229
+ * The placeholder for the pattern at `index`: "Member A" to "Member Z", then "Member AA"; an email's is an address
230
+ * and a handle's (`@name`) a handle. A pattern such as `member` or `example` would match its own placeholder, which the
231
+ * second lint then refuses.
232
+ */
233
+ function placeholder(index, pattern) {
234
+ let letters = "";
235
+ for (let n = index + 1; n > 0; n = Math.floor((n - 1) / 26))
236
+ letters = String.fromCharCode(65 + ((n - 1) % 26)) + letters;
237
+ if (pattern.startsWith("@"))
238
+ return `@member-${letters.toLowerCase()}`;
239
+ return pattern.includes("@") ? `member-${letters.toLowerCase()}@example.invalid` : `Member ${letters}`;
240
+ }
241
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
242
+ function filesUnder(root) {
243
+ const found = [];
244
+ const walk = (relative) => {
245
+ const full = node_path_1.default.join(root, relative);
246
+ if (node_fs_1.default.lstatSync(full).isDirectory())
247
+ for (const name of node_fs_1.default.readdirSync(full).sort())
248
+ walk(relative ? node_path_1.default.posix.join(relative, name) : name);
249
+ else
250
+ found.push(relative);
251
+ };
252
+ walk("");
253
+ return found;
254
+ }
255
+ /**
256
+ * Replaces every match in the contents of each file under `root` with its pattern's placeholder. A file that isn't
257
+ * UTF-8 text is left as it is, so the lint after this refuses it if it holds a pattern.
258
+ */
259
+ function redact(root, patterns) {
260
+ const order = patterns.map((pattern, index) => ({ pattern, index })).sort((a, b) => b.pattern.length - a.pattern.length || a.index - b.index);
261
+ let strings = 0;
262
+ let files = 0;
263
+ for (const relative of filesUnder(root)) {
264
+ const full = node_path_1.default.join(root, relative);
265
+ let text;
266
+ try {
267
+ text = utf8.decode(node_fs_1.default.readFileSync(full));
268
+ }
269
+ catch {
270
+ continue;
271
+ }
272
+ let here = 0;
273
+ for (const { pattern, index } of order) {
274
+ text = text.replace(wordPattern(pattern), () => { here += 1; return placeholder(index, pattern); });
275
+ }
276
+ if (here > 0) {
277
+ // A failed write's error names the file, whose path the lint hasn't checked yet.
278
+ try {
279
+ node_fs_1.default.writeFileSync(full, text);
280
+ }
281
+ catch {
282
+ refuse("a projected file couldn't be rewritten with placeholders");
283
+ }
284
+ strings += here;
285
+ files += 1;
286
+ }
287
+ }
288
+ return { strings, files };
289
+ }
207
290
  /** Every file or folder under `root` whose path, or a file's contents, holds a pattern, by its path relative to `root`. */
208
291
  function leakLint(root, patterns) {
209
292
  const flagged = [];
210
- const holds = (text) => patterns.some((pattern) => text.toLowerCase().includes(pattern));
293
+ const holds = (text) => holdsAny(text, patterns);
211
294
  const walk = (relative) => {
212
295
  const full = node_path_1.default.join(root, relative);
213
296
  if (node_fs_1.default.lstatSync(full).isDirectory()) {
@@ -237,6 +320,7 @@ function projectSlugger(input) {
237
320
  const patterns = readLeakPatterns(input.archive);
238
321
  node_fs_1.default.mkdirSync(input.out, { recursive: true, mode: 0o755 });
239
322
  const gaps = [];
323
+ let redactedStrings = 0;
240
324
  try {
241
325
  for (const include of input.include.filter((each) => each !== "agent.json")) {
242
326
  const parts = include.split("/");
@@ -267,8 +351,12 @@ function projectSlugger(input) {
267
351
  node_fs_1.default.mkdirSync(node_path_1.default.join(input.out, dir), { recursive: true });
268
352
  node_fs_1.default.writeFileSync(node_path_1.default.join(input.out, "books/ledger.ndjson"), "");
269
353
  gaps.push("psyche/TACIT.md and psyche/memory: left out", "friends, state, arc, desk and books: start empty", "browser: left out");
354
+ const redacted = redact(input.out, patterns);
355
+ redactedStrings = redacted.strings;
356
+ if (redacted.strings > 0)
357
+ gaps.push(`${redacted.strings} private strings replaced with placeholders in ${redacted.files} ${redacted.files === 1 ? "file" : "files"}`);
270
358
  // Gaps go into every report, so they are checked like the files are.
271
- const flagged = leakLint(input.out, patterns).length + gaps.filter((gap) => patterns.some((pattern) => gap.toLowerCase().includes(pattern))).length;
359
+ const flagged = leakLint(input.out, patterns).length + gaps.filter((gap) => holdsAny(gap, patterns)).length;
272
360
  if (flagged > 0)
273
361
  refuse(`${flagged} projected path(s) or gap(s) hold a leak pattern; nothing was run`);
274
362
  }
@@ -276,7 +364,7 @@ function projectSlugger(input) {
276
364
  node_fs_1.default.rmSync(input.out, { recursive: true, force: true });
277
365
  throw error;
278
366
  }
279
- (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.slugger_projection", message: "projected Slugger's bundle", meta: { gaps: gaps.length } });
367
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.slugger_projection", message: "projected Slugger's bundle", meta: { gaps: gaps.length, redacted: redactedStrings } });
280
368
  return { gaps };
281
369
  }
282
370
  /** Slugger's profile for a run on an archive `archiveBundle` made; the caller removes the archive afterwards. */
@@ -560,7 +560,8 @@ function toResponsesTools(ccTools) {
560
560
  name: t.function.name,
561
561
  description: t.function.description ?? null,
562
562
  parameters: t.function.parameters ?? null,
563
- strict: false,
563
+ // A tool that asks for strict schemas keeps it; every other tool is sent non-strict, as before.
564
+ strict: t.function.strict ?? false,
564
565
  }));
565
566
  }
566
567
  /** Providers send an empty string for a tool called with no arguments; every reader expects a JSON object. */
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1503",
3
+ "version": "0.1.0-alpha.1505",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1503",
9
+ "version": "0.1.0-alpha.1505",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1503",
3
+ "version": "0.1.0-alpha.1505",
4
4
  "description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
5
5
  "homepage": "https://ouroboros.bot/",
6
6
  "engines": {