talentos 1.4.10 → 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.
Files changed (41) hide show
  1. package/README.md +3 -3
  2. package/dist/agent/adapters.js +207 -14
  3. package/dist/agent/codex-policy.js +22 -0
  4. package/dist/agent/codex-probe.js +114 -30
  5. package/dist/agent/gemini-login.js +74 -0
  6. package/dist/agent/gemini-policy.js +91 -0
  7. package/dist/agent/gemini-probe.js +308 -0
  8. package/dist/agent/mcp-entry.js +22 -9
  9. package/dist/agent/native/approvals.js +15 -11
  10. package/dist/agent/native/codex-launch.js +3 -0
  11. package/dist/agent/native/config.js +4 -2
  12. package/dist/agent/native/gate.js +160 -8
  13. package/dist/agent/native/hook-entry.js +33 -8
  14. package/dist/agent/native/launch.js +3 -0
  15. package/dist/agent/native/native-issue.js +3 -3
  16. package/dist/agent/native/policy.js +62 -14
  17. package/dist/agent/native/probe.js +13 -1
  18. package/dist/agent/native/touch.js +33 -1
  19. package/dist/agent/node-floor.js +140 -0
  20. package/dist/agent/provider-failure.js +2 -2
  21. package/dist/agent/provider-login.js +134 -0
  22. package/dist/agent/room-profile.js +41 -4
  23. package/dist/agent/serve.js +75 -9
  24. package/dist/agent-config.js +6 -1
  25. package/dist/agent-http.js +57 -0
  26. package/dist/agent-link.js +4 -2
  27. package/dist/agent-session.js +137 -0
  28. package/dist/args.js +1 -0
  29. package/dist/client.js +11 -2
  30. package/dist/commands/agent-native.js +0 -3
  31. package/dist/commands/agent-serve.js +7 -2
  32. package/dist/commands/agent-session.js +160 -0
  33. package/dist/commands/agent.js +37 -3
  34. package/dist/commands/init.js +2 -2
  35. package/dist/commands/login.js +2 -2
  36. package/dist/gateway-install.js +50 -11
  37. package/dist/index.js +13 -4
  38. package/dist/install.js +39 -14
  39. package/dist/mcp-proxy.js +30 -2
  40. package/dist/provider-binary.js +12 -2
  41. package/package.json +2 -2
