talentos 1.4.11 → 1.4.12

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.
@@ -10,7 +10,9 @@ import { redactAgentOutput, } from "../agent-link.js";
10
10
  import { gatewayLauncherPath } from "../gateway-install.js";
11
11
  import { providerPathEnv, resolveProviderBinary } from "../provider-binary.js";
12
12
  import { codexRoomArgs, ROOM_TOOLS } from "./codex-policy.js";
13
- import { binaryIdentity, CodexBoundaryError, codexWebProven, probeCodexBoundary, } from "./codex-probe.js";
13
+ import { binaryIdentity, CodexBoundaryError, CodexProbeInterrupted, codexWebProven, probeCodexBoundary, } from "./codex-probe.js";
14
+ import { geminiRoomArgs } from "./gemini-policy.js";
15
+ import { GeminiBoundaryError, probeGeminiBoundary } from "./gemini-probe.js";
14
16
  import { prepareCodexOwnerLaunch } from "./native/codex-launch.js";
15
17
  import { prepareOwnerLaunch } from "./native/launch.js";
16
18
  import { readReceipts } from "./native/receipts.js";
@@ -35,6 +37,17 @@ const CHILD_ENV = [
35
37
  ];
36
38
  const CLAUDE_VERSION = /^\d+\.\d+\.\d+/u;
37
39
  const CODEX_VERSION = /\b\d+\.\d+\.\d+\b/u;
40
+ const GEMINI_VERSION = /\b\d+\.\d+\.\d+\b/u;
41
+ // What the room launch needs from this Gemini CLI: its own policy files, the
42
+ // workspace-trust skip, headless streaming events, an approval mode and an MCP
43
+ // server allowlist. A Gemini without them cannot hold the room boundary.
44
+ const GEMINI_ROOM_FLAGS = [
45
+ "--policy",
46
+ "--skip-trust",
47
+ "--output-format",
48
+ "--approval-mode",
49
+ "--allowed-mcp-server-names",
50
+ ];
38
51
  const DONT_ASK = /\bdontAsk\b/u;
39
52
  // What the room line says while a job uses web. Neither names a page or a
40
53
  // query, and neither is a private tool, so an owner job shows them too.
