talentos 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,6 +12,7 @@ import { providerPathEnv, resolveProviderBinary } from "../provider-binary.js";
12
12
  import { codexRoomArgs, ROOM_TOOLS } from "./codex-policy.js";
13
13
  import { CodexBoundaryError, probeCodexBoundary } from "./codex-probe.js";
14
14
  import { prepareOwnerLaunch } from "./native/launch.js";
15
+ import { readReceipts } from "./native/receipts.js";
15
16
  const CHILD_ENV = [
16
17
  "HOME",
17
18
  "PATH",
@@ -205,6 +206,7 @@ export async function runProvider(input) {
205
206
  jobId: job.jobId,
206
207
  prompt,
207
208
  sessionId,
209
+ sharedRoom: job.native?.sharedRoom,
208
210
  workspace: input.owner.workspace,
209
211
  });
210
212
  command = binary;
@@ -375,6 +377,12 @@ export async function runProvider(input) {
375
377
  await rm(mcpPath, { force: true });
376
378
  await rm(catalogPath, { force: true });
377
379
  stopWatching?.();
380
+ if (ownerLaunch && input.receipts) {
381
+ // Best effort: a lost record never changes how the job ended.
382
+ await readReceipts(ownerLaunch.jobDir)
383
+ .then((rows) => (rows.length > 0 ? input.receipts?.(rows) : undefined))
384
+ .catch(() => undefined);
385
+ }
378
386
  await ownerLaunch?.cleanup();
379
387
  }
380
388
  }
@@ -36,7 +36,9 @@ export class AgentGateway {
36
36
  }
37
37
  return response.status === 204 ? null : (await response.json());
38
38
  }
39
- async subscribe(wake, fallback) {
39
+ async subscribe(wake, fallback,
40
+ // Jobs of this agent that were cancelled (the owner's Stop): end them now.
41
+ stopped) {
40
42
  const initial = await this.request("/agent-gateway/token");
41
43
  if (!(initial && isSecureUrl(new URL(initial.convexUrl)))) {
42
44
  throw new Error("Agent push is unavailable.");
@@ -62,8 +64,12 @@ export class AgentGateway {
62
64
  wake();
63
65
  }
64
66
  }, () => fallback());
67
+ const unsubscribeStops = stopped
68
+ ? client.onUpdate(makeFunctionReference("externalAgents/jobs:jobControl"), {}, (jobIds) => stopped(jobIds), () => undefined)
69
+ : undefined;
65
70
  return async () => {
66
71
  unsubscribe();
72
+ unsubscribeStops?.();
67
73
  await client.close();
68
74
  };
69
75
  }
@@ -18,6 +18,18 @@ const MAX_LINE = 4096;
18
18
  const asAnswer = (status) => status === "approved" || status === "denied" || status === "expired"
19
19
  ? status
20
20
  : undefined;