@@ -0,0 +1,308 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { createServer } from "node:http";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { createInterface } from "node:readline";
7
+ import { writePrivateFile } from "../agent-config.js";
8
+ import { ProviderBinaryError } from "../provider-binary.js";
9
+ import { geminiRoomArgs, geminiRoomPolicy, geminiRoomSettings, geminiToolName, } from "./gemini-policy.js";
10
+ // Proves, against the real binary and with no login, that this Gemini CLI keeps
11
+ // a room job inside its room tools. It runs the exact launch a job uses (same
12
+ // policy, settings and flags) in a throwaway home, pointed at a loopback stand-in
13
+ // for the Gemini API and a loopback stand-in for the room endpoint, and checks
14
+ // four things: every request offers the model the room tool alone, a call to a
15
+ // file tool the model names anyway is refused and reads nothing, and a call to
16
+ // the room tool does reach the room endpoint (so the allow rule is live, not
17
+ // only the offer), and an @file reference in its input is not expanded into the
18
+ // request. A Gemini that fails it serves no room job. The result is
19
+ // 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
+ export class GeminiBoundaryError extends ProviderBinaryError {
25
+ constructor(version) {
26
+ 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.`);
27
+ }
28
+ }
29
+ function toolNames(body) {
30
+ const tools = body?.tools;
31
+ if (!Array.isArray(tools)) {
32
+ return [];
33
+ }
34
+ return tools.flatMap((tool) => Array.isArray(tool.functionDeclarations)
35
+ ? tool.functionDeclarations
36
+ .map((declaration) => declaration.name)
37
+ .filter((name) => typeof name === "string")
38
+ : []);
39
+ }
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
+ /**
53
+ * The Gemini API stand-in: first answers with a call to the room tool and one
54
+ * to a file tool, then text.
55
+ */
56
+ function fakeApi(seen, secretPath) {
57
+ return createServer(async (request, response) => {
58
+ try {
59
+ const body = await readBody(request);
60
+ let parsed;
61
+ try {
62
+ parsed = JSON.parse(body);
63
+ }
64
+ catch {
65
+ parsed = null;
66
+ }
67
+ if (request.url?.includes("countTokens")) {
68
+ response.setHeader("content-type", "application/json");
69
+ response.end(JSON.stringify({ totalTokens: 1 }));
70
+ return;
71
+ }
72
+ // The CLI asks the model first to route the turn (a non-streaming call
73
+ // that wants JSON); any routing answer will do, and it offers no tools.
74
+ if (!request.url?.includes("stream")) {
75
+ response.setHeader("content-type", "application/json");
76
+ response.end(JSON.stringify({
77
+ candidates: [
78
+ {
79
+ content: {
80
+ parts: [
81
+ {
82
+ text: JSON.stringify({
83
+ complexity_reasoning: "probe",
84
+ complexity_score: 10,
85
+ model_choice: "flash",
86
+ reasoning: "probe",
87
+ }),
88
+ },
89
+ ],
90
+ role: "model",
91
+ },
92
+ finishReason: "STOP",
93
+ index: 0,
94
+ },
95
+ ],
96
+ }));
97
+ return;
98
+ }
99
+ seen.requests.push({ body, tools: toolNames(parsed) });
100
+ // Answered once the last thing in the conversation is a tool result.
101
+ const contents = parsed?.contents;
102
+ const last = Array.isArray(contents) ? contents.at(-1) : undefined;
103
+ const answered = JSON.stringify(last ?? "").includes("functionResponse");
104
+ const parts = answered
105
+ ? [{ text: "probe done" }]
106
+ : [
107
+ { functionCall: { args: {}, name: geminiToolName(ROOM_TOOL) } },
108
+ {
109
+ functionCall: {
110
+ args: { file_path: secretPath },
111
+ name: "read_file",
112
+ },
113
+ },
114
+ ];
115
+ const payload = {
116
+ candidates: [
117
+ {
118
+ content: { parts, role: "model" },
119
+ finishReason: "STOP",
120
+ index: 0,
121
+ },
122
+ ],
123
+ usageMetadata: {
124
+ candidatesTokenCount: 1,
125
+ promptTokenCount: 1,
126
+ totalTokenCount: 2,
127
+ },
128
+ };
129
+ if (request.url?.includes("stream")) {
130
+ response.setHeader("content-type", "text/event-stream");
131
+ response.end(`data: ${JSON.stringify(payload)}\n\n`);
132
+ }
133
+ else {
134
+ response.setHeader("content-type", "application/json");
135
+ response.end(JSON.stringify(payload));
136
+ }
137
+ }
138
+ catch {
139
+ response.statusCode = 500;
140
+ response.end();
141
+ }
142
+ });
143
+ }
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
+ /** Runs the probe and returns what it saw; `probeGeminiBoundary` judges it. */
196
+ export async function runGeminiProbe(input) {
197
+ const dir = await mkdtemp(join(tmpdir(), "talentos-gemini-probe-"));
198
+ const seen = { requests: [], roomCalls: [] };
199
+ const secretPath = join(dir, "secret.txt");
200
+ const api = fakeApi(seen, secretPath);
201
+ const room = fakeRoom(seen);
202
+ try {
203
+ await writeFile(secretPath, SECRET, { mode: 0o600 });
204
+ const [apiPort, roomPort] = await Promise.all([listen(api), listen(room)]);
205
+ const home = join(dir, "home");
206
+ const dotGemini = join(home, ".gemini");
207
+ const work = join(home, "work");
208
+ await mkdir(dotGemini, { recursive: true, mode: 0o700 });
209
+ await mkdir(work, { recursive: true, mode: 0o700 });
210
+ const policyPath = join(dotGemini, "room-policy.toml");
211
+ await writePrivateFile(policyPath, geminiRoomPolicy());
212
+ await writePrivateFile(join(dotGemini, "settings.json"), geminiRoomSettings({
213
+ apiKey: "tos_probe",
214
+ authType: "gemini-api-key",
215
+ mcpUrl: `http://127.0.0.1:${roomPort}/mcp`,
216
+ }));
217
+ const child = spawn(input.binary, geminiRoomArgs({ policyPath }), {
218
+ cwd: work,
219
+ env: {
220
+ ...input.env,
221
+ GEMINI_API_KEY: "probe",
222
+ GEMINI_CLI_HOME: home,
223
+ GOOGLE_GEMINI_BASE_URL: `http://127.0.0.1:${apiPort}`,
224
+ },
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;
248
+ }
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
+ }
261
+ });
262
+ clearTimeout(timer);
263
+ return {
264
+ advertised: [...new Set(seen.requests.flatMap((r) => r.tools))],
265
+ readRefused,
266
+ roomCalls: seen.roomCalls,
267
+ secretLeaked: seen.requests.some((request) => request.body.includes(SECRET)),
268
+ };
269
+ }
270
+ finally {
271
+ await Promise.all([closeServer(api), closeServer(room)]);
272
+ await rm(dir, { force: true, recursive: true });
273
+ }
274
+ }
275
+ /**
276
+ * Whether what the probe saw is a Gemini that keeps a room job in its room tool:
277
+ * only that tool offered on every request, it ran and nothing else did, the file
278
+ * tool was refused and its secret never reached the model.
279
+ */
280
+ export function geminiBoundaryHolds(result) {
281
+ return (result.advertised.length === 1 &&
282
+ result.advertised[0] === geminiToolName(ROOM_TOOL) &&
283
+ result.roomCalls.length === 1 &&
284
+ result.roomCalls[0] === ROOM_TOOL &&
285
+ result.readRefused &&
286
+ !result.secretLeaked);
287
+ }
288
+ const proofs = new Map();
289
+ /**
290
+ * 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.
293
+ */
294
+ 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
+ }, () => {
303
+ throw new GeminiBoundaryError(input.version);
304
+ });
305
+ proofs.set(key, proof);
306
+ }
307
+ return proof;
308
+ }
@@ -1,17 +1,30 @@
1
1
  import { localAgents } from "../agent-config.js";