@@ -100,6 +113,13 @@ export async function verifyClaudeCode(configured) {
100
113
  const verifiedCodex = new Map();
101
114
  const webVerifiedCodex = new Map();
102
115
  const roomCatalogs = new Map();
116
+ // The job room's file ids from the packet; undefined when it lists none, so the
117
+ // hook taints every read by id (#13471).
118
+ function roomFileIds(packet) {
119
+ return Array.isArray(packet.files)
120
+ ? packet.files.flatMap((file) => typeof file?.id === "string" ? [file.id] : [])
121
+ : undefined;
122
+ }
103
123
  async function identityOrUndefined(binary) {
104
124
  try {
105
125
  return await binaryIdentity(binary);
@@ -151,13 +171,53 @@ export async function verifyCodex(configured, signal) {
151
171
  }
152
172
  }
153
173
  catch (error) {
154
- if (error instanceof CodexBoundaryError) {
174
+ if (error instanceof CodexBoundaryError ||
175
+ error instanceof CodexProbeInterrupted) {
155
176
  throw error;
156
177
  }
157
178
  // Provider diagnostics can contain login details.
158
179
  }
159
180
  throw new Error(`Update Codex (${version}) to a version supporting isolated room turns, exec/resume flags and a local model catalog.`);
160
181
  }
182
+ /**
183
+ * Gemini CLI can run a room job when it has the flags the launch uses and the
184
+ * real binary keeps a job inside its room tools (the loopback probe, which
185
+ * needs no sign-in). A signed-out Gemini still passes: sign-in is a job-time
186
+ * failure with its own plain reason.
187
+ */
188
+ export async function verifyGemini(configured, signal) {
189
+ const binary = resolveProviderBinary("gemini_cli", configured);
190
+ const execute = promisify(execFile);
191
+ const options = {
192
+ env: childEnvironment(process.env, binary),
193
+ timeout: 8000,
194
+ signal,
195
+ maxBuffer: 256_000,
196
+ };
197
+ let version = "unknown";
198
+ try {
199
+ const detected = await execute(binary, ["--version"], options);
200
+ version = GEMINI_VERSION.exec(detected.stdout)?.[0] ?? "unknown";
201
+ const help = await execute(binary, ["--help"], options);
202
+ if (version !== "unknown" &&
203
+ GEMINI_ROOM_FLAGS.every((flag) => help.stdout.includes(flag))) {
204
+ await probeGeminiBoundary({
205
+ binary,
206
+ env: childEnvironment(process.env, binary),
207
+ signal,
208
+ version,
209
+ });
210
+ return;
211
+ }
212
+ }
213
+ catch (error) {
214
+ if (error instanceof GeminiBoundaryError) {
215
+ throw error;
216
+ }
217
+ // Provider diagnostics can contain login details.
218
+ }
219
+ throw new Error(`Update Gemini CLI (${version}) to a version that supports ${GEMINI_ROOM_FLAGS.join(", ")}.`);
220
+ }
161
221
  /**
162
222
  * Proves this Codex's tool surface with live web search on, after the room
163
223
  * proof passed. Optional: a Codex that fails it (or cannot be probed) still
@@ -290,6 +350,27 @@ export function readProviderEvent(provider, value) {
290
350
  };
291
351
  }
292
352
  }
353
+ else if (provider === "gemini_cli") {
354
+ // stream-json: init, message (user and assistant chunks), tool_use,
355
+ // tool_result, error (a warning) and result (status and stats).
356
+ if (event.type === "message" && event.role === "assistant") {
357
+ return typeof event.content === "string"
358
+ ? { textDelta: event.content }
359
+ : {};
360
+ }
361
+ if (event.type === "tool_use") {
362
+ return { status: "Using room tools…", textReset: true };
363
+ }
364
+ if (event.type === "result" && event.status === "error") {
365
+ const error = event.error;
366
+ return {
367
+ failed: true,
368
+ failure: typeof error?.message === "string"
369
+ ? matchFailureText(error.message)
370
+ : undefined,
371
+ };
372
+ }
373
+ }
293
374
  else {
294
375
  if (event.type === "thread.started" &&
295
376
  typeof event.thread_id === "string") {
@@ -321,10 +402,12 @@ export function readProviderEvent(provider, value) {
321
402
  export async function runProvider(input) {
322
403
  const { config, job, workDir, sessionId, signal } = input;
323
404
  const { instructions, ...context } = job.packet;
324
- const prompt = JSON.stringify(config.provider === "claude_code" ? context : job.packet), mcpPath = join(dirname(workDir), ROOM_MCP_FILE);
405
+ const prompt = JSON.stringify(config.provider === "codex" ? job.packet : context), mcpPath = join(dirname(workDir), ROOM_MCP_FILE);
325
406
  const catalogPath = join(dirname(workDir), ROOM_CATALOG_FILE);
326
407
  const binary = resolveProviderBinary(config.provider, config.providerPath);
327
408
  let command, args;
409
+ // Gemini CLI reads the packet from stdin; the others take it as an argument.
410
+ let stdinText;
328
411
  let ownerLaunch;
329
412
  let stopWatching;
330
413
  // Only a room-only job: an owner job runs in the owner's own setup on purpose.
@@ -341,6 +424,8 @@ export async function runProvider(input) {
341
424
  jobId: job.jobId,
342
425
  prompt,
343
426
  roomId: job.packet.room?.id,
427
+ roomFileIds: roomFileIds(job.packet),
428
+ triggerId: job.packet.trigger?.id,
344
429
  sessionId,
345
430
  sharedRoom: job.native?.sharedRoom,
346
431
  workspace: input.owner.workspace,
@@ -348,6 +433,35 @@ export async function runProvider(input) {
348
433
  command = binary;
349
434
  args = ownerLaunch.args;
350
435
  }
436
+ else if (config.provider === "gemini_cli") {
437
+ // Gemini CLI never runs the owner's setup (the server never grants it
438
+ // either); a job that arrives as one runs nowhere.
439
+ if (input.owner) {
440
+ throw new Error("A Gemini CLI job is always room-only.");
441
+ }
442
+ command = binary;
443
+ roomProfile = await prepareRoomProfile({
444
+ directory: dirname(workDir),
445
+ env: process.env,
446
+ gemini: {
447
+ apiKey: config.apiKey,
448
+ mcpUrl: new URL("/mcp", config.apiUrl).href,
449
+ },
450
+ jobId: job.jobId,
451
+ provider: config.provider,
452
+ });
453
+ try {
454
+ // The room playbook is the job's own GEMINI.md: its directory is empty and
455
+ // nothing above it is read.
456
+ await writePrivateFile(join(roomProfile.cwd, "GEMINI.md"), instructions);
457
+ }
458
+ catch (error) {
459
+ await roomProfile.cleanup();
460
+ throw error;
461
+ }
462
+ stdinText = prompt;
463
+ args = geminiRoomArgs({ policyPath: roomProfile.geminiPolicyPath ?? "" });
464
+ }
351
465
  else if (input.owner && config.provider === "codex" && input.owner.codex) {
352
466
  const watching = await input.owner.watch?.();
353
467
  stopWatching = watching?.stop;
@@ -363,6 +477,8 @@ export async function runProvider(input) {
363
477
  jobId: job.jobId,
364
478
  prompt,
365
479
  roomId: job.packet.room?.id,
480
+ roomFileIds: roomFileIds(job.packet),
481
+ triggerId: job.packet.trigger?.id,
366
482
  sessionId,
367
483
  sharedRoom: job.native?.sharedRoom,
368
484
  signal,
@@ -497,9 +613,15 @@ export async function runProvider(input) {
497
613
  },
498
614
  // stderr is matched to name a failure, never forwarded: it can hold login
499
615
  // details.
500
- stdio: ["ignore", "pipe", "pipe"],
616
+ stdio: [stdinText === undefined ? "ignore" : "pipe", "pipe", "pipe"],
501
617
  detached: process.platform !== "win32",
502
618
  });
619
+ if (stdinText !== undefined) {
620
+ // A provider that exits before reading it closes the pipe; that is its
621
+ // failure to report, not an error here.
622
+ child.stdin?.on("error", () => undefined);
623
+ child.stdin?.end(stdinText);
624
+ }
503
625
  const marked = new Set();
504
626
  const mark = (name) => {
505
627
  if (!marked.has(name)) {
@@ -548,7 +670,7 @@ export async function runProvider(input) {
548
670
  stop();
549
671
  }
550
672
  try {
551
- let text = "", failure, failed = false, sawResult = false, webReported = false;
673
+ let text = "", segment = "", failure, failed = false, sawResult = false, webReported = false;
552
674
  if (!child.stdout) {
553
675
  throw new Error("Provider output is unavailable.");
554
676
  }
@@ -589,6 +711,13 @@ export async function runProvider(input) {
589
711
  ? "Working on your computer…"
590
712
  : event.status);
591
713
  }
714
+ if (event.textReset) {
715
+ segment = "";
716
+ }
717
+ if (event.textDelta) {
718
+ segment = (segment + event.textDelta).slice(0, 12_000);
719
+ text = segment;
720
+ }
592
721
  if (event.text !== undefined) {
593
722
  text = event.text.slice(0, 12_000);
594
723
  }
@@ -2,6 +2,7 @@
2
2
  // server: the shell fence (#10987). The proxy classifies the command.
3
3
  export const ROOM_LOCAL_TOOLS = ["run_command"];
4
4
  export const ROOM_TOOLS = [
5
+ "add_todo",
5
6
  "list_rooms",
6
7
  "list_threads",
7
8
  "reply_route",
@@ -11,6 +12,8 @@ export const ROOM_TOOLS = [
11
12
  "write_room_memory",
12
13
  "list_room_files",
13
14
  "read_file",
15
+ "read_file_comments",
16
+ "read_web_page",
14
17
  "read_app_state",
15
18
  "write_app_state",
16
19
  "get_skill",
@@ -18,21 +21,29 @@ export const ROOM_TOOLS = [
18
21
  "search_memory",
19
22
  "list_connections",
20
23
  "use_connection",
24
+ "change_connection",
25
+ "prepare_connection",
21
26
  "ask_talent",
22
27
  "get_thread",
23
28
  "list_routines",
24
29
  "run_routine",
25
30
  "remember",
31
+ "save_skill",
26
32
  "suggest_change",
33
+ "patch_live_page",
27
34
  "create_file",
28
35
  "create_deck",
36
+ "create_spreadsheet",
29
37
  "create_web_app",
38
+ "export_file",
30
39
  "revise_web_app",
31
40
  "upload_file",
32
41
  "prepare_upload",
33
42
  "commit_upload",
34
43
  "post_message",
44
+ "edit_own_message",
35
45
  "post_to_thread",
46
+ "reply_to_comment",
36
47
  "start_thread",
37
48
  "share_link",
38
49
  "room_default_set",
@@ -35,11 +35,54 @@ const RESOURCE_HELPERS = [
35
35
  "list_mcp_resource_templates", // Sole tools-only MCP server: no templates.
36
36
  "read_mcp_resource", // MCP RPC only; the proxy has no resources/read handler.
37
37
  ];
38
+ // The newest Codex this proof was proven against (codex-boundary.test.ts). One at
39
+ // or past it that fails is a build TalentOS has not learned yet; updating Codex
40
+ // cannot fix that, and a current Codex may have nothing newer to update to.
41
+ const PROVEN_CODEX = [0, 162, 1];
42
+ const RELEASE = /(\d+)\.(\d+)\.(\d+)/u;
43
+ const WHITESPACE = /\s+/gu;
44
+ function provenOrNewer(version) {
45
+ const parts = RELEASE.exec(version)?.slice(1).map(Number);
46
+ if (!parts) {
47
+ return false;
48
+ }
49
+ for (const [index, proven] of PROVEN_CODEX.entries()) {
50
+ const part = parts[index] ?? 0;
51
+ if (part !== proven) {
52
+ return part > proven;
53
+ }
54
+ }
55
+ return true;
56
+ }
38
57
  export class CodexBoundaryError extends ProviderBinaryError {
39
- constructor(version) {
40
- super(`Codex ${version} cannot safely run room jobs. Update Codex, then run talentos agent repair. If this persists, report this version to TalentOS support.`);
58
+ /** The check that failed, for the gateway log; no login or owner data. */
59
+ check;
60
+ constructor(version, check) {
61
+ const why = check ? ` (check failed: ${check})` : "";
62
+ super(provenOrNewer(version)
63
+ ? `Codex ${version} cannot safely run room jobs${why}. TalentOS doesn't support this Codex version yet, so it stays off until it does; there is nothing to update on this computer. Please report this version to TalentOS support.`
64
+ : `Codex ${version} cannot safely run room jobs${why}. Update Codex, then run talentos agent repair. If this persists, report this version to TalentOS support.`);
65
+ this.check = check;
66
+ }
67
+ }
68
+ /** One line of a failure, bounded: it goes to a log and carries no owner data. */
69
+ const oneLine = (text, max = 300) => text.replace(WHITESPACE, " ").trim().slice(0, max);
70
+ /**
71
+ * The check ran out of road (a timeout, a shutdown, a full disk, a child that
72
+ * died, the file replaced mid-check), so it says nothing about this Codex. The
73
+ * CLI exits plainly, not with the refusal's 78, and the service manager starts
74
+ * it again (a minute apart), which checks again.
75
+ */
76
+ export class CodexProbeInterrupted extends Error {
77
+ check;
78
+ constructor(version, check) {
79
+ super(`Codex ${version} could not be checked just now (${check}). TalentOS checks again by itself.`);
80
+ this.check = check;
41
81
  }
42
82
  }
83
+ /** What Codex did or offered differed from the room boundary: a verdict, not a mishap. */
84
+ class BoundaryMismatch extends Error {
85
+ }
43
86
  function record(value) {
44
87
  if (!value || typeof value !== "object" || Array.isArray(value)) {
45
88
  throw new Error("Invalid tool envelope");
@@ -65,7 +108,7 @@ export function codexAdvertisedTools(value) {
65
108
  tool.function !== undefined ||
66
109
  tool.namespace !== undefined ||
67
110
  !["functions", "mcp__talentos"].includes(String(tool.name))) {
68
- throw new Error("Unknown namespace");
111
+ throw new Error(`unexpected tool namespace "${oneLine(String(tool.name), 60)}"`);
69
112
  }
70
113
  inspect(tool.tools, String(tool.name));
71
114
  }
@@ -76,7 +119,7 @@ export function codexAdvertisedTools(value) {
76
119
  (namespace &&
77
120
  tool.namespace !== undefined &&
78
121
  tool.namespace !== namespace)) {
79
- throw new Error("Conflicting tool envelope");
122
+ throw new Error(`conflicting tool envelope for "${oneLine(String(tool.name), 60)}"`);
80
123
  }
81
124
  const ns = namespace ||
82
125
  (typeof tool.namespace === "string" ? tool.namespace : "");
@@ -87,12 +130,12 @@ export function codexAdvertisedTools(value) {
87
130
  if (!(allowed && tool.parameters) ||
88
131
  typeof tool.parameters !== "object" ||
89
132
  Array.isArray(tool.parameters)) {
90
- throw new Error("Unexpected callable tool");
133
+ throw new Error(`unexpected tool "${oneLine(`${ns}.${name}`, 80)}"`);
91
134
  }
92
135
  names.push(`${ns}.${name}`);
93
136
  }
94
137
  else {
95
- throw new Error("Unknown tool schema");
138
+ throw new Error(`unknown tool schema "${oneLine(String(tool.type), 40)}"`);
96
139
  }
97
140
  }
98
141
  }
