talentos 1.4.3 → 1.4.5

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.
@@ -14,6 +14,7 @@ import { CodexBoundaryError, probeCodexBoundary } from "./codex-probe.js";
14
14
  import { prepareCodexOwnerLaunch } from "./native/codex-launch.js";
15
15
  import { prepareOwnerLaunch } from "./native/launch.js";
16
16
  import { readReceipts } from "./native/receipts.js";
17
+ import { classifyProviderFailure, matchFailureText, ProviderFailureError, } from "./provider-failure.js";
17
18
  const CHILD_ENV = [
18
19
  "HOME",
19
20
  "PATH",
@@ -33,6 +34,8 @@ const CHILD_ENV = [
33
34
  const CLAUDE_VERSION = /^\d+\.\d+\.\d+/u;
34
35
  const CODEX_VERSION = /\b\d+\.\d+\.\d+\b/u;
35
36
  const DONT_ASK = /\bdontAsk\b/u;
37
+ // What Codex prints when the required room server never listed its tools.
38
+ const ROOM_SERVER_FAILED = /required MCP servers failed to initialize/u;
36
39
  const CLAUDE_TOOLS = ROOM_TOOLS.map((tool) => `mcp__talentos__${tool}`).join(",");
37
40
  export function childEnvironment(source = process.env, binary) {
38
41
  return {
@@ -142,6 +145,12 @@ async function codexRoomCatalog(binary) {
142
145
  throw new Error("Update Codex to a version supporting a local room-only model catalog.");
143
146
  }
144
147
  }
148
+ /** Codex could not start its room tools, so the job fails with that reason. */
149
+ export class RoomToolsUnavailableError extends ProviderFailureError {
150
+ constructor() {
151
+ super("room_tools", "Codex couldn't reach its room tools. Try again.");
152
+ }
153
+ }
145
154
  export function readProviderEvent(provider, value) {
146
155
  if (!value || typeof value !== "object") {
147
156
  return {};
@@ -150,7 +159,10 @@ export function readProviderEvent(provider, value) {
150
159
  if (provider === "claude_code") {
151
160
  if (event.type === "result") {
152
161
  if (event.is_error) {
153
- return { failed: true };
162
+ return {
163
+ failed: true,
164
+ failure: matchFailureText([event.result, event.api_error_status].join(" ")),
165
+ };
154
166
  }
155
167
  return {
156
168
  ...(typeof event.session_id === "string"
@@ -160,6 +172,10 @@ export function readProviderEvent(provider, value) {
160
172
  };
161
173
  }
162
174
  const message = event.message;
175
+ // Claude Code tags an assistant turn it could not get from the API.
176
+ if (event.type === "assistant" && typeof event.error === "string") {
177
+ return { failure: matchFailureText(event.error) };
178
+ }
163
179
  if (event.type === "assistant" &&
164
180
  Array.isArray(message?.content) &&
165
181
  message.content.some((part) => part.type === "tool_use")) {
@@ -172,7 +188,12 @@ export function readProviderEvent(provider, value) {
172
188
  return { sessionId: event.thread_id };
173
189
  }
174
190
  if (event.type === "turn.failed" || event.type === "error") {
175
- return { failed: true };
191
+ const error = event.error;
192
+ const text = error?.message ?? event.message;
193
+ return {
194
+ failed: true,
195
+ failure: typeof text === "string" ? matchFailureText(text) : undefined,
196
+ };
176
197
  }
177
198
  const item = event.item;
178
199
  if (event.type === "item.completed" &&
@@ -303,7 +324,9 @@ export async function runProvider(input) {
303
324
  .join(delimiter),
304
325
  }
305
326
  : childEnvironment(process.env, binary),
306
- stdio: ["ignore", "pipe", "ignore"],
327
+ // stderr is matched to name a failure, never forwarded: it can hold login
328
+ // details.
329
+ stdio: ["ignore", "pipe", "pipe"],
307
330
  detached: process.platform !== "win32",
308
331
  });
309
332
  const marked = new Set();
@@ -314,6 +337,11 @@ export async function runProvider(input) {
314
337
  }
315
338
  };
316
339
  child.once("spawn", () => mark("spawn"));
340
+ // The last 8 kB is enough for a provider's closing error line.
341
+ let stderrTail = "";
342
+ child.stderr?.on("data", (chunk) => {
343
+ stderrTail = (stderrTail + chunk.toString()).slice(-8192);
344
+ });
317
345
  let killTimer;
318
346
  const stop = () => {
319
347
  const pid = child.pid;
@@ -336,16 +364,20 @@ export async function runProvider(input) {
336
364
  kill("SIGTERM");
337
365
  killTimer ??= setTimeout(() => kill("SIGKILL"), 5000);
338
366
  };
367
+ let spawnError;
339
368
  const ended = new Promise((resolve) => {
340
- child.once("error", () => resolve(null));
341
- child.once("close", resolve);
369
+ child.once("error", (error) => {
370
+ spawnError = error.code;
371
+ resolve({ code: null, signal: null });
372
+ });
373
+ child.once("close", (code, signal) => resolve({ code, signal }));
342
374
  });
343
375
  signal.addEventListener("abort", stop, { once: true });
344
376
  if (signal.aborted) {
345
377
  stop();
346
378
  }
347
379
  try {
348
- let text = "", failed = false, sawResult = false;
380
+ let text = "", failure, failed = false, sawResult = false;
349
381
  if (!child.stdout) {
350
382
  throw new Error("Provider output is unavailable.");
351
383
  }
@@ -369,6 +401,10 @@ export async function runProvider(input) {
369
401
  if (event.failed) {
370
402
  failed = true;
371
403
  }
404
+ // Sign-in outranks a limit when the provider reported both.
405
+ if (event.failure && failure !== "signed_out") {
406
+ failure = event.failure;
407
+ }
372
408
  if (event.sessionId) {
373
409
  await input.remember(event.sessionId);
374
410
  }
@@ -384,9 +420,21 @@ export async function runProvider(input) {
384
420
  sawResult = true;
385
421
  }
386
422
  }
387
- const code = await ended;
388
- if (code !== 0 || failed || !sawResult || signal.aborted) {
389
- throw new Error("Provider could not finish this turn. Check its login and quota.");
423
+ const exit = await ended;
424
+ if (exit.code !== 0 &&
425
+ !signal.aborted &&
426
+ ROOM_SERVER_FAILED.test(stderrTail)) {
427
+ throw new RoomToolsUnavailableError();
428
+ }
429
+ if (exit.code !== 0 || failed || !sawResult || signal.aborted) {
430
+ throw new ProviderFailureError(signal.aborted
431
+ ? "unknown"
432
+ : classifyProviderFailure({
433
+ ...exit,
434
+ eventHint: failure,
435
+ spawnError,
436
+ stderrTail,
437
+ }), "Provider could not finish this turn. Check its login and quota.");
390
438
  }
391
439
  return { text: redactAgentOutput(text, [config.apiKey]) };
392
440
  }
@@ -6,6 +6,7 @@ export const ROOM_TOOLS = [
6
6
  "read_room",
7
7
  "list_room_files",
8
8
  "read_file",
9
+ "read_app_state",
9
10
  "get_skill",
10
11
  "suggest_change",
11
12
  "create_file",
@@ -61,6 +62,12 @@ export function codexRoomArgs(input) {
61
62
  `model_catalog_json=${JSON.stringify(catalogPath)}`,
62
63
  "-c",
63
64
  `mcp_servers.talentos.enabled_tools=${JSON.stringify(ROOM_TOOLS)}`,
65
+ // Codex >= 0.147 runs the turn without an optional MCP server that has not
66
+ // listed its tools within ~1 s; our proxy needs several round trips to
67
+ // /mcp first, so the model got no room tools (#12225). A required server is
68
+ // awaited, and one that cannot start fails the turn instead.
69
+ "-c",
70
+ "mcp_servers.talentos.required=true",
64
71
  "-c",
65
72
  `mcp_servers.talentos.command=${JSON.stringify(mcpCommand)}`,
66
73
  "-c",
@@ -11,7 +11,12 @@ import { ProviderBinaryError, providerPathEnv } from "../provider-binary.js";
11
11
  import { codexRoomArgs, ROOM_TOOLS } from "./codex-policy.js";
12
12
  const PROBE_MS = 30_000;
13
13
  const MAX_BYTES = 4_000_000;
14
- const PROBE_REVISION = 2;
14
+ const PROBE_REVISION = 3;
15
+ // Codex >= 0.147 gives an optional MCP server ~1 s to list its tools, then runs
16
+ // the turn without them (#12225). The real room proxy needs several round trips
17
+ // to /mcp, so the stand-in lists later than that: only a launch that makes Codex
18
+ // wait for the room server passes.
19
+ export const SLOW_LIST_MS = 1500;
15
20
  const RESOURCE_REFUSAL = /Method not found|unknown MCP server/u;
16
21
  const INPUT_TYPES = new Set([
17
22
  "message",
@@ -255,7 +260,7 @@ async function proveCodexBoundary(binary, version, catalog, stop) {
255
260
  import {StdioServerTransport} from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/server/stdio.js"))};
256
261
  import {ListToolsRequestSchema,CallToolRequestSchema} from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/types.js"))};
257
262
  const server=new Server({name:'talentos',version:'probe'},{capabilities:{tools:{}}});
258
- server.setRequestHandler(ListToolsRequestSchema,async()=>({tools:${JSON.stringify([...ROOM_TOOLS, "search_memory", "run_routine"].map((name) => ({ name, description: name, inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } })))}}));
263
+ server.setRequestHandler(ListToolsRequestSchema,async()=>{await new Promise(r=>setTimeout(r,Number(process.argv[2])));return {tools:${JSON.stringify([...ROOM_TOOLS, "search_memory", "run_routine"].map((name) => ({ name, description: name, inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } })))}};});
259
264
  server.setRequestHandler(CallToolRequestSchema,async r=>({content:[{type:'text',text:r.params.name==='read_room'?${JSON.stringify(marker)}:'private-tool-refused'}]}));
260
265
  await server.connect(new StdioServerTransport());`, { mode: 0o600 });
261
266
  server.on("request", async (request, response) => {
@@ -383,7 +388,8 @@ await server.connect(new StdioServerTransport());`, { mode: 0o600 });
383
388
  const args = codexRoomArgs({
384
389
  catalogPath,
385
390
  mcpCommand: process.execPath,
386
- mcpArgs: [mcp],
391
+ // One slow listing is enough to prove Codex waits; keep resume quick.
392
+ mcpArgs: [mcp, String(turn === 0 ? SLOW_LIST_MS : 0)],
387
393
  prompt: "Verify the room boundary.",
388
394
  sessionId: session,
389
395
  });
@@ -392,7 +398,7 @@ await server.connect(new StdioServerTransport());`, { mode: 0o600 });
392
398
  if (failure ||
393
399
  !finished[turn] ||
394
400
  calls[turn]?.length !== turnSteps[turn]?.length ||
395
- !observations[turn]?.has("mcp__talentos.read_room")) {
401
+ !ROOM_TOOLS.every((name) => observations[turn]?.has(`mcp__talentos.${name}`))) {
396
402
  throw new Error("Incomplete boundary proof");
397
403
  }
398
404
  const events = output
@@ -0,0 +1,22 @@
1
+ // How long the CLI keeps a provider running while the server cannot be reached
2
+ // (a Convex push took the gateway away for 76 s and 78 s on staging,
3
+ // 2026-10-21). The server honours a lapsed lease for its own grace, then puts
4
+ // the job back in the queue and hands the same computer its own claim back at
5
+ // once, so a quiet gateway alone never costs the agent its job.
6
+ //
7
+ // Only the server's word ends a job early: a 409 on a renewal means another
8
+ // claim holds it. This is the backstop for a gateway that never comes back.
9
+ const SERVER_GRACE_MS = 150_000; // convex/externalAgents/jobLease.model.ts
10
+ const NATIVE_LEASE_MS = 30_000;
11
+ const ROOM_ONLY_HOLD_MS = 15 * 60_000;
12
+ // An owner job runs the owner's real setup on their computer, so it fails
13
+ // closed once the server has stopped counting it: after lease plus grace.
14
+ const NATIVE_HOLD_MS = NATIVE_LEASE_MS + SERVER_GRACE_MS - 5000;
15
+ export function holdMs(native) {
16
+ return native ? NATIVE_HOLD_MS : ROOM_ONLY_HOLD_MS;
17
+ }
18
+ // A missed renewal is retried every few seconds, not at the next 20 s beat.
19
+ const RETRY_MS = 3000;
20
+ export function renewDelayMs(beatMs, failedRenewals) {
21
+ return failedRenewals > 0 ? Math.min(beatMs, RETRY_MS) : beatMs;
22
+ }
@@ -7,7 +7,7 @@ import { tmpdir } from "node:os";
7
7
  import { join } from "node:path";
8
8
  import { writePrivateFile } from "../../agent-config.js";
9
9
  import { ROOM_LOCAL_TOOLS } from "../codex-policy.js";
10
- import { probeResponse } from "../codex-probe.js";
10
+ import { probeResponse, SLOW_LIST_MS } from "../codex-probe.js";
11
11
  import { codexOwnerArgs, ownerCatalog, ownerToolAllowlist, } from "./codex-fence.js";
12
12
  import { codexHookArgs, trustHookArgs } from "./codex-owner.js";
13
13
  // The GATE probe for Codex owner-native (#10987 slice 1). codex-owner-probe.ts
@@ -69,7 +69,7 @@ process.stdin.on("end", () => {
69
69
  // calls, and returns ok. run_command execution and classification live in
70
70
  // codex-run-command.ts and its test; here we only prove the tool is exposed and
71
71
  // the exact command string reaches the proxy (so the approval shows what runs).
72
- function roomServerSource(recordPath) {
72
+ function roomServerSource(recordPath, listDelayMs) {
73
73
  const all = [...STANDIN_ROOM_TOOLS, ...ROOM_LOCAL_TOOLS];
74
74
  return `import {Server} from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/server/index.js"))};
75
75
  import {StdioServerTransport} from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/server/stdio.js"))};
@@ -77,7 +77,7 @@ import {ListToolsRequestSchema,CallToolRequestSchema} from ${JSON.stringify(impo
77
77
  import {appendFileSync} from "node:fs";
78
78
  const tools=${JSON.stringify(all)}.map((n)=>({name:n,description:n,inputSchema:{type:"object",properties:{command:{type:"string"}},additionalProperties:true}}));
79
79
  const s=new Server({name:"talentos_room",version:"1"},{capabilities:{tools:{}}});
80
- s.setRequestHandler(ListToolsRequestSchema,async()=>({tools}));
80
+ s.setRequestHandler(ListToolsRequestSchema,async()=>{await new Promise((r)=>setTimeout(r,${listDelayMs}));return {tools};});
81
81
  s.setRequestHandler(CallToolRequestSchema,async(r)=>{appendFileSync(${JSON.stringify(recordPath)},JSON.stringify({name:r.params.name,arguments:r.params.arguments})+"\\n");return {content:[{type:"text",text:"ok"}]};});
82
82
  await s.connect(new StdioServerTransport());`;
83
83
  }
@@ -91,7 +91,7 @@ async function runCell(binary, root, options, signal) {
91
91
  const hook = join(root, "hook.js");
92
92
  writeFileSync(hook, HOOK, { mode: 0o700 });
93
93
  const roomServer = join(root, `room-${createHash("sha1").update(work).digest("hex")}.mjs`);
94
- writeFileSync(roomServer, roomServerSource(roomRec));
94
+ writeFileSync(roomServer, roomServerSource(roomRec, options.slowList ? SLOW_LIST_MS : 0));
95
95
  const jobDir = join(root, `job-${createHash("sha1").update(home).digest("hex")}`);
96
96
  mkdirSync(jobDir, { recursive: true });
97
97
  writeFileSync(join(jobDir, "context.json"), JSON.stringify({ home, writeRoots: [work] }));
@@ -321,6 +321,7 @@ export async function probeCodexFence(binary, version, signal = AbortSignal.time
321
321
  await cell("tool_list", async () => {
322
322
  const run = await runCell(binary, root, {
323
323
  script: "text(JSON.stringify(Object.keys(tools).sort()))",
324
+ slowList: true,
324
325
  }, signal);
325
326
  const out = lastText(run);
326
327
  if (!out) {
@@ -133,6 +133,10 @@ export function codexOwnerArgs(input) {
133
133
  ...ROOM_TOOLS,
134
134
  ...ROOM_LOCAL_TOOLS,
135
135
  ])}`,
136
+ // Wait for the room server's tools rather than run without them (#12225,
137
+ // see codexRoomArgs).
138
+ "-c",
139
+ `mcp_servers.${ROOM_SERVER}.required=true`,
136
140
  // Our PreToolUse hook is the gate, so Codex must not add its own approval
137
141
  // prompt in front of the room server (under workspace-write an MCP call
138
142
  // would otherwise be refused as "requires approval, but policy is never").
@@ -1,30 +1,17 @@
1
1
  import { mkdir, rm } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
3
  import { writePrivateFile } from "../../agent-config.js";
5
- import { gatewayLauncherPath } from "../../gateway-install.js";
6
4
  import { codexOwnerArgs, ownerCatalog } from "./codex-fence.js";
7
5
  import { codexHookArgs, trustHookArgs } from "./codex-owner.js";
8
- import { HOOK_ENTRY, ownerRules } from "./launch.js";
6
+ import { HOOK_ENTRY, ownerRules, roomMcpEntry } from "./launch.js";
9
7
  /** The room MCP proxy command for a Codex owner job: adds the owner job dir. */
10
8
  export function codexRoomMcpEntry(input) {
11
- const launcher = gatewayLauncherPath(input.home);
12
- const useLauncher = process.platform !== "win32";
9
+ // Claude's entry, so both fall back to the CLI when no launcher is installed.
10
+ const entry = roomMcpEntry(input.agentId, input.home, input.uploadRoot);
13
11
  return {
14
- command: useLauncher ? launcher : process.execPath,
15
- args: [
16
- ...(useLauncher
17
- ? []
18
- : [fileURLToPath(new URL("../../index.js", import.meta.url))]),
19
- "agent",
20
- "mcp",
21
- "--agent",
22
- input.agentId,
23
- ...(input.uploadRoot ? ["--upload-root", input.uploadRoot] : []),
24
- // Turns on run_command, served and gated by the proxy for this job only.
25
- "--owner-job-dir",
26
- input.jobDir,
27
- ],
12
+ command: entry.command,
13
+ // Turns on run_command, served and gated by the proxy for this job only.
14
+ args: [...entry.args, "--owner-job-dir", input.jobDir],
28
15
  };
29
16
  }
30
17
  export async function prepareCodexOwnerLaunch(input) {
@@ -0,0 +1,64 @@
1
+ import { ProviderBinaryError } from "../provider-binary.js";
2
+ /**
3
+ * Why a provider (claude / codex) turn failed, read from what its process left
4
+ * behind. Only the enum leaves this computer: stderr and the provider's own
5
+ * error text can hold login details, so they are matched here and dropped.
6
+ * The server stores the value as fixed text (convex/externalAgents/jobs.ts
7
+ * failJob); `unknown` is the generic failure an old CLI always sent.
8
+ */
9
+ export const PROVIDER_FAILURE_REASONS = [
10
+ "signed_out",
11
+ "usage_limit",
12
+ "missing_binary",
13
+ "crashed",
14
+ "unknown",
15
+ ];
16
+ const SIGNED_OUT = /invalid api key|run \/login|codex login|not logged in|not signed in|log(?:ged)? in again|unauthori[sz]ed|(?:status|http|error|code)[ :]+401\b|authentication[_ ](?:failed|error)|oauth token (?:has )?expired|token[_ ](?:has )?expired|refresh token/iu;
17
+ const USAGE_LIMIT = /usage limit|hit your limit|limit reached|rate[_ ]limit|(?:status|http|error|code)[ :]+429\b|credit balance|quota|billing[_ ]error|out of credits|insufficient[_ ]credit/iu;
18
+ const CRASHED = /\bpanicked\b|segmentation fault|fatal error|out of memory|uncaught exception|^\s+at .+\(.+:\d+:\d+\)$/imu;
19
+ // 126 is "found but not executable"; 127 is the shell's "command not found".
20
+ const NOT_STARTED = new Set(["ENOENT", "EACCES", "ENOTDIR"]);
21
+ /**
22
+ * What a provider's own words say went wrong. The text is read here and
23
+ * dropped, so a caller holds a label, never the words.
24
+ */
25
+ export function matchFailureText(text) {
26
+ if (SIGNED_OUT.test(text)) {
27
+ return "signed_out";
28
+ }
29
+ return USAGE_LIMIT.test(text) ? "usage_limit" : undefined;
30
+ }
31
+ /** Sign-in first: an expired login often prints a limit-looking line too. */
32
+ export function classifyProviderFailure(exit) {
33
+ if ((exit.spawnError && NOT_STARTED.has(exit.spawnError)) ||
34
+ exit.code === 126 ||
35
+ exit.code === 127) {
36
+ return "missing_binary";
37
+ }
38
+ const hints = [exit.eventHint, matchFailureText(exit.stderrTail)];
39
+ if (hints.includes("signed_out")) {
40
+ return "signed_out";
41
+ }
42
+ if (hints.includes("usage_limit")) {
43
+ return "usage_limit";
44
+ }
45
+ if (exit.signal || CRASHED.test(exit.stderrTail)) {
46
+ return "crashed";
47
+ }
48
+ return "unknown";
49
+ }
50
+ /** A failed provider turn, carrying the one reason the server is told. */
51
+ export class ProviderFailureError extends Error {
52
+ reason;
53
+ constructor(reason, message) {
54
+ super(message);
55
+ this.reason = reason;
56
+ }
57
+ }
58
+ /** The reason to send for a job that threw; absent keeps the generic failure. */
59
+ export function failureReasonOf(error) {
60
+ if (error instanceof ProviderFailureError) {
61
+ return error.reason;
62
+ }
63
+ return error instanceof ProviderBinaryError ? "missing_binary" : undefined;
64
+ }
@@ -5,19 +5,21 @@ import { setTimeout as delay } from "node:timers/promises";
5
5
  import { installSharedGateway, newerInstalledVersion, } from "../gateway-install.js";
6
6
  import { compareGatewayVersions } from "../gateway-version.js";
7
7
  import { homeDir } from "../install.js";
8
- import { runProvider } from "./adapters.js";
8
+ import { RoomToolsUnavailableError, runProvider, } from "./adapters.js";
9
9
  import { AgentGateway, GatewayError } from "./gateway.js";
10
+ import { holdMs, renewDelayMs } from "./lease-hold.js";
10
11
  import { ApprovalBridge } from "./native/approvals.js";
11
12
  import { NativeGate } from "./native/gate.js";
12
13
  import { ROOM_ONLY_STATUS } from "./native/native-issue.js";
13
14
  import { ProjectRequests } from "./native/project-requests.js";
14
15
  import { mirrorOf } from "./native/projects.js";
16
+ import { failureReasonOf } from "./provider-failure.js";
15
17
  import { SessionMap } from "./sessions.js";
16
18
  const HEARTBEAT_MS = 20_000;
17
- const LEASE_SAFETY_MS = 55_000;
18
19
  // A native job holds a 30 s server lease and is re-derived on every renewal.
19
20
  const NATIVE_RENEW_MS = 10_000;
20
- const NATIVE_SAFETY_MS = 25_000;
21
+ // A launch waits this long for the server before it starts the provider anyway.
22
+ const START_WAIT_MS = 120_000;
21
23
  const IDLE_MS = 30 * 60_000;
22
24
  // The room-only reason stays up this long before progress lines resume.
23
25
  const FALLBACK_HOLD_MS = 5000;
@@ -135,6 +137,40 @@ export async function serveAgent(config, directory, version, stop, verify, optio
135
137
  post: (path, body) => gateway.request(path, body, signal),
136
138
  })
137
139
  : undefined;
140
+ const beat = (native) => options.lease?.beatMs ?? (native ? NATIVE_RENEW_MS : HEARTBEAT_MS);
141
+ const holdFor = (native) => options.lease?.holdMs ?? holdMs(native);
142
+ let failedRenewals = 0;
143
+ // The server is away: a 5xx or no answer at all, as during a Convex push.
144
+ const serverAway = (error) => !(error instanceof GatewayError) || error.status >= 500;
145
+ // A claim can land just before a push; the provider's room tools are
146
+ // listed once at its start, so wait for the server before launching it.
147
+ const waitForServer = async (job, cancel) => {
148
+ const until = Date.now() + (options.lease?.startWaitMs ?? START_WAIT_MS);
149
+ const step = options.lease?.stepMs ?? 1000;
150
+ for (let wait = step; !signal.aborted; wait = Math.min(wait * 2, step * 10)) {
151
+ try {
152
+ await gateway.request(`/agent-gateway/jobs/${job.jobId}/renew`, { leaseToken: job.leaseToken }, signal);
153
+ return;
154
+ }
155
+ catch (error) {
156
+ if (error instanceof GatewayError && error.status === 409) {
157
+ cancel.abort();
158
+ }
159
+ failService(error);
160
+ if (!serverAway(error) || Date.now() >= until) {
161
+ return;
162
+ }
163
+ }
164
+ await delay(wait, undefined, {
165
+ signal: AbortSignal.any([signal, cancel.signal]),
166
+ }).catch(() => {
167
+ /* Shutdown or a lost claim interrupts the wait. */
168
+ });
169
+ if (cancel.signal.aborted) {
170
+ return;
171
+ }
172
+ }
173
+ };
138
174
  const heartbeatLoop = async () => {
139
175
  while (!signal.aborted) {
140
176
  const started = Date.now();
@@ -145,19 +181,24 @@ export async function serveAgent(config, directory, version, stop, verify, optio
145
181
  ? gateway
146
182
  .request(`/agent-gateway/jobs/${leased.job.jobId}/renew`, { leaseToken: leased.job.leaseToken }, signal)
147
183
  .then(() => {
148
- if (active === leased) {
184
+ failedRenewals = 0;
185
+ if (active === leased && !leased.answered) {
149
186
  leased.deadline =
150
- started +
151
- (leased.job.native ? NATIVE_SAFETY_MS : LEASE_SAFETY_MS);
187
+ started + holdFor(Boolean(leased.job.native));
152
188
  }
153
189
  })
154
190
  .catch((error) => {
155
191
  if (active !== leased) {
156
192
  return;
157
193
  }
194
+ // Only the server's word ends the job: 409 is another
195
+ // claim. Anything else is a gateway that will be back.
158
196
  if (error instanceof GatewayError && error.status === 409) {
159
197
  leased.cancel.abort();
160
198
  }
199
+ else {
200
+ failedRenewals++;
201
+ }
161
202
  failService(error);
162
203
  })
163
204
  : Promise.resolve(),
@@ -166,7 +207,7 @@ export async function serveAgent(config, directory, version, stop, verify, optio
166
207
  if (active?.job.native && active.owner && !gate.optedIn()) {
167
208
  active.cancel.abort();
168
209
  }
169
- await delay(Math.max(1, (active?.job.native ? NATIVE_RENEW_MS : HEARTBEAT_MS) -
210
+ await delay(Math.max(1, renewDelayMs(beat(Boolean(active?.job.native)), failedRenewals) -
170
211
  (Date.now() - started)), undefined, { signal }).catch(() => {
171
212
  /* Shutdown interrupts the timer. */
172
213
  });
@@ -175,7 +216,8 @@ export async function serveAgent(config, directory, version, stop, verify, optio
175
216
  let heartbeats;
176
217
  let updateAfter = 0;
177
218
  const watchdog = setInterval(() => {
178
- if (active && Date.now() >= active.deadline) {
219
+ // A made answer is never dropped for a quiet gateway; only a 409 ends it.
220
+ if (active && !active.answered && Date.now() >= active.deadline) {
179
221
  active.cancel.abort();
180
222
  }
181
223
  }, 1000);
@@ -254,9 +296,9 @@ export async function serveAgent(config, directory, version, stop, verify, optio
254
296
  const current = {
255
297
  job,
256
298
  cancel,
257
- deadline: claimStartedAt +
258
- (job.native ? NATIVE_SAFETY_MS : LEASE_SAFETY_MS),
299
+ deadline: claimStartedAt + holdFor(Boolean(job.native)),
259
300
  owner: false,
301
+ answered: false,
260
302
  };
261
303
  active = current;
262
304
  let lastStatusAt = 0;
@@ -266,6 +308,7 @@ export async function serveAgent(config, directory, version, stop, verify, optio
266
308
  const receivedAt = performance.now();
267
309
  const timings = {};
268
310
  try {
311
+ await waitForServer(job, cancel);
269
312
  // An owner job runs the owner's real setup only when the plane
270
313
  // confirmed owner authority just now AND this computer is ready;
271
314
  // anything less is the room-only profile, as before.
@@ -380,6 +423,10 @@ export async function serveAgent(config, directory, version, stop, verify, optio
380
423
  .catch(failService);
381
424
  },
382
425
  });
426
+ // The answer is made: only the server saying another claim holds the
427
+ // job may drop it, never the quiet-gateway backstop. The server
428
+ // takes a late completion from this attempt until a newer claim.
429
+ current.answered = true;
383
430
  // A transient delivery error retries this same completion. It must
384
431
  // never become a new provider run or a duplicate final reply.
385
432
  while (!(signal.aborted || cancel.signal.aborted)) {
@@ -398,10 +445,26 @@ export async function serveAgent(config, directory, version, stop, verify, optio
398
445
  }
399
446
  }
400
447
  }
401
- catch {
402
- if (!(signal.aborted || cancel.signal.aborted)) {
448
+ catch (error) {
449
+ if (!(signal.aborted ||
450
+ cancel.signal.aborted ||
451
+ (error instanceof RoomToolsUnavailableError &&
452
+ (await gateway
453
+ .request(`/agent-gateway/jobs/${job.jobId}/renew`, { leaseToken: job.leaseToken }, signal)
454
+ .then(() => false)
455
+ .catch((probe) => {
456
+ if (probe instanceof GatewayError &&
457
+ probe.status === 409) {
458
+ cancel.abort();
459
+ }
460
+ return serverAway(probe) || cancel.signal.aborted;
461
+ }))))) {
403
462
  await gateway
404
- .request(`/agent-gateway/jobs/${job.jobId}/fail`, { leaseToken: job.leaseToken }, signal)
463
+ .request(`/agent-gateway/jobs/${job.jobId}/fail`, {
464
+ leaseToken: job.leaseToken,
465
+ // A fixed code; the server owns the room's wording.
466
+ reason: failureReasonOf(error),
467
+ }, signal)
405
468
  .catch(failService);
406
469
  }
407
470
  }
@@ -4,13 +4,26 @@ import { isSecureUrl, } from "./agent-link.js";
4
4
  import { resolveProviderBinary } from "./provider-binary.js";
5
5
  const REQUEST_TIMEOUT_MS = 10_000;
6
6
  const HEARTBEAT_WINDOW_MS = 60_000;
7
+ // A refusal sentence longer than this, or on more than one line, is not one
8
+ // the server wrote for people; the generic hedge is printed instead.
9
+ const REFUSAL_MAX_LENGTH = 300;
10
+ const ONE_LINE = /^[^\p{Cc}]+$/u;
11
+ const NEW_PROMPT_STEP = "Ask for a new setup prompt.";
12
+ // The server's code for a used or expired link: that link can never work.
13
+ const DEAD_LINK_CODES = new Set(["link_expired", "link_used"]);
7
14
  export class AgentHttpError extends Error {
8
15
  status;
9
16
  retryAfterMs;
10
- constructor(operation, response) {
11
- super(response.status === 426
12
- ? "Update TalentOS CLI: run npx --yes --prefer-online talentos@latest agent link again with your setup URL."
13
- : `${operation} (HTTP ${response.status}). Ask for a fresh setup prompt if this link expired.`);
17
+ constructor(operation, response, refusal) {
18
+ let message = `${operation} (HTTP ${response.status}). Ask for a fresh setup prompt if this link expired.`;
19
+ if (response.status === 426) {
20
+ message =
21
+ "Update TalentOS CLI: run npx --yes --prefer-online talentos@latest agent link again with your setup URL.";
22
+ }
23
+ else if (refusal) {
24
+ message = `${refusal.sentence}\n${refusal.dead ? "This link won't work again. " : ""}${NEW_PROMPT_STEP}`;
25
+ }
26
+ super(message);
14
27
  this.status = response.status;
15
28
  const seconds = Number(response.headers.get("Retry-After"));
16
29
  this.retryAfterMs = Number.isFinite(seconds)
@@ -88,7 +101,9 @@ export async function redeemAgent(apiUrl, body) {
88
101
  body: JSON.stringify(body),
89
102
  });
90
103
  if (!response.ok) {
91
- throw new AgentHttpError("Could not redeem this link", response);
104
+ throw new AgentHttpError("Could not redeem this link", response, response.status === 400
105
+ ? await linkRefusal(response, body.token)
106
+ : undefined);
92
107
  }
93
108
  const value = await readJson(response);
94
109
  if (!value ||
@@ -178,6 +193,31 @@ async function safeFetch(url, init = {}) {
178
193
  throw new Error("Could not reach TalentOS. Check the network and try again.");
179
194
  }
180
195
  }
196
+ // The server's sentence for a refused link (#12215): why, and where to make a
197
+ // new one. Never a body that echoes the token.
198
+ async function linkRefusal(response, token) {
199
+ let value;
200
+ try {
201
+ value = await response.json();
202
+ }
203
+ catch {
204
+ return;
205
+ }
206
+ if (!value || typeof value !== "object") {
207
+ return;
208
+ }
209
+ const sentence = "error" in value ? value.error : undefined;
210
+ const code = "code" in value ? value.code : undefined;
211
+ return typeof sentence === "string" &&
212
+ sentence.length <= REFUSAL_MAX_LENGTH &&
213
+ ONE_LINE.test(sentence) &&
214
+ !sentence.includes(token)
215
+ ? {
216
+ dead: typeof code === "string" && DEAD_LINK_CODES.has(code),
217
+ sentence,
218
+ }
219
+ : undefined;
220
+ }
181
221
  async function readJson(response) {
182
222
  try {
183
223
  return await response.json();
package/dist/client.js CHANGED
@@ -4,13 +4,27 @@ import { requireCredentials, resolveApiUrl, } from "./config.js";
4
4
  const CLIENT_INFO = { name: "talentos-cli", version: "1.0.0" };
5
5
  const UNAUTHORIZED_HINT = /\b401\b|unauthoriz/i;
6
6
  const UNREACHABLE_HINT = /fetch failed|ECONNREFUSED|ENOTFOUND/i;
7
+ // A Convex push answers 5xx or drops connections for over a minute. The room
8
+ // tools are listed once, when a provider starts its turn, and a provider gives
9
+ // up on a server that does not list within its own startup timeout: Codex
10
+ // waits 30 s for tools/list (its "required MCP servers failed to initialize"
11
+ // error), so the waits here stay inside it, with room for the spawn and the
12
+ // initialize round trip. A longer outage is covered a layer up: the CLI waits
13
+ // for the server before it launches a provider, and takes a job back when the
14
+ // listing failed while the server was away (agent/serve.ts). A call is never
15
+ // retried: it may have landed.
16
+ export const PROVIDER_START_TIMEOUT_MS = 30_000;
17
+ export const LIST_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 12_000];
18
+ const TRANSIENT_HINT = /fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|socket hang up|terminated/iu;
7
19
  export const UNAUTHORIZED = "Not logged in or key revoked. Run `talentos login`.";
8
20
  /** MCP client for the remote TalentOS server, one process-lived connection. */
9
21
  export class AgentClient {
10
22
  credentials;
11
23
  client;
12
- constructor(credentials) {
24
+ retryDelaysMs;
25
+ constructor(credentials, retryDelaysMs = LIST_RETRY_DELAYS_MS) {
13
26
  this.credentials = credentials;
27
+ this.retryDelaysMs = retryDelaysMs;
14
28
  }
15
29
  async call(name, args) {
16
30
  const client = await this.connect();
@@ -22,8 +36,10 @@ export class AgentClient {
22
36
  return { text, data: result.structuredContent };
23
37
  }
24
38
  async listTools() {
25
- const client = await this.connect();
26
- return await withFriendlyErrors(() => client.listTools());
39
+ return await this.whileServerIsAway(async () => {
40
+ const client = await this.connect();
41
+ return await withFriendlyErrors(() => client.listTools());
42
+ });
27
43
  }
28
44
  async callTool(params) {
29
45
  const client = await this.connect();
@@ -34,6 +50,21 @@ export class AgentClient {
34
50
  this.client = undefined;
35
51
  await client?.close();
36
52
  }
53
+ async whileServerIsAway(run) {
54
+ for (const wait of this.retryDelaysMs) {
55
+ try {
56
+ return await run();
57
+ }
58
+ catch (error) {
59
+ if (!isTransient(error)) {
60
+ throw error;
61
+ }
62
+ this.client = undefined;
63
+ await new Promise((resolve) => setTimeout(resolve, wait));
64
+ }
65
+ }
66
+ return await run();
67
+ }
37
68
  async connect() {
38
69
  if (this.client) {
39
70
  return this.client;
@@ -62,6 +93,13 @@ export async function withClient(apiUrlOverride, run) {
62
93
  await client.close();
63
94
  }
64
95
  }
96
+ function isTransient(error) {
97
+ const status = error?.code;
98
+ const message = error instanceof Error ? error.message : String(error);
99
+ return ((typeof status === "number" && status >= 500) ||
100
+ TRANSIENT_HINT.test(message) ||
101
+ message.includes("Cannot reach TalentOS"));
102
+ }
65
103
  function firstText(result) {
66
104
  const block = result.content?.[0];
67
105
  return block && block.type === "text" ? block.text : "";
@@ -71,7 +109,10 @@ async function withFriendlyErrors(run) {
71
109
  return await run();
72
110
  }
73
111
  catch (error) {
74
- throw new Error(describe(error));
112
+ // The HTTP status rides along so a caller can tell a server that is away.
113
+ throw Object.assign(new Error(describe(error)), {
114
+ code: error?.code,
115
+ });
75
116
  }
76
117
  }
77
118
  function describe(error) {
@@ -62,6 +62,14 @@ async function getSkill(parsed) {
62
62
  throw new Error("Usage: talentos skills get <id|slug> [--out <dir>]");
63
63
  }
64
64
  const { text, data } = await withClient(parsed.options["api-url"], (client) => client.call("get_skill", { skillId }));
65
+ // A built-in guide (the canvas deck guide) is text only: no package files.
66
+ if (data === undefined) {
67
+ if (parsed.options.json || parsed.options.out !== undefined) {
68
+ throw new Error(`This guide has no package. Run \`talentos skills get ${skillId}\` without --out or --json to read it.`);
69
+ }
70
+ emit(text);
71
+ return;
72
+ }
65
73
  if (parsed.options.json) {
66
74
  emitJson(data);
67
75
  return;
package/dist/mcp-proxy.js CHANGED
@@ -62,11 +62,7 @@ ownerJobDir) {
62
62
  }
63
63
  async function runUpload(client, args, root) {
64
64
  try {
65
- const text = await uploadFile(client, {
66
- path: String(args.path ?? ""),
67
- roomId: String(args.roomId ?? ""),
68
- title: typeof args.title === "string" ? args.title : undefined,
69
- }, root);
65
+ const text = await uploadFile(client, args, root);
70
66
  return { content: [{ text, type: "text" }] };
71
67
  }
72
68
  catch (error) {
@@ -8,7 +8,11 @@ import { canonical, protectedPaths, protectedReason, } from "./agent/native/path
8
8
  // The server caps and re-checks everything (type, size, names, content); this
9
9
  // is the client's half of the boundary: only a regular file inside the folder
10
10
  // the agent works in, and never a credential store, whatever the model asks.
11
- export const UPLOAD_BYTES_MAX = 50 * 1024 * 1024;
11
+ // The size cap is the server's (it refuses at prepare, before any byte moves),
12
+ // so a cap change needs no CLI release. This ceiling is only the server's 2 GiB
13
+ // cap on an agent's open uploads, which no single file can pass: it spares
14
+ // hashing a 40 GB file for a minute just to be refused.
15
+ export const UPLOAD_BYTES_MAX = 2 * 1024 * 1024 * 1024;
12
16
  const DENIED_SEGMENTS = new Set([
13
17
  ".aws",
14
18
  ".azure",
@@ -129,32 +133,50 @@ export async function openUploadSource(requested, root, home = homedir()) {
129
133
  throw error;
130
134
  }
131
135
  }
136
+ const megabytes = (bytes) => (bytes / 1_000_000).toFixed(1);
132
137
  // prepare -> stream the bytes straight to storage -> commit. Nothing about the
133
- // file's contents passes through the model or an MCP argument.
138
+ // file's contents passes through the model or an MCP argument. Every other
139
+ // upload_file argument (roomId, title, artifactId, baseVersionId, and any the
140
+ // server adds later) goes to prepare_upload as given; the file's own name,
141
+ // hash and size come from the file and always win.
134
142
  export async function uploadFile(client, args, root, fetchImpl = fetch, home = homedir()) {
135
- const source = await openUploadSource(args.path, root, home);
143
+ const { path, ...forwarded } = args;
144
+ const source = await openUploadSource(String(path ?? ""), root, home);
136
145
  try {
137
146
  const prepared = await client.call("prepare_upload", {
147
+ ...forwarded,
138
148
  filename: source.name,
139
- roomId: args.roomId,
140
149
  sha256: source.sha256,
141
150
  sizeBytes: source.size,
142
- ...(args.title ? { title: args.title } : {}),
143
151
  });
144
152
  if (prepared.data.status === "committed" || !prepared.data.uploadUrl) {
145
153
  return prepared.text;
146
154
  }
147
- const response = await fetchImpl(prepared.data.uploadUrl, {
148
- body: Readable.toWeb(source.stream()),
149
- duplex: "half",
150
- headers: {
151
- "Content-Length": String(source.size),
152
- "Content-Type": "application/octet-stream",
153
- },
154
- method: "POST",
155
+ let sent = 0;
156
+ const body = source.stream();
157
+ body.on("data", (chunk) => {
158
+ sent += chunk.length;
155
159
  });
160
+ // Storage gives an upload URL about two minutes, so a large file on a
161
+ // slow line is cut off; say so in terms the agent can act on.
162
+ const failed = (status) => refuse(`The upload stopped after ${megabytes(sent)} of ${megabytes(source.size)} MB${status}. An upload has about two minutes: try again, and if it fails again, export a smaller file (lower bitrate or resolution).`);
163
+ let response;
164
+ try {
165
+ response = await fetchImpl(prepared.data.uploadUrl, {
166
+ body: Readable.toWeb(body),
167
+ duplex: "half",
168
+ headers: {
169
+ "Content-Length": String(source.size),
170
+ "Content-Type": "application/octet-stream",
171
+ },
172
+ method: "POST",
173
+ });
174
+ }
175
+ catch {
176
+ return failed("");
177
+ }
156
178
  if (!response.ok) {
157
- refuse(`The upload failed (${response.status}). Try again.`);
179
+ failed(` (${response.status})`);
158
180
  }
159
181
  const { storageId } = (await response.json());
160
182
  if (!storageId) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "talentos",
3
- "version": "1.4.3",
3
+ "version": "1.4.5",
4
4
  "type": "module",
5
5
  "description": "TalentOS CLI: push and pull skills, read and write team memory, and delegate work to your Talent from any coding agent.",
6
6
  "repository": {