talentos 1.4.4 → 1.4.6
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.
- package/README.md +10 -4
- package/dist/agent/adapters.js +104 -25
- package/dist/agent/codex-policy.js +14 -2
- package/dist/agent/lease-hold.js +22 -0
- package/dist/agent/provider-failure.js +64 -0
- package/dist/agent/room-profile.js +130 -0
- package/dist/agent/serve.js +76 -24
- package/dist/client.js +45 -4
- package/dist/commands/skills.js +8 -0
- package/dist/mcp-proxy.js +1 -5
- package/dist/upload-file.js +36 -14
- package/package.json +1 -1
- package/dist/agent/sessions.js +0 -36
package/README.md
CHANGED
|
@@ -83,11 +83,17 @@ before it is sent, and stored only once TalentOS accepts it.
|
|
|
83
83
|
### Agents in Rooms
|
|
84
84
|
|
|
85
85
|
`talentos agent serve --agent <id>` runs the linked provider in its private
|
|
86
|
-
work folder. It keeps one turn active
|
|
87
|
-
|
|
86
|
+
work folder. It keeps one turn active and starts a fresh Claude Code or Codex
|
|
87
|
+
session for every job, including retries and service restarts. Follow-ups use
|
|
88
|
+
the current room packet and room tools; native project files stay in the
|
|
89
|
+
thread's workspace. Old `~/.talentos/agents/<id>/sessions.json` files are ignored
|
|
90
|
+
and left untouched. A room-only job (a teammate's ask, a not-ready owner job,
|
|
91
|
+
every Codex job) runs in its own empty folder and does not load your CLAUDE.md,
|
|
92
|
+
rules, hooks, memory or Codex AGENTS.md and skills (not even their names); only
|
|
93
|
+
your provider login is used. Final text posts automatically.
|
|
88
94
|
The service heartbeats every 20 seconds and stops the child if its lease is
|
|
89
95
|
lost. A required CLI update installs under the agent directory between turns.
|
|
90
|
-
Signing-key provisioning
|
|
96
|
+
Signing-key provisioning and real staging latency proofs are
|
|
91
97
|
tracked in [Agent access](../../docs/features/agent-access/README.md).
|
|
92
98
|
|
|
93
99
|
Use the setup prompt from TalentOS to link Claude Code or Codex. The fragment
|
|
@@ -96,7 +102,7 @@ required even when its desktop app is signed in. Approve the user service
|
|
|
96
102
|
installation interactively or pass `--yes` after approval.
|
|
97
103
|
|
|
98
104
|
Linking waits for a recent gateway heartbeat before reporting Connected. Real
|
|
99
|
-
provider connection
|
|
105
|
+
provider connection and latency proofs remain staged after publication.
|
|
100
106
|
If the service cannot start, use the printed foreground
|
|
101
107
|
`talentos agent serve --agent <id>` command.
|
|
102
108
|
|
package/dist/agent/adapters.js
CHANGED
|
@@ -14,6 +14,8 @@ 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";
|
|
18
|
+
import { prepareRoomProfile, ROOM_CATALOG_FILE, ROOM_MCP_FILE, } from "./room-profile.js";
|
|
17
19
|
const CHILD_ENV = [
|
|
18
20
|
"HOME",
|
|
19
21
|
"PATH",
|
|
@@ -33,6 +35,11 @@ const CHILD_ENV = [
|
|
|
33
35
|
const CLAUDE_VERSION = /^\d+\.\d+\.\d+/u;
|
|
34
36
|
const CODEX_VERSION = /\b\d+\.\d+\.\d+\b/u;
|
|
35
37
|
const DONT_ASK = /\bdontAsk\b/u;
|
|
38
|
+
// A room-only job needs both to keep the owner's profile and transcripts out.
|
|
39
|
+
const CLAUDE_ISOLATION_FLAGS = [
|
|
40
|
+
"--setting-sources",
|
|
41
|
+
"--no-session-persistence",
|
|
42
|
+
];
|
|
36
43
|
// What Codex prints when the required room server never listed its tools.
|
|
37
44
|
const ROOM_SERVER_FAILED = /required MCP servers failed to initialize/u;
|
|
38
45
|
const CLAUDE_TOOLS = ROOM_TOOLS.map((tool) => `mcp__talentos__${tool}`).join(",");
|
|
@@ -58,14 +65,16 @@ export async function verifyClaudeCode(configured) {
|
|
|
58
65
|
const detected = await execute(binary, ["--version"], options);
|
|
59
66
|
version = CLAUDE_VERSION.exec(detected.stdout.trim())?.[0] ?? "unknown";
|
|
60
67
|
const help = await execute(binary, ["--help"], options);
|
|
61
|
-
if (version !== "unknown" &&
|
|
68
|
+
if (version !== "unknown" &&
|
|
69
|
+
DONT_ASK.test(help.stdout) &&
|
|
70
|
+
CLAUDE_ISOLATION_FLAGS.every((flag) => help.stdout.includes(flag))) {
|
|
62
71
|
return;
|
|
63
72
|
}
|
|
64
73
|
}
|
|
65
74
|
catch {
|
|
66
75
|
// Never include provider stderr, which may contain login details.
|
|
67
76
|
}
|
|
68
|
-
throw new Error(`Update Claude Code (${version}) to a version that supports --permission-mode dontAsk.`);
|
|
77
|
+
throw new Error(`Update Claude Code (${version}) to a version that supports --permission-mode dontAsk, --setting-sources and --no-session-persistence.`);
|
|
69
78
|
}
|
|
70
79
|
export async function verifyCodex(configured, signal) {
|
|
71
80
|
const binary = resolveProviderBinary("codex", configured);
|
|
@@ -145,9 +154,9 @@ async function codexRoomCatalog(binary) {
|
|
|
145
154
|
}
|
|
146
155
|
}
|
|
147
156
|
/** Codex could not start its room tools, so the job fails with that reason. */
|
|
148
|
-
export class RoomToolsUnavailableError extends
|
|
157
|
+
export class RoomToolsUnavailableError extends ProviderFailureError {
|
|
149
158
|
constructor() {
|
|
150
|
-
super("Codex couldn't reach its room tools. Try again.");
|
|
159
|
+
super("room_tools", "Codex couldn't reach its room tools. Try again.");
|
|
151
160
|
}
|
|
152
161
|
}
|
|
153
162
|
export function readProviderEvent(provider, value) {
|
|
@@ -158,7 +167,10 @@ export function readProviderEvent(provider, value) {
|
|
|
158
167
|
if (provider === "claude_code") {
|
|
159
168
|
if (event.type === "result") {
|
|
160
169
|
if (event.is_error) {
|
|
161
|
-
return {
|
|
170
|
+
return {
|
|
171
|
+
failed: true,
|
|
172
|
+
failure: matchFailureText([event.result, event.api_error_status].join(" ")),
|
|
173
|
+
};
|
|
162
174
|
}
|
|
163
175
|
return {
|
|
164
176
|
...(typeof event.session_id === "string"
|
|
@@ -168,6 +180,10 @@ export function readProviderEvent(provider, value) {
|
|
|
168
180
|
};
|
|
169
181
|
}
|
|
170
182
|
const message = event.message;
|
|
183
|
+
// Claude Code tags an assistant turn it could not get from the API.
|
|
184
|
+
if (event.type === "assistant" && typeof event.error === "string") {
|
|
185
|
+
return { failure: matchFailureText(event.error) };
|
|
186
|
+
}
|
|
171
187
|
if (event.type === "assistant" &&
|
|
172
188
|
Array.isArray(message?.content) &&
|
|
173
189
|
message.content.some((part) => part.type === "tool_use")) {
|
|
@@ -180,7 +196,12 @@ export function readProviderEvent(provider, value) {
|
|
|
180
196
|
return { sessionId: event.thread_id };
|
|
181
197
|
}
|
|
182
198
|
if (event.type === "turn.failed" || event.type === "error") {
|
|
183
|
-
|
|
199
|
+
const error = event.error;
|
|
200
|
+
const text = error?.message ?? event.message;
|
|
201
|
+
return {
|
|
202
|
+
failed: true,
|
|
203
|
+
failure: typeof text === "string" ? matchFailureText(text) : undefined,
|
|
204
|
+
};
|
|
184
205
|
}
|
|
185
206
|
const item = event.item;
|
|
186
207
|
if (event.type === "item.completed" &&
|
|
@@ -197,12 +218,14 @@ export function readProviderEvent(provider, value) {
|
|
|
197
218
|
export async function runProvider(input) {
|
|
198
219
|
const { config, job, workDir, sessionId, signal } = input;
|
|
199
220
|
const { instructions, ...context } = job.packet;
|
|
200
|
-
const prompt = JSON.stringify(config.provider === "claude_code" ? context : job.packet), mcpPath = join(dirname(workDir),
|
|
201
|
-
const catalogPath = join(dirname(workDir),
|
|
221
|
+
const prompt = JSON.stringify(config.provider === "claude_code" ? context : job.packet), mcpPath = join(dirname(workDir), ROOM_MCP_FILE);
|
|
222
|
+
const catalogPath = join(dirname(workDir), ROOM_CATALOG_FILE);
|
|
202
223
|
const binary = resolveProviderBinary(config.provider, config.providerPath);
|
|
203
224
|
let command, args;
|
|
204
225
|
let ownerLaunch;
|
|
205
226
|
let stopWatching;
|
|
227
|
+
// Only a room-only job: an owner job runs in the owner's own setup on purpose.
|
|
228
|
+
let roomProfile;
|
|
206
229
|
if (input.owner && config.provider === "claude_code") {
|
|
207
230
|
const watching = await input.owner.watch?.();
|
|
208
231
|
stopWatching = watching?.stop;
|
|
@@ -253,6 +276,13 @@ export async function runProvider(input) {
|
|
|
253
276
|
},
|
|
254
277
|
},
|
|
255
278
|
}));
|
|
279
|
+
// Last step that can fail: nothing after it leaves the job's files behind.
|
|
280
|
+
roomProfile = await prepareRoomProfile({
|
|
281
|
+
directory: dirname(workDir),
|
|
282
|
+
env: process.env,
|
|
283
|
+
jobId: job.jobId,
|
|
284
|
+
provider: config.provider,
|
|
285
|
+
});
|
|
256
286
|
command = binary;
|
|
257
287
|
args = [
|
|
258
288
|
"-p",
|
|
@@ -273,16 +303,35 @@ export async function runProvider(input) {
|
|
|
273
303
|
"Bash,Agent,Task",
|
|
274
304
|
"--permission-mode",
|
|
275
305
|
"dontAsk",
|
|
306
|
+
// None of the owner's CLAUDE.md, rules, hooks or output style. The login
|
|
307
|
+
// keys they need ride in the job's own settings file.
|
|
308
|
+
"--setting-sources",
|
|
309
|
+
"",
|
|
310
|
+
...(roomProfile.settingsPath
|
|
311
|
+
? ["--settings", roomProfile.settingsPath]
|
|
312
|
+
: []),
|
|
276
313
|
];
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
314
|
+
// A room-only job never resumes: the transcript would live in the owner's
|
|
315
|
+
// profile, and the job must not leave one there.
|
|
316
|
+
args.push("--no-session-persistence");
|
|
280
317
|
}
|
|
281
318
|
else {
|
|
319
|
+
if (input.owner) {
|
|
320
|
+
// A Codex owner job needs its own launch inputs; it must never run with
|
|
321
|
+
// the room-only profile's environment.
|
|
322
|
+
throw new Error("A Codex owner job is missing its launch inputs.");
|
|
323
|
+
}
|
|
282
324
|
command = binary;
|
|
283
325
|
const launcher = gatewayLauncherPath();
|
|
284
326
|
const useLauncher = process.platform !== "win32" && existsSync(launcher);
|
|
285
327
|
await writePrivateFile(catalogPath, await codexRoomCatalog(binary));
|
|
328
|
+
// Last step that can fail: nothing after it leaves the job's files behind.
|
|
329
|
+
roomProfile = await prepareRoomProfile({
|
|
330
|
+
directory: dirname(workDir),
|
|
331
|
+
env: process.env,
|
|
332
|
+
jobId: job.jobId,
|
|
333
|
+
provider: config.provider,
|
|
334
|
+
});
|
|
286
335
|
// Resume has a different flag surface. Root overrides are inherited by
|
|
287
336
|
// both exec paths; shell_tool=false enforces ADR 0093's default no-Bash.
|
|
288
337
|
args = codexRoomArgs({
|
|
@@ -298,11 +347,11 @@ export async function runProvider(input) {
|
|
|
298
347
|
config.agentId,
|
|
299
348
|
],
|
|
300
349
|
prompt,
|
|
301
|
-
|
|
350
|
+
isolated: true,
|
|
302
351
|
});
|
|
303
352
|
}
|
|
304
353
|
const child = spawn(command, args, {
|
|
305
|
-
cwd: input.owner?.workspace.cwd ?? workDir,
|
|
354
|
+
cwd: input.owner?.workspace.cwd ?? roomProfile?.cwd ?? workDir,
|
|
306
355
|
env: input.owner
|
|
307
356
|
? {
|
|
308
357
|
...input.owner.env,
|
|
@@ -310,9 +359,21 @@ export async function runProvider(input) {
|
|
|
310
359
|
.filter(Boolean)
|
|
311
360
|
.join(delimiter),
|
|
312
361
|
}
|
|
313
|
-
:
|
|
314
|
-
|
|
315
|
-
|
|
362
|
+
: {
|
|
363
|
+
...childEnvironment(process.env, binary),
|
|
364
|
+
// Login variables from the owner's settings; never written to a file.
|
|
365
|
+
...roomProfile?.env,
|
|
366
|
+
// The owner's memory stays out; the job's own directory is fresh.
|
|
367
|
+
...(config.provider === "claude_code"
|
|
368
|
+
? { CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1" }
|
|
369
|
+
: {}),
|
|
370
|
+
...(roomProfile?.codexHome
|
|
371
|
+
? { CODEX_HOME: roomProfile.codexHome }
|
|
372
|
+
: {}),
|
|
373
|
+
},
|
|
374
|
+
// stderr is matched to name a failure, never forwarded: it can hold login
|
|
375
|
+
// details.
|
|
376
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
316
377
|
detached: process.platform !== "win32",
|
|
317
378
|
});
|
|
318
379
|
const marked = new Set();
|
|
@@ -323,7 +384,7 @@ export async function runProvider(input) {
|
|
|
323
384
|
}
|
|
324
385
|
};
|
|
325
386
|
child.once("spawn", () => mark("spawn"));
|
|
326
|
-
// The last 8 kB is enough for
|
|
387
|
+
// The last 8 kB is enough for a provider's closing error line.
|
|
327
388
|
let stderrTail = "";
|
|
328
389
|
child.stderr?.on("data", (chunk) => {
|
|
329
390
|
stderrTail = (stderrTail + chunk.toString()).slice(-8192);
|
|
@@ -350,16 +411,20 @@ export async function runProvider(input) {
|
|
|
350
411
|
kill("SIGTERM");
|
|
351
412
|
killTimer ??= setTimeout(() => kill("SIGKILL"), 5000);
|
|
352
413
|
};
|
|
414
|
+
let spawnError;
|
|
353
415
|
const ended = new Promise((resolve) => {
|
|
354
|
-
child.once("error", () =>
|
|
355
|
-
|
|
416
|
+
child.once("error", (error) => {
|
|
417
|
+
spawnError = error.code;
|
|
418
|
+
resolve({ code: null, signal: null });
|
|
419
|
+
});
|
|
420
|
+
child.once("close", (code, signal) => resolve({ code, signal }));
|
|
356
421
|
});
|
|
357
422
|
signal.addEventListener("abort", stop, { once: true });
|
|
358
423
|
if (signal.aborted) {
|
|
359
424
|
stop();
|
|
360
425
|
}
|
|
361
426
|
try {
|
|
362
|
-
let text = "", failed = false, sawResult = false;
|
|
427
|
+
let text = "", failure, failed = false, sawResult = false;
|
|
363
428
|
if (!child.stdout) {
|
|
364
429
|
throw new Error("Provider output is unavailable.");
|
|
365
430
|
}
|
|
@@ -383,8 +448,12 @@ export async function runProvider(input) {
|
|
|
383
448
|
if (event.failed) {
|
|
384
449
|
failed = true;
|
|
385
450
|
}
|
|
451
|
+
// Sign-in outranks a limit when the provider reported both.
|
|
452
|
+
if (event.failure && failure !== "signed_out") {
|
|
453
|
+
failure = event.failure;
|
|
454
|
+
}
|
|
386
455
|
if (event.sessionId) {
|
|
387
|
-
await input.remember(event.sessionId);
|
|
456
|
+
await input.remember?.(event.sessionId);
|
|
388
457
|
}
|
|
389
458
|
if (event.status) {
|
|
390
459
|
// Room-visible status never names the owner's private tools.
|
|
@@ -398,12 +467,21 @@ export async function runProvider(input) {
|
|
|
398
467
|
sawResult = true;
|
|
399
468
|
}
|
|
400
469
|
}
|
|
401
|
-
const
|
|
402
|
-
if (code !== 0 &&
|
|
470
|
+
const exit = await ended;
|
|
471
|
+
if (exit.code !== 0 &&
|
|
472
|
+
!signal.aborted &&
|
|
473
|
+
ROOM_SERVER_FAILED.test(stderrTail)) {
|
|
403
474
|
throw new RoomToolsUnavailableError();
|
|
404
475
|
}
|
|
405
|
-
if (code !== 0 || failed || !sawResult || signal.aborted) {
|
|
406
|
-
throw new
|
|
476
|
+
if (exit.code !== 0 || failed || !sawResult || signal.aborted) {
|
|
477
|
+
throw new ProviderFailureError(signal.aborted
|
|
478
|
+
? "unknown"
|
|
479
|
+
: classifyProviderFailure({
|
|
480
|
+
...exit,
|
|
481
|
+
eventHint: failure,
|
|
482
|
+
spawnError,
|
|
483
|
+
stderrTail,
|
|
484
|
+
}), "Provider could not finish this turn. Check its login and quota.");
|
|
407
485
|
}
|
|
408
486
|
return { text: redactAgentOutput(text, [config.apiKey]) };
|
|
409
487
|
}
|
|
@@ -416,6 +494,7 @@ export async function runProvider(input) {
|
|
|
416
494
|
}
|
|
417
495
|
await rm(mcpPath, { force: true });
|
|
418
496
|
await rm(catalogPath, { force: true });
|
|
497
|
+
await roomProfile?.cleanup();
|
|
419
498
|
stopWatching?.();
|
|
420
499
|
if (ownerLaunch && input.receipts) {
|
|
421
500
|
// Best effort: a lost record never changes how the job ended.
|
|
@@ -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",
|
|
@@ -20,7 +21,7 @@ export const ROOM_TOOLS = [
|
|
|
20
21
|
"whoami",
|
|
21
22
|
];
|
|
22
23
|
export function codexRoomArgs(input) {
|
|
23
|
-
const { catalogPath, mcpCommand, mcpArgs, prompt, sessionId } = input;
|
|
24
|
+
const { catalogPath, mcpCommand, mcpArgs, prompt, sessionId, isolated } = input;
|
|
24
25
|
const args = [
|
|
25
26
|
"-c",
|
|
26
27
|
'sandbox_mode="read-only"',
|
|
@@ -71,11 +72,22 @@ export function codexRoomArgs(input) {
|
|
|
71
72
|
`mcp_servers.talentos.command=${JSON.stringify(mcpCommand)}`,
|
|
72
73
|
"-c",
|
|
73
74
|
`mcp_servers.talentos.args=${JSON.stringify(mcpArgs)}`,
|
|
75
|
+
// An empty directory has no AGENTS.md, but a repo above it could. The
|
|
76
|
+
// owner's skills (~/.agents/skills, and ~/.codex/skills in a repo home) are
|
|
77
|
+
// listed to the model by name and description unless told not to.
|
|
78
|
+
...(isolated
|
|
79
|
+
? [
|
|
80
|
+
"-c",
|
|
81
|
+
"project_doc_max_bytes=0",
|
|
82
|
+
"-c",
|
|
83
|
+
"skills.include_instructions=false",
|
|
84
|
+
]
|
|
85
|
+
: []),
|
|
74
86
|
"exec",
|
|
75
87
|
];
|
|
76
88
|
if (sessionId) {
|
|
77
89
|
args.push("resume", sessionId);
|
|
78
90
|
}
|
|
79
|
-
args.push("--json", "--skip-git-repo-check", "--ignore-user-config", "--ignore-rules", prompt);
|
|
91
|
+
args.push("--json", "--skip-git-repo-check", "--ignore-user-config", "--ignore-rules", ...(isolated ? ["--ephemeral"] : []), prompt);
|
|
80
92
|
return args;
|
|
81
93
|
}
|
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { access, mkdir, readFile, rm, rmdir, symlink } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { writePrivateFile } from "../agent-config.js";
|
|
5
|
+
import { homeDir } from "../install.js";
|
|
6
|
+
import { ProviderFailureError } from "./provider-failure.js";
|
|
7
|
+
// The room-only profile (#12712): a job for a teammate, a not-ready owner job
|
|
8
|
+
// and every Codex room job sees what TalentOS hands it (the packet and the room
|
|
9
|
+
// tools) and nothing from the owner's own setup. Each job gets an empty working
|
|
10
|
+
// directory and, for Codex, a CODEX_HOME that holds only the login. Owner jobs
|
|
11
|
+
// never come through here (docs/features/agent-access/README.md).
|
|
12
|
+
export const ROOM_MCP_FILE = ".talentos-mcp.json";
|
|
13
|
+
export const ROOM_CATALOG_FILE = ".talentos-codex-models.json";
|
|
14
|
+
const ROOM_JOBS = "room-jobs";
|
|
15
|
+
// Claude Code reads its login helpers and provider routing from user settings,
|
|
16
|
+
// and `--setting-sources ""` skips that file. These keys alone carry across so
|
|
17
|
+
// a login that works today keeps working; hooks, permissions, plugins and
|
|
18
|
+
// output style never do. The `env` entries can hold credentials themselves, so
|
|
19
|
+
// they go to the child's environment and never to a file.
|
|
20
|
+
const CLAUDE_LOGIN_KEYS = [
|
|
21
|
+
"apiKeyHelper",
|
|
22
|
+
"awsAuthRefresh",
|
|
23
|
+
"awsCredentialExport",
|
|
24
|
+
"forceLoginMethod",
|
|
25
|
+
"forceLoginOrgUUID",
|
|
26
|
+
"gcpAuthRefresh",
|
|
27
|
+
"model",
|
|
28
|
+
];
|
|
29
|
+
const CLAUDE_LOGIN_ENV = /^(?:ANTHROPIC_|CLAUDE_CODE_USE_|CLAUDE_CODE_SKIP_|AWS_|GOOGLE_|CLOUD_ML_|VERTEX_|(?:HTTPS?|NO)_PROXY$|NODE_EXTRA_CA_CERTS$)/iu;
|
|
30
|
+
function isPlainObject(value) {
|
|
31
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
32
|
+
}
|
|
33
|
+
async function claudeLoginSettings(env) {
|
|
34
|
+
const directory = env.CLAUDE_CONFIG_DIR || join(homeDir(env), ".claude");
|
|
35
|
+
let settings;
|
|
36
|
+
try {
|
|
37
|
+
settings = JSON.parse(await readFile(join(directory, "settings.json"), "utf8"));
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// Missing or unreadable settings carry no login; never echo what failed.
|
|
41
|
+
return {};
|
|
42
|
+
}
|
|
43
|
+
if (!isPlainObject(settings)) {
|
|
44
|
+
return {};
|
|
45
|
+
}
|
|
46
|
+
const forwarded = {};
|
|
47
|
+
for (const key of CLAUDE_LOGIN_KEYS) {
|
|
48
|
+
if (typeof settings[key] === "string") {
|
|
49
|
+
forwarded[key] = settings[key];
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const login = isPlainObject(settings.env)
|
|
53
|
+
? Object.fromEntries(Object.entries(settings.env).filter((entry) => CLAUDE_LOGIN_ENV.test(entry[0]) && typeof entry[1] === "string"))
|
|
54
|
+
: {};
|
|
55
|
+
return {
|
|
56
|
+
...(Object.keys(login).length > 0 ? { env: login } : {}),
|
|
57
|
+
...(Object.keys(forwarded).length > 0
|
|
58
|
+
? { file: JSON.stringify(forwarded) }
|
|
59
|
+
: {}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** Codex could not be kept apart from the owner's setup, so no job runs. */
|
|
63
|
+
export class RoomIsolationError extends ProviderFailureError {
|
|
64
|
+
constructor() {
|
|
65
|
+
super("unknown", "Codex could not be isolated from your setup on this computer.");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export async function prepareRoomProfile(input) {
|
|
69
|
+
const jobDir = join(input.directory, ROOM_JOBS, input.jobId.replace(/[^\w-]/gu, ""));
|
|
70
|
+
const cwd = join(jobDir, "cwd");
|
|
71
|
+
const profile = {
|
|
72
|
+
cleanup: async () => {
|
|
73
|
+
await rm(jobDir, { force: true, recursive: true });
|
|
74
|
+
// Claude Code logs under a cache directory named for the cwd: one small
|
|
75
|
+
// directory per job would pile up. Linux and macOS locations only.
|
|
76
|
+
if (input.provider === "claude_code") {
|
|
77
|
+
const home = homeDir(input.env);
|
|
78
|
+
const key = cwd.replace(/[^a-zA-Z0-9]/gu, "-");
|
|
79
|
+
await Promise.all([
|
|
80
|
+
join(input.env.XDG_CACHE_HOME || join(home, ".cache")),
|
|
81
|
+
join(home, "Library", "Caches"),
|
|
82
|
+
].map((cache) => rm(join(cache, "claude-cli-nodejs", key), {
|
|
83
|
+
force: true,
|
|
84
|
+
recursive: true,
|
|
85
|
+
})));
|
|
86
|
+
}
|
|
87
|
+
// Leave no empty room-jobs/ behind; a job still running keeps it.
|
|
88
|
+
await rmdir(join(input.directory, ROOM_JOBS)).catch(() => undefined);
|
|
89
|
+
},
|
|
90
|
+
cwd,
|
|
91
|
+
};
|
|
92
|
+
try {
|
|
93
|
+
// A retry of the same job starts from nothing, whatever an earlier attempt left.
|
|
94
|
+
await profile.cleanup();
|
|
95
|
+
await mkdir(cwd, { recursive: true, mode: 0o700 });
|
|
96
|
+
if (input.provider === "claude_code") {
|
|
97
|
+
const login = await claudeLoginSettings(input.env);
|
|
98
|
+
profile.env = login.env;
|
|
99
|
+
if (login.file) {
|
|
100
|
+
profile.settingsPath = join(jobDir, "settings.json");
|
|
101
|
+
await writePrivateFile(profile.settingsPath, login.file);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
profile.codexHome = join(jobDir, "codex-home");
|
|
106
|
+
await mkdir(profile.codexHome, { mode: 0o700 });
|
|
107
|
+
const login = join(input.env.CODEX_HOME || join(homeDir(input.env), ".codex"), "auth.json");
|
|
108
|
+
// A link, never a copy: Codex rotates the refresh token in place, and a
|
|
109
|
+
// copy would leave the owner's own file holding the one it retired.
|
|
110
|
+
if (await access(login, constants.F_OK).then(() => true, () => false)) {
|
|
111
|
+
await symlink(login, join(profile.codexHome, "auth.json")).catch(() => {
|
|
112
|
+
throw new RoomIsolationError();
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
await profile.cleanup();
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
return profile;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Anything left from a job the daemon never finished: the per-agent lock means
|
|
125
|
+
* no job of this agent is running when it starts, and a job's profile can hold
|
|
126
|
+
* a login key. The agent key's config files go with it.
|
|
127
|
+
*/
|
|
128
|
+
export async function sweepRoomJobs(directory) {
|
|
129
|
+
await Promise.all([ROOM_JOBS, ROOM_MCP_FILE, ROOM_CATALOG_FILE].map((name) => rm(join(directory, name), { force: true, recursive: true })));
|
|
130
|
+
}
|
package/dist/agent/serve.js
CHANGED
|
@@ -7,17 +7,19 @@ import { compareGatewayVersions } from "../gateway-version.js";
|
|
|
7
7
|
import { homeDir } from "../install.js";
|
|
8
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";
|
|
15
|
-
import {
|
|
16
|
+
import { failureReasonOf } from "./provider-failure.js";
|
|
17
|
+
import { sweepRoomJobs } from "./room-profile.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
|
-
|
|
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;
|
|
@@ -69,7 +71,9 @@ export async function installGatewayUpdate(directory, minimum, signal) {
|
|
|
69
71
|
export async function serveAgent(config, directory, version, stop, verify, options = {}) {
|
|
70
72
|
const release = await acquireLock(directory);
|
|
71
73
|
try {
|
|
72
|
-
|
|
74
|
+
// This agent has no job running: whatever a crashed job left is stale.
|
|
75
|
+
await sweepRoomJobs(directory);
|
|
76
|
+
const workDir = join(directory, "work"), gateway = new AgentGateway(config);
|
|
73
77
|
await mkdir(workDir, { recursive: true, mode: 0o700 });
|
|
74
78
|
const deviceId = randomUUID();
|
|
75
79
|
const gate = options.gate ??
|
|
@@ -135,6 +139,40 @@ export async function serveAgent(config, directory, version, stop, verify, optio
|
|
|
135
139
|
post: (path, body) => gateway.request(path, body, signal),
|
|
136
140
|
})
|
|
137
141
|
: undefined;
|
|
142
|
+
const beat = (native) => options.lease?.beatMs ?? (native ? NATIVE_RENEW_MS : HEARTBEAT_MS);
|
|
143
|
+
const holdFor = (native) => options.lease?.holdMs ?? holdMs(native);
|
|
144
|
+
let failedRenewals = 0;
|
|
145
|
+
// The server is away: a 5xx or no answer at all, as during a Convex push.
|
|
146
|
+
const serverAway = (error) => !(error instanceof GatewayError) || error.status >= 500;
|
|
147
|
+
// A claim can land just before a push; the provider's room tools are
|
|
148
|
+
// listed once at its start, so wait for the server before launching it.
|
|
149
|
+
const waitForServer = async (job, cancel) => {
|
|
150
|
+
const until = Date.now() + (options.lease?.startWaitMs ?? START_WAIT_MS);
|
|
151
|
+
const step = options.lease?.stepMs ?? 1000;
|
|
152
|
+
for (let wait = step; !signal.aborted; wait = Math.min(wait * 2, step * 10)) {
|
|
153
|
+
try {
|
|
154
|
+
await gateway.request(`/agent-gateway/jobs/${job.jobId}/renew`, { leaseToken: job.leaseToken }, signal);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
if (error instanceof GatewayError && error.status === 409) {
|
|
159
|
+
cancel.abort();
|
|
160
|
+
}
|
|
161
|
+
failService(error);
|
|
162
|
+
if (!serverAway(error) || Date.now() >= until) {
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
await delay(wait, undefined, {
|
|
167
|
+
signal: AbortSignal.any([signal, cancel.signal]),
|
|
168
|
+
}).catch(() => {
|
|
169
|
+
/* Shutdown or a lost claim interrupts the wait. */
|
|
170
|
+
});
|
|
171
|
+
if (cancel.signal.aborted) {
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
138
176
|
const heartbeatLoop = async () => {
|
|
139
177
|
while (!signal.aborted) {
|
|
140
178
|
const started = Date.now();
|
|
@@ -145,19 +183,24 @@ export async function serveAgent(config, directory, version, stop, verify, optio
|
|
|
145
183
|
? gateway
|
|
146
184
|
.request(`/agent-gateway/jobs/${leased.job.jobId}/renew`, { leaseToken: leased.job.leaseToken }, signal)
|
|
147
185
|
.then(() => {
|
|
148
|
-
|
|
186
|
+
failedRenewals = 0;
|
|
187
|
+
if (active === leased && !leased.answered) {
|
|
149
188
|
leased.deadline =
|
|
150
|
-
started +
|
|
151
|
-
(leased.job.native ? NATIVE_SAFETY_MS : LEASE_SAFETY_MS);
|
|
189
|
+
started + holdFor(Boolean(leased.job.native));
|
|
152
190
|
}
|
|
153
191
|
})
|
|
154
192
|
.catch((error) => {
|
|
155
193
|
if (active !== leased) {
|
|
156
194
|
return;
|
|
157
195
|
}
|
|
196
|
+
// Only the server's word ends the job: 409 is another
|
|
197
|
+
// claim. Anything else is a gateway that will be back.
|
|
158
198
|
if (error instanceof GatewayError && error.status === 409) {
|
|
159
199
|
leased.cancel.abort();
|
|
160
200
|
}
|
|
201
|
+
else {
|
|
202
|
+
failedRenewals++;
|
|
203
|
+
}
|
|
161
204
|
failService(error);
|
|
162
205
|
})
|
|
163
206
|
: Promise.resolve(),
|
|
@@ -166,7 +209,7 @@ export async function serveAgent(config, directory, version, stop, verify, optio
|
|
|
166
209
|
if (active?.job.native && active.owner && !gate.optedIn()) {
|
|
167
210
|
active.cancel.abort();
|
|
168
211
|
}
|
|
169
|
-
await delay(Math.max(1, (active?.job.native
|
|
212
|
+
await delay(Math.max(1, renewDelayMs(beat(Boolean(active?.job.native)), failedRenewals) -
|
|
170
213
|
(Date.now() - started)), undefined, { signal }).catch(() => {
|
|
171
214
|
/* Shutdown interrupts the timer. */
|
|
172
215
|
});
|
|
@@ -175,7 +218,8 @@ export async function serveAgent(config, directory, version, stop, verify, optio
|
|
|
175
218
|
let heartbeats;
|
|
176
219
|
let updateAfter = 0;
|
|
177
220
|
const watchdog = setInterval(() => {
|
|
178
|
-
|
|
221
|
+
// A made answer is never dropped for a quiet gateway; only a 409 ends it.
|
|
222
|
+
if (active && !active.answered && Date.now() >= active.deadline) {
|
|
179
223
|
active.cancel.abort();
|
|
180
224
|
}
|
|
181
225
|
}, 1000);
|
|
@@ -254,9 +298,9 @@ export async function serveAgent(config, directory, version, stop, verify, optio
|
|
|
254
298
|
const current = {
|
|
255
299
|
job,
|
|
256
300
|
cancel,
|
|
257
|
-
deadline: claimStartedAt +
|
|
258
|
-
(job.native ? NATIVE_SAFETY_MS : LEASE_SAFETY_MS),
|
|
301
|
+
deadline: claimStartedAt + holdFor(Boolean(job.native)),
|
|
259
302
|
owner: false,
|
|
303
|
+
answered: false,
|
|
260
304
|
};
|
|
261
305
|
active = current;
|
|
262
306
|
let lastStatusAt = 0;
|
|
@@ -266,6 +310,7 @@ export async function serveAgent(config, directory, version, stop, verify, optio
|
|
|
266
310
|
const receivedAt = performance.now();
|
|
267
311
|
const timings = {};
|
|
268
312
|
try {
|
|
313
|
+
await waitForServer(job, cancel);
|
|
269
314
|
// An owner job runs the owner's real setup only when the plane
|
|
270
315
|
// confirmed owner authority just now AND this computer is ready;
|
|
271
316
|
// anything less is the room-only profile, as before.
|
|
@@ -309,11 +354,6 @@ export async function serveAgent(config, directory, version, stop, verify, optio
|
|
|
309
354
|
.catch(() => undefined);
|
|
310
355
|
}
|
|
311
356
|
}
|
|
312
|
-
// A project's sessions are its own; the root from before projects
|
|
313
|
-
// keeps its key so those threads still resume.
|
|
314
|
-
const sessionKey = owner
|
|
315
|
-
? `${job.packet.thread.id}:owner${owner.project.legacy ? "" : `:${owner.project.id}`}`
|
|
316
|
-
: job.packet.thread.id;
|
|
317
357
|
// Which code the work started from, on the owner's record.
|
|
318
358
|
const base = owner?.workspace.base;
|
|
319
359
|
const baseRow = base && {
|
|
@@ -349,11 +389,9 @@ export async function serveAgent(config, directory, version, stop, verify, optio
|
|
|
349
389
|
job,
|
|
350
390
|
workDir,
|
|
351
391
|
owner: owner && { ...owner, watch: bridge },
|
|
352
|
-
|
|
392
|
+
// Room tools and the current packet carry continuity. Replaying
|
|
393
|
+
// provider history grows forever and carries stale file copies.
|
|
353
394
|
signal: AbortSignal.any([signal, cancel.signal]),
|
|
354
|
-
remember: async (sessionId) => {
|
|
355
|
-
await sessions.remember(sessionKey, sessionId);
|
|
356
|
-
},
|
|
357
395
|
receipts: async (hookRows) => {
|
|
358
396
|
const rows = baseRow
|
|
359
397
|
? [baseRow, ...hookRows].map((row, seq) => ({ ...row, seq }))
|
|
@@ -380,6 +418,10 @@ export async function serveAgent(config, directory, version, stop, verify, optio
|
|
|
380
418
|
.catch(failService);
|
|
381
419
|
},
|
|
382
420
|
});
|
|
421
|
+
// The answer is made: only the server saying another claim holds the
|
|
422
|
+
// job may drop it, never the quiet-gateway backstop. The server
|
|
423
|
+
// takes a late completion from this attempt until a newer claim.
|
|
424
|
+
current.answered = true;
|
|
383
425
|
// A transient delivery error retries this same completion. It must
|
|
384
426
|
// never become a new provider run or a duplicate final reply.
|
|
385
427
|
while (!(signal.aborted || cancel.signal.aborted)) {
|
|
@@ -399,14 +441,24 @@ export async function serveAgent(config, directory, version, stop, verify, optio
|
|
|
399
441
|
}
|
|
400
442
|
}
|
|
401
443
|
catch (error) {
|
|
402
|
-
if (!(signal.aborted ||
|
|
444
|
+
if (!(signal.aborted ||
|
|
445
|
+
cancel.signal.aborted ||
|
|
446
|
+
(error instanceof RoomToolsUnavailableError &&
|
|
447
|
+
(await gateway
|
|
448
|
+
.request(`/agent-gateway/jobs/${job.jobId}/renew`, { leaseToken: job.leaseToken }, signal)
|
|
449
|
+
.then(() => false)
|
|
450
|
+
.catch((probe) => {
|
|
451
|
+
if (probe instanceof GatewayError &&
|
|
452
|
+
probe.status === 409) {
|
|
453
|
+
cancel.abort();
|
|
454
|
+
}
|
|
455
|
+
return serverAway(probe) || cancel.signal.aborted;
|
|
456
|
+
}))))) {
|
|
403
457
|
await gateway
|
|
404
458
|
.request(`/agent-gateway/jobs/${job.jobId}/fail`, {
|
|
405
459
|
leaseToken: job.leaseToken,
|
|
406
460
|
// A fixed code; the server owns the room's wording.
|
|
407
|
-
|
|
408
|
-
? { reason: "room_tools" }
|
|
409
|
-
: {}),
|
|
461
|
+
reason: failureReasonOf(error),
|
|
410
462
|
}, signal)
|
|
411
463
|
.catch(failService);
|
|
412
464
|
}
|
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
|
-
|
|
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
|
-
|
|
26
|
-
|
|
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
|
-
|
|
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) {
|
package/dist/commands/skills.js
CHANGED
|
@@ -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) {
|
package/dist/upload-file.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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
|
-
|
|
179
|
+
failed(` (${response.status})`);
|
|
158
180
|
}
|
|
159
181
|
const { storageId } = (await response.json());
|
|
160
182
|
if (!storageId) {
|
package/package.json
CHANGED
package/dist/agent/sessions.js
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { readFile } from "node:fs/promises";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
import { isMissing, writePrivateFile } from "../agent-config.js";
|
|
4
|
-
// One file per agent already supplies the agentId half of the session key.
|
|
5
|
-
export class SessionMap {
|
|
6
|
-
path;
|
|
7
|
-
constructor(directory) {
|
|
8
|
-
this.path = join(directory, "sessions.json");
|
|
9
|
-
}
|
|
10
|
-
async get(threadId) {
|
|
11
|
-
return (await this.read())[threadId];
|
|
12
|
-
}
|
|
13
|
-
async remember(threadId, sessionId) {
|
|
14
|
-
const sessions = await this.read();
|
|
15
|
-
sessions[threadId] = sessionId;
|
|
16
|
-
await writePrivateFile(this.path, `${JSON.stringify(sessions)}\n`);
|
|
17
|
-
}
|
|
18
|
-
async read() {
|
|
19
|
-
try {
|
|
20
|
-
const value = JSON.parse(await readFile(this.path, "utf8"));
|
|
21
|
-
if (!value ||
|
|
22
|
-
typeof value !== "object" ||
|
|
23
|
-
Array.isArray(value) ||
|
|
24
|
-
Object.values(value).some((session) => typeof session !== "string")) {
|
|
25
|
-
throw new Error("Agent sessions are invalid. Restore sessions.json before serving.");
|
|
26
|
-
}
|
|
27
|
-
return value;
|
|
28
|
-
}
|
|
29
|
-
catch (error) {
|
|
30
|
-
if (isMissing(error)) {
|
|
31
|
-
return {};
|
|
32
|
-
}
|
|
33
|
-
throw error;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
}
|