@@ -105,14 +148,14 @@ export function codexAdvertisedTools(value) {
105
148
  for (const item of request.input) {
106
149
  const input = record(item);
107
150
  if (typeof input.type !== "string" || !INPUT_TYPES.has(input.type)) {
108
- throw new Error("Unknown input envelope");
151
+ throw new Error(`unknown input item "${oneLine(String(input.type), 40)}"`);
109
152
  }
110
153
  if (input.type === "additional_tools" ||
111
154
  input.type === "tool_search_output") {
112
155
  inspect(input.tools);
113
156
  }
114
157
  else if (input.tools !== undefined || input.functions !== undefined) {
115
- throw new Error("Unknown schema envelope");
158
+ throw new Error(`tools on an "${input.type}" input item`);
116
159
  }
117
160
  }
118
161
  return names;
@@ -145,7 +188,13 @@ async function execute(binary, args, cwd, env, signal) {
145
188
  cwd,
146
189
  env,
147
190
  detached: process.platform !== "win32",
148
- stdio: ["ignore", "pipe", "ignore"],
191
+ stdio: ["ignore", "pipe", "pipe"],
192
+ });
193
+ // The probe's environment holds no login or owner data, so the child's last
194
+ // words are safe to log; they say why a computer fails a proof.
195
+ let stderrTail = "";
196
+ child.stderr.on("data", (chunk) => {
197
+ stderrTail = (stderrTail + chunk.toString()).slice(-600);
149
198
  });