21
+ function parseReport(line) {
22
+ try {
23
+ const value = JSON.parse(line);
24
+ if (value.touch === true || value.taint === true) {
25
+ return { taint: value.taint === true, touch: value.touch === true };
26
+ }
27
+ }
28
+ catch {
29
+ // Not a report.
30
+ }
31
+ return;
32
+ }
21
33
  function parseAsk(line) {
22
34
  try {
23
35
  const value = JSON.parse(line);
@@ -46,6 +58,10 @@ export class ApprovalBridge {
46
58
  onWaiting;
47
59
  statusEveryMs;
48
60
  waiters = new Map();
61
+ reported = {
62
+ taint: undefined,
63
+ touch: undefined,
64
+ };
49
65
  waiting = false;
50
66
  polling = false;
51
67
  lastPollAt = 0;
@@ -96,8 +112,14 @@ export class ApprovalBridge {
96
112
  if (end < 0) {
97
113
  return;
98
114
  }
99
- const ask = parseAsk(buffer.slice(0, end));
115
+ const line = buffer.slice(0, end);
100
116
  buffer = "";
117
+ const report = parseReport(line);
118
+ if (report) {
119
+ this.report(report, socket);
120
+ return;
121
+ }
122
+ const ask = parseAsk(line);
101
123
  if (!ask) {
102
124
  socket.destroy();
103
125
  return;
@@ -114,6 +136,36 @@ export class ApprovalBridge {
114
136
  this.signal();
115
137
  });
116
138
  }
139
+ // Each flag is reported once per job; every later hook gets the cached
140
+ // answer. A failed report is retried by the next call, and the hook that
141
+ // asked is refused until one lands.
142
+ report(flags, socket) {
143
+ const need = {
144
+ taint: flags.taint && !this.reported.taint,
145
+ touch: flags.touch && !this.reported.touch,
146
+ };
147
+ if (need.taint || need.touch) {
148
+ const request = this.gateway.touch(need).catch((error) => {
149
+ for (const key of ["taint", "touch"]) {
150
+ if (need[key]) {
151
+ this.reported[key] = undefined;
152
+ }
153
+ }
154
+ throw error;
155
+ });
156
+ for (const key of ["taint", "touch"]) {
157
+ if (need[key]) {
158
+ this.reported[key] = request;
159
+ }
160
+ }
161
+ }
162
+ const pending = ["taint", "touch"].flatMap((key) => flags[key] && this.reported[key]
163
+ ? [this.reported[key]]
164
+ : []);
165
+ Promise.all(pending)
166
+ .then(() => socket.end(`${JSON.stringify({ touched: true })}\n`))
167
+ .catch(() => socket.destroy());
168
+ }
117
169
  async forward(ask, socket) {
118
170
  try {
119
171
  const { status } = await this.gateway.request(ask);
@@ -0,0 +1,389 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
4
+ import { createServer } from "node:http";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { probeResponse } from "../codex-probe.js";
8
+ import { codexHookArgs, trustHookArgs } from "./codex-owner.js";
9
+ // The behavioural proof Codex owner-native would rest on (#10987, R13's musts).
10
+ // A real `codex` runs against a loopback Responses API that scripts one tool
11
+ // call per cell, with our PreToolUse hook installed and trusted by hash exactly
12
+ // as a job would, in an isolated CODEX_HOME. Every cell is "the call was seen by
13
+ // the hook AND its refusal held" (or, for the bypass classes, "the effect never
14
+ // happened"). Anything not proven is a failure: a Codex version that fails any
15
+ // cell stays room-only. Opt-in test: TALENTOS_TEST_CODEX.
16
+ export const CODEX_PROBE_REVISION = 1;
17
+ const RUN_MS = 25_000;
18
+ const MCP_NAME = /probe_mcp/u;
19
+ export const CODEX_CELLS = [
20
+ "trust",
21
+ "bash",
22
+ "stdin",
23
+ "apply_patch",
24
+ "view_image",
25
+ "mcp_tool",
26
+ "mcp_resource",
27
+ "subagent",
28
+ "exec_js",
29
+ "owner_trust_untouched",
30
+ "repo_hooks_ignored",
31
+ ];
32
+ // The hook our probe installs: records every call, allows only the opening
33
+ // `sh` of the stdin cell, refuses everything else.
34
+ const HOOK = `#!/usr/bin/env node
35
+ let raw = "";
36
+ process.stdin.on("data", (c) => (raw += c));
37
+ process.stdin.on("end", () => {
38
+ const call = JSON.parse(raw);
39
+ require("node:fs").appendFileSync(process.env.PROBE_RECORDS, raw.replace(/\\n/g, " ") + "\\n");
40
+ const open =
41
+ (call.tool_name === "Bash" && call.tool_input?.command === "sh") ||
42
+ call.tool_name === "collaborationspawn_agent";
43
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: {
44
+ hookEventName: "PreToolUse",
45
+ permissionDecision: open ? "allow" : "deny",
46
+ permissionDecisionReason: "probe",
47
+ } }));
48
+ });
49
+ `;
50
+ function message(text) {
51
+ return {
52
+ type: "message",
53
+ id: "answer",
54
+ role: "assistant",
55
+ status: "completed",
56
+ content: [{ type: "output_text", text, annotations: [] }],
57
+ };
58
+ }
59
+ // The subagent cell's parent: spawn, wait for the child, finish.
60
+ function parentStep(turn) {
61
+ if (turn === 1) {
62
+ return {
63
+ type: "function_call",
64
+ id: "spawn",
65
+ call_id: "spawn",
66
+ name: "spawn_agent",
67
+ namespace: "collaboration",
68
+ arguments: JSON.stringify({
69
+ message: "child task",
70
+ task_name: "probe_child",
71
+ }),
72
+ status: "completed",
73
+ };
74
+ }
75
+ if (turn === 2) {
76
+ return {
77
+ type: "function_call",
78
+ id: "wait",
79
+ call_id: "wait",
80
+ name: "wait_agent",
81
+ namespace: "collaboration",
82
+ arguments: JSON.stringify({ timeout_ms: 15_000 }),
83
+ status: "completed",
84
+ };
85
+ }
86
+ return message("done");
87
+ }
88
+ async function runCell(binary, root, options, signal) {
89
+ const home = mkdtempSync(join(root, "home-"));
90
+ const work = mkdtempSync(join(root, "work-"));
91
+ const records = join(root, `records-${createHash("sha1").update(home).digest("hex")}`);
92
+ writeFileSync(records, "");
93
+ const hook = join(root, "hook.js");
94
+ writeFileSync(hook, HOOK, { mode: 0o700 });
95
+ if (options.ownerConfig) {
96
+ writeFileSync(join(home, "config.toml"), options.ownerConfig);
97
+ }
98
+ if (options.repoConfig) {
99
+ mkdirSync(join(work, ".codex"), { recursive: true });
100
+ writeFileSync(join(work, ".codex", "config.toml"), options.repoConfig);
101
+ }
102
+ let canaryHits = 0;
103
+ let turn = 0;
104
+ let canaryUrl = "";
105
+ const scriptText = () => typeof options.script === "function"
106
+ ? options.script(canaryUrl)
107
+ : options.script;
108
+ const server = createServer(async (request, response) => {
109
+ let raw = "";
110
+ for await (const chunk of request) {
111
+ raw += chunk.toString();
112
+ }
113
+ if (request.url?.startsWith("/canary")) {
114
+ canaryHits += 1;
115
+ response.end("canary");
116
+ return;
117
+ }
118
+ const body = JSON.parse(raw);
119
+ const input = (body.input ?? []);
120
+ const answered = input.some((item) => String(item.type).endsWith("_output"));
121
+ const last = input.at(-1);
122
+ if (options.child) {
123
+ // A parent that spawns a subagent and WAITS for it, so the child's call
124
+ // is made before the run ends; the child's own turn is scripted too.
125
+ if (last?.type === "agent_message" && !answered) {
126
+ probeResponse(response, options.child());
127
+ return;
128
+ }
129
+ if (last?.type === "custom_tool_call_output") {
130
+ probeResponse(response, message("child done"));
131
+ return;
132
+ }
133
+ turn += 1;
134
+ probeResponse(response, parentStep(turn));
135
+ return;
136
+ }
137
+ turn += 1;
138
+ probeResponse(response, turn === 1 && !answered
139
+ ? {
140
+ type: "custom_tool_call",
141
+ id: "call",
142
+ call_id: "call",
143
+ name: "exec",
144
+ input: scriptText(),
145
+ status: "completed",
146
+ }
147
+ : message("done"));
148
+ });
149
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
150
+ const address = server.address();
151
+ if (!address || typeof address === "string") {
152
+ throw new Error("Missing probe port");
153
+ }
154
+ canaryUrl = `http://127.0.0.1:${address.port}/canary`;
155
+ const env = {
156
+ CODEX_HOME: home,
157
+ HOME: home,
158
+ PATH: process.env.PATH,
159
+ PROBE_RECORDS: records,
160
+ TALENTOS_PROBE_KEY: "loopback-only",
161
+ };
162
+ try {
163
+ const hookArgs = codexHookArgs(hook);
164
+ const trust = options.trusted === false
165
+ ? []
166
+ : await trustHookArgs({
167
+ binary,
168
+ command: hook,
169
+ cwd: work,
170
+ env,
171
+ signal,
172
+ });
173
+ const args = [
174
+ "-c",
175
+ 'model_provider="talentos_probe"',
176
+ "-c",
177
+ 'model_providers.talentos_probe.name="Loopback"',
178
+ "-c",
179
+ `model_providers.talentos_probe.base_url="http://127.0.0.1:${address.port}/v1"`,
180
+ "-c",
181
+ 'model_providers.talentos_probe.wire_api="responses"',
182
+ "-c",
183
+ 'model_providers.talentos_probe.env_key="TALENTOS_PROBE_KEY"',
184
+ "-c",
185
+ 'sandbox_mode="danger-full-access"',
186
+ "-c",
187
+ `approval_policy="${options.approval ?? "never"}"`,
188
+ ...hookArgs,
189
+ ...trust,
190
+ ...(options.extraArgs ?? []),
191
+ "exec",
192
+ "--json",
193
+ "--skip-git-repo-check",
194
+ "probe",
195
+ ];
196
+ const child = spawn(binary, args, {
197
+ cwd: work,
198
+ env,
199
+ stdio: ["ignore", "ignore", "ignore"],
200
+ });
201
+ const stop = () => child.kill("SIGKILL");
202
+ signal.addEventListener("abort", stop, { once: true });
203
+ const timer = setTimeout(stop, RUN_MS);
204
+ await new Promise((resolve) => child.once("close", resolve));
205
+ clearTimeout(timer);
206
+ signal.removeEventListener("abort", stop);
207
+ }
208
+ finally {
209
+ server.closeAllConnections();
210
+ await new Promise((resolve) => server.close(() => resolve()));
211
+ }
212
+ const records_ = readFileSync(records, "utf8")
213
+ .split("\n")
214
+ .filter(Boolean)
215
+ .map((line) => JSON.parse(line));
216
+ return { canaryHits, home, records: records_, work };
217
+ }
218
+ const seen = (run, tool) => run.records.filter((record) => record.tool_name === tool);
219
+ /**
220
+ * Proves, on the real binary, every class of call our hook has to see. A
221
+ * failing cell makes this Codex version room-only. Never run per job.
222
+ */
223
+ export async function probeCodexOwnerNative(binary, version, signal = AbortSignal.timeout(180_000)) {
224
+ const root = mkdtempSync(join(tmpdir(), "talentos-codex-owner-"));
225
+ const marker = (name) => join(root, `marker-${name}`);
226
+ const cells = Object.fromEntries(CODEX_CELLS.map((cell) => [cell, "fail"]));
227
+ const cell = async (name, check) => {
228
+ try {
229
+ cells[name] = (await check()) ? "pass" : "fail";
230
+ }
231
+ catch {
232
+ cells[name] = "fail";
233
+ }
234
+ };
235
+ // A script is code-mode JavaScript: it can only reach the outside through
236
+ // nested tools, which is what makes the hook sufficient.
237
+ const js = (body) => body;
238
+ try {
239
+ // Trust: our hook runs with no bypass flag, and without its hash it does
240
+ // NOT run (the fail-open a launcher must never leave open).
241
+ await cell("trust", async () => {
242
+ const script = js(`await tools.exec_command({cmd: ${JSON.stringify(`echo x > ${marker("trust-a")}`)}});`);
243
+ const trusted = await runCell(binary, root, { script }, signal);
244
+ const held = seen(trusted, "Bash").length === 1 && !existsSync(marker("trust-a"));
245
+ // Control: with no trust the hook is silently skipped and the command runs.
246
+ const untrusted = await runCell(binary, root, { script, trusted: false }, signal);
247
+ return (held && untrusted.records.length === 0 && existsSync(marker("trust-a")));
248
+ });
249
+ await cell("bash", async () => {
250
+ for (const approval of ["never", "on-request"]) {
251
+ const file = marker(`bash-${approval}`);
252
+ const run = await runCell(binary, root, {
253
+ approval,
254
+ script: js(`await tools.exec_command({cmd: ${JSON.stringify(`echo x > ${file}`)}});`),
255
+ }, signal);
256
+ if (seen(run, "Bash").length !== 1 || existsSync(file)) {
257
+ return false;
258
+ }
259
+ }
260
+ return true;
261
+ });
262
+ // R13 (1): an open exec session driven through write_stdin. The first `sh`
263
+ // is allowed; what the model then types into it must never run.
264
+ await cell("stdin", async () => {
265
+ const file = marker("stdin");
266
+ await runCell(binary, root, {
267
+ script: js(`const r = await tools.exec_command({cmd: "sh", tty: true, yield_time_ms: 300});
268
+ if (r.session_id !== undefined) { await tools.write_stdin({session_id: r.session_id, chars: ${JSON.stringify(`echo x > ${file}\n`)}, yield_time_ms: 800}); }`),
269
+ }, signal);
270
+ return !existsSync(file);
271
+ });
272
+ // R13 (2): the hook sees every path of a patch, renames and deletes too.
273
+ await cell("apply_patch", async () => {
274
+ const dir = join(root, "patch");
275
+ mkdirSync(dir, { recursive: true });
276
+ writeFileSync(join(dir, "old.txt"), "a\n");
277
+ writeFileSync(join(dir, "gone.txt"), "x");
278
+ const patch = `*** Begin Patch\n*** Add File: ${dir}/new.txt\n+hello\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`;
279
+ const run = await runCell(binary, root, { script: js(`await tools.apply_patch(${JSON.stringify(patch)});`) }, signal);
280
+ const [call] = seen(run, "apply_patch");
281
+ const text = String(call?.tool_input?.command ?? "");
282
+ return ([
283
+ `${dir}/new.txt`,
284
+ `${dir}/old.txt`,
285
+ `${dir}/moved.txt`,
286
+ `${dir}/gone.txt`,
287
+ ].every((path) => text.includes(path)) &&
288
+ !existsSync(join(dir, "new.txt")) &&
289
+ !existsSync(join(dir, "moved.txt")) &&
290
+ existsSync(join(dir, "gone.txt")));
291
+ });
292
+ await cell("view_image", async () => {
293
+ const run = await runCell(binary, root, {
294
+ script: js(`await tools.view_image({path: ${JSON.stringify(join(root, "x.png"))}});`),
295
+ }, signal);
296
+ return seen(run, "view_image").length === 1;
297
+ });
298
+ await cell("mcp_resource", async () => {
299
+ const run = await runCell(binary, root, {
300
+ script: js(`await tools.read_mcp_resource({server: "probe", uri: "file:///etc/hosts"});`),
301
+ }, signal);
302
+ return seen(run, "read_mcp_resource").length === 1;
303
+ });
304
+ await cell("mcp_tool", async () => {
305
+ const file = marker("mcp");
306
+ const server = join(root, "mcp.mjs");
307
+ writeFileSync(server, `import {Server} from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/server/index.js"))};
308
+ import {StdioServerTransport} from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/server/stdio.js"))};
309
+ import {ListToolsRequestSchema,CallToolRequestSchema} from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/types.js"))};
310
+ import {writeFileSync} from "node:fs";
311
+ const s=new Server({name:"probe_mcp",version:"1"},{capabilities:{tools:{}}});
312
+ s.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[{name:"mark",description:"mark",inputSchema:{type:"object",properties:{}}}]}));
313
+ s.setRequestHandler(CallToolRequestSchema,async()=>{writeFileSync(${JSON.stringify(file)},"1");return {content:[{type:"text",text:"ok"}]};});
314
+ await s.connect(new StdioServerTransport());`);
315
+ const run = await runCell(binary, root, {
316
+ extraArgs: [
317
+ "-c",
318
+ `mcp_servers.probe_mcp.command=${JSON.stringify(process.execPath)}`,
319
+ "-c",
320
+ `mcp_servers.probe_mcp.args=${JSON.stringify([server])}`,
321
+ ],
322
+ script: js("await tools.mcp__probe_mcp__mark({});"),
323
+ }, signal);
324
+ return (run.records.some((record) => MCP_NAME.test(String(record.tool_name))) &&
325
+ !existsSync(file));
326
+ });
327
+ // A subagent's calls are hooked and refused too (they carry an agent_id).
328
+ await cell("subagent", async () => {
329
+ const file = marker("subagent");
330
+ const run = await runCell(binary, root, {
331
+ child: () => ({
332
+ type: "custom_tool_call",
333
+ id: "child",
334
+ call_id: "child",
335
+ name: "exec",
336
+ input: `await tools.exec_command({cmd: ${JSON.stringify(`echo x > ${file}`)}});`,
337
+ status: "completed",
338
+ }),
339
+ script: "",
340
+ }, signal);
341
+ return (run.records.some((record) => record.tool_name === "Bash" && record.agent_id) && !existsSync(file));
342
+ });
343
+ // Rooms lead: the code-mode JavaScript has no file system or network of its
344
+ // own. If it can reach either without a nested tool, the hook cannot see it.
345
+ await cell("exec_js", async () => {
346
+ const file = marker("execjs");
347
+ const run = await runCell(binary, root, {
348
+ script: (canary) => js(`const tries = [
349
+ async () => fetch(${JSON.stringify(canary)}),
350
+ async () => (await import("node:fs")).writeFileSync(${JSON.stringify(file)}, "1"),
351
+ async () => require("fs").writeFileSync(${JSON.stringify(file)}, "1"),
352
+ async () => process.env.PATH,
353
+ async () => Deno.writeTextFileSync(${JSON.stringify(file)}, "1"),
354
+ async () => new XMLHttpRequest(),
355
+ ];
356
+ for (const t of tries) { try { await t(); } catch (e) {} }`),
357
+ }, signal);
358
+ return run.canaryHits === 0 && !existsSync(file);
359
+ });
360
+ // R13 (3): the owner's own trust state is byte-identical after a job.
361
+ await cell("owner_trust_untouched", async () => {
362
+ const config = `[hooks.state."owner:hook:0"]\ntrusted_hash = "sha256:owner"\n`;
363
+ const run = await runCell(binary, root, {
364
+ ownerConfig: config,
365
+ script: js(`await tools.exec_command({cmd: "true"});`),
366
+ }, signal);
367
+ return (readFileSync(join(run.home, "config.toml"), "utf8") === config &&
368
+ !existsSync(join(run.home, "hooks.json")));
369
+ });
370
+ // R13 (3): a hook that lives in the workspace is never trusted or loaded
371
+ // through our job.
372
+ await cell("repo_hooks_ignored", async () => {
373
+ const file = marker("repohook");
374
+ const run = await runCell(binary, root, {
375
+ repoConfig: `[[hooks.PreToolUse]]\nmatcher = "*"\n[[hooks.PreToolUse.hooks]]\ntype = "command"\ncommand = ${JSON.stringify(`sh -c 'echo x > ${file}'`)}\n`,
376
+ script: js(`await tools.exec_command({cmd: "true"});`),
377
+ }, signal);
378
+ return !existsSync(file) && seen(run, "Bash").length === 1;
379
+ });
380
+ }
381
+ finally {
382
+ rmSync(root, { force: true, recursive: true });
383
+ }
384
+ return {
385
+ cells,
386
+ safe: CODEX_CELLS.every((name) => cells[name] === "pass"),
387
+ version,
388
+ };
389
+ }
@@ -0,0 +1,160 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { promisify } from "node:util";
5
+ // Codex owner-native, PR 1 (#10987): what we know about running the owner's own
6
+ // Codex behind our PreToolUse hook, and the checks that keep a Codex that cannot
7
+ // be fenced out of owner jobs. Nothing here launches an owner job: the findings
8
+ // (docs/features/agent-access/README.md) say why Codex 0.162.1 stays room-only.
9
+ const exec = promisify(execFile);
10
+ const APP_SERVER_MS = 20_000;
11
+ const VERSION = /(\d+\.\d+\.\d+)/u;
12
+ const FEATURE_LINE = /^(\S+)\s+\S+(?:\s+\S+)*?\s+(true|false)\s*$/u;
13
+ /** `-c` arguments that add our command as a PreToolUse hook for one run. */
14
+ export function codexHookArgs(command) {
15
+ return [
16
+ "-c",
17
+ `hooks.PreToolUse=[{matcher="*",hooks=[{type="command",command=${JSON.stringify(command)},timeout=900}]}]`,
18
+ ];
19
+ }
20
+ /**
21
+ * An inline hook is UNTRUSTED by default and Codex then silently does not run
22
+ * it: the command just executes (fail open). `hooks/list` on the app server
23
+ * reports each hook's key and current hash; passing `hooks.state` with that
24
+ * hash trusts exactly our hook for this run, persists nothing and needs no
25
+ * `--dangerously-bypass-hook-trust`. Throws unless our hook is listed once.
26
+ */
27
+ export async function trustHookArgs(input) {
28
+ const list = await appServerRequest({
29
+ args: ["app-server", ...codexHookArgs(input.command)],
30
+ binary: input.binary,
31
+ cwd: input.cwd,
32
+ env: input.env,
33
+ method: "hooks/list",
34
+ params: { cwds: [input.cwd] },
35
+ signal: input.signal,
36
+ });
37
+ const ours = (list.data ?? [])
38
+ .flatMap((entry) => entry.hooks ?? [])
39
+ .filter((hook) => hook.source === "sessionFlags" &&
40
+ hook.eventName === "preToolUse" &&
41
+ hook.command === input.command);
42
+ const [hook] = ours;
43
+ if (ours.length !== 1 || !hook?.key || !hook.currentHash) {
44
+ throw new Error("Our hook was not listed exactly once.");
45
+ }
46
+ return [
47
+ "-c",
48
+ `hooks.state={${JSON.stringify(hook.key)}={trusted_hash=${JSON.stringify(hook.currentHash)}}}`,
49
+ ];
50
+ }
51
+ async function appServerRequest(input) {
52
+ const child = spawn(input.binary, input.args, {
53
+ cwd: input.cwd,
54
+ env: input.env,
55
+ stdio: ["pipe", "pipe", "ignore"],
56
+ });
57
+ try {
58
+ return await new Promise((resolve, reject) => {
59
+ const timer = setTimeout(() => reject(new Error("app-server timed out")), APP_SERVER_MS);
60
+ const stop = () => reject(new Error("aborted"));
61
+ input.signal?.addEventListener("abort", stop, { once: true });
62
+ let buffer = "";
63
+ child.once("error", reject);
64
+ child.stdout.setEncoding("utf8");
65
+ child.stdout.on("data", (chunk) => {
66
+ buffer += chunk;
67
+ for (let end = buffer.indexOf("\n"); end >= 0; end = buffer.indexOf("\n")) {
68
+ const line = buffer.slice(0, end);
69
+ buffer = buffer.slice(end + 1);
70
+ try {
71
+ const message = JSON.parse(line);
72
+ if (message.id === 1) {
73
+ child.stdin.write(`${JSON.stringify({ method: "initialized" })}\n`);
74
+ child.stdin.write(`${JSON.stringify({ id: 2, method: input.method, params: input.params })}\n`);
75
+ }
76
+ else if (message.id === 2) {
77
+ clearTimeout(timer);
78
+ if (message.result === undefined) {
79
+ reject(new Error("app-server request failed"));
80
+ }
81
+ else {
82
+ resolve(message.result);
83
+ }
84
+ }
85
+ }
86
+ catch {
87
+ // Notifications and log lines are not responses.
88
+ }
89
+ }
90
+ });
91
+ child.stdin.write(`${JSON.stringify({ id: 1, method: "initialize", params: { clientInfo: { name: "talentos", version: "0" } } })}\n`);
92
+ });
93
+ }
94
+ finally {
95
+ child.kill();
96
+ }
97
+ }
98
+ /** The Codex version, or undefined when the binary does not answer. */
99
+ export async function codexVersion(binary, env) {
100
+ try {
101
+ const { stdout } = await exec(binary, ["--version"], {
102
+ env,
103
+ timeout: 10_000,
104
+ });
105
+ return VERSION.exec(stdout)?.[1];
106
+ }
107
+ catch {
108
+ return;
109
+ }
110
+ }
111
+ /**
112
+ * Static reasons this owner's Codex cannot run our hook at all: hooks turned
113
+ * off in the effective config, or a binary that does not answer. Checked at
114
+ * every owner job (not cached), like the Claude disqualifier.
115
+ */
116
+ export async function codexDisqualifier(binary, env) {
117
+ try {
118
+ const { stdout } = await exec(binary, ["features", "list"], {
119
+ env,
120
+ timeout: 15_000,
121
+ });
122
+ const hooks = stdout
123
+ .split("\n")
124
+ .map((line) => FEATURE_LINE.exec(line.trim()))
125
+ .find((match) => match?.[1] === "hooks");
126
+ if (hooks?.[2] !== "true") {
127
+ return "Codex hooks are turned off in this Codex's configuration.";
128
+ }
129
+ }
130
+ catch {
131
+ return "Codex did not report its features.";
132
+ }
133
+ return;
134
+ }
135
+ // Owner-level context that reaches Codex with no tool call: user AGENTS.md,
136
+ // skills, memories, MCP servers, profiles, notify and shell environment rules
137
+ // (R13). In a room with other people a job that starts with any of it loaded
138
+ // cannot be called untouched. Fail closed: unreadable or unknown = present.
139
+ const CONFIG_CONTEXT = /^\s*(?:\[(?:mcp_servers|profiles|hooks|plugins|marketplaces|shell_environment_policy|skills)\b|(?:notify|profile|model_instructions_file|developer_instructions|instructions|compact_prompt|experimental_instructions_file)\s*=)/mu;
140
+ const CONTEXT_FILES = ["AGENTS.md", "AGENTS.override.md", "hooks.json"];
141
+ const CONTEXT_DIRS = ["skills", "memories", "prompts", "rules", "plugins"];
142
+ export function codexOwnerContextPresent(codexHome) {
143
+ try {
144
+ if (CONTEXT_FILES.some((name) => existsSync(join(codexHome, name)))) {
145
+ return true;
146
+ }
147
+ for (const name of CONTEXT_DIRS) {
148
+ const dir = join(codexHome, name);
149
+ if (existsSync(dir) &&
150
+ (!statSync(dir).isDirectory() || readdirSync(dir).length > 0)) {
151
+ return true;
152
+ }
153
+ }
154
+ const config = join(codexHome, "config.toml");
155
+ return (existsSync(config) && CONFIG_CONTEXT.test(readFileSync(config, "utf8")));
156
+ }
157
+ catch {
158
+ return true;
159
+ }
160
+ }