talentos 1.4.14 → 1.4.16

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,16 +10,16 @@ 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 { codexImagesProven, probeCodexImages } from "./codex-image-probe.js";
13
- import { codexRoomArgs, ROOM_TOOLS } from "./codex-policy.js";
13
+ import { codexRoomArgs, ROOM_DIRECT_TOOLS, ROOM_PROXY_ONLY_TOOLS, } from "./codex-policy.js";
14
14
  import { binaryIdentity, CodexBoundaryError, CodexProbeInterrupted, codexWebProven, probeCodexBoundary, } from "./codex-probe.js";
15
- import { geminiRoomArgs } from "./gemini-policy.js";
16
- import { GeminiBoundaryError, probeGeminiBoundary } from "./gemini-probe.js";
17
15
  import { prepareCodexOwnerLaunch } from "./native/codex-launch.js";
18
16
  import { prepareOwnerLaunch } from "./native/launch.js";
19
17
  import { readReceipts } from "./native/receipts.js";
18
+ import { orderPacketForPrompt } from "./packet-order.js";
20
19
  import { classifyProviderFailure, matchFailureText, ProviderFailureError, } from "./provider-failure.js";
21
20
  import { READ_PAGE_TOOL, ROOM_WEB_MCP_ENTRY, ROOM_WEB_SERVER, } from "./room-page.js";
22
21
  import { prepareRoomProfile, ROOM_CATALOG_FILE, ROOM_MCP_FILE, } from "./room-profile.js";
22
+ import { roomProvider } from "./room-providers.js";
23
23
  const CHILD_ENV = [
24
24
  "HOME",
25
25
  "PATH",
@@ -38,17 +38,6 @@ const CHILD_ENV = [
38
38
  ];
39
39
  const CLAUDE_VERSION = /^\d+\.\d+\.\d+/u;
40
40
  const CODEX_VERSION = /\b\d+\.\d+\.\d+\b/u;
41
- const GEMINI_VERSION = /\b\d+\.\d+\.\d+\b/u;
42
- // What the room launch needs from this Gemini CLI: its own policy files, the
43
- // workspace-trust skip, headless streaming events, an approval mode and an MCP
44
- // server allowlist. A Gemini without them cannot hold the room boundary.
45
- const GEMINI_ROOM_FLAGS = [
46
- "--policy",
47
- "--skip-trust",
48
- "--output-format",
49
- "--approval-mode",
50
- "--allowed-mcp-server-names",
51
- ];
52
41
  const DONT_ASK = /\bdontAsk\b/u;
53
42
  // What the room line says while a job uses web. Neither names a page or a
54
43
  // query, and neither is a private tool, so an owner job shows them too.
@@ -67,7 +56,15 @@ const CLAUDE_ISOLATION_FLAGS = [
67
56
  ];
68
57
  // What Codex prints when the required room server never listed its tools.
69
58
  const ROOM_SERVER_FAILED = /required MCP servers failed to initialize/u;
70
- const CLAUDE_TOOLS = ROOM_TOOLS.map((tool) => `mcp__talentos__${tool}`).join(",");
59
+ const CLAUDE_TOOLS = ROOM_DIRECT_TOOLS.map((tool) => `mcp__talentos__${tool}`).join(",");
60
+ // Denied as well as left out of the allow list: a denied tool is not shown to
61
+ // the model, an unlisted one is only refused when it is called.
62
+ const CLAUDE_DISALLOWED = [
63
+ "Bash",
64
+ "Agent",
65
+ "Task",
66
+ ...ROOM_PROXY_ONLY_TOOLS.map((tool) => `mcp__talentos__${tool}`),
67
+ ].join(",");
71
68
  // A room job with web: Claude's own search (run by Anthropic, it reads nothing on
72
69
  // this computer), no other built-in tool. WebFetch stays out: it would run on the
73
70
  // owner's computer and could be pointed at their network (#13155 review). Pages
@@ -184,13 +181,13 @@ export async function verifyCodex(configured, signal) {
184
181
  throw new Error(`Update Codex (${version}) to a version supporting isolated room turns, exec/resume flags and a local model catalog.`);
185
182
  }
186
183
  /**
187
- * Gemini CLI can run a room job when it has the flags the launch uses and the
188
- * real binary keeps a job inside its room tools (the loopback probe, which
189
- * needs no sign-in). A signed-out Gemini still passes: sign-in is a job-time
190
- * failure with its own plain reason.
184
+ * A room-only provider can run a room job when it has the flags the launch
185
+ * uses and the real binary keeps a job inside its room tools (the loopback
186
+ * probe, which needs no sign-in). A signed-out CLI still passes: sign-in is a
187
+ * job-time failure with its own plain reason.
191
188
  */
192
- export async function verifyGemini(configured, signal) {
193
- const binary = resolveProviderBinary("gemini_cli", configured);
189
+ export async function verifyRoomProvider(profile, configured, signal) {
190
+ const binary = resolveProviderBinary(profile.provider, configured);
194
191
  const execute = promisify(execFile);
195
192
  const options = {
196
193
  env: childEnvironment(process.env, binary),
@@ -200,12 +197,19 @@ export async function verifyGemini(configured, signal) {
200
197
  };
201
198
  let version = "unknown";
202
199
  try {
203
- const detected = await execute(binary, ["--version"], options);
204
- version = GEMINI_VERSION.exec(detected.stdout)?.[0] ?? "unknown";
205
- const help = await execute(binary, ["--help"], options);
200
+ const detected = await execute(binary, ["--version"], options).catch((error) => {
201
+ // Hermes prints its version, then looks for updates over the network;
202
+ // an offline computer can stall there, so what was printed counts.
203
+ if (profile.versionMayStall && error.killed && error.stdout) {
204
+ return { stdout: error.stdout };
205
+ }
206
+ throw error;
207
+ });
208
+ version = profile.versionPattern.exec(detected.stdout)?.[0] ?? "unknown";
209
+ const help = await execute(binary, profile.helpArgs, options);
206
210
  if (version !== "unknown" &&
207
- GEMINI_ROOM_FLAGS.every((flag) => help.stdout.includes(flag))) {
208
- await probeGeminiBoundary({
211
+ profile.requiredFlags.every((flag) => help.stdout.includes(flag))) {
212
+ await profile.probe({
209
213
  binary,
210
214
  env: childEnvironment(process.env, binary),
211
215
  signal,
@@ -215,12 +219,12 @@ export async function verifyGemini(configured, signal) {
215
219
  }
216
220
  }
217
221
  catch (error) {
218
- if (error instanceof GeminiBoundaryError) {
222
+ if (profile.isBoundaryError(error)) {
219
223
  throw error;
220
224
  }
221
225
  // Provider diagnostics can contain login details.
222
226
  }
223
- throw new Error(`Update Gemini CLI (${version}) to a version that supports ${GEMINI_ROOM_FLAGS.join(", ")}.`);
227
+ throw new Error(`Update ${profile.label} (${version}) to a version that supports ${profile.requiredFlags.join(", ")}.`);
224
228
  }
225
229
  /**
226
230
  * Proves this Codex's tool surface with live web search on, after the room
@@ -359,6 +363,7 @@ export function readProviderEvent(provider, value) {
359
363
  return {};
360
364
  }
361
365
  const event = value;
366
+ const room = roomProvider(provider);
362
367
  if (provider === "claude_code") {
363
368
  if (event.type === "result") {
364
369
  if (event.is_error) {
@@ -392,26 +397,8 @@ export function readProviderEvent(provider, value) {
392
397
  };
393
398
  }
394
399
  }
395
- else if (provider === "gemini_cli") {
396
- // stream-json: init, message (user and assistant chunks), tool_use,
397
- // tool_result, error (a warning) and result (status and stats).
398
- if (event.type === "message" && event.role === "assistant") {
399
- return typeof event.content === "string"
400
- ? { textDelta: event.content }
401
- : {};
402
- }
403
- if (event.type === "tool_use") {
404
- return { status: "Using room tools…", textReset: true };
405
- }
406
- if (event.type === "result" && event.status === "error") {
407
- const error = event.error;
408
- return {
409
- failed: true,
410
- failure: typeof error?.message === "string"
411
- ? matchFailureText(error.message)
412
- : undefined,
413
- };
414
- }
400
+ else if (room) {
401
+ return room.readEvent(event);
415
402
  }
416
403
  else {
417
404
  if (event.type === "thread.started" &&
@@ -444,11 +431,12 @@ export function readProviderEvent(provider, value) {
444
431
  export async function runProvider(input) {
445
432
  const { config, job, workDir, sessionId, signal } = input;
446
433
  const { instructions, ...context } = job.packet;
447
- const prompt = JSON.stringify(config.provider === "codex" ? job.packet : context), mcpPath = join(dirname(workDir), ROOM_MCP_FILE);
434
+ const prompt = JSON.stringify(orderPacketForPrompt(config.provider === "codex" ? job.packet : context)), mcpPath = join(dirname(workDir), ROOM_MCP_FILE);
448
435
  const catalogPath = join(dirname(workDir), ROOM_CATALOG_FILE);
449
436
  const binary = resolveProviderBinary(config.provider, config.providerPath);
437
+ const room = roomProvider(config.provider);
450
438
  let command, args;
451
- // Gemini CLI reads the packet from stdin; the others take it as an argument.
439
+ // A room-only profile reads the packet from stdin; the others take it as an argument.
452
440
  let stdinText;
453
441
  let ownerLaunch;
454
442
  let stopWatching;
@@ -468,6 +456,7 @@ export async function runProvider(input) {
468
456
  roomId: job.packet.room?.id,
469
457
  roomFileIds: roomFileIds(job.packet),
470
458
  triggerId: job.packet.trigger?.id,
459
+ ownAsk: job.native?.ownAsk,
471
460
  sessionId,
472
461
  sharedRoom: job.native?.sharedRoom,
473
462
  workspace: input.owner.workspace,
@@ -475,34 +464,26 @@ export async function runProvider(input) {
475
464
  command = binary;
476
465
  args = ownerLaunch.args;
477
466
  }
478
- else if (config.provider === "gemini_cli") {
479
- // Gemini CLI never runs the owner's setup (the server never grants it
480
- // either); a job that arrives as one runs nowhere.
467
+ else if (room) {
468
+ // A room-only provider never runs the owner's setup (the server never
469
+ // grants it either); a job that arrives as one runs nowhere.
481
470
  if (input.owner) {
482
- throw new Error("A Gemini CLI job is always room-only.");
471
+ throw new Error(`A ${room.label} job is always room-only.`);
483
472
  }
484
473
  command = binary;
485
474
  roomProfile = await prepareRoomProfile({
486
- directory: dirname(workDir),
487
- env: process.env,
488
- gemini: {
475
+ agent: {
489
476
  apiKey: config.apiKey,
490
477
  mcpUrl: new URL("/mcp", config.apiUrl).href,
491
478
  },
479
+ directory: dirname(workDir),
480
+ env: process.env,
481
+ instructions,
492
482
  jobId: job.jobId,
493
483
  provider: config.provider,
494
484
  });
495
- try {
496
- // The room playbook is the job's own GEMINI.md: its directory is empty and
497
- // nothing above it is read.
498
- await writePrivateFile(join(roomProfile.cwd, "GEMINI.md"), instructions);
499
- }
500
- catch (error) {
501
- await roomProfile.cleanup();
502
- throw error;
503
- }
485
+ args = roomProfile.launch?.args ?? [];
504
486
  stdinText = prompt;
505
- args = geminiRoomArgs({ policyPath: roomProfile.geminiPolicyPath ?? "" });
506
487
  }
507
488
  else if (input.owner && config.provider === "codex" && input.owner.codex) {
508
489
  const watching = await input.owner.watch?.();
@@ -521,6 +502,7 @@ export async function runProvider(input) {
521
502
  roomId: job.packet.room?.id,
522
503
  roomFileIds: roomFileIds(job.packet),
523
504
  triggerId: job.packet.trigger?.id,
505
+ ownAsk: job.native?.ownAsk,
524
506
  sessionId,
525
507
  sharedRoom: job.native?.sharedRoom,
526
508
  signal,
@@ -576,7 +558,7 @@ export async function runProvider(input) {
576
558
  ? `${CLAUDE_TOOLS},${CLAUDE_WEB_TOOLS},${READ_PAGE_TOOL}`
577
559
  : CLAUDE_TOOLS,
578
560
  "--disallowedTools",
579
- "Bash,Agent,Task",
561
+ CLAUDE_DISALLOWED,
580
562
  "--permission-mode",
581
563
  "dontAsk",
582
564
  // None of the owner's CLAUDE.md, rules, hooks or output style. The login
@@ -44,14 +44,29 @@ export const ROOM_TOOLS = [
44
44
  "post_message",
45
45
  "ask_owner",
46
46
  "edit_own_message",
47
+ "react_to_message",
47
48
  "post_to_thread",
48
49
  "reply_to_comment",
49
50
  "start_thread",
51
+ "rename_thread",
50
52
  "share_link",
51
53
  "room_default_set",
52
54
  "room_default_remove",
53
55
  "whoami",
54
56
  ];
57
+ // The upload tools run in the talentos CLI's stdio proxy (mcp-proxy.ts), which
58
+ // reads the file from the job's folder and streams it to storage; the server's
59
+ // own upload_file only refuses. A room-only Claude Code or Gemini CLI job
60
+ // reaches /mcp directly, with no proxy, and has no shell or file tool that could
61
+ // make a file to name, so those launches never offer these (a Codex job, which
62
+ // goes through the proxy, keeps them).
63
+ const PROXY_ONLY_TOOLS = new Set([
64
+ "upload_file",
65
+ "prepare_upload",
66
+ "commit_upload",
67
+ ]);
68
+ export const ROOM_DIRECT_TOOLS = ROOM_TOOLS.filter((tool) => !PROXY_ONLY_TOOLS.has(tool));
69
+ export const ROOM_PROXY_ONLY_TOOLS = ROOM_TOOLS.filter((tool) => PROXY_ONLY_TOOLS.has(tool));
55
70
  // A TOML inline table of string pairs, for a `-c` value.
56
71
  const tomlTable = (pairs) => `{${pairs.map(([key, value]) => `${JSON.stringify(key)}=${JSON.stringify(value)}`).join(",")}}`;
57
72
  export function codexRoomArgs(input) {
@@ -1,4 +1,4 @@
1
- import { ROOM_TOOLS } from "./codex-policy.js";
1
+ import { ROOM_DIRECT_TOOLS } from "./codex-policy.js";
2
2
  // A Gemini CLI room job's boundary, written as the CLI's own policy engine and
3
3
  // user settings (verified against @google/gemini-cli 0.65.0 with its own
4
4
  // binary: see docs/features/agent-access/README.md, "Gemini CLI"). Three layers:
@@ -34,7 +34,7 @@ denyMessage = "A room job can only use its room tools."
34
34
 
35
35
  [[rule]]
36
36
  mcpName = "${GEMINI_SERVER}"
37
- toolName = ${JSON.stringify([...ROOM_TOOLS])}
37
+ toolName = ${JSON.stringify([...ROOM_DIRECT_TOOLS])}
38
38
  decision = "allow"
39
39
  priority = 100
40
40
  `;
@@ -58,7 +58,7 @@ export function geminiRoomSettings(input) {
58
58
  httpUrl: input.mcpUrl,
59
59
  // The server lists more than a room job may use: only these are ever
60
60
  // registered with the model.
61
- includeTools: [...ROOM_TOOLS],
61
+ includeTools: [...ROOM_DIRECT_TOOLS],
62
62
  },
63
63
  },
64
64
  privacy: { usageStatisticsEnabled: false },
@@ -1,12 +1,11 @@
1
- import { spawn } from "node:child_process";
2
1
  import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3
2
  import { createServer } from "node:http";
4
3
  import { tmpdir } from "node:os";
5
4
  import { join } from "node:path";
6
- import { createInterface } from "node:readline";
7
5
  import { writePrivateFile } from "../agent-config.js";
8
6
  import { ProviderBinaryError } from "../provider-binary.js";
9
7
  import { geminiRoomArgs, geminiRoomPolicy, geminiRoomSettings, geminiToolName, } from "./gemini-policy.js";
8
+ import { cachedProof, closeServer, fakeRoom, listen, ROOM_TOOL, readBody, runProbeChild, SECRET, } from "./room-probe.js";
10
9
  // Proves, against the real binary and with no login, that this Gemini CLI keeps
11
10
  // a room job inside its room tools. It runs the exact launch a job uses (same
12
11
  // policy, settings and flags) in a throwaway home, pointed at a loopback stand-in
@@ -17,10 +16,6 @@ import { geminiRoomArgs, geminiRoomPolicy, geminiRoomSettings, geminiToolName, }
17
16
  // only the offer), and an @file reference in its input is not expanded into the
18
17
  // request. A Gemini that fails it serves no room job. The result is
19
18
  // cached for the binary and its version.
20
- const PROBE_MS = 45_000;
21
- const MAX_BYTES = 2_000_000;
22
- const SECRET = "probe-secret-must-never-reach-the-model";
23
- const ROOM_TOOL = "whoami";
24
19
  export class GeminiBoundaryError extends ProviderBinaryError {
25
20
  constructor(version) {
26
21
  super(`Gemini CLI ${version} cannot safely run room jobs. Update Gemini CLI, then run talentos agent repair. If this persists, report this version to TalentOS support.`);
@@ -37,18 +32,6 @@ function toolNames(body) {
37
32
  .filter((name) => typeof name === "string")
38
33
  : []);
39
34
  }
40
- async function readBody(request) {
41
- let size = 0;
42
- const chunks = [];
43
- for await (const chunk of request) {
44
- size += chunk.length;
45
- if (size > MAX_BYTES) {
46
- throw new Error("Probe request exceeded its limit.");
47
- }
48
- chunks.push(chunk);
49
- }
50
- return Buffer.concat(chunks).toString("utf8");
51
- }
52
35
  /**
53
36
  * The Gemini API stand-in: first answers with a call to the room tool and one
54
37
  * to a file tool, then text.
@@ -141,64 +124,13 @@ function fakeApi(seen, secretPath) {
141
124
  }
142
125
  });
143
126
  }
144
- /** The room endpoint stand-in: one room tool and one tool that is not a room tool. */
145
- function fakeRoom(seen) {
146
- return createServer(async (request, response) => {
147
- const body = await readBody(request).catch(() => "");
148
- let message = {};
149
- try {
150
- message = JSON.parse(body);
151
- }
152
- catch {
153
- // A GET or an empty body: nothing to answer.
154
- }
155
- const reply = (result) => {
156
- response.setHeader("content-type", "application/json");
157
- response.end(JSON.stringify({ id: message.id, jsonrpc: "2.0", result }));
158
- };
159
- const empty = { properties: {}, type: "object" };
160
- if (message.method === "initialize") {
161
- reply({
162
- capabilities: { tools: {} },
163
- protocolVersion: "2025-03-26",
164
- serverInfo: { name: "probe", version: "1" },
165
- });
166
- }
167
- else if (message.method === "tools/list") {
168
- reply({
169
- tools: [
170
- { description: "who", inputSchema: empty, name: ROOM_TOOL },
171
- { description: "no", inputSchema: empty, name: "not_a_room_tool" },
172
- ],
173
- });
174
- }
175
- else if (message.method === "tools/call") {
176
- seen.roomCalls.push(String(message.params?.name));
177
- reply({ content: [{ text: "ok", type: "text" }] });
178
- }
179
- else {
180
- response.statusCode = 202;
181
- response.end();
182
- }
183
- });
184
- }
185
- function listen(server) {
186
- return new Promise((resolve, reject) => {
187
- server.once("error", reject);
188
- server.listen(0, "127.0.0.1", () => resolve(server.address().port));
189
- });
190
- }
191
- const closeServer = (server) => new Promise((resolve) => {
192
- server.closeAllConnections?.();
193
- server.close(() => resolve());
194
- });
195
127
  /** Runs the probe and returns what it saw; `probeGeminiBoundary` judges it. */
196
128
  export async function runGeminiProbe(input) {
197
129
  const dir = await mkdtemp(join(tmpdir(), "talentos-gemini-probe-"));
198
130
  const seen = { requests: [], roomCalls: [] };
199
131
  const secretPath = join(dir, "secret.txt");
200
132
  const api = fakeApi(seen, secretPath);
201
- const room = fakeRoom(seen);
133
+ const room = fakeRoom(seen.roomCalls);
202
134
  try {
203
135
  await writeFile(secretPath, SECRET, { mode: 0o600 });
204
136
  const [apiPort, roomPort] = await Promise.all([listen(api), listen(room)]);
@@ -214,7 +146,10 @@ export async function runGeminiProbe(input) {
214
146
  authType: "gemini-api-key",
215
147
  mcpUrl: `http://127.0.0.1:${roomPort}/mcp`,
216
148
  }));
217
- const child = spawn(input.binary, geminiRoomArgs({ policyPath }), {
149
+ let readRefused = false;
150
+ await runProbeChild({
151
+ args: geminiRoomArgs({ policyPath }),
152
+ binary: input.binary,
218
153
  cwd: work,
219
154
  env: {
220
155
  ...input.env,
@@ -222,44 +157,26 @@ export async function runGeminiProbe(input) {
222
157
  GEMINI_CLI_HOME: home,
223
158
  GOOGLE_GEMINI_BASE_URL: `http://127.0.0.1:${apiPort}`,
224
159
  },
225
- stdio: ["pipe", "pipe", "ignore"],
226
- });
227
- // A Gemini that exits before reading stdin must fail the probe, not crash the
228
- // CLI with an unhandled EPIPE.
229
- child.stdin?.on("error", () => undefined);
230
- // Headless Gemini expands @file references in what it is given; the packet
231
- // holds room text anyone can write, so a reference to a file outside the
232
- // job's directory must read nothing (`secretLeaked` judges it).
233
- child.stdin?.end(JSON.stringify({ probe: true, text: `look at @${secretPath}` }));
234
- const timer = setTimeout(() => child.kill("SIGKILL"), PROBE_MS);
235
- input.signal?.addEventListener("abort", () => child.kill("SIGKILL"), {
236
- once: true,
237
- });
238
- let readRefused = false;
239
- const lines = createInterface({ input: child.stdout });
240
- for await (const line of lines) {
241
- try {
242
- const event = JSON.parse(line);
243
- if (event.type === "tool_result" &&
244
- String(event.tool_id).startsWith("read_file") &&
245
- event.status === "error" &&
246
- event.error?.type === "tool_not_registered") {
247
- readRefused = true;
160
+ onLine: (line) => {
161
+ try {
162
+ const event = JSON.parse(line);
163
+ if (event.type === "tool_result" &&
164
+ String(event.tool_id).startsWith("read_file") &&
165
+ event.status === "error" &&
166
+ event.error?.type === "tool_not_registered") {
167
+ readRefused = true;
168
+ }
248
169
  }
249
- }
250
- catch {
251
- // Not an event line.
252
- }
253
- }
254
- await new Promise((resolve) => {
255
- if (child.exitCode === null) {
256
- child.once("close", () => resolve());
257
- }
258
- else {
259
- resolve();
260
- }
170
+ catch {
171
+ // Not an event line.
172
+ }
173
+ },
174
+ signal: input.signal,
175
+ // Headless Gemini expands @file references in what it is given; the
176
+ // packet holds room text anyone can write, so a reference to a file
177
+ // outside the job's directory must read nothing (`secretLeaked` judges it).
178
+ stdin: JSON.stringify({ probe: true, text: `look at @${secretPath}` }),
261
179
  });
262
- clearTimeout(timer);
263
180
  return {
264
181
  advertised: [...new Set(seen.requests.flatMap((r) => r.tools))],
265
182
  readRefused,
@@ -285,24 +202,18 @@ export function geminiBoundaryHolds(result) {
285
202
  result.readRefused &&
286
203
  !result.secretLeaked);
287
204
  }
288
- const proofs = new Map();
289
205
  /**
290
206
  * Throws GeminiBoundaryError unless this binary offered the model only the room
291
- * tool on every request, ran it, and refused the file tool it was asked to run. Cached per binary and
292
- * version; a failure is cached too, so a bad Gemini is not retried on every job.
207
+ * tool on every request, ran it, and refused the file tool it was asked to run.
208
+ * Cached per binary and version; a failure is cached too, so a bad Gemini is not
209
+ * retried on every job.
293
210
  */
294
211
  export function probeGeminiBoundary(input) {
295
- const key = `${input.binary}@${input.version}`;
296
- let proof = proofs.get(key);
297
- if (!proof) {
298
- proof = runGeminiProbe(input).then((result) => {
299
- if (!geminiBoundaryHolds(result)) {
300
- throw new GeminiBoundaryError(input.version);
301
- }
302
- }, () => {
212
+ return cachedProof(`gemini:${input.binary}@${input.version}`, () => runGeminiProbe(input).then((result) => {
213
+ if (!geminiBoundaryHolds(result)) {
303
214
  throw new GeminiBoundaryError(input.version);
304
- });
305
- proofs.set(key, proof);
306
- }
307
- return proof;
215
+ }
216
+ }, () => {
217
+ throw new GeminiBoundaryError(input.version);
218
+ }));
308
219
  }
@@ -0,0 +1,92 @@
1
+ import { mkdir, symlink } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { writePrivateFile } from "../agent-config.js";
4
+ import { GEMINI_CREDENTIAL_FILES, geminiSignedIn, readGeminiLogin, } from "./gemini-login.js";
5
+ import { geminiRoomArgs, geminiRoomPolicy, geminiRoomSettings, } from "./gemini-policy.js";
6
+ import { GeminiBoundaryError, probeGeminiBoundary } from "./gemini-probe.js";
7
+ import { matchFailureText } from "./provider-failure.js";
8
+ import { RoomIsolationError, } from "./room-provider.js";
9
+ // What the room launch needs from this Gemini CLI: its own policy files, the
10
+ // workspace-trust skip, headless streaming events, an approval mode and an MCP
11
+ // server allowlist. A Gemini without them cannot hold the room boundary.
12
+ const GEMINI_ROOM_FLAGS = [
13
+ "--policy",
14
+ "--skip-trust",
15
+ "--output-format",
16
+ "--approval-mode",
17
+ "--allowed-mcp-server-names",
18
+ ];
19
+ // stream-json: init, message (user and assistant chunks), tool_use,
20
+ // tool_result, error (a warning) and result (status and stats).
21
+ function readGeminiEvent(event) {
22
+ if (event.type === "message" && event.role === "assistant") {
23
+ return typeof event.content === "string"
24
+ ? { textDelta: event.content }
25
+ : {};
26
+ }
27
+ if (event.type === "tool_use") {
28
+ return { status: "Using room tools…", textReset: true };
29
+ }
30
+ if (event.type === "result" && event.status === "error") {
31
+ const error = event.error;
32
+ return {
33
+ failed: true,
34
+ failure: typeof error?.message === "string"
35
+ ? matchFailureText(error.message)
36
+ : undefined,
37
+ };
38
+ }
39
+ return {};
40
+ }
41
+ export const geminiRoomProfile = {
42
+ helpArgs: ["--help"],
43
+ isBoundaryError: (error) => error instanceof GeminiBoundaryError,
44
+ label: "Gemini CLI",
45
+ async prepare(input) {
46
+ const login = readGeminiLogin(input.env);
47
+ // Gemini CLI reads context files from the working directory upward to its
48
+ // home, so its directory sits inside the job's own home: nothing above it is
49
+ // ever read.
50
+ const home = join(input.jobDir, "home");
51
+ const cwd = join(home, "work");
52
+ await mkdir(cwd, { mode: 0o700, recursive: true });
53
+ const dotGemini = join(home, ".gemini");
54
+ await mkdir(dotGemini, { mode: 0o700, recursive: true });
55
+ const policyPath = join(dotGemini, "room-policy.toml");
56
+ await writePrivateFile(policyPath, geminiRoomPolicy());
57
+ await writePrivateFile(join(dotGemini, "settings.json"), geminiRoomSettings({
58
+ apiKey: input.agent.apiKey,
59
+ // An OAuth sign-in with no method named in settings is still OAuth.
60
+ authType: login.authType ??
61
+ (login.files.includes("oauth_creds.json")
62
+ ? "oauth-personal"
63
+ : undefined),
64
+ mcpUrl: input.agent.mcpUrl,
65
+ }));
66
+ // Links, never copies: Gemini refreshes the token in place.
67
+ for (const name of GEMINI_CREDENTIAL_FILES) {
68
+ if (login.files.includes(name)) {
69
+ await symlink(join(login.dir, name), join(dotGemini, name)).catch(() => {
70
+ throw new RoomIsolationError("Gemini CLI");
71
+ });
72
+ }
73
+ }
74
+ // The room playbook is the job's own GEMINI.md: its directory is empty and
75
+ // nothing above it is read.
76
+ await writePrivateFile(join(cwd, "GEMINI.md"), input.instructions);
77
+ return {
78
+ args: geminiRoomArgs({ policyPath }),
79
+ cwd,
80
+ env: { ...login.env, GEMINI_CLI_HOME: home },
81
+ home,
82
+ };
83
+ },
84
+ probe: probeGeminiBoundary,
85
+ provider: "gemini_cli",
86
+ readEvent: readGeminiEvent,
87
+ requiredFlags: GEMINI_ROOM_FLAGS,
88
+ signInProblem: (env) => geminiSignedIn(readGeminiLogin(env))
89
+ ? undefined
90
+ : "Sign in through the official gemini CLI before linking: start gemini once and choose how to sign in.",
91
+ versionPattern: /\b\d+\.\d+\.\d+\b/u,
92
+ };