150
199
  const kill = () => {
151
200
  try {
@@ -168,13 +217,15 @@ async function execute(binary, args, cwd, env, signal) {
168
217
  output += chunk.toString();
169
218
  if (Buffer.byteLength(output) > MAX_BYTES) {
170
219
  kill();
171
- reject(new Error("Probe output limit"));
220
+ reject(new BoundaryMismatch("Codex printed more than the probe allows"));
172
221
  }
173
222
  });
174
223
  child.once("error", reject);
175
- child.once("close", (code) => code === 0 && !signal.aborted
224
+ child.once("close", (code, exitSignal) => code === 0 && !signal.aborted
176
225
  ? resolve(output)
177
- : reject(new Error("Probe failed")));
226
+ : reject(new Error(signal.aborted
227
+ ? `Codex was stopped after ${PROBE_MS / 1000} s or by shutdown: ${oneLine(stderrTail)}`
228
+ : `Codex exited with code ${code ?? exitSignal}: ${oneLine(stderrTail)}`)));
178
229
  });
179
230
  }
180
231
  finally {
@@ -212,8 +263,11 @@ export async function probeCodexBoundary(binary, version, catalog, stop, { web =
212
263
  try {
213
264
  await proveCodexBoundary(binary, version, catalog, stop, web);
214
265
  }
215
- catch {
216
- throw new CodexBoundaryError(version);
266
+ catch (error) {
267
+ const check = oneLine(error instanceof Error ? error.message : "unknown");
268
+ throw error instanceof BoundaryMismatch
269
+ ? new CodexBoundaryError(version, check)
270
+ : new CodexProbeInterrupted(version, check);
217
271
  }
218
272
  }
219
273
  // The web proof's cache key leaves the version out: a job has the binary and
@@ -301,7 +355,7 @@ async function proveCodexBoundary(binary, version, catalog, stop, web = false) {
301
355
  import {StdioServerTransport} from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/server/stdio.js"))};
302
356
  import {ListToolsRequestSchema,CallToolRequestSchema} from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/types.js"))};
303
357
  const server=new Server({name:'talentos',version:'probe'},{capabilities:{tools:{}}});
304
- server.setRequestHandler(ListToolsRequestSchema,async()=>{await new Promise(r=>setTimeout(r,Number(process.argv[2])));return {tools:${JSON.stringify([...ROOM_TOOLS, "save_skill", "share_skill"].map((name) => ({ name, description: name, inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } })))}};});
358
+ server.setRequestHandler(ListToolsRequestSchema,async()=>{await new Promise(r=>setTimeout(r,Number(process.argv[2])));return {tools:${JSON.stringify([...ROOM_TOOLS, "share_skill"].map((name) => ({ name, description: name, inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } })))}};});
305
359
  server.setRequestHandler(CallToolRequestSchema,async r=>({content:[{type:'text',text:r.params.name==='read_room'?${JSON.stringify(marker)}:'private-tool-refused'}]}));
306
360
  await server.connect(new StdioServerTransport());`, { mode: 0o600 });
307
361
  server.on("request", async (request, response) => {
@@ -309,7 +363,7 @@ await server.connect(new StdioServerTransport());`, { mode: 0o600 });
309
363
  if (request.method !== "POST" ||
310
364
  request.url !== "/v1/responses" ||
311
365
  ++requests > 20) {
312
- throw new Error("Unexpected probe request");
366
+ throw new Error(`unexpected request ${request.method} ${oneLine(String(request.url).split("?")[0] ?? "", 80)}`);
313
367
  }
314
368
  let raw = "";
315
369
  for await (const chunk of request) {
@@ -401,7 +455,10 @@ await server.connect(new StdioServerTransport());`, { mode: 0o600 });
401
455
  });
402
456
  }
403
457
  catch (error) {
404
- failure = error;
458
+ // A request cut off by the timeout or a shutdown is not Codex's doing.
459
+ if (!(failure || signal.aborted)) {
460
+ failure = error;
461
+ }
405
462
  response.writeHead(400).end();
406
463
  controller.abort();
407
464
  }
@@ -436,27 +493,50 @@ await server.connect(new StdioServerTransport());`, { mode: 0o600 });
436
493
  web,
437
494
  });
