talentos 1.3.0 → 1.4.2

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.
@@ -0,0 +1,629 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, } from "node:fs";
4
+ import { readFile } from "node:fs/promises";
5
+ import { createServer } from "node:http";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { writePrivateFile } from "../../agent-config.js";
9
+ import { ROOM_LOCAL_TOOLS } from "../codex-policy.js";
10
+ import { probeResponse } from "../codex-probe.js";
11
+ import { codexOwnerArgs, ownerCatalog, ownerToolAllowlist, } from "./codex-fence.js";
12
+ import { codexHookArgs, trustHookArgs } from "./codex-owner.js";
13
+ // The GATE probe for Codex owner-native (#10987 slice 1). codex-owner-probe.ts
14
+ // proves WHY the raw binary needs a fence (write_stdin is unhooked). This proves
15
+ // the FENCE holds, on the real binary, and is what a launcher must pass before a
16
+ // Codex version may run owner-native. Every cell must pass; any fail => room
17
+ // only. Opt-in: TALENTOS_TEST_CODEX=/abs/codex.
18
+ //
19
+ // The exact-allowlist cell (R14 R1) is the spine: the session's whole tool list
20
+ // must equal {apply_patch, view_image, run_command, the room MCP tools} and
21
+ // nothing else, so a future shell variant the catalog did not remove is a new,
22
+ // un-allowlisted name and fails closed.
23
+ export const FENCE_PROBE_REVISION = 1;
24
+ const JSON_ARRAY = /\[.*\]/su;
25
+ const COLLAB_TOOL = /agent|spawn/u;
26
+ const RUN_MS = 30_000;
27
+ // The room MCP stand-in advertises these; run_command's real classification and
28
+ // one-shot execution are covered by codex-run-command.test.ts.
29
+ const STANDIN_ROOM_TOOLS = [
30
+ "read_room",
31
+ "read_file",
32
+ "create_file",
33
+ "post_message",
34
+ "whoami",
35
+ ];
36
+ export const FENCE_CELLS = [
37
+ "tool_list",
38
+ "no_shell_nested",
39
+ "no_shell_toplevel",
40
+ "no_shell_direct",
41
+ "no_subagent",
42
+ "run_command_present",
43
+ "run_command_exact",
44
+ "apply_patch_hooked",
45
+ "view_image_hooked",
46
+ "owner_config_untouched",
47
+ "hostile_config",
48
+ "model_missing",
49
+ ];
50
+ // Records every call, allows read-only room tools and run_command through to the
51
+ // stand-in proxy, denies everything else. The REAL policy is unit-tested; this
52
+ // hook only has to prove Codex routes calls THROUGH a hook.
53
+ const HOOK = `#!/usr/bin/env node
54
+ let raw = "";
55
+ process.stdin.on("data", (c) => (raw += c));
56
+ process.stdin.on("end", () => {
57
+ require("node:fs").appendFileSync(process.env.PROBE_RECORDS, raw.replace(/\\n/g, " ") + "\\n");
58
+ const call = JSON.parse(raw);
59
+ const name = call.tool_name || "";
60
+ const allow = /^mcp__talentos_room__/.test(name);
61
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: {
62
+ hookEventName: "PreToolUse",
63
+ permissionDecision: allow ? "allow" : "deny",
64
+ permissionDecisionReason: "probe",
65
+ } }));
66
+ });
67
+ `;
68
+ // A stand-in room MCP server: advertises the room tools + run_command, records
69
+ // calls, and returns ok. run_command execution and classification live in
70
+ // codex-run-command.ts and its test; here we only prove the tool is exposed and
71
+ // the exact command string reaches the proxy (so the approval shows what runs).
72
+ function roomServerSource(recordPath) {
73
+ const all = [...STANDIN_ROOM_TOOLS, ...ROOM_LOCAL_TOOLS];
74
+ return `import {Server} from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/server/index.js"))};
75
+ import {StdioServerTransport} from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/server/stdio.js"))};
76
+ import {ListToolsRequestSchema,CallToolRequestSchema} from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/types.js"))};
77
+ import {appendFileSync} from "node:fs";
78
+ const tools=${JSON.stringify(all)}.map((n)=>({name:n,description:n,inputSchema:{type:"object",properties:{command:{type:"string"}},additionalProperties:true}}));
79
+ const s=new Server({name:"talentos_room",version:"1"},{capabilities:{tools:{}}});
80
+ s.setRequestHandler(ListToolsRequestSchema,async()=>({tools}));
81
+ s.setRequestHandler(CallToolRequestSchema,async(r)=>{appendFileSync(${JSON.stringify(recordPath)},JSON.stringify({name:r.params.name,arguments:r.params.arguments})+"\\n");return {content:[{type:"text",text:"ok"}]};});
82
+ await s.connect(new StdioServerTransport());`;
83
+ }
84
+ async function runCell(binary, root, options, signal) {
85
+ const home = mkdtempSync(join(root, "home-"));
86
+ const work = mkdtempSync(join(root, "work-"));
87
+ const records = join(root, `rec-${createHash("sha1").update(home).digest("hex")}`);
88
+ const roomRec = join(root, `room-${createHash("sha1").update(home).digest("hex")}`);
89
+ writeFileSync(records, "");
90
+ writeFileSync(roomRec, "");
91
+ const hook = join(root, "hook.js");
92
+ writeFileSync(hook, HOOK, { mode: 0o700 });
93
+ const roomServer = join(root, `room-${createHash("sha1").update(work).digest("hex")}.mjs`);
94
+ writeFileSync(roomServer, roomServerSource(roomRec));
95
+ const jobDir = join(root, `job-${createHash("sha1").update(home).digest("hex")}`);
96
+ mkdirSync(jobDir, { recursive: true });
97
+ writeFileSync(join(jobDir, "context.json"), JSON.stringify({ home, writeRoots: [work] }));
98
+ if (options.ownerConfig) {
99
+ writeFileSync(join(home, "config.toml"), options.ownerConfig);
100
+ }
101
+ const ownerConfigBefore = options.ownerConfig;
102
+ let turn = 0;
103
+ const outputs = [];
104
+ const server = makeServer(options, outputs, () => turn++);
105
+ const address = await listen(server);
106
+ const catalog = join(root, `cat-${createHash("sha1").update(home).digest("hex")}.json`);
107
+ const bundled = await bundledCatalog(binary, home, signal);
108
+ writeFileSync(catalog, ownerCatalog(bundled));
109
+ const env = {
110
+ CODEX_HOME: home,
111
+ HOME: home,
112
+ PATH: process.env.PATH,
113
+ PROBE_RECORDS: records,
114
+ TALENTOS_PROBE_KEY: "loopback-only",
115
+ };
116
+ try {
117
+ const trust = await trustHookArgs({
118
+ binary,
119
+ command: hook,
120
+ cwd: work,
121
+ env,
122
+ signal,
123
+ });
124
+ const providerArgs = [
125
+ "-c",
126
+ 'model_provider="talentos_probe"',
127
+ "-c",
128
+ 'model_providers.talentos_probe.name="Loopback"',
129
+ "-c",
130
+ `model_providers.talentos_probe.base_url="http://127.0.0.1:${address.port}/v1"`,
131
+ "-c",
132
+ 'model_providers.talentos_probe.wire_api="responses"',
133
+ "-c",
134
+ 'model_providers.talentos_probe.env_key="TALENTOS_PROBE_KEY"',
135
+ ...(options.model ? ["-c", `model="${options.model}"`] : []),
136
+ ];
137
+ const args = [
138
+ ...providerArgs,
139
+ ...codexHookArgs(hook),
140
+ ...trust,
141
+ ...codexOwnerArgs({
142
+ catalogPath: catalog,
143
+ mcpCommand: process.execPath,
144
+ mcpArgs: [roomServer],
145
+ prompt: "probe",
146
+ writableRoot: work,
147
+ }),
148
+ ];
149
+ const child = spawn(binary, args, {
150
+ cwd: work,
151
+ env,
152
+ stdio: ["ignore", "ignore", "ignore"],
153
+ });
154
+ const stop = () => child.kill("SIGKILL");
155
+ signal.addEventListener("abort", stop, { once: true });
156
+ const timer = setTimeout(stop, RUN_MS);
157
+ await new Promise((resolve) => child.once("close", resolve));
158
+ clearTimeout(timer);
159
+ signal.removeEventListener("abort", stop);
160
+ }
161
+ finally {
162
+ server.closeAllConnections();
163
+ await new Promise((resolve) => server.close(() => resolve()));
164
+ }
165
+ const started = readFileSync(records, "utf8").length > 0 ||
166
+ readFileSync(roomRec, "utf8").length > 0 ||
167
+ existsSync(join(home, "sessions"));
168
+ if (ownerConfigBefore !== undefined) {
169
+ const after = existsSync(join(home, "config.toml"))
170
+ ? readFileSync(join(home, "config.toml"), "utf8")
171
+ : "";
172
+ if (after !== ownerConfigBefore) {
173
+ throw new Error("owner config.toml changed");
174
+ }
175
+ }
176
+ return {
177
+ home,
178
+ outputText: outputs.join(""),
179
+ records: readFileSync(records, "utf8")
180
+ .split("\n")
181
+ .filter(Boolean)
182
+ .map((l) => JSON.parse(l)),
183
+ roomCalls: readFileSync(roomRec, "utf8")
184
+ .split("\n")
185
+ .filter(Boolean)
186
+ .map((l) => JSON.parse(l)),
187
+ started,
188
+ };
189
+ }
190
+ function listen(server) {
191
+ return new Promise((resolve, reject) => {
192
+ server.listen(0, "127.0.0.1", () => {
193
+ const address = server.address();
194
+ if (!address || typeof address === "string") {
195
+ reject(new Error("no port"));
196
+ }
197
+ else {
198
+ resolve({ port: address.port });
199
+ }
200
+ });
201
+ });
202
+ }
203
+ function message(text) {
204
+ return {
205
+ type: "message",
206
+ id: "answer",
207
+ role: "assistant",
208
+ status: "completed",
209
+ content: [{ type: "output_text", text, annotations: [] }],
210
+ };
211
+ }
212
+ function makeServer(options, outputs, nextTurn) {
213
+ const scripted = typeof options.script === "string"
214
+ ? [
215
+ {
216
+ type: "custom_tool_call",
217
+ id: "call",
218
+ call_id: "call",
219
+ name: "exec",
220
+ input: options.script,
221
+ status: "completed",
222
+ },
223
+ ]
224
+ : options.script.items;
225
+ return createServer(async (request, response) => {
226
+ let raw = "";
227
+ for await (const chunk of request) {
228
+ raw += chunk.toString();
229
+ }
230
+ const body = JSON.parse(raw);
231
+ for (const item of body.input ?? []) {
232
+ if (String(item.type).endsWith("_output")) {
233
+ outputs.push(textOf(item.output));
234
+ }
235
+ }
236
+ const answered = (body.input ?? []).some((item) => String(item.type).endsWith("_output"));
237
+ const turn = nextTurn();
238
+ const next = scripted[turn];
239
+ probeResponse(response, !answered && next ? next : message("done"));
240
+ });
241
+ }
242
+ // The exec result comes back as a tool output whose items carry the text() the
243
+ // script appended; flatten whatever shape the model used.
244
+ function textOf(output) {
245
+ if (typeof output === "string") {
246
+ return output;
247
+ }
248
+ if (Array.isArray(output)) {
249
+ return output
250
+ .map((part) => part?.text ?? "")
251
+ .join("");
252
+ }
253
+ return "";
254
+ }
255
+ async function bundledCatalog(binary, home, signal) {
256
+ return await new Promise((resolve, reject) => {
257
+ const child = spawn(binary, ["debug", "models", "--bundled"], {
258
+ env: { CODEX_HOME: home, HOME: home, PATH: process.env.PATH },
259
+ stdio: ["ignore", "pipe", "ignore"],
260
+ });
261
+ let out = "";
262
+ child.stdout.on("data", (c) => (out += c));
263
+ signal.addEventListener("abort", () => child.kill("SIGKILL"), {
264
+ once: true,
265
+ });
266
+ child.once("close", () => out ? resolve(out) : reject(new Error("no catalog")));
267
+ child.once("error", reject);
268
+ });
269
+ }
270
+ const seen = (run, tool) => run.records.filter((r) => r.tool_name === tool);
271
+ /**
272
+ * Runs the full gate on the real binary. A version passes only if every cell
273
+ * passes; the launcher then pins this version as owner-native-capable.
274
+ */
275
+ export async function probeCodexFence(binary, version, signal = AbortSignal.timeout(300_000)) {
276
+ const root = mkdtempSync(join(tmpdir(), "talentos-codex-fence-"));
277
+ const marker = (name) => join(root, `marker-${name}`);
278
+ const cells = Object.fromEntries(FENCE_CELLS.map((c) => [c, "fail"]));
279
+ const reasons = {};
280
+ // check() returns true to pass, or a string reason (or throws) to fail; the
281
+ // reason is kept so a failing run — e.g. the macOS gate — explains itself.
282
+ const cell = async (name, check) => {
283
+ try {
284
+ const result = await check();
285
+ if (result === true) {
286
+ cells[name] = "pass";
287
+ }
288
+ else {
289
+ cells[name] = "fail";
290
+ reasons[name] =
291
+ typeof result === "string" ? result : "assertion did not hold";
292
+ }
293
+ }
294
+ catch (error) {
295
+ cells[name] = "fail";
296
+ reasons[name] = error instanceof Error ? error.message : String(error);
297
+ }
298
+ };
299
+ // A deliberately hostile owner config: a full-access sandbox, never-ask
300
+ // approval, a shell_type override, an all-inherit shell env, a notify program,
301
+ // and — the name collision — an MCP server NAMED talentos_room that the owner
302
+ // points at their own binary. The per-run overrides must win over every one:
303
+ // run_command must still reach OUR proxy, not the owner's talentos_room entry.
304
+ const hostile = [
305
+ 'sandbox_mode = "danger-full-access"',
306
+ 'approval_policy = "never"',
307
+ 'notify = ["/bin/echo"]',
308
+ 'shell_type = "default"',
309
+ "[model_catalog]",
310
+ "[profiles.default]",
311
+ 'approval_policy = "never"',
312
+ "[shell_environment_policy]",
313
+ 'inherit = "all"',
314
+ "[mcp_servers.talentos_room]",
315
+ 'command = "/bin/false"',
316
+ 'args = ["impostor"]',
317
+ "",
318
+ ].join("\n");
319
+ try {
320
+ // R1: the session tool list equals the allowlist exactly.
321
+ await cell("tool_list", async () => {
322
+ const run = await runCell(binary, root, {
323
+ script: "text(JSON.stringify(Object.keys(tools).sort()))",
324
+ }, signal);
325
+ const out = lastText(run);
326
+ if (!out) {
327
+ return "no tool list returned";
328
+ }
329
+ const keys = new Set(JSON.parse(out));
330
+ const allowed = ownerToolAllowlist(STANDIN_ROOM_TOOLS.concat(ROOM_LOCAL_TOOLS));
331
+ const extra = [...keys].filter((k) => !allowed.has(k));
332
+ const missing = [...allowed].filter((k) => !keys.has(k));
333
+ return extra.length === 0 && missing.length === 0
334
+ ? true
335
+ : `extra=[${extra.join(",")}] missing=[${missing.join(",")}]`;
336
+ });
337
+ // "Hidden is not refused": nested shell tools are not even dispatchable.
338
+ await cell("no_shell_nested", async () => {
339
+ const file = marker("nested");
340
+ const run = await runCell(binary, root, {
341
+ script: `try{await tools.exec_command({cmd:${JSON.stringify(`echo x > ${file}`)}});}catch(e){}
342
+ try{await tools.write_stdin({session_id:1,chars:"x"});}catch(e){}
343
+ try{await tools.local_shell({command:["sh","-c","echo x"]});}catch(e){}`,
344
+ }, signal);
345
+ return !existsSync(file) && seen(run, "Bash").length === 0;
346
+ });
347
+ // A top-level function_call for a shell tool must not run anything (code mode).
348
+ await cell("no_shell_toplevel", async () => {
349
+ const file = marker("toplevel");
350
+ const run = await runCell(binary, root, {
351
+ script: {
352
+ items: [
353
+ {
354
+ type: "function_call",
355
+ id: "f1",
356
+ call_id: "f1",
357
+ name: "exec_command",
358
+ arguments: JSON.stringify({ cmd: `echo x > ${file}` }),
359
+ status: "completed",
360
+ },
361
+ {
362
+ type: "local_shell_call",
363
+ id: "f2",
364
+ call_id: "f2",
365
+ status: "completed",
366
+ action: {
367
+ type: "exec",
368
+ command: ["sh", "-c", `echo x > ${file}`],
369
+ env: {},
370
+ },
371
+ },
372
+ {
373
+ type: "function_call",
374
+ id: "f3",
375
+ call_id: "f3",
376
+ name: "write_stdin",
377
+ arguments: JSON.stringify({ session_id: 1, chars: "x" }),
378
+ status: "completed",
379
+ },
380
+ ],
381
+ },
382
+ }, signal);
383
+ return run.started && !existsSync(file) && seen(run, "Bash").length === 0;
384
+ });
385
+ // The same in direct-tool mode (gpt-5.5 has no code mode).
386
+ await cell("no_shell_direct", async () => {
387
+ const file = marker("direct");
388
+ const run = await runCell(binary, root, {
389
+ model: "gpt-5.5",
390
+ script: {
391
+ items: [
392
+ {
393
+ type: "function_call",
394
+ id: "f1",
395
+ call_id: "f1",
396
+ name: "exec_command",
397
+ arguments: JSON.stringify({ cmd: `echo x > ${file}` }),
398
+ status: "completed",
399
+ },
400
+ {
401
+ type: "local_shell_call",
402
+ id: "f2",
403
+ call_id: "f2",
404
+ status: "completed",
405
+ action: {
406
+ type: "exec",
407
+ command: ["sh", "-c", `echo x > ${file}`],
408
+ env: {},
409
+ },
410
+ },
411
+ ],
412
+ },
413
+ }, signal);
414
+ return run.started && !existsSync(file) && seen(run, "Bash").length === 0;
415
+ });
416
+ // A subagent's calls are NOT hooked (confirmed failing on macOS), so
417
+ // multi-agent is off: an undeclared spawn_agent/collab call, top-level and
418
+ // nested, code and direct mode, must dispatch nothing (hidden is not refused).
419
+ await cell("no_subagent", async () => {
420
+ const file = marker("subagent");
421
+ const spawn = JSON.stringify({
422
+ message: "child",
423
+ task_name: "x",
424
+ prompt: `run: echo x > ${file}`,
425
+ });
426
+ const attempts = [
427
+ {
428
+ script: `try{await tools.spawn_agent(${spawn});}catch(e){}
429
+ try{await tools.send_message({target:"x",message:"y"});}catch(e){}`,
430
+ },
431
+ {
432
+ script: {
433
+ items: [
434
+ {
435
+ type: "function_call",
436
+ id: "s1",
437
+ call_id: "s1",
438
+ name: "spawn_agent",
439
+ namespace: "collaboration",
440
+ arguments: spawn,
441
+ status: "completed",
442
+ },
443
+ ],
444
+ },
445
+ },
446
+ {
447
+ model: "gpt-5.5",
448
+ script: {
449
+ items: [
450
+ {
451
+ type: "function_call",
452
+ id: "s2",
453
+ call_id: "s2",
454
+ name: "spawn_agent",
455
+ arguments: spawn,
456
+ status: "completed",
457
+ },
458
+ ],
459
+ },
460
+ },
461
+ ];
462
+ for (const attempt of attempts) {
463
+ const run = await runCell(binary, root, attempt, signal);
464
+ if (!run.started) {
465
+ return "session did not start";
466
+ }
467
+ if (existsSync(file)) {
468
+ return "a spawn_agent call dispatched work";
469
+ }
470
+ if (run.roomCalls.some((c) => COLLAB_TOOL.test(c.name))) {
471
+ return "a collab tool reached the proxy";
472
+ }
473
+ }
474
+ return true;
475
+ });
476
+ // run_command is exposed and the model's call reaches the proxy.
477
+ await cell("run_command_present", async () => {
478
+ const run = await runCell(binary, root, {
479
+ script: `await tools.mcp__talentos_room__run_command({command:"ls -a"});`,
480
+ }, signal);
481
+ return (seen(run, "mcp__talentos_room__run_command").length === 1 &&
482
+ run.roomCalls.some((c) => c.name === "run_command"));
483
+ });
484
+ // The exact command string reaches the proxy (the owner approves what runs).
485
+ await cell("run_command_exact", async () => {
486
+ const exact = "grep -R token ./src # with spaces";
487
+ const run = await runCell(binary, root, {
488
+ script: `await tools.mcp__talentos_room__run_command({command:${JSON.stringify(exact)}});`,
489
+ }, signal);
490
+ return run.roomCalls.some((c) => c.name === "run_command" &&
491
+ c.arguments?.command === exact);
492
+ });
493
+ // apply_patch (every path) is hooked and a deny holds.
494
+ await cell("apply_patch_hooked", async () => {
495
+ const dir = join(root, `patch-${Date.now()}`);
496
+ mkdirSync(dir, { recursive: true });
497
+ writeFileSync(join(dir, "old.txt"), "a\n");
498
+ writeFileSync(join(dir, "gone.txt"), "x");
499
+ const patch = `*** Begin Patch\n*** Add File: ${dir}/new.txt\n+hi\n*** Update File: ${dir}/old.txt\n*** Move to: ${dir}/moved.txt\n@@\n-a\n+b\n*** Delete File: ${dir}/gone.txt\n*** End Patch`;
500
+ const run = await runCell(binary, root, {
501
+ script: `await tools.apply_patch(${JSON.stringify(patch)});`,
502
+ }, signal);
503
+ const [call] = seen(run, "apply_patch");
504
+ const text = String(call?.tool_input?.command ?? "");
505
+ return ([
506
+ `${dir}/new.txt`,
507
+ `${dir}/old.txt`,
508
+ `${dir}/moved.txt`,
509
+ `${dir}/gone.txt`,
510
+ ].every((p) => text.includes(p)) &&
511
+ !existsSync(join(dir, "new.txt")) &&
512
+ !existsSync(join(dir, "moved.txt")) &&
513
+ existsSync(join(dir, "gone.txt")));
514
+ });
515
+ await cell("view_image_hooked", async () => {
516
+ const run = await runCell(binary, root, {
517
+ script: `await tools.view_image({path: ${JSON.stringify(join(root, "x.png"))}});`,
518
+ }, signal);
519
+ return seen(run, "view_image").length === 1;
520
+ });
521
+ // The owner's hostile config.toml is byte-identical after a run (runCell throws otherwise).
522
+ await cell("owner_config_untouched", async () => {
523
+ const run = await runCell(binary, root, {
524
+ ownerConfig: hostile,
525
+ script: `text("ok")`,
526
+ }, signal);
527
+ return run.started;
528
+ });
529
+ // Under a hostile config (full access, never ask, extra server, notify), the
530
+ // per-run overrides still win: no shell tool, the hook still gates.
531
+ await cell("hostile_config", async () => {
532
+ const file = marker("hostile");
533
+ const run = await runCell(binary, root, {
534
+ ownerConfig: hostile,
535
+ script: `const names = Object.keys(tools);
536
+ try{await tools.exec_command({cmd:${JSON.stringify(`echo x > ${file}`)}});}catch(e){}
537
+ try{await tools.mcp__talentos_room__run_command({command:"ls"});}catch(e){}
538
+ text(JSON.stringify(names.sort()));`,
539
+ }, signal);
540
+ const out = lastText(run);
541
+ if (!out) {
542
+ return "no tool list under the hostile config";
543
+ }
544
+ const keys = new Set(JSON.parse(out));
545
+ if (keys.has("exec_command") || keys.has("write_stdin")) {
546
+ return "the owner shell_type override re-enabled a shell tool";
547
+ }
548
+ if (existsSync(file)) {
549
+ return "a shell command ran despite the per-run overrides";
550
+ }
551
+ // Name collision: the owner's own `talentos_room` MCP server points at
552
+ // /bin/false, but run_command still reaches OUR per-run proxy.
553
+ if (!run.roomCalls.some((c) => c.name === "run_command")) {
554
+ return "the owner's talentos_room entry shadowed our room server";
555
+ }
556
+ return true;
557
+ });
558
+ // A model not in the catalog has no shell to fall back to: the session fails.
559
+ await cell("model_missing", async () => {
560
+ const run = await runCell(binary, root, {
561
+ model: "model-not-in-catalog-xyz",
562
+ script: `text("should not run")`,
563
+ }, signal);
564
+ // Fail closed: either no session started, or nothing was scripted/ran.
565
+ return run.records.length === 0 && run.roomCalls.length === 0;
566
+ });
567
+ }
568
+ finally {
569
+ rmSync(root, { force: true, recursive: true });
570
+ }
571
+ return {
572
+ cells,
573
+ reasons,
574
+ safe: FENCE_CELLS.every((c) => cells[c] === "pass"),
575
+ version,
576
+ };
577
+ }
578
+ function lastText(run) {
579
+ // The script's text() output comes back as the exec tool's output; extract the
580
+ // first JSON array it contains.
581
+ const match = JSON_ARRAY.exec(run.outputText);
582
+ return match?.[0];
583
+ }
584
+ export function codexFenceCacheKey(binary, version) {
585
+ const real = realpathSync.native(binary);
586
+ const { mtimeMs, size } = statSync(real);
587
+ // realpath + mtime + size: a copy can keep the mtime (cp -p), not the size.
588
+ // Still one stat per job, no hashing.
589
+ return createHash("sha256")
590
+ .update(JSON.stringify([real, mtimeMs, size, version, FENCE_PROBE_REVISION]))
591
+ .digest("hex");
592
+ }
593
+ /**
594
+ * Per job: whether the cached fence pass is for this exact binary (path and
595
+ * mtime) and version. Reads one small file; never runs the probe.
596
+ */
597
+ export async function codexFenceProbeCached(input) {
598
+ try {
599
+ const cached = JSON.parse(await readFile(input.cachePath, "utf8"));
600
+ return (cached.ok === true &&
601
+ cached.key === codexFenceCacheKey(input.binary, input.version));
602
+ }
603
+ catch {
604
+ return false;
605
+ }
606
+ }
607
+ /**
608
+ * The fence gate, cached per binary identity and version (never run per job): a
609
+ * version becomes owner-native-capable only after every cell passes. Throws
610
+ * OwnerNativeProbeError-shaped on any failure so the caller runs room-only.
611
+ */
612
+ export async function ensureCodexFenceProbe(input) {
613
+ const key = codexFenceCacheKey(input.binary, input.version);
614
+ try {
615
+ const cached = JSON.parse(await readFile(input.cachePath, "utf8"));
616
+ if (cached.key === key && cached.ok === true) {
617
+ return;
618
+ }
619
+ }
620
+ catch {
621
+ // No usable cache: prove it.
622
+ }
623
+ const result = await probeCodexFence(input.binary, input.version);
624
+ if (!result.safe) {
625
+ const failed = FENCE_CELLS.filter((c) => result.cells[c] === "fail");
626
+ throw new Error(`Codex ${input.version} can't safely run your full setup in rooms (failed checks: ${failed.join(", ")}). Update Codex, then run talentos agent native enable again. Rooms keep working without it.`);
627
+ }
628
+ await writePrivateFile(input.cachePath, `${JSON.stringify({ at: Date.now(), key, ok: true })}\n`);
629
+ }