2
+ import { readSessionKey, sessionUploadRoot } from "../agent-session.js";
2
3
  import { parseArgv } from "../args.js";
3
4
  import { AgentClient } from "../client.js";
5
+ import { homeDir } from "../install.js";
4
6
  import { startMcpProxy } from "../mcp-proxy.js";
5
7
  // A local stdio entry avoids putting the bearer key in Codex's argv or child
6
8
  // environment. Only the MCP proxy reads the linked-agent credential file.
7
9
  const { options } = parseArgv(process.argv.slice(2));
8
- const config = (await localAgents()).find((agent) => agent.agentId === options.agent);
9
- if (!config) {
10
- throw new Error("Linked agent configuration is unavailable.");
10
+ if (options.surface === "session") {
11
+ // The member's own terminal acting as the agent (#10527): its own key, from
12
+ // its own private file, and whatever folder the terminal runs in.
13
+ const key = await readSessionKey(options.agent ?? "", homeDir());
14
+ if (!key) {
15
+ throw new Error("This terminal is not connected. Run talentos agent connect-session.");
16
+ }
17
+ await startMcpProxy(new AgentClient(key), await sessionUploadRoot(process.cwd(), homeDir()));
18
+ }
19
+ else {
20
+ const config = (await localAgents()).find((agent) => agent.agentId === options.agent);
21
+ if (!config) {
22
+ throw new Error("Linked agent configuration is unavailable.");
23
+ }
24
+ await startMcpProxy(new AgentClient({ apiUrl: config.apiUrl, apiKey: config.apiKey }),
25
+ // The launcher names the job's workspace; a job with none uploads nothing.
26
+ options["upload-root"],
27
+ // Set only for an owner-native Codex job: the folder whose context.json and
28
+ // hook gate run_command (#10987). Absent for every room-only job.
29
+ options["owner-job-dir"]);
11
30
  }
12
- await startMcpProxy(new AgentClient({ apiUrl: config.apiUrl, apiKey: config.apiKey }),
13
- // The launcher names the job's workspace; a job with none uploads nothing.
14
- options["upload-root"],
15
- // Set only for an owner-native Codex job: the folder whose context.json and
16
- // hook gate run_command (#10987). Absent for every room-only job.
17
- options["owner-job-dir"]);
@@ -18,6 +18,12 @@ const MAX_LINE = 4096;
18
18
  const asAnswer = (status) => status === "approved" || status === "denied" || status === "expired"
19
19
  ? status
20
20
  : undefined;
21
+ const asRefusedBy = (value) => Array.isArray(value) &&
22
+ value.length > 0 &&
23
+ value.length <= 5 &&
24
+ value.every((name) => typeof name === "string")
25
+ ? value
26
+ : undefined;
21
27
  function parseReport(line) {
22
28
  try {
23
29
  const value = JSON.parse(line);
@@ -168,10 +174,10 @@ export class ApprovalBridge {
168
174
  }
169
175
  async forward(ask, socket) {
170
176
  try {
171
- const { status } = await this.gateway.request(ask);
177
+ const { refusedBy, status } = await this.gateway.request(ask);
172
178
  const answer = asAnswer(status);
173
179
  if (answer) {
174
- this.reply(socket, answer);
180
+ this.reply(socket, answer, refusedBy);
175
181
  return;
176
182
  }
177
183
  }
@@ -196,16 +202,13 @@ export class ApprovalBridge {
196
202
  this.lastPollAt = Date.now();
197
203
  try {
198
204
  const keys = [...this.waiters.keys()].slice(0, 10);
199
- const answers = new Map((await this.gateway.status(keys)).map((row) => [
200
- row.actionKey,
201
- row.status,
202
- ]));
205
+ const answers = new Map((await this.gateway.status(keys)).map((row) => [row.actionKey, row]));
203
206
  for (const key of keys) {
204
- const status = answers.get(key);
205
- const answer = status === undefined ? "expired" : asAnswer(status);
207
+ const row = answers.get(key);
208
+ const answer = row === undefined ? "expired" : asAnswer(row.status);
206
209
  if (answer) {
207
210
  for (const socket of this.waiters.get(key) ?? []) {
208
- this.reply(socket, answer);
211
+ this.reply(socket, answer, row?.refusedBy);
209
212
  }
210
213
  this.waiters.delete(key);
211
214
  }
@@ -227,8 +230,9 @@ export class ApprovalBridge {
227
230
  this.signal();
228
231
  }
229
232
  }
230
- reply(socket, status) {
231
- socket.end(`${JSON.stringify({ status })}\n`);
233
+ reply(socket, status, refusedBy) {
234
+ const classes = status === "denied" ? asRefusedBy(refusedBy) : undefined;
235
+ socket.end(`${JSON.stringify(classes ? { status, refusedBy: classes } : { status })}\n`);
232
236
  }
233
237
  signal() {
234
238
  const waiting = this.waiters.size > 0;
@@ -20,6 +20,9 @@ export async function prepareCodexOwnerLaunch(input) {
20
20
  await writePrivateFile(join(jobDir, "context.json"), JSON.stringify({
21
21
  ...(input.askSocket ? { askSocket: input.askSocket } : {}),
22
22
  home: input.home,
23
+ ...(input.roomId ? { roomId: input.roomId } : {}),
24
+ ...(input.roomFileIds ? { roomFileIds: input.roomFileIds } : {}),
25
+ ...(input.triggerId ? { triggerId: input.triggerId } : {}),
23
26
  writeRoots: input.workspace.writeRoots,
24
27
  }));
25
28
  const catalogPath = join(jobDir, "catalog.json");
@@ -7,6 +7,7 @@ import { isMissing, writePrivateFile } from "../../agent-config.js";
7
7
  import { isInside, protectedPaths, reachesProtected } from "./paths.js";
8
8
  const exec = promisify(execFile);
9
9
  export const NATIVE_FILE = "native.json";
10
+ export const NATIVE_OFF_FILE = "native-off.json";
10
11
  export async function readNativeConfig(directory) {
11
12
  try {
12
13
  const value = JSON.parse(await readFile(join(directory, NATIVE_FILE), "utf8"));
@@ -42,6 +43,7 @@ export async function readNativeFallback(directory) {
42
43
  }
43
44
  }
44
45
  export async function disableNative(directory) {
46
+ await writePrivateFile(join(directory, NATIVE_OFF_FILE), JSON.stringify(Date.now()));
45
47
  await rm(join(directory, NATIVE_FILE), { force: true });
46
48
  }
47
49
  /** [a-z0-9-] only: a display name never forms a path. */
@@ -111,8 +113,8 @@ export function rootProblem(config, home) {
111
113
  * runs in, otherwise ~/TalentOS/<name>-<id>/ (created here, empty).
112
114
  */
113
115
  export async function enableNative(input) {
114
- let root = await repoRoot(input.cwd);
115
- let kind = "repo";
116
+ let root = input.root ?? (input.cwd ? await repoRoot(input.cwd) : undefined);
117
+ let kind = input.root ? (input.kind ?? "repo") : "repo";
116
118
  if (root) {
117
119
  root = realpathSync.native(root);
118
120
  }