438
495
  args.unshift("-c", 'model_provider="talentos_probe"', "-c", 'model_providers.talentos_probe.name="Loopback"', "-c", `model_providers.talentos_probe.base_url="http://127.0.0.1:${address.port}/v1"`, "-c", 'model_providers.talentos_probe.wire_api="responses"', "-c", 'model_providers.talentos_probe.env_key="TALENTOS_PROBE_KEY"');
439
- const output = await execute(binary, args, directory, env, signal);
440
- if (failure ||
441
- !finished[turn] ||
442
- calls[turn]?.length !== turnSteps[turn]?.length ||
443
- !ROOM_TOOLS.every((name) => observations[turn]?.has(`mcp__talentos.${name}`))) {
444
- throw new Error("Incomplete boundary proof");
496
+ // The stand-in aborts the child when it sees a bad request, so its own
497
+ // word on what was wrong beats the child's "stopped".
498
+ const output = await execute(binary, args, directory, env, signal).catch((error) => {
499
+ throw failure
500
+ ? new BoundaryMismatch(`${turn === 0 ? "fresh" : "resumed"} turn: ${failure?.message ?? failure}`)
501
+ : error;
502
+ });
503
+ const missing = ROOM_TOOLS.filter((name) => !observations[turn]?.has(`mcp__talentos.${name}`));
504
+ const incomplete = failure
505
+ ? String(failure?.message ?? failure)
506
+ : (!finished[turn] && "Codex stopped before its final answer") ||
507
+ (calls[turn]?.length !== turnSteps[turn]?.length &&
508
+ `${calls[turn]?.length ?? 0} of ${turnSteps[turn]?.length ?? 0} expected tool calls ran`) ||
509
+ (missing.length > 0 &&
510
+ `room tools not offered to the model: ${missing.slice(0, 3).join(", ")}`);
511
+ if (incomplete) {
512
+ throw new BoundaryMismatch(`${turn === 0 ? "fresh" : "resumed"} turn: ${incomplete}`);
445
513
  }
514
+ // Only the JSON events count; a line Codex prints for people (a notice, a
515
+ // warning) is neither an event nor a reason to refuse a safe tool list.
446
516
  const events = output
447
517
  .trim()
448
518
  .split("\n")
449
- .map((line) => record(JSON.parse(line)));
519
+ .flatMap((line) => {
520
+ try {
521
+ const event = JSON.parse(line);
522
+ return event && typeof event === "object" && !Array.isArray(event)
523
+ ? [event]
524
+ : [];
525
+ }
526
+ catch {
527
+ return [];
528
+ }
529
+ });
450
530
  const thread = events.find((event) => event.type === "thread.started")?.thread_id;
451
531
  if (typeof thread !== "string" ||
452
532
  (session && session !== thread) ||
453
533
  !events.some((event) => event.type === "turn.completed")) {
454
- throw new Error("Missing resumed session");
534
+ throw new BoundaryMismatch(`${turn === 0 ? "fresh" : "resumed"} turn: no thread, or it did not complete`);
455
535
  }
456
536
  session = thread;
457
537
  }
458
538
  if ((await binaryIdentity(binary)) !== before) {
459
- throw new Error("Codex changed during probe");
539
+ throw new Error("the Codex file changed while it was checked");
460
540
  }
461
541
  signal.throwIfAborted();
462
542
  // Failure to persist an optimization does not invalidate a completed proof.
@@ -0,0 +1,74 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { homeDir } from "../install.js";
4
+ // Where a Gemini CLI login lives (docs: geminicli.com authentication, and the
5
+ // binary's own start-up message): an OAuth sign-in leaves oauth_creds.json and
6
+ // google_accounts.json under ~/.gemini, an API key or a Vertex project lives in
7
+ // the environment or in ~/.gemini/.env, and settings.json names the method the
8
+ // owner picked. A room job gets a fresh home, so exactly these carry across:
9
+ // the login, never the owner's memory, extensions, skills or other settings.
10
+ /** The variables that carry a login or its routing. Never written to a file. */
11
+ export const GEMINI_LOGIN_ENV = /^(?:GEMINI_API_KEY|GOOGLE_API_KEY|GOOGLE_GENAI_USE_VERTEXAI|GOOGLE_GENAI_USE_GCA|GOOGLE_CLOUD_PROJECT|GOOGLE_CLOUD_PROJECT_ID|GOOGLE_CLOUD_LOCATION|GOOGLE_APPLICATION_CREDENTIALS|(?:HTTPS?|NO)_PROXY|NODE_EXTRA_CA_CERTS)$/iu;
12
+ /** The OAuth files, linked (never copied): Gemini refreshes the token in place. */
13
+ export const GEMINI_CREDENTIAL_FILES = [
14
+ "oauth_creds.json",
15
+ "google_accounts.json",
16
+ ];
17
+ const ENV_LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/u;
18
+ const QUOTED = /^(["'])(.*)\1$/u;
19
+ export function geminiDir(env) {
20
+ return join(env.GEMINI_CLI_HOME || homeDir(env), ".gemini");
21
+ }
22
+ function parseDotenv(text) {
23
+ const values = {};
24
+ for (const line of text.split("\n")) {
25
+ if (line.trimStart().startsWith("#")) {
26
+ continue;
27
+ }
28
+ const match = ENV_LINE.exec(line);
29
+ if (match?.[1] && GEMINI_LOGIN_ENV.test(match[1])) {
30
+ const raw = match[2] ?? "";
31
+ values[match[1]] = QUOTED.exec(raw)?.[2] ?? raw;
32
+ }
33
+ }
34
+ return values;
35
+ }
36
+ function readText(path) {
37
+ try {
38
+ return readFileSync(path, "utf8");
39
+ }
40
+ catch {
41
+ // Missing or unreadable carries no login; never echo what failed.
42
+ return;
43
+ }
44
+ }
45
+ // Synchronous on purpose: two small files, read once per job or once at link.
46
+ export function readGeminiLogin(env) {
47
+ const dir = geminiDir(env);
48
+ const settingsText = readText(join(dir, "settings.json"));
49
+ const dotenvText = readText(join(dir, ".env"));
50
+ let authType;
51
+ try {
52
+ const type = JSON.parse(settingsText ?? "null")?.security?.auth?.selectedType;
53
+ authType = typeof type === "string" && type.length <= 64 ? type : undefined;
54
+ }
55
+ catch {
56
+ authType = undefined;
57
+ }
58
+ const fromProcess = Object.fromEntries(Object.entries(env).filter((entry) => GEMINI_LOGIN_ENV.test(entry[0]) && typeof entry[1] === "string"));
59
+ return {
60
+ ...(authType ? { authType } : {}),
61
+ dir,
62
+ env: { ...parseDotenv(dotenvText ?? ""), ...fromProcess },
63
+ files: GEMINI_CREDENTIAL_FILES.filter((name) => existsSync(join(dir, name))),
64
+ };
65
+ }
66
+ /** Does this computer have any way for Gemini CLI to sign in? */
67
+ export function geminiSignedIn(login) {
68
+ return (login.files.includes("oauth_creds.json") ||
69
+ Boolean(login.env.GEMINI_API_KEY ||
70
+ login.env.GOOGLE_API_KEY ||
71
+ login.env.GOOGLE_GENAI_USE_VERTEXAI ||
72
+ login.env.GOOGLE_GENAI_USE_GCA) ||
73
+ login.authType === "compute-default-credentials");
74
+ }