talentos 1.4.9 → 1.4.11

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.
@@ -1,5 +1,6 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { existsSync, readdirSync, readFileSync, realpathSync, statSync, } from "node:fs";
2
- import { basename, dirname, join, sep } from "node:path";
3
+ import { basename, dirname, join, resolve, sep } from "node:path";
3
4
  import { ROOM_LOCAL_TOOLS, ROOM_TOOLS } from "../codex-policy.js";
4
5
  import { canonical, inGitDir, isInside, protectedPaths, protectedReason, reachesProtected, WRITE_PROTECTED_SEGMENTS, } from "./paths.js";
5
6
  import { parseShell } from "./shell.js";
@@ -502,7 +503,7 @@ const GIT_GLOBAL_OK = new Set([
502
503
  ]);
503
504
  const GIT_DIR_FLAG = /^(--(?:git-dir|work-tree))=(.+)$/u;
504
505
  // `git [globals] <sub> ...`: only the globals above are understood.
505
- function splitGit(args) {
506
+ export function splitGit(args) {
506
507
  const dirs = [];
507
508
  let index = 0;
508
509
  while (index < args.length && isFlag(args[index])) {
@@ -623,11 +624,18 @@ const CHECKOUT_SAFE_FLAG = /^(?:-b|-t|--track|--no-track|-q|--quiet|--detach)$/u
623
624
  const SWITCH_SAFE_FLAG = /^(?:-d|--detach|-t|--track|--no-track|-q|--quiet|--guess|--no-guess)$/u;
624
625
  // Clone options that set config or hooks, or run a program.
625
626
  const CLONE_BAD_FLAG = /^(?:-\w*[cu]|--config|--template|--upload-pack|--separate-git-dir)/u;
627
+ // Fetch and pull follow the push rules (#12933): `origin` only, plain flags,
628
+ // no `+` refspec. `--force`, `--all`, `--update-head-ok`, `--refmap`,
629
+ // submodules and merge strategies are tier 1.
630
+ const FETCH_SAFE_FLAG = /^(?:-[qvp]+|--quiet|--verbose|--prune|--tags|--no-tags|--progress|--no-progress|--depth=\d+|--unshallow)$/u;
631
+ const PULL_SAFE_FLAG = /^(?:-[qvr]+|--quiet|--verbose|--rebase|--no-rebase|--ff|--ff-only|--no-ff|--no-edit|--autostash|--no-autostash|--progress|--no-progress)$/u;
632
+ // A remote given as a URL: `scheme://…`, `file:` or scp-like `[user@]host:path`.
633
+ const REMOTE_URL = /^[a-z][\w+.-]*:\/\/|^file:|^[^/:\s]+:/iu;
626
634
  const GIT_DIR_PARTS = ["HEAD", "objects", "refs"];
627
- // Git work that touches only `.git` and the network, never the folders around it.
628
635
  const TRAILING_SLASHES = /[/\\]+$/u;
629
636
  const URL_PATH_SEPARATOR = /[/:]/u;
630
637
  const GIT_SUFFIX = /\.git$/u;
638
+ // Git work that touches only `.git` and the network, never the folders around it.
631
639
  const GIT_KEEPS_TREE = new Set(["add", "commit", "fetch", "push"]);
632
640
  const RESTORE_SAFE_FLAG = /^(?:-S|--staged|-q|--quiet|--)$/u;
633
641
  const STASH_KEEPS = new Set([
@@ -655,6 +663,15 @@ function pushesToThread(refspec) {
655
663
  branch.startsWith("talentos/") &&
656
664
  !PROTECTED_BRANCH.test(branch));
657
665
  }
666
+ function gitFetchTier(sub, rest) {
667
+ const [remote, ...refspecs] = rest.filter((word) => !isFlag(word));
668
+ const safe = sub === "fetch" ? FETCH_SAFE_FLAG : PULL_SAFE_FLAG;
669
+ return rest.filter(isFlag).every((flag) => safe.test(flag.text)) &&
670
+ (remote === undefined || remote.text === "origin") &&
671
+ refspecs.every((refspec) => !refspec.text.startsWith("+"))
672
+ ? 2
673
+ : 1;
674
+ }
658
675
  function gitPushTier(rest) {
659
676
  const [remote, ...refspecs] = rest.filter((word) => !isFlag(word));
660
677
  // Only `origin` is the owner's own remote; a URL, a path or another name
@@ -846,7 +863,12 @@ function writeProtected(real, ctx) {
846
863
  // config (a worktree reads the main repository's) or the owner's global config,
847
864
  // and any hook installed in the repository's `hooks` folder.
848
865
  function hookSetup(ctx) {
849
- const setup = { dirs: [], installed: false, linked: [] };
866
+ const setup = {
867
+ dirs: [],
868
+ folders: [],
869
+ installed: false,
870
+ linked: [],
871
+ };
850
872
  for (const root of ctx.writeRoots) {
851
873
  const repo = gitRepoAt(root);
852
874
  if (!repo) {
@@ -867,10 +889,15 @@ function hookSetup(ctx) {
867
889
  for (const [, value] of configText(config, ctx.home).matchAll(HOOKS_PATH)) {
868
890
  if (value) {
869
891
  folders.push(canonical(value, top, ctx.home));
892
+ // Husky locates the user script from $0, before following folder links.
893
+ setup.folders.push(value === "~" || value.startsWith("~/")
894
+ ? join(ctx.home, value.slice(1))
895
+ : resolve(top, value));
870
896
  }
871
897
  }
872
898
  }
873
899
  setup.dirs.push(...folders.slice(1));
900
+ setup.folders.push(...folders);
874
901
  for (const dir of new Set([top, root])) {
875
902
  setup.linked.push(...linkedHookTargets(dir));
876
903
  }
@@ -915,6 +942,60 @@ function hookConfig(real, ctx, content) {
915
942
  PACKAGE_HOOK_KEY.test(content) ||
916
943
  PACKAGE_HOOK_KEY.test(readText(real))));
917
944
  }
945
+ // Pull includes both paths: config can select rebase without a CLI flag.
946
+ const GIT_HOOKS = {
947
+ commit: [
948
+ "pre-commit",
949
+ "prepare-commit-msg",
950
+ "commit-msg",
951
+ "post-commit",
952
+ "post-rewrite",
953
+ ],
954
+ push: ["pre-push"],
955
+ checkout: ["post-checkout"],
956
+ switch: ["post-checkout"],
957
+ restore: ["post-checkout"],
958
+ pull: [
959
+ "post-merge",
960
+ "pre-merge-commit",
961
+ "prepare-commit-msg",
962
+ "commit-msg",
963
+ "pre-rebase",
964
+ "post-rewrite",
965
+ "post-checkout",
966
+ ],
967
+ };
968
+ // Husky 9.1.7 exits before loading init code when the user's script is absent.
969
+ // Pin both helper and stub: a replacement may run code without that script.
970
+ const HUSKY_HELPER_SHA256 = "70200b200ca709b0622784f93839a5b2872333a917a09afddefd7dc2d8cdc680";
971
+ const HUSKY_STUB = '#!/usr/bin/env sh\n. "$(dirname "$0")/h"';
972
+ function hookMayExist(path) {
973
+ try {
974
+ statSync(path);
975
+ return true;
976
+ }
977
+ catch (error) {
978
+ return error.code !== "ENOENT";
979
+ }
980
+ }
981
+ function gitHookRuns(folder, name) {
982
+ const hook = join(folder, name);
983
+ if (!hookMayExist(hook)) {
984
+ return false;
985
+ }
986
+ return (readText(hook) !== HUSKY_STUB ||
987
+ createHash("sha256")
988
+ .update(readText(join(folder, "h")))
989
+ .digest("hex") !== HUSKY_HELPER_SHA256 ||
990
+ hookMayExist(join(dirname(folder), name)));
991
+ }
992
+ function gitRunsHooks(sub, ctx) {
993
+ const hooks = GIT_HOOKS[sub];
994
+ if (!hooks) {
995
+ return false;
996
+ }
997
+ return hookSetup(ctx).folders.some((folder) => hooks.some((name) => gitHookRuns(folder, name)));
998
+ }
918
999
  // A clone into a folder that holds a hooks folder or a hook config's target
919
1000
  // fills it from the clone (#13118).
920
1001
  function holdsHooks(target, ctx) {
@@ -973,7 +1054,12 @@ function shellAsk(command, ctx) {
973
1054
  if (sub === "push") {
974
1055
  tier = gitPushTier(git.rest);
975
1056
  }
1057
+ else if (sub === "fetch" || sub === "pull") {
1058
+ tier = gitFetchTier(sub, git.rest);
1059
+ }
976
1060
  else if (!gitKeepsWork(sub, git.rest, cwd, ctx.home) ||
1061
+ (sub === "clone" &&
1062
+ git.rest.some((word) => !isFlag(word) && REMOTE_URL.test(word.text))) ||
977
1063
  (sub === "clone" &&
978
1064
  cloneTargets(git, ctx).some((word) => word.glob ||
979
1065
  !ctx.writeRoots.some((root) => isInside(word.text, root)) ||
@@ -981,7 +1067,15 @@ function shellAsk(command, ctx) {
981
1067
  holdsHooks(word.text, ctx)))) {
982
1068
  tier = 1;
983
1069
  }
984
- return { kind: `git:${sub}`, tier };
1070
+ // R5 for git hooks (#13115, #13440): after an edit, hooks load configs
1071
+ // and tests the model may have changed, so it also needs the owner's tests
1072
+ // consent. The server reads `run:hooks` as the tests class.
1073
+ return {
1074
+ kind: tier === 2 && ctx.dirty && gitRunsHooks(sub, ctx)
1075
+ ? `git:${sub} + run:hooks`
1076
+ : `git:${sub}`,
1077
+ tier,
1078
+ };
985
1079
  }
986
1080
  if (FILE_UTILS.has(program)) {
987
1081
  const inside = args
@@ -1192,10 +1286,13 @@ export function classifyShell(source, ctx) {
1192
1286
  here = moved.moved;
1193
1287
  continue;
1194
1288
  }
1195
- const verdict = classifySimple(command, here);
1289
+ // An earlier part that writes is an edit for R5 too: `echo x > a.ts && npm
1290
+ // test` runs the changed file (#13115).
1291
+ const local = wrote && !here.dirty ? { ...here, dirty: true } : here;
1292
+ const verdict = classifySimple(command, local);
1196
1293
  // The disk is read before the chain runs, so a repository an earlier part
1197
1294
  // clones or builds is not there yet (#12926).
1198
- const blind = wrote && runsBlind(command, here);
1295
+ const blind = wrote && runsBlind(command, local);
1199
1296
  if (verdict.allow && !blind) {
1200
1297
  mutates ||= verdict.mutates;
1201
1298
  wrote ||= verdict.mutates;
@@ -1204,7 +1301,7 @@ export function classifyShell(source, ctx) {
1204
1301
  if (!verdict.allow && verdict.tier === 0) {
1205
1302
  return verdict;
1206
1303
  }
1207
- const ask = shellAsk(command, here);
1304
+ const ask = shellAsk(command, local);
1208
1305
  asked.push(blind ? { ...ask, tier: 1 } : ask);
1209
1306
  const held = blind ? deny(1) : verdict;
1210
1307
  if (!(held.allow || (worst && !worst.allow && held.tier >= worst.tier))) {
@@ -1217,7 +1314,9 @@ export function classifyShell(source, ctx) {
1217
1314
  }
1218
1315
  // One ask covers the whole command. Its tier is the strictest part's, and its
1219
1316
  // kind names every part, so a rule for one program never covers a chain.
1220
- const kinds = [...new Set(asked.map((entry) => entry.kind))].sort();
1317
+ const kinds = [
1318
+ ...new Set(asked.flatMap((entry) => entry.kind.split(" + "))),
1319
+ ].sort();
1221
1320
  const joined = kinds.join(" + ");
1222
1321
  const kind = joined.length <= 80 ? joined : `${kinds[0]} +${kinds.length - 1}`;
1223
1322
  const tier = Math.min(...asked.map((entry) => entry.tier));
@@ -443,7 +443,7 @@ export async function probeOwnerNative(input) {
443
443
  }
444
444
  }
445
445
  }
446
- function cacheKey(binary, version, hookEntry) {
446
+ export function cacheKey(binary, version, hookEntry) {
447
447
  const real = realpathSync.native(binary);
448
448
  return createHash("sha256")
449
449
  .update(JSON.stringify([
@@ -455,6 +455,18 @@ function cacheKey(binary, version, hookEntry) {
455
455
  ]))
456
456
  .digest("hex");
457
457
  }
458
+ /** Whether the cached pass still names this exact binary, version, probe and hook code. */
459
+ export async function ownerNativeProbeCached(input) {
460
+ try {
461
+ const cached = JSON.parse(await readFile(input.cachePath, "utf8"));
462
+ return (cached.ok === true &&
463
+ cached.key ===
464
+ cacheKey(input.binary, input.version, input.hookEntry ?? HOOK_ENTRY));
465
+ }
466
+ catch {
467
+ return false;
468
+ }
469
+ }
458
470
  /** Cached probe: re-proves only when the binary, its version, the probe or the hook code changed. */
459
471
  export async function ensureOwnerNativeProbe(input) {
460
472
  const hookEntry = input.hookEntry ?? HOOK_ENTRY;
@@ -1,5 +1,6 @@
1
+ import { basename } from "node:path";
1
2
  import { canonical, isInside } from "./paths.js";
2
- import { applyPatchPaths, } from "./policy.js";
3
+ import { applyPatchPaths, splitGit, } from "./policy.js";
3
4
  import { parseShell } from "./shell.js";
4
5
  // "Private-touched" (#10987 PR 2b, R12 R1): did this call reach into the owner's
5
6
  // own setup, so that what it returns may be private? The server records it;
@@ -11,6 +12,9 @@ import { parseShell } from "./shell.js";
11
12
  // workspace, a command the policy had to ask about, a tool we do not know)
12
13
  // counts as touched.
13
14
  const ROOM_SERVER_PREFIX = "mcp__talentos_room__";
15
+ // The room tools that reach beyond a room's own id: `list_rooms` has no roomId
16
+ // and names every room the agent can reach.
17
+ const ALL_ROOMS_TOOL = `${ROOM_SERVER_PREFIX}list_rooms`;
14
18
  // Tools that read files by path; the path decides.
15
19
  const PATH_TOOLS = new Set(["Glob", "Grep", "LS", "NotebookRead", "Read"]);
16
20
  const EDIT_TOOLS = new Set(["Edit", "MultiEdit", "NotebookEdit", "Write"]);
@@ -36,6 +40,16 @@ const PATH_START = /[/~]/u;
36
40
  function text(value) {
37
41
  return typeof value === "string" && value.length > 0 ? value : undefined;
38
42
  }
43
+ // A room tool aimed at another room reads words the server's "alone" check does
44
+ // not cover: it judges the job's own room only (#13436). A job whose room is
45
+ // unknown fails closed, so every room read taints.
46
+ function readsOtherRoom(call, jobRoomId) {
47
+ if (call.tool === ALL_ROOMS_TOOL) {
48
+ return true;
49
+ }
50
+ const aimed = call.toolInput.roomId;
51
+ return aimed !== undefined && aimed !== jobRoomId;
52
+ }
39
53
  export function touchesPrivate(call, context, allowedByPolicy) {
40
54
  // The policy had to ask the owner: it is outward, irreversible or unknown, and
41
55
  // once approved it may read anything.
@@ -51,7 +65,8 @@ export function touchesPrivate(call, context, allowedByPolicy) {
51
65
  return context.writeRoots.some((root) => isInside(real, root));
52
66
  };
53
67
  if (tool.startsWith("mcp__")) {
54
- return !tool.startsWith(ROOM_SERVER_PREFIX);
68
+ return (!tool.startsWith(ROOM_SERVER_PREFIX) ||
69
+ readsOtherRoom(call, context.roomId));
55
70
  }
56
71
  if (NEUTRAL_TOOLS.has(tool)) {
57
72
  return false;
@@ -87,14 +102,33 @@ export function touchesPrivate(call, context, allowedByPolicy) {
87
102
  return true;
88
103
  }
89
104
  const isRun = (part) => part.startsWith("run:");
105
+ // Git commands that bring outside content into the workspace (#13255).
106
+ const GIT_FETCHES = new Set(["clone", "fetch", "pull"]);
107
+ function fetchesOutside(call) {
108
+ const source = call.tool === "Bash" ? text(call.toolInput.command) : undefined;
109
+ const parsed = source ? parseShell(source) : undefined;
110
+ return Boolean(parsed?.ok &&
111
+ parsed.commands.some((command) => {
112
+ const [program, ...args] = command.argv;
113
+ if (basename(program?.text ?? "") !== "git") {
114
+ return false;
115
+ }
116
+ const git = splitGit(args);
117
+ // Globals the reader does not know: any fetch-like word counts.
118
+ return git.ok
119
+ ? GIT_FETCHES.has(git.sub?.text ?? "")
120
+ : args.some((word) => GIT_FETCHES.has(word.text));
121
+ }));
122
+ }
90
123
  /**
91
124
  * Did this call pull untrusted input into the job (Auto mode, R13)? Anything
92
- * the owner's private setup touch covers, plus web search and any serious
93
- * (tier 1) action the owner approved. After the first, tests and builds ask
125
+ * the owner's private setup touch covers, plus web search, a git fetch, pull or
126
+ * clone from any remote, and any serious (tier 1) action the owner approved. After the first, tests and builds ask
94
127
  * again for the rest of the job and the thread.
95
128
  */
96
129
  export function taintsJob(call, context, asked) {
97
130
  return (call.tool === "WebSearch" ||
131
+ fetchesOutside(call) ||
98
132
  // A test or build the owner (or Auto mode) allowed brings in nothing; any
99
133
  // other serious action does.
100
134
  (asked?.tier === 1 && !asked.kind.split(" + ").every(isRun)) ||
@@ -0,0 +1,140 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { launcherNodeCandidates, npmSpawnEnv } from "../gateway-install.js";
4
+ import { compareGatewayVersions } from "../gateway-version.js";
5
+ const exec = promisify(execFile);
6
+ const NPM_VIEW_TIMEOUT_MS = 15_000;
7
+ // Only the grammar `engines.node` uses here: `||` sets of space-separated
8
+ // comparators. Anything else (^, ~, x, hyphen ranges) is "can't tell".
9
+ const COMPARATOR = /^(>=|<=|>|<|=)?(\d+)(?:\.(\d+))?(?:\.(\d+))?$/u;
10
+ const WHITESPACE = /\s+/u;
11
+ const NODE_RANGE = /^[\w<>=.|\s-]{1,200}$/u;
12
+ function compareTriples(a, b) {
13
+ return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
14
+ }
15
+ function satisfiesComparator(node, token) {
16
+ const match = COMPARATOR.exec(token);
17
+ if (!match) {
18
+ return;
19
+ }
20
+ const [, operator = "=", major, minor, patch] = match;
21
+ const partial = minor === undefined || patch === undefined;
22
+ const bound = [Number(major), Number(minor ?? 0), Number(patch ?? 0)];
23
+ const difference = compareTriples(node, bound);
24
+ if (operator === ">=") {
25
+ return difference >= 0;
26
+ }
27
+ if (operator === "<") {
28
+ return difference < 0;
29
+ }
30
+ // A partial bound on the others means "the whole 22.x", which this does not
31
+ // model.
32
+ if (partial) {
33
+ return;
34
+ }
35
+ if (operator === ">") {
36
+ return difference > 0;
37
+ }
38
+ return operator === "<=" ? difference <= 0 : difference === 0;
39
+ }
40
+ /**
41
+ * Whether `nodeVersion` satisfies an `engines.node` range: true, false, or
42
+ * undefined when the range is outside the small grammar read here, so the
43
+ * caller never blocks on a range it did not understand.
44
+ */
45
+ export function nodeSatisfies(range, nodeVersion) {
46
+ const node = nodeVersion.split(".").map(Number);
47
+ if (!NODE_RANGE.test(range) ||
48
+ node.length !== 3 ||
49
+ node.some((part) => !Number.isInteger(part))) {
50
+ return;
51
+ }
52
+ let unknown = false;
53
+ for (const set of range.split("||")) {
54
+ const results = set
55
+ .trim()
56
+ .split(WHITESPACE)
57
+ .map((token) => satisfiesComparator(node, token));
58
+ if (results.length === 0 || results.includes(undefined)) {
59
+ unknown = true;
60
+ }
61
+ else if (results.every(Boolean)) {
62
+ return true;
63
+ }
64
+ }
65
+ return unknown ? undefined : false;
66
+ }
67
+ /**
68
+ * The `engines.node` range the registry publishes for a CLI version, or
69
+ * undefined when it cannot be read (offline, npm missing, no range): the
70
+ * caller then updates as before and never goes offline over a metadata miss.
71
+ */
72
+ export async function targetNodeRange(version, signal) {
73
+ // The version reaches a shell on Windows, so only a plain version passes.
74
+ if (compareGatewayVersions(version, version) === undefined) {
75
+ return;
76
+ }
77
+ const windows = process.platform === "win32";
78
+ try {
79
+ const { stdout } = await exec(windows ? "npm.cmd" : "npm", ["view", `talentos@${version}`, "engines.node", "--json"], {
80
+ env: npmSpawnEnv(),
81
+ shell: windows,
82
+ signal,
83
+ timeout: NPM_VIEW_TIMEOUT_MS,
84
+ });
85
+ const range = JSON.parse(stdout.trim() || "null");
86
+ return typeof range === "string" && range.length <= 200 ? range : undefined;
87
+ }
88
+ catch {
89
+ return;
90
+ }
91
+ }
92
+ const PROBE_TIMEOUT_MS = 3000;
93
+ // The whole candidate walk is bounded: a hung Node must not hold up claims.
94
+ const PROBE_BUDGET_MS = 10_000;
95
+ const NODE_VERSION = /^\d{1,3}\.\d{1,3}\.\d{1,3}$/u;
96
+ /** The version a Node executable runs, as the launcher asks it; undefined when it is missing, not executable or silent. */
97
+ export async function probeNodeVersion(path, signal) {
98
+ try {
99
+ const { stdout } = await exec(path, ["-p", "process.versions.node"], {
100
+ signal,
101
+ timeout: PROBE_TIMEOUT_MS,
102
+ });
103
+ const version = stdout.trim();
104
+ return NODE_VERSION.test(version) ? version : undefined;
105
+ }
106
+ catch {
107
+ return;
108
+ }
109
+ }
110
+ /**
111
+ * Whether installing `version` would leave this computer unable to start it:
112
+ * `engines.node` excludes the running Node AND every other Node the launcher
113
+ * would start (its own candidate list, probed). Anything unreadable, or a range
114
+ * outside the grammar read here, is not a block.
115
+ */
116
+ export async function nodeBlocksUpdate(version, options = {}) {
117
+ const nodeVersion = options.nodeVersion ?? process.versions.node;
118
+ const range = await (options.range ?? targetNodeRange)(version, options.signal);
119
+ if (!range || nodeSatisfies(range, nodeVersion) !== false) {
120
+ return;
121
+ }
122
+ const probe = options.probe ?? probeNodeVersion;
123
+ const deadline = Date.now() + PROBE_BUDGET_MS;
124
+ for (const candidate of await (options.candidates?.() ??
125
+ launcherNodeCandidates())) {
126
+ if (Date.now() >= deadline || options.signal?.aborted) {
127
+ // Out of time to look is not proof that none qualifies.
128
+ return;
129
+ }
130
+ const found = await probe(candidate, options.signal);
131
+ if (found && nodeSatisfies(range, found) !== false) {
132
+ return;
133
+ }
134
+ }
135
+ return {
136
+ forVersion: version,
137
+ range,
138
+ message: `TalentOS CLI ${version} needs Node ${range}; this computer runs ${nodeVersion}. Update Node, then run npx talentos@${version} agent repair.`,
139
+ };
140
+ }
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { mkdir, open, readFile, rm } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
4
  import { setTimeout as delay } from "node:timers/promises";
5
- import { installSharedGateway, newerInstalledVersion, } from "../gateway-install.js";
5
+ import { installSharedGateway, launcherNodeCandidates, newerInstalledVersion, } from "../gateway-install.js";
6
6
  import { compareGatewayVersions } from "../gateway-version.js";
7
7
  import { homeDir } from "../install.js";
8
8
  import { RoomToolsUnavailableError, runProvider, } from "./adapters.js";
@@ -13,6 +13,7 @@ import { NativeGate } from "./native/gate.js";
13
13
  import { ROOM_ONLY_STATUS, roomOnlyStatus } from "./native/native-issue.js";
14
14
  import { ProjectRequests } from "./native/project-requests.js";
15
15
  import { mirrorOf } from "./native/projects.js";
16
+ import { nodeBlocksUpdate } from "./node-floor.js";
16
17
  import { failureReasonOf } from "./provider-failure.js";
17
18
  import { sweepRoomJobs } from "./room-profile.js";
18
19
  const HEARTBEAT_MS = 20_000;
@@ -21,6 +22,9 @@ const NATIVE_RENEW_MS = 10_000;
21
22
  // A launch waits this long for the server before it starts the provider anyway.
22
23
  const START_WAIT_MS = 120_000;
23
24
  const IDLE_MS = 30 * 60_000;
25
+ // A declined update (no Node here can run it) is not looked at again sooner,
26
+ // unless the floor it was declined for changes.
27
+ const NODE_BLOCK_RETRY_MS = 60 * 60_000;
24
28
  // The room-only reason stays up this long before progress lines resume.
25
29
  const FALLBACK_HOLD_MS = 5000;
26
30
  export function needsUpdate(current, minimum) {
@@ -87,7 +91,10 @@ export async function serveAgent(config, directory, version, stop, verify, optio
87
91
  wakeResolve?.();
88
92
  };
89
93
  let active;
90
- let minimum = version, lastJobAt = Date.now(), push = false, dispose;
94
+ let minimum = version,
95
+ // The Node range of an update this computer declined, reported until the
96
+ // update is no longer blocked.
97
+ blocked, lastJobAt = Date.now(), push = false, dispose;
91
98
  let terminalError;
92
99
  const failService = (error) => {
93
100
  if (error instanceof GatewayError &&
@@ -116,6 +123,11 @@ export async function serveAgent(config, directory, version, stop, verify, optio
116
123
  const issue = gate.issue?.();
117
124
  const response = await gateway.request("/agent-gateway/heartbeat", {
118
125
  cliVersion: version,
126
+ nodeVersion: options.node?.nodeVersion ?? process.versions.node,
127
+ // Only while the update it was declined for is still the one due.
128
+ ...(blocked?.forVersion === minimum && needsUpdate(version, minimum)
129
+ ? { updateBlockedNodeRange: blocked.range }
130
+ : {}),
119
131
  nativeOptIn: gate.reportable(),
120
132
  ...(mirror ? { projects: mirror } : {}),
121
133
  // Why an opted-in computer can't use full setup (an untested Codex),
@@ -272,16 +284,45 @@ export async function serveAgent(config, directory, version, stop, verify, optio
272
284
  return newer;
273
285
  }
274
286
  }
287
+ // A block is for one floor: a new floor is looked at at once, and when
288
+ // no update is due the range stops being sent.
289
+ if (blocked &&
290
+ (blocked.forVersion !== minimum || !needsUpdate(version, minimum))) {
291
+ blocked = undefined;
292
+ updateAfter = 0;
293
+ }
275
294
  if (needsUpdate(version, minimum) && Date.now() >= updateAfter) {
276
295
  if (process.platform === "win32") {
277
296
  throw new Error(`Gateway update required; re-run npx talentos@${minimum} agent serve --agent ${config.agentId}. Windows gateways update in the foreground.`);
278
297
  }
279
- try {
280
- return await installGatewayUpdate(directory, minimum, signal);
298
+ // Never update into a CLI no Node here can start: it would go offline
299
+ // with nothing but the owner's terminal saying why. An unreadable or
300
+ // unfamiliar range is not a block, and the update goes ahead.
301
+ const block = await nodeBlocksUpdate(minimum, {
302
+ candidates: () => launcherNodeCandidates(dirname(dirname(dirname(directory)))),
303
+ ...options.node,
304
+ signal,
305
+ });
306
+ if (block) {
307
+ updateAfter = Date.now() + NODE_BLOCK_RETRY_MS;
308
+ if (block.range !== blocked?.range ||
309
+ block.forVersion !== blocked.forVersion) {
310
+ blocked = block;
311
+ console.error(block.message);
312
+ // Tell the server now, not at the next beat, so a waiting job's
313
+ // room line names Node.
314
+ await heartbeat().catch(failService);
315
+ }
281
316
  }
282
- catch {
283
- updateAfter = Date.now() + 60_000;
284
- console.error("Gateway update unavailable. Serving the current version; retrying in one minute.");
317
+ else {
318
+ blocked = undefined;
319
+ try {
320
+ return await installGatewayUpdate(directory, minimum, signal);
321
+ }
322
+ catch {
323
+ updateAfter = Date.now() + 60_000;
324
+ console.error("Gateway update unavailable. Serving the current version; retrying in one minute.");
325
+ }
285
326
  }
286
327
  }
287
328
  if (config.provider === "codex") {
@@ -401,6 +442,11 @@ export async function serveAgent(config, directory, version, stop, verify, optio
401
442
  job,
402
443
  workDir,
403
444
  owner: owner && { ...owner, watch: bridge },
445
+ // Tells the server the job read the web, before it can write
446
+ // what a page steered (#13163).
447
+ webRead: async () => {
448
+ await gateway.request(`/agent-gateway/jobs/${job.jobId}/web-read`, { leaseToken: job.leaseToken }, signal);
449
+ },
404
450
  // Room tools and the current packet carry continuity. Replaying
405
451
  // provider history grows forever and carries stale file copies.
406
452
  signal: AbortSignal.any([signal, cancel.signal]),
@@ -152,6 +152,41 @@ export async function unlinkRemoteAgent(agent) {
152
152
  }
153
153
  return true;
154
154
  }
155
+ /**
156
+ * Asks, with the agent's gateway key, for a terminal key bound to the same
157
+ * agent (#10527). Only the new key's hash is sent; a repeat replaces the
158
+ * agent's previous terminal key, so `replaced` says one was cut.
159
+ */
160
+ export async function registerSessionKey(agent, keyHash) {
161
+ const response = await safeFetch(`${apiOrigin(agent.apiUrl)}/agent-link/session-key`, {
162
+ method: "POST",
163
+ headers: {
164
+ Authorization: `Bearer ${agent.apiKey}`,
165
+ "Content-Type": "application/json",
166
+ },
167
+ body: JSON.stringify({ keyHash }),
168
+ });
169
+ if (response.status === 409) {
170
+ // The server's own sentence: a busy agent says to try again later.
171
+ throw new Error((await refusalSentence(response)) ?? "Could not connect this terminal.");
172
+ }
173
+ if (!response.ok) {
174
+ throw new AgentHttpError("Could not connect this terminal", response);
175
+ }
176
+ const value = (await readJson(response));
177
+ return { replaced: value.replaced === true };
178
+ }
179
+ /** Stops every terminal key of the agent. False when the agent itself is gone. */
180
+ export async function revokeSessionKeys(agent) {
181
+ const response = await safeFetch(`${apiOrigin(agent.apiUrl)}/agent-link/session-key`, { method: "DELETE", headers: { Authorization: `Bearer ${agent.apiKey}` } });
182
+ if (response.status === 401) {
183
+ return false;
184
+ }
185
+ if (!response.ok) {
186
+ throw new AgentHttpError("Could not disconnect this terminal", response);
187
+ }
188
+ return true;
189
+ }
155
190
  export async function waitForHeartbeat(agent, options = {}) {
156
191
  const deadline = Date.now() + (options.timeoutMs ?? 10 * 60_000);
157
192
  let serverStartedAt;
@@ -218,6 +253,19 @@ async function linkRefusal(response, token) {
218
253
  }
219
254
  : undefined;
220
255
  }
256
+ async function refusalSentence(response) {
257
+ try {
258
+ const value = (await response.json());
259
+ return typeof value.error === "string" &&
260
+ value.error.length <= REFUSAL_MAX_LENGTH &&
261
+ ONE_LINE.test(value.error)
262
+ ? value.error
263
+ : undefined;
264
+ }
265
+ catch {
266
+ return;
267
+ }
268
+ }
221
269
  async function readJson(response) {
222
270
  try {
223
271
  return await response.json();