@sagentlab/navarch-runtime 0.1.173 → 0.1.175

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.
@@ -6,14 +6,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.DEPENDENCY_CACHE_DIRNAME = void 0;
7
7
  exports.npmEnvironment = npmEnvironment;
8
8
  exports.prepareDependencyCache = prepareDependencyCache;
9
+ exports.pullRequestNumberInRepository = pullRequestNumberInRepository;
9
10
  exports.dependencyCacheKey = dependencyCacheKey;
10
11
  exports.renderDependencyCacheNote = renderDependencyCacheNote;
11
12
  exports.lockfileRefusal = lockfileRefusal;
12
13
  exports.npmrcRefusal = npmrcRefusal;
13
14
  exports.copyTree = copyTree;
15
+ const node_child_process_1 = require("node:child_process");
14
16
  const node_crypto_1 = require("node:crypto");
15
17
  const node_fs_1 = require("node:fs");
16
18
  const node_path_1 = __importDefault(require("node:path"));
19
+ const node_util_1 = require("node:util");
17
20
  const logger_cjs_1 = require("./logger.cjs");
18
21
  const sandbox_cjs_1 = require("./sandbox.cjs");
19
22
  /**
@@ -47,6 +50,10 @@ const sandbox_cjs_1 = require("./sandbox.cjs");
47
50
  * become part of a commit or replace files the checkout already has.
48
51
  * - npm workspaces are skipped: their install also writes into the
49
52
  * workspace packages, which a root-level copy does not reproduce.
53
+ * - A session that checks another commit (a verify or review of a pull
54
+ * request) passes that commit as `inputsCommit`. The install inputs are
55
+ * then read from that commit's tree, so the prepared tree matches the pull
56
+ * request's lockfile and not the claim commit's. The same refusals apply.
50
57
  *
51
58
  * Every step degrades to a recorded `skipped`/`failed` result. Dependency
52
59
  * preparation never fails the session.
@@ -87,12 +94,19 @@ function npmEnvironment(env) {
87
94
  return out;
88
95
  }
89
96
  async function prepareDependencyCache(options) {
97
+ if (options.signal?.aborted)
98
+ return [];
90
99
  const runner = options.runner ?? sandbox_cjs_1.nodeCommandRunner;
91
100
  const npmBin = options.npmBin ?? "npm";
92
101
  const env = npmEnvironment(options.env ?? process.env);
93
- const dirs = await trackedLockfileDirs(runner, options.worktreePath);
102
+ const commitDirs = options.inputsCommit && /^[0-9a-f]{40,64}$/i.test(options.inputsCommit)
103
+ ? await commitLockfileDirs(runner, options.worktreePath, options.inputsCommit)
104
+ : null;
105
+ const inputsCommit = commitDirs ? options.inputsCommit : undefined;
106
+ const dirs = commitDirs ?? await trackedLockfileDirs(runner, options.worktreePath);
94
107
  if (dirs.length === 0)
95
108
  return [];
109
+ const source = inputsCommit ? { inputsCommit } : {};
96
110
  let npmVersion = null;
97
111
  const results = [];
98
112
  for (const dir of dirs) {
@@ -104,34 +118,42 @@ async function prepareDependencyCache(options) {
104
118
  results.push({ dir, status: "present" });
105
119
  continue;
106
120
  }
121
+ // A package directory the other commit adds has no place in this checkout.
122
+ if (inputsCommit && !(await exists(node_path_1.default.join(options.worktreePath, dir)))) {
123
+ results.push({ dir, status: "skipped", detail: "this directory is not in the session checkout", ...source });
124
+ continue;
125
+ }
107
126
  if (!(await isIgnored(runner, options.worktreePath, node_path_1.default.join(dir, "node_modules")))) {
108
127
  results.push({ dir, status: "skipped", detail: "node_modules is not ignored by git in this checkout" });
109
128
  continue;
110
129
  }
111
- const packageJson = await readInput(node_path_1.default.join(options.worktreePath, dir, "package.json"));
112
- const lockfile = await readInput(node_path_1.default.join(options.worktreePath, dir, LOCKFILE));
113
- const npmrc = await readInput(node_path_1.default.join(options.worktreePath, dir, ".npmrc"));
130
+ const read = (name) => inputsCommit
131
+ ? readCommitInput(options.worktreePath, inputsCommit, dir === "." ? name : `${dir}/${name}`)
132
+ : readInput(node_path_1.default.join(options.worktreePath, dir, name));
133
+ const packageJson = await read("package.json");
134
+ const lockfile = await read(LOCKFILE);
135
+ const npmrc = await read(".npmrc");
114
136
  const unreadable = [packageJson, lockfile, npmrc].find((input) => input.state === "invalid");
115
137
  if (unreadable?.state === "invalid") {
116
- results.push({ dir, status: "skipped", detail: unreadable.detail });
138
+ results.push({ dir, status: "skipped", detail: unreadable.detail, ...source });
117
139
  continue;
118
140
  }
119
141
  if (packageJson.state !== "file" || lockfile.state !== "file") {
120
- results.push({ dir, status: "skipped", detail: "no package.json next to package-lock.json" });
142
+ results.push({ dir, status: "skipped", detail: "no package.json next to package-lock.json", ...source });
121
143
  continue;
122
144
  }
123
145
  if (usesWorkspaces(packageJson.data)) {
124
- results.push({ dir, status: "skipped", detail: "npm workspaces are not supported by the dependency cache" });
146
+ results.push({ dir, status: "skipped", detail: "npm workspaces are not supported by the dependency cache", ...source });
125
147
  continue;
126
148
  }
127
149
  const refusal = lockfileRefusal(lockfile.data) ?? (npmrc.state === "file" ? npmrcRefusal(npmrc.data) : null);
128
150
  if (refusal) {
129
- results.push({ dir, status: "skipped", detail: refusal });
151
+ results.push({ dir, status: "skipped", detail: refusal, ...source });
130
152
  continue;
131
153
  }
132
154
  npmVersion ??= await readNpmVersion(runner, npmBin, env);
133
155
  if (!npmVersion) {
134
- results.push({ dir, status: "failed", detail: "npm is not available to the runtime" });
156
+ results.push({ dir, status: "failed", detail: "npm is not available to the runtime", ...source });
135
157
  continue;
136
158
  }
137
159
  const inputs = {
@@ -197,19 +219,32 @@ async function prepareDependencyCache(options) {
197
219
  }
198
220
  }
199
221
  if (failure) {
200
- results.push({ dir, status: "failed", key, detail: failure });
222
+ results.push({ dir, status: "failed", key, detail: failure, ...source });
201
223
  continue;
202
224
  }
203
- results.push({ dir, status, key });
225
+ results.push({ dir, status, key, ...source });
204
226
  await pruneEntries(options.cacheRoot, options.repository, dir, options.keepPerLockfile ?? DEFAULT_KEEP_PER_LOCKFILE)
205
227
  .catch((error) => log.warn(`dependency cache prune failed: ${String(error)}`));
206
228
  }
207
229
  catch (error) {
208
- results.push({ dir, status: "failed", detail: `unexpected error: ${error.message ?? String(error)}` });
230
+ results.push({ dir, status: "failed", detail: `unexpected error: ${error.message ?? String(error)}`, ...source });
209
231
  }
210
232
  }
211
233
  return results;
212
234
  }
235
+ /**
236
+ * The pull request number when `url` is a pull request of `repository`
237
+ * ("owner/name"), else null. A verify or review task carries its pull
238
+ * request in `github_issue_url`; a task that links an issue has no head to
239
+ * prepare for.
240
+ */
241
+ function pullRequestNumberInRepository(url, repository) {
242
+ const match = /^https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/pull\/(\d{1,10})(?:[/?#]|$)/i.exec(url ?? "");
243
+ if (!match || match[1].toLowerCase() !== repository.toLowerCase())
244
+ return null;
245
+ const number = Number(match[2]);
246
+ return number > 0 ? number : null;
247
+ }
213
248
  function dependencyCacheKey(input) {
214
249
  return sha256(Buffer.from(JSON.stringify({
215
250
  v: KEY_VERSION,
@@ -229,7 +264,9 @@ function dependencyCacheKey(input) {
229
264
  * Prompt section that tells the agent what the runtime prepared. Returns null
230
265
  * when the worktree has no tracked lockfile, so unrelated sessions see nothing.
231
266
  */
232
- function renderDependencyCacheNote(results) {
267
+ function renderDependencyCacheNote(results,
268
+ /** The pull request under check, even when its head could not be read. */
269
+ pullRequestNumber) {
233
270
  if (results.length === 0)
234
271
  return null;
235
272
  const label = (dir) => (dir === "." ? "`node_modules`" : `\`${dir}/node_modules\``);
@@ -237,10 +274,20 @@ function renderDependencyCacheNote(results) {
237
274
  const notReady = results.filter((r) => r.status === "skipped" || r.status === "failed");
238
275
  const lines = ["## Prepared dependencies", ""];
239
276
  if (ready.length > 0) {
240
- lines.push(`Navarch installed locked dependencies before this session started: ${ready.map((r) => `${label(r.dir)} (cache ${r.status === "hit" ? "hit" : "built"}, key \`${r.key.slice(0, 12)}\`)`).join(", ")}.`, "The runtime ran `npm ci --ignore-scripts` outside the sandbox, keyed on the repository, `package-lock.json`, `package.json`, `.npmrc`, Node, npm, and platform, and copied the result into this checkout.", "Use these directories for local tests, type checks, and builds. Do not run `npm ci` or `npm install`: the sandbox has no registry access.", "Lifecycle scripts did not run. If a step fails because a package needs its install script (for example a native addon build), report that exact package and command as a capability gap.");
277
+ lines.push(`Navarch installed locked dependencies before this session started: ${ready.map((r) => `${label(r.dir)} (cache ${r.status === "hit" ? "hit" : "built"}, key \`${r.key.slice(0, 12)}\`)`).join(", ")}.`, "The runtime ran `npm ci --ignore-scripts` outside the sandbox, keyed on the repository, `package-lock.json`, `package.json`, `.npmrc`, Node, npm, and platform, and copied the result into this checkout.", "Use these directories for local tests, type checks, and builds when their install inputs match. Do not run `npm ci` or `npm install`: the sandbox has no registry access.", "Lifecycle scripts did not run. If a step fails because a package needs its install script (for example a native addon build), report that exact package and command as a capability gap.");
278
+ const commit = ready.find((r) => r.inputsCommit)?.inputsCommit;
279
+ if (commit) {
280
+ const subject = pullRequestNumber ? `pull request #${pullRequestNumber}'s head` : "the commit under check,";
281
+ lines.push(`The install inputs (\`package.json\`, \`package-lock.json\`, \`.npmrc\`) came from ${subject} \`${commit.slice(0, 12)}\`, not from this checkout's claim commit, so the packages match the change you check.`, "Link or copy these directories into the detached worktree where you check that commit out. If the head moved and any install input changed, record the affected checks as `NOT RUN (prepared dependencies are for an older head)`.");
282
+ }
283
+ else if (pullRequestNumber) {
284
+ lines.push(`The runtime could not read the head of pull request #${pullRequestNumber} and used the session checkout's install inputs.`, "Before reusing these packages in the detached worktree, compare `package.json`, `package-lock.json`, and `.npmrc` for each package directory. If any input differs, record the affected checks as `NOT RUN (prepared dependencies use different install inputs)`.");
285
+ }
241
286
  }
242
287
  for (const r of results.filter((result) => result.status === "present")) {
243
288
  lines.push(`${label(r.dir)} was already in the checkout, so the runtime left it unchanged.`);
289
+ if (pullRequestNumber)
290
+ lines.push("Confirm that these existing packages match the pull request's install inputs before using them.");
244
291
  }
245
292
  for (const r of notReady) {
246
293
  lines.push(`${label(r.dir)} was not prepared (${r.status}): ${r.detail ?? "no detail"}.`);
@@ -251,14 +298,30 @@ async function trackedLockfileDirs(runner, worktreePath) {
251
298
  const listed = await runner.run("git", ["-C", worktreePath, "ls-files", "-z", "--", LOCKFILE, `*/${LOCKFILE}`], { timeoutMs: 30_000 });
252
299
  if (listed.code !== 0)
253
300
  return [];
254
- const dirs = listed.stdout
255
- .split("\0")
256
- .filter(Boolean)
301
+ return selectLockfileDirs(listed.stdout.split("\0").filter(Boolean));
302
+ }
303
+ /** Root and first-level directories only, root first, never a vendored node_modules copy. */
304
+ function selectLockfileDirs(files) {
305
+ const dirs = files
257
306
  .map((file) => node_path_1.default.posix.dirname(file))
258
- // Root and first-level packages only, never a vendored node_modules copy.
259
307
  .filter((dir) => dir === "." || (!dir.includes("/") && dir !== "node_modules"));
260
308
  return [...new Set(dirs)].sort((a, b) => (a === "." ? -1 : b === "." ? 1 : a.localeCompare(b))).slice(0, MAX_LOCKFILES);
261
309
  }
310
+ /**
311
+ * Lockfile directories in a commit's tree, or null when git cannot read the
312
+ * commit. `ls-tree` takes literal paths, so the first-level directories are
313
+ * listed first and each one's lockfile path is then looked up by name.
314
+ */
315
+ async function commitLockfileDirs(runner, worktreePath, commit) {
316
+ const top = await runner.run("git", ["-C", worktreePath, "ls-tree", "-d", "-z", "--name-only", `${commit}^{commit}`], { timeoutMs: 30_000 });
317
+ if (top.code !== 0)
318
+ return null;
319
+ const candidates = [LOCKFILE, ...top.stdout.split("\0").filter(Boolean).map((dir) => `${dir}/${LOCKFILE}`)];
320
+ const listed = await runner.run("git", ["-C", worktreePath, "ls-tree", "-z", "--name-only", commit, "--", ...candidates], { timeoutMs: 30_000 });
321
+ if (listed.code !== 0)
322
+ return null;
323
+ return selectLockfileDirs(listed.stdout.split("\0").filter(Boolean));
324
+ }
262
325
  async function isIgnored(runner, worktreePath, relativePath) {
263
326
  const result = await runner.run("git", ["-C", worktreePath, "check-ignore", "-q", "--", `${relativePath.split(node_path_1.default.sep).join("/")}/`], { timeoutMs: 30_000 });
264
327
  return result.code === 0;
@@ -553,6 +616,40 @@ async function readInput(file) {
553
616
  await handle.close();
554
617
  }
555
618
  }
619
+ const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
620
+ /**
621
+ * Reads an install input from a commit's tree. Only a regular blob counts: a
622
+ * symlink or submodule entry is refused, as `readInput` refuses a link. The
623
+ * bytes come straight from git, so the cache key equals the one computed from
624
+ * the same file in a checkout.
625
+ */
626
+ async function readCommitInput(worktreePath, commit, file) {
627
+ const name = node_path_1.default.posix.basename(file);
628
+ const unreadable = { state: "invalid", detail: `${name} could not be read from commit ${commit.slice(0, 12)}` };
629
+ let line;
630
+ try {
631
+ const listed = await execFileAsync("git", ["-C", worktreePath, "ls-tree", "-l", "-z", commit, "--", file], { encoding: "buffer", timeout: 30_000 });
632
+ line = listed.stdout.toString("utf8").split("\0").find(Boolean);
633
+ }
634
+ catch {
635
+ return unreadable;
636
+ }
637
+ if (!line)
638
+ return { state: "absent" };
639
+ const match = /^(\d{6}) (\w+) ([0-9a-f]{40,64}) +(\d+|-)\t/.exec(line);
640
+ if (!match || match[2] !== "blob" || (match[1] !== "100644" && match[1] !== "100755")) {
641
+ return { state: "invalid", detail: `${name} is not a regular file` };
642
+ }
643
+ if (Number(match[4]) > MAX_INPUT_BYTES)
644
+ return { state: "invalid", detail: `${name} is larger than 64 MB` };
645
+ try {
646
+ const blob = await execFileAsync("git", ["-C", worktreePath, "cat-file", "blob", match[3]], { encoding: "buffer", timeout: 30_000, maxBuffer: MAX_INPUT_BYTES + 1 });
647
+ return { state: "file", data: blob.stdout };
648
+ }
649
+ catch {
650
+ return unreadable;
651
+ }
652
+ }
556
653
  async function touch(file) {
557
654
  const now = new Date();
558
655
  await node_fs_1.promises.utimes(file, now, now).catch(() => undefined);
@@ -427,6 +427,28 @@ class GitWorktree {
427
427
  return null;
428
428
  }
429
429
  }
430
+ /**
431
+ * Fetches a pull request's head for dependency preparation. The worktree-local
432
+ * ref keeps the commit reachable for this session and avoids races with other
433
+ * sessions fetching the same pull request into the shared repository.
434
+ */
435
+ async fetchPullRequestHead(pullRequestNumber, signal) {
436
+ if (!Number.isSafeInteger(pullRequestNumber) || pullRequestNumber <= 0)
437
+ return null;
438
+ if (signal?.aborted)
439
+ return null;
440
+ const localRef = `refs/worktree/navarch/pull/${pullRequestNumber}/head`;
441
+ const options = { signal, timeoutMs: 30_000 };
442
+ try {
443
+ await this.runGit(["-C", this.worktreePath, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "origin", `+refs/pull/${pullRequestNumber}/head:${localRef}`], true, options);
444
+ const resolved = await this.runGit(["-C", this.worktreePath, "rev-parse", "--verify", `${localRef}^{commit}`], false, options);
445
+ const sha = resolved.stdout.trim();
446
+ return /^[0-9a-f]{40,64}$/i.test(sha) ? sha : null;
447
+ }
448
+ catch {
449
+ return null;
450
+ }
451
+ }
430
452
  /**
431
453
  * Puts the snapshot's files in the working tree as uncommitted edits on top
432
454
  * of the branch, which already sits on the hosted agent's HEAD: the state the
@@ -858,11 +880,11 @@ class GitWorktree {
858
880
  throw error;
859
881
  }
860
882
  }
861
- async runGit(args, authenticated) {
883
+ async runGit(args, authenticated, options) {
862
884
  if (authenticated && this.gitGrant) {
863
885
  // The helper reads the grant file the runtime refreshes; no token enters
864
886
  // argv or the environment.
865
- const grantResult = await this.runner.run("git", ["-c", "credential.helper=", "-c", `credential.helper=${this.gitGrant.credentialHelper}`, ...args], { env: gitEnvWithoutGithubTokens() });
887
+ const grantResult = await this.runner.run("git", ["-c", "credential.helper=", "-c", `credential.helper=${this.gitGrant.credentialHelper}`, ...args], { ...options, env: gitEnvWithoutGithubTokens() });
866
888
  if (grantResult.code !== 0) {
867
889
  throw new Error(`git ${args[0] ?? "command"} failed: ${grantResult.stderr || grantResult.stdout}`);
868
890
  }
@@ -878,6 +900,7 @@ class GitWorktree {
878
900
  ]
879
901
  : [];
880
902
  const result = await this.runner.run("git", [...credentialArgs, ...args], {
903
+ ...options,
881
904
  env: githubToken
882
905
  ? { ...process.env, GITHUB_TOKEN: githubToken, GIT_TERMINAL_PROMPT: "0" }
883
906
  : { ...process.env, GIT_TERMINAL_PROMPT: "0" },
@@ -4,6 +4,7 @@ exports.LiveTranscriptPublisher = void 0;
4
4
  exports.renderSessionTranscript = renderSessionTranscript;
5
5
  exports.renderLiveTranscript = renderLiveTranscript;
6
6
  exports.liveUploadIntervalMs = liveUploadIntervalMs;
7
+ const upload_errors_cjs_1 = require("./upload-errors.cjs");
7
8
  /** The shape both the live snapshots and the completion upload use. */
8
9
  function renderSessionTranscript(attempts, redact) {
9
10
  return attempts
@@ -46,6 +47,8 @@ function renderLiveTranscript(attempts, currentStdout, redact, knownSecrets = []
46
47
  /** Signed upload URLs last an hour; refresh well before that. */
47
48
  const UPLOAD_URL_TTL_MS = 45 * 60_000;
48
49
  const DEFAULT_INTERVAL_MS = 10_000;
50
+ /** Longest wait between retries while storage keeps failing. */
51
+ const MAX_FAILURE_BACKOFF_MS = 5 * 60_000;
49
52
  function liveUploadIntervalMs(bytes, baseMs = DEFAULT_INTERVAL_MS) {
50
53
  if (bytes > 8 * 1024 * 1024)
51
54
  return Math.max(baseMs, 60_000);
@@ -66,6 +69,7 @@ class LiveTranscriptPublisher {
66
69
  lastUploaded = "";
67
70
  uploadUrl = null;
68
71
  published = null;
72
+ failures = 0;
69
73
  constructor(options) {
70
74
  this.options = options;
71
75
  this.now = options.now ?? Date.now;
@@ -100,7 +104,12 @@ class LiveTranscriptPublisher {
100
104
  schedule() {
101
105
  if (this.timer || this.inFlight || this.stopped || this.paused)
102
106
  return;
103
- const gap = liveUploadIntervalMs(this.lastUploaded.length, this.intervalMs);
107
+ const base = liveUploadIntervalMs(this.lastUploaded.length, this.intervalMs);
108
+ // While storage keeps failing, double the wait per failure instead of
109
+ // re-sending a multi-megabyte snapshot into an outage every interval.
110
+ const gap = this.failures
111
+ ? Math.max(base, Math.min(base * 2 ** this.failures, MAX_FAILURE_BACKOFF_MS))
112
+ : base;
104
113
  const wait = Math.max(0, this.lastUploadedAt + gap - this.now());
105
114
  this.timer = setTimeout(() => {
106
115
  this.timer = null;
@@ -129,11 +138,20 @@ class LiveTranscriptPublisher {
129
138
  await this.options.upload(this.uploadUrl.url, content);
130
139
  this.lastUploaded = content;
131
140
  this.published = this.uploadUrl.publicUrl;
141
+ if (this.failures)
142
+ this.options.onRecover?.(this.failures);
143
+ this.failures = 0;
132
144
  }
133
145
  catch (error) {
134
- // A rejected signature is refreshed on the next attempt.
135
- this.uploadUrl = null;
136
- this.options.onError?.(error);
146
+ // A storage outage says nothing about the signature, so keep the URL;
147
+ // anything else (an expired or rejected signature) gets a fresh one.
148
+ if (!(0, upload_errors_cjs_1.isTransientUploadError)(error))
149
+ this.uploadUrl = null;
150
+ this.failures += 1;
151
+ this.options.onError?.(error, this.failures);
152
+ // Retry the unsent snapshot even if the agent goes quiet.
153
+ if (!this.paused && !this.stopped)
154
+ this.dirty = true;
137
155
  }
138
156
  finally {
139
157
  this.lastUploadedAt = this.now();
package/dist/session.cjs CHANGED
@@ -64,6 +64,9 @@ const DELIVERY_CORRECTION_RETRIES = 1;
64
64
  */
65
65
  const STEERING_COMPLETION_RESENDS = 3;
66
66
  const STEERING_COMPLETION_RESEND_DELAY_MS = 1_000;
67
+ /** Final transcript PUT: 1 s, 2 s, 4 s between attempts rides out a short
68
+ * R2 blip without holding completion for long. */
69
+ const COMPLETION_UPLOAD_RETRY = { attempts: 4, baseDelayMs: 1_000 };
67
70
  /**
68
71
  * How long an agent process may run before the messages in its prompt count as
69
72
  * delivered, when it has printed nothing yet. A launch that fails does so
@@ -851,6 +854,20 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
851
854
  activeAbortController = dependencyAbort;
852
855
  if (leaseLost || deps.shutdownSignal?.aborted)
853
856
  dependencyAbort.abort();
857
+ // A verify or review checks the pull request's head in a detached
858
+ // worktree, not this checkout's claim commit. When the pull request
859
+ // changes the lockfile, dependencies from the claim commit are the wrong
860
+ // packages (sagentlab/navarch#3266: verify had an SDK without the new
861
+ // API and ended BLOCKED). Install from the head's lockfile instead.
862
+ const checkedPullRequest = task.task_type === "verify" || task.task_type === "review"
863
+ ? (0, dependency_cache_cjs_1.pullRequestNumberInRepository)(task.github_issue_url, bundle.repository?.full_name ?? task.repo)
864
+ : null;
865
+ const checkedHeadSha = checkedPullRequest
866
+ ? await gitWorktree.fetchPullRequestHead(checkedPullRequest, dependencyAbort.signal)
867
+ : null;
868
+ if (checkedPullRequest && !checkedHeadSha && !dependencyAbort.signal.aborted) {
869
+ log.warn(`dependency cache for ${leaseId}: pull request #${checkedPullRequest} head could not be fetched; using the checkout's lockfile.`);
870
+ }
854
871
  const dependencyResults = await (0, dependency_cache_cjs_1.prepareDependencyCache)({
855
872
  cacheRoot: node_path_1.default.join(config.workspaceRoot, dependency_cache_cjs_1.DEPENDENCY_CACHE_DIRNAME),
856
873
  worktreePath: gitWorktree.worktreePath,
@@ -858,6 +875,7 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
858
875
  repository: task.repo,
859
876
  timeoutMs: config.dependencyCacheTimeoutMs,
860
877
  signal: dependencyAbort.signal,
878
+ ...(checkedHeadSha ? { inputsCommit: checkedHeadSha } : {}),
861
879
  }).catch((error) => {
862
880
  log.warn(`dependency cache for ${leaseId} failed: ${(0, redact_cjs_1.redactText)(String(error), registry.list())}`);
863
881
  return [];
@@ -871,7 +889,7 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
871
889
  else
872
890
  log.info(message);
873
891
  }
874
- const dependencyNote = (0, dependency_cache_cjs_1.renderDependencyCacheNote)(dependencyResults);
892
+ const dependencyNote = (0, dependency_cache_cjs_1.renderDependencyCacheNote)(dependencyResults, checkedPullRequest ?? undefined);
875
893
  if (dependencyNote) {
876
894
  promptText = `${promptText}\n\n${dependencyNote}`;
877
895
  await node_fs_1.promises.writeFile(node_path_1.default.join(workDir, "prompt.md"), promptText, "utf8");
@@ -913,7 +931,10 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
913
931
  },
914
932
  upload: upload_cjs_1.uploadTranscript,
915
933
  render: () => (0, live_transcript_cjs_1.renderLiveTranscript)(attempts, liveStdout, (text) => (0, redact_cjs_1.redactText)(text, registry.list()), registry.list()),
916
- onError: (error) => log.warn(`live transcript upload failed for ${leaseId}: ${(0, redact_cjs_1.redactText)(String(error), registry.list())}`),
934
+ onError: (error, failures) => log.warn(`live transcript upload failed for ${leaseId}` +
935
+ `${failures > 1 ? ` (${failures} in a row; retrying with backoff)` : ""}: ` +
936
+ (0, redact_cjs_1.redactText)(String(error), registry.list())),
937
+ onRecover: (failures) => log.info(`live transcript upload for ${leaseId} recovered after ${failures} failed attempt(s)`),
917
938
  });
918
939
  const agentBudgetStartedAt = node_perf_hooks_1.performance.now();
919
940
  const maxRuntimeMs = task.max_runtime_ms ?? config.sessionTimeoutMs;
@@ -1361,7 +1382,9 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
1361
1382
  let transcriptUrl;
1362
1383
  try {
1363
1384
  const { upload_url, public_url } = await api.getTranscriptUploadUrl(leaseId);
1364
- await (0, upload_cjs_1.uploadTranscript)(upload_url, transcript);
1385
+ // The final transcript is the one the task view keeps, so ride out a
1386
+ // short storage blip (R2 InternalError 500s) instead of dropping it.
1387
+ await (0, upload_cjs_1.uploadTranscript)(upload_url, transcript, fetch, COMPLETION_UPLOAD_RETRY);
1365
1388
  transcriptUrl = public_url;
1366
1389
  }
1367
1390
  catch (err) {
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ /**
3
+ * Transcript upload failure classification, kept apart from upload.cts so
4
+ * modules that only classify failures (live-transcript.cts) do not depend on
5
+ * the upload implementation that tests replace wholesale.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.TranscriptUploadError = void 0;
9
+ exports.isTransientUploadError = isTransientUploadError;
10
+ /** A failed transcript PUT. `status` is null when no response arrived. */
11
+ class TranscriptUploadError extends Error {
12
+ status;
13
+ constructor(message, status) {
14
+ super(message);
15
+ this.status = status;
16
+ this.name = "TranscriptUploadError";
17
+ }
18
+ }
19
+ exports.TranscriptUploadError = TranscriptUploadError;
20
+ /**
21
+ * Storage-side failures (R2 `InternalError` 500s, 503s, throttling, a dropped
22
+ * connection) say nothing about the signed URL, so the same URL is worth
23
+ * retrying. Any other failure, such as a 403 for an expired signature, needs a
24
+ * fresh URL.
25
+ */
26
+ function isTransientUploadError(error) {
27
+ if (!(error instanceof TranscriptUploadError))
28
+ return false;
29
+ return error.status === null || error.status === 429 || error.status >= 500;
30
+ }
package/dist/upload.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isTransientUploadError = exports.TranscriptUploadError = void 0;
3
4
  exports.uploadTranscript = uploadTranscript;
4
5
  /**
5
6
  * PUTs an already-redacted transcript to the presigned R2 URL the
@@ -7,18 +8,44 @@ exports.uploadTranscript = uploadTranscript;
7
8
  * implementation-plan.md WP-07). Kept as its own module so the storage
8
9
  * mechanism is a one-function swap if it ever changes.
9
10
  */
11
+ const upload_errors_cjs_1 = require("./upload-errors.cjs");
12
+ Object.defineProperty(exports, "TranscriptUploadError", { enumerable: true, get: function () { return upload_errors_cjs_1.TranscriptUploadError; } });
13
+ Object.defineProperty(exports, "isTransientUploadError", { enumerable: true, get: function () { return upload_errors_cjs_1.isTransientUploadError; } });
10
14
  /** Storage error bodies are small JSON blobs; cap in case we get an HTML page. */
11
15
  const MAX_ERROR_BODY = 500;
12
- async function uploadTranscript(uploadUrl, content, fetchImpl = fetch) {
13
- const response = await fetchImpl(uploadUrl, {
14
- method: "PUT",
15
- headers: { "content-type": "text/plain; charset=utf-8" },
16
- body: content,
17
- });
16
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
17
+ async function uploadTranscript(uploadUrl, content, fetchImpl = fetch, retry = {}) {
18
+ const attempts = Math.max(1, retry.attempts ?? 1);
19
+ const baseDelayMs = retry.baseDelayMs ?? 1_000;
20
+ const sleep = retry.sleep ?? defaultSleep;
21
+ for (let attempt = 1;; attempt += 1) {
22
+ try {
23
+ await putOnce(uploadUrl, content, fetchImpl);
24
+ return;
25
+ }
26
+ catch (error) {
27
+ if (attempt >= attempts || !(0, upload_errors_cjs_1.isTransientUploadError)(error))
28
+ throw error;
29
+ await sleep(baseDelayMs * 2 ** (attempt - 1));
30
+ }
31
+ }
32
+ }
33
+ async function putOnce(uploadUrl, content, fetchImpl) {
34
+ let response;
35
+ try {
36
+ response = await fetchImpl(uploadUrl, {
37
+ method: "PUT",
38
+ headers: { "content-type": "text/plain; charset=utf-8" },
39
+ body: content,
40
+ });
41
+ }
42
+ catch (error) {
43
+ throw new upload_errors_cjs_1.TranscriptUploadError(`Transcript upload failed: ${String(error)}`, null);
44
+ }
18
45
  if (!response.ok) {
19
46
  // Include the bounded storage response to distinguish expired signatures
20
47
  // from bucket misconfiguration.
21
- throw new Error(`Transcript upload failed with ${response.status}: ${await readErrorBody(response)}`);
48
+ throw new upload_errors_cjs_1.TranscriptUploadError(`Transcript upload failed with ${response.status}: ${await readErrorBody(response)}`, response.status);
22
49
  }
23
50
  }
24
51
  async function readErrorBody(response) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sagentlab/navarch-runtime",
3
- "version": "0.1.173",
3
+ "version": "0.1.175",
4
4
  "description": "Navarch machine-side session manager: claims delivery tasks and runs them through local coding agents.",
5
5
  "type": "commonjs",
6
6
  "license": "MIT",