@sagentlab/navarch-runtime 0.1.155 → 0.1.158

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.
@@ -289,27 +289,24 @@ function isJqAlternativeOperator(command, start, token, heredocs) {
289
289
  }
290
290
 
291
291
  /**
292
- * True when a "/"-leading token is comment or markup text rather than a path:
293
- * a closing tag (`</p>`), a block-comment opener (`/**`, `/*`), or a line
294
- * comment (`// note`). Each rule is deliberately narrow so real escapes stay
295
- * screened: tag names that exist at the filesystem root (`</home>`) are still
296
- * checked, `/*` and `//` only count at a comment position (line start, right
297
- * after an opening quote, or after `;`) so `rm -rf /*`, `find // -name x`
292
+ * True when a "/"-leading token is comment text rather than a path:
293
+ * a block-comment opener (`/**`, `/*`) or a line comment (`// note`).
294
+ * Closing tags use mayNameRootEntry instead: `</home>out` is also a shell
295
+ * redirection, so policy roots must stay screened even when hidden or absent.
296
+ * Each comment rule is deliberately narrow: `/*` and `//` only count at a
297
+ * comment position (line start, right after an opening quote, or after `;`)
298
+ * so `rm -rf /*`, `find // -name x`
298
299
  * and `rm -rf "" /*` stay blocked, and a block comment needs a closing
299
300
  * `*` + `/` later in the text. The jq alternative operator inside a quoted jq
300
301
  * program is exempt under the separate, narrower rule in
301
302
  * isJqAlternativeOperator.
302
303
  */
303
- function isCommentOrMarkupToken(command, start, token, heredocs) {
304
+ function isCommentToken(command, start, token, heredocs) {
304
305
  const end = start + token.length;
305
306
  const next = command[end];
306
307
 
307
308
  if (isJqAlternativeOperator(command, start, token, heredocs)) return true;
308
309
 
309
- if (command[start - 1] === "<" && next === ">" && /^\/[A-Za-z][\w:.-]*$/.test(token)) {
310
- return !fs.existsSync(token);
311
- }
312
-
313
310
  const atCommentPosition =
314
311
  isInsideOpeningQuote(command, start) ||
315
312
  ["", ";"].includes(previousSignificantChar(command, start));
@@ -1267,7 +1264,7 @@ function extractBashPathCandidates(command) {
1267
1264
  let match;
1268
1265
  while ((match = absoluteRe.exec(command))) {
1269
1266
  const start = match.index + match[0].length - match[1].length;
1270
- if (isCommentOrMarkupToken(command, start, match[1], getHeredocs)) continue;
1267
+ if (isCommentToken(command, start, match[1], getHeredocs)) continue;
1271
1268
  const token = clean(match[1]);
1272
1269
  // Quotes keep `$`, `(` and `{` literal only for a command that does not
1273
1270
  // hand the word to a shell, such as `sed '/^$/d'`; `sh -c '... /$D'` expands.
package/dist/abort.cjs ADDED
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.waitWithAbort = waitWithAbort;
4
+ /** Cancel a wait. Its producer must separately cancel owned side effects. */
5
+ function waitWithAbort(pending, signal) {
6
+ if (!signal)
7
+ return pending;
8
+ return new Promise((resolve, reject) => {
9
+ const abort = () => reject(signal.reason ?? new Error("Aborted"));
10
+ signal.addEventListener("abort", abort, { once: true });
11
+ pending.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
12
+ if (signal.aborted)
13
+ abort();
14
+ });
15
+ }
package/dist/api.cjs CHANGED
@@ -61,6 +61,7 @@ class NavarchApiClient {
61
61
  }
62
62
  headers.authorization = `Bearer ${this.token}`;
63
63
  }
64
+ Object.assign(headers, opts?.headers);
64
65
  const requestUrl = `${this.baseUrl}${pathname}`;
65
66
  const abortController = new AbortController();
66
67
  const timeoutMs = opts?.timeoutMs ?? this.requestTimeoutMs;
@@ -180,9 +181,23 @@ class NavarchApiClient {
180
181
  allowEmpty: true,
181
182
  });
182
183
  }
184
+ async runnerEnvironment(leaseId, signal) {
185
+ return (await this.request("POST", `/api/dispatch/${encodeURIComponent(leaseId)}/environment`, {}, { signal }));
186
+ }
187
+ async postQaResults(leaseId, results) {
188
+ await this.request("POST", "/api/dispatch/qa-results", { results }, {
189
+ headers: { "x-navarch-lease-id": leaseId },
190
+ });
191
+ }
192
+ async artifactTool(leaseId, name, args) {
193
+ const response = await this.request("POST", "/api/mcp", { jsonrpc: "2.0", id: name, method: "tools/call", params: { name, arguments: args } }, { headers: { "x-navarch-lease-id": leaseId, accept: "application/json, text/event-stream", "mcp-protocol-version": "2025-06-18" } });
194
+ if (response?.error || response?.result?.isError || !response?.result?.structuredContent)
195
+ throw new Error(`Artifact ${name} failed`);
196
+ return response.result.structuredContent;
197
+ }
183
198
  /** schema-design.md §7 — `POST /api/broker/issue {lease_id, secret names} → values (scoped, logged)`. */
184
- async issueSecrets(req) {
185
- const result = await this.request("POST", "/api/broker/issue", req);
199
+ async issueSecrets(req, signal) {
200
+ const result = await this.request("POST", "/api/broker/issue", req, { signal });
186
201
  if (!result)
187
202
  throw new Error("issueSecrets: empty response from control plane.");
188
203
  return result;
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.BROWSER_CAPABILITY = void 0;
7
7
  exports.probeBrowserCapability = probeBrowserCapability;
8
8
  exports.capabilitiesAfterBrowserProbe = capabilitiesAfterBrowserProbe;
9
+ exports.qaRunnerCapabilities = qaRunnerCapabilities;
9
10
  exports.codexSandboxNeedsProbe = codexSandboxNeedsProbe;
10
11
  exports.codexSandboxProbeArgs = codexSandboxProbeArgs;
11
12
  exports.summarizeLaunchFailure = summarizeLaunchFailure;
@@ -98,6 +99,12 @@ function capabilitiesAfterBrowserProbe(capabilities, probe) {
98
99
  ? capabilities.filter((capability) => capability !== exports.BROWSER_CAPABILITY)
99
100
  : capabilities;
100
101
  }
102
+ /** This protocol ships in 0.1.158. Skipped probes never qualify a runner. */
103
+ function qaRunnerCapabilities(capabilities, probe, sandboxMode, platform = process.platform) {
104
+ const base = capabilities.filter(capability => capability !== "qa-runner");
105
+ return platform !== "win32" && probe.status === "passed" && sandboxMode === "host" && base.includes(exports.BROWSER_CAPABILITY)
106
+ ? [...base, "qa-runner"] : base;
107
+ }
101
108
  /**
102
109
  * Codex runs agent shell commands under its own OS sandbox (seatbelt on
103
110
  * macOS, Landlock/seccomp on Linux) unless the operator bypassed it. Every
package/dist/cli.cjs CHANGED
@@ -265,7 +265,7 @@ async function startCommand(flags) {
265
265
  }
266
266
  const config = {
267
267
  ...configuredConfig,
268
- capabilities: (0, browser_probe_cjs_1.capabilitiesAfterBrowserProbe)(configuredConfig.capabilities, browserProbe),
268
+ capabilities: (0, browser_probe_cjs_1.qaRunnerCapabilities)((0, browser_probe_cjs_1.capabilitiesAfterBrowserProbe)(configuredConfig.capabilities, browserProbe), browserProbe, configuredConfig.sandboxMode),
269
269
  };
270
270
  const api = new api_cjs_1.NavarchApiClient({ baseUrl: identity.api_base, token: identity.token });
271
271
  const capacity = new capacity_cjs_1.CapacityTracker(config.maxSessions);
@@ -8,6 +8,7 @@ exports.proxyCloneUrl = proxyCloneUrl;
8
8
  exports.branchSlug = branchSlug;
9
9
  exports.hostedCheckpointRef = hostedCheckpointRef;
10
10
  const node_path_1 = __importDefault(require("node:path"));
11
+ const abort_cjs_1 = require("./abort.cjs");
11
12
  const worktree_janitor_cjs_1 = require("./worktree-janitor.cjs");
12
13
  const node_fs_1 = require("node:fs");
13
14
  const sandbox_cjs_1 = require("./sandbox.cjs");
@@ -102,10 +103,12 @@ class GitWorktree {
102
103
  this.hostedCheckpointRef = options.restoreHostedCheckpoint ? hostedCheckpointRef(options.taskId) : null;
103
104
  this.hostedCheckpointLocalRef = `refs/navarch/restored-checkpoints/${taskKey}`;
104
105
  }
105
- async prepare() {
106
+ async prepare(signal) {
107
+ signal?.throwIfAborted();
106
108
  await node_fs_1.promises.mkdir(node_path_1.default.dirname(this.repositoryPath), { recursive: true });
107
109
  await node_fs_1.promises.mkdir(this.sessionRoot, { recursive: true });
108
110
  await withRepositoryLock(this.repositoryPath, async () => {
111
+ signal?.throwIfAborted();
109
112
  await this.ensureRepositoryCache();
110
113
  await this.installDeliveryBranchGuard();
111
114
  try {
@@ -122,7 +125,7 @@ class GitWorktree {
122
125
  `active worktrees; retry after active sessions finish or repair the cache in place: ${errorMessage(error)}`);
123
126
  }
124
127
  await this.installRepoLocalGithubToken();
125
- });
128
+ }, signal);
126
129
  }
127
130
  /**
128
131
  * Makes a broker-issued GitHub credential visible to workflows that require
@@ -798,7 +801,7 @@ function removeMarkedConfigBlock(config, marker) {
798
801
  const endNewline = config.indexOf("\n", endStart + end.length);
799
802
  return config.slice(0, blockStart) + config.slice(endNewline < 0 ? config.length : endNewline + 1);
800
803
  }
801
- async function withRepositoryLock(key, work) {
804
+ async function withRepositoryLock(key, work, signal) {
802
805
  const previous = repositoryLocks.get(key) ?? Promise.resolve();
803
806
  let release;
804
807
  const current = new Promise((resolve) => {
@@ -806,14 +809,16 @@ async function withRepositoryLock(key, work) {
806
809
  });
807
810
  const queued = previous.then(() => current);
808
811
  repositoryLocks.set(key, queued);
809
- await previous;
810
812
  try {
813
+ await (0, abort_cjs_1.waitWithAbort)(previous, signal);
814
+ signal?.throwIfAborted();
811
815
  return await work();
812
816
  }
813
817
  finally {
814
818
  release();
815
- if (repositoryLocks.get(key) === queued)
816
- repositoryLocks.delete(key);
819
+ // An aborted waiter must not unlock the preceding owner's operation.
820
+ void queued.then(() => { if (repositoryLocks.get(key) === queued)
821
+ repositoryLocks.delete(key); });
817
822
  }
818
823
  }
819
824
  async function pathExists(value) {
@@ -13,6 +13,7 @@ const node_crypto_1 = require("node:crypto");
13
13
  const node_fs_1 = require("node:fs");
14
14
  const node_os_1 = __importDefault(require("node:os"));
15
15
  const node_path_1 = __importDefault(require("node:path"));
16
+ const abort_cjs_1 = require("./abort.cjs");
16
17
  const zod_1 = require("zod");
17
18
  const dependency_cache_cjs_1 = require("./dependency-cache.cjs");
18
19
  const kill_agent_cjs_1 = require("./kill-agent.cjs");
@@ -152,7 +153,7 @@ function createPlaywrightServer(options) {
152
153
  let queue = Promise.resolve();
153
154
  let closed = false;
154
155
  const assertActive = () => {
155
- if (closed || !options.isActive())
156
+ if (closed || options.signal?.aborted || !options.isActive())
156
157
  throw new Error("The Playwright browser server's lease is no longer active.");
157
158
  };
158
159
  async function stop() {
@@ -168,7 +169,9 @@ function createPlaywrightServer(options) {
168
169
  }
169
170
  /** Installs playwright-core@version and its Chromium once per machine; returns the package dir. */
170
171
  function ensureInstalled(version) {
171
- const key = `${node_path_1.default.resolve(options.cacheRoot)}\0${version}`;
172
+ // A cancellable runner owns its install promise. Its deadline must not
173
+ // cancel another lease waiting for the same package version.
174
+ const key = `${node_path_1.default.resolve(options.cacheRoot)}\0${version}${options.signal ? `\0${options.workDir}` : ""}`;
172
175
  let pending = installs.get(key);
173
176
  if (!pending) {
174
177
  pending = install(version).finally(() => installs.delete(key));
@@ -200,11 +203,12 @@ function createPlaywrightServer(options) {
200
203
  "--logs-dir",
201
204
  node_path_1.default.join(options.cacheRoot, ".logs"),
202
205
  `playwright-core@${version}`,
203
- ], { cwd: staging, env: npmEnv, timeoutMs: NPM_TIMEOUT_MS });
206
+ ], { cwd: staging, env: npmEnv, timeoutMs: NPM_TIMEOUT_MS, signal: options.signal });
204
207
  if (result.code !== 0) {
205
208
  log.warn(`npm install playwright-core@${version} exited ${result.code}: ${tail(result.stderr || result.stdout)}`);
206
209
  throw new Error(`The runtime could not install playwright-core@${version} (npm exited ${result.code}).`);
207
210
  }
211
+ assertActive();
208
212
  await node_fs_1.promises.writeFile(node_path_1.default.join(staging, COMPLETE_MARKER), `${new Date().toISOString()}\n`);
209
213
  await node_fs_1.promises.rename(staging, entry).catch(async (error) => {
210
214
  // Another runtime process finished the same version first.
@@ -221,6 +225,7 @@ function createPlaywrightServer(options) {
221
225
  cwd: entry,
222
226
  env: npmEnv,
223
227
  timeoutMs: BROWSER_INSTALL_TIMEOUT_MS,
228
+ signal: options.signal,
224
229
  });
225
230
  if (browser.code !== 0) {
226
231
  log.warn(`playwright-core@${version} install chromium exited ${browser.code}: ${tail(browser.stderr || browser.stdout)}`);
@@ -273,8 +278,10 @@ function createPlaywrightServer(options) {
273
278
  let stdout = "";
274
279
  let stderr = "";
275
280
  const timer = setTimeout(() => fail(new Error("did not start within 60 s")), START_TIMEOUT_MS);
281
+ const abort = () => fail(new Error("lease execution cancelled"));
276
282
  const fail = (error) => {
277
283
  clearTimeout(timer);
284
+ options.signal?.removeEventListener("abort", abort);
278
285
  (0, kill_agent_cjs_1.killAgent)(child);
279
286
  reject(new Error(`The Playwright ${version} browser server could not start: ${error.message}${launchDetail(stderr)}`));
280
287
  };
@@ -284,6 +291,7 @@ function createPlaywrightServer(options) {
284
291
  if (!match)
285
292
  return;
286
293
  clearTimeout(timer);
294
+ options.signal?.removeEventListener("abort", abort);
287
295
  running = { child, endpoint: match[1], version };
288
296
  resolve(match[1]);
289
297
  });
@@ -292,6 +300,9 @@ function createPlaywrightServer(options) {
292
300
  stderr += chunk.toString();
293
301
  });
294
302
  child.on("error", fail);
303
+ options.signal?.addEventListener("abort", abort, { once: true });
304
+ if (options.signal?.aborted)
305
+ abort();
295
306
  child.on("exit", (code, signal) => {
296
307
  if (running?.child === child)
297
308
  running = undefined;
@@ -314,7 +325,7 @@ function createPlaywrightServer(options) {
314
325
  return { endpoint: live.endpoint, version, reused: true };
315
326
  }
316
327
  await stop();
317
- const coreDir = await ensureInstalled(version);
328
+ const coreDir = await (0, abort_cjs_1.waitWithAbort)(ensureInstalled(version), options.signal);
318
329
  assertActive();
319
330
  const endpoint = await launch(version, coreDir);
320
331
  if (closed || !options.isActive()) {
@@ -0,0 +1,275 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.qaCaseGrep = void 0;
7
+ exports.parseQaReport = parseQaReport;
8
+ exports.qaSelectionArgs = qaSelectionArgs;
9
+ exports.runnerCommandScript = runnerCommandScript;
10
+ exports.executeQaRunner = executeQaRunner;
11
+ const node_fs_1 = require("node:fs");
12
+ const node_path_1 = __importDefault(require("node:path"));
13
+ const node_crypto_1 = require("node:crypto");
14
+ const sandbox_cjs_1 = require("./sandbox.cjs");
15
+ const playwright_server_cjs_1 = require("./playwright-server.cjs");
16
+ const lease_heartbeat_cjs_1 = require("./lease-heartbeat.cjs");
17
+ const api_cjs_1 = require("./api.cjs");
18
+ /** Aggregate every matching test/project: one failed viewport fails the case. */
19
+ function parseQaReport(raw, assignment, missingReason = "automation_missing") {
20
+ if (!raw || typeof raw !== "object" || !Array.isArray(raw.suites))
21
+ throw new Error("Invalid Playwright JSON report");
22
+ const found = new Map();
23
+ const selected = new Set(assignment.items.map(item => item.case_id));
24
+ const walk = (suite, parents) => {
25
+ const titles = [...parents, suite.title ?? ""];
26
+ for (const spec of suite.specs ?? []) {
27
+ for (const test of spec.tests ?? []) {
28
+ const text = [...titles, spec.title ?? "", ...(spec.tags ?? []), ...(test.tags ?? [])].join(" ");
29
+ const ids = new Set([...text.matchAll(/@TC-[A-Z0-9]+(?:-[A-Z0-9]+)*(?:#[1-9][0-9]*)?(?![A-Za-z0-9_#-])/g)].map(match => match[0].slice(1)));
30
+ const attempts = test.results ?? [];
31
+ const last = attempts.at(-1);
32
+ // Expected failures are still product failures for case reporting.
33
+ const status = last?.status === "passed" ? "passed" : last?.status === "skipped" ? "skipped" : last?.status === "interrupted" && missingReason === "runner_timeout" ? "blocked" : "failed";
34
+ for (const id of ids) {
35
+ if (!selected.has(id) || !last)
36
+ continue;
37
+ const rows = found.get(id) ?? [];
38
+ rows.push({ run_id: assignment.run.id, case_id: id, attempt: 1, status,
39
+ flaky: status === "passed" && ((last.retry ?? 0) > 0 || attempts.some(result => ["failed", "timedOut", "interrupted"].includes(result.status ?? ""))),
40
+ duration_ms: Math.min(2147483647, attempts.reduce((sum, result) => sum + Math.max(0, result.duration ?? 0), 0)),
41
+ ...(["failed", "blocked"].includes(status) ? { failure_summary: status === "blocked" ? missingReason : (last.error?.message ?? `Playwright: ${last.status ?? "unknown"}`).slice(0, 8000) } : {}),
42
+ traces: attempts.flatMap(result => (result.attachments ?? []).filter(a => a.name === "trace" && a.path).map(a => a.path)),
43
+ });
44
+ found.set(id, rows);
45
+ }
46
+ }
47
+ }
48
+ for (const child of suite.suites ?? [])
49
+ walk(child, titles);
50
+ };
51
+ walk(raw, []);
52
+ return assignment.items.filter(item => ["queued", "running"].includes(item.status)).map(item => {
53
+ const rows = found.get(item.case_id) ?? [];
54
+ const failed = rows.find(row => row.status === "failed");
55
+ const blocked = rows.find(row => row.status === "blocked");
56
+ const skipped = rows.some(row => row.status === "skipped");
57
+ return { run_id: assignment.run.id, case_id: item.case_id, attempt: item.attempt ?? 1,
58
+ status: failed ? "failed" : blocked ? "blocked" : skipped ? "skipped" : rows.length ? "passed" : "blocked",
59
+ flaky: rows.some(row => row.flaky), duration_ms: Math.min(2147483647, rows.reduce((sum, row) => sum + (row.duration_ms ?? 0), 0)),
60
+ ...(!rows.length ? { failure_summary: missingReason } : failed || blocked ? { failure_summary: (failed ?? blocked).failure_summary } : {}),
61
+ traces: [...new Set(rows.flatMap(row => row.traces))], };
62
+ });
63
+ }
64
+ const qaCaseGrep = (ids) => `@(?:${ids.map(id => id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})(?![A-Za-z0-9_#-])`;
65
+ exports.qaCaseGrep = qaCaseGrep;
66
+ /** Long selections live in config, never in argv or one oversized env value. */
67
+ async function qaSelectionArgs(repo, workDir, ids) {
68
+ const grep = (0, exports.qaCaseGrep)(ids);
69
+ if (Buffer.byteLength(grep) < 16_000)
70
+ return ["--grep", grep];
71
+ const selection = node_path_1.default.join(workDir, "qa-selection.txt");
72
+ const config = node_path_1.default.join(repo, ".navarch-qa-playwright.config.mts");
73
+ await node_fs_1.promises.writeFile(selection, grep);
74
+ let original;
75
+ for (const ext of ["ts", "js", "mts", "mjs", "cts", "cjs"]) {
76
+ const candidate = node_path_1.default.join(repo, `playwright.config.${ext}`);
77
+ if (await node_fs_1.promises.stat(candidate).then(s => s.isFile(), () => false)) {
78
+ original = candidate;
79
+ break;
80
+ }
81
+ }
82
+ await node_fs_1.promises.writeFile(config, `${original ? `import base from ${JSON.stringify(original)};` : "const base = {};"}
83
+ import { readFileSync } from 'node:fs';
84
+ const grep = new RegExp(readFileSync(${JSON.stringify(selection)}, 'utf8'));
85
+ export default { ...base, grep, ...(base.projects ? { projects: base.projects.map(project => ({ ...project, grep })) } : {}) };
86
+ `);
87
+ return ["--config", config];
88
+ }
89
+ /** Forward explicit positional args, or append them to a final simple CLI.
90
+ * Reject ambiguous shell syntax before executing an unfiltered suite. */
91
+ function runnerCommandScript(run) {
92
+ const body = run.trimEnd();
93
+ const last = body.split("\n").at(-1) ?? "";
94
+ if (!last.includes("#") && /"\$(?:@|\{@\})"$/.test(last))
95
+ return body;
96
+ if (!last.trim() || /[#;{}|&<>`]/.test(last) || /^\s*(?:if|then|else|fi|do|done|esac|case|for|while|until)\b/.test(last)) {
97
+ throw new Error('Runner command must end in a simple CLI invocation or forward "$@" explicitly');
98
+ }
99
+ return `${body} "$@"`;
100
+ }
101
+ /** Repository commands receive recipe variables and their declared secrets only. */
102
+ function baseEnvironment() {
103
+ return Object.fromEntries(["PATH", "HOME", "TMPDIR", "TEMP", "TMP", "SystemRoot", "LANG"].flatMap(key => process.env[key] === undefined ? [] : [[key, process.env[key]]]));
104
+ }
105
+ async function executeQaRunner(deps) {
106
+ const { api, claimed, repo, workDir } = deps;
107
+ const leaseId = claimed.lease_id;
108
+ const assignment = claimed.context_bundle.qa_run_assignment;
109
+ if (!assignment)
110
+ throw new Error("Runner shard has no assignment");
111
+ if (!/^[a-f0-9]{40}$/i.test(assignment.target.commit_sha))
112
+ throw new Error("Invalid run commit");
113
+ if (!assignment.items.some(item => ["queued", "running"].includes(item.status))) {
114
+ await api.completeLease(leaseId, { status: "completed", report: "QA runner: all shard cases already reported.", evidence_urls: [],
115
+ cost: { tokens_in: 0, tokens_out: 0, cost_usd: 0 }, exit_status: "completed", sandbox_profile: "host" });
116
+ return;
117
+ }
118
+ const runner = deps.runner ?? sandbox_cjs_1.nodeCommandRunner;
119
+ const controller = new AbortController();
120
+ let timedOut = false, leaseLost = false, heartbeatBusy = false;
121
+ const shutdown = () => { leaseLost = true; controller.abort(); };
122
+ deps.signal?.addEventListener("abort", shutdown, { once: true });
123
+ if (deps.signal?.aborted)
124
+ shutdown();
125
+ const guard = new lease_heartbeat_cjs_1.LeaseHeartbeatGuard(claimed.expires_at, shutdown);
126
+ const timer = deps.maxRuntimeMs > 0 ? setTimeout(() => { timedOut = true; controller.abort(); }, deps.maxRuntimeMs) : undefined;
127
+ const heartbeat = setInterval(() => {
128
+ if (heartbeatBusy || leaseLost)
129
+ return;
130
+ heartbeatBusy = true;
131
+ void api.heartbeatLease(leaseId).then(result => {
132
+ if (result)
133
+ guard.renew(result.expires_at);
134
+ }).catch(error => {
135
+ if (error instanceof api_cjs_1.NavarchApiError && [403, 404, 409, 410].includes(error.status))
136
+ shutdown();
137
+ }).finally(() => { heartbeatBusy = false; });
138
+ }, deps.heartbeatMs);
139
+ const server = deps.browserServer ?? (0, playwright_server_cjs_1.createPlaywrightServer)({ worktreePath: repo, workDir,
140
+ signal: controller.signal, cacheRoot: node_path_1.default.join(deps.workspaceRoot, playwright_server_cjs_1.PLAYWRIGHT_SERVER_DIRNAME), isActive: () => !controller.signal.aborted });
141
+ const jsonFile = node_path_1.default.join(workDir, "playwright.json");
142
+ const htmlDir = node_path_1.default.join(workDir, "playwright-report");
143
+ const traceDir = node_path_1.default.join(workDir, "test-results");
144
+ let report = { suites: [] }, failure;
145
+ const run = async (bin, args, env, timeoutMs) => {
146
+ controller.signal.throwIfAborted();
147
+ const result = await runner.run(bin, args, { cwd: repo, env, timeoutMs, signal: controller.signal });
148
+ controller.signal.throwIfAborted();
149
+ return result;
150
+ };
151
+ try {
152
+ try {
153
+ await deps.prepare(controller.signal);
154
+ const environment = await api.runnerEnvironment(leaseId, controller.signal);
155
+ const recipe = environment.recipe?.body;
156
+ const commandName = environment.qa_runner?.e2e_command;
157
+ if (!recipe || !commandName || !/^[a-z][a-z0-9_-]{0,31}$/.test(commandName) || !recipe.commands[commandName])
158
+ throw new Error("Runner requires a recipe e2e command");
159
+ const command = recipe.commands[commandName];
160
+ const commandScript = runnerCommandScript(command.run);
161
+ const entryEnv = async (names) => {
162
+ const env = { ...baseEnvironment(), ...recipe.env.vars };
163
+ if (names.length) {
164
+ const issued = await api.issueSecrets({ lease_id: leaseId, secret_names: names }, controller.signal);
165
+ for (const name of names) {
166
+ const value = issued.secrets[name];
167
+ if (typeof value !== "string")
168
+ throw new Error("Runner recipe secret unavailable");
169
+ const converted = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(name) ? name : name.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
170
+ env[/^[0-9]/.test(converted) ? `_${converted}` : converted] = value;
171
+ }
172
+ }
173
+ return env;
174
+ };
175
+ const init = recipe.scripts.initialize;
176
+ if (init) {
177
+ if (environment.skip_phases.initialize)
178
+ throw new Error("Runner initialize phase disabled");
179
+ const result = await run("/bin/sh", ["-eu", "-c", init.run], await entryEnv(init.secrets), init.timeout_s * 1000);
180
+ if (result.code !== 0)
181
+ throw new Error("Runner initialize failed");
182
+ }
183
+ const env = { ...await entryEnv(command.secrets), BASE_URL: assignment.target.url,
184
+ PLAYWRIGHT_JSON_OUTPUT_NAME: jsonFile, PLAYWRIGHT_HTML_OUTPUT_DIR: htmlDir, PLAYWRIGHT_HTML_OPEN: "never" };
185
+ // The runtime is outside the agent sandbox. On macOS the existing server
186
+ // gives loopback fixtures the same restricted browser used by agent suites.
187
+ if (process.platform === "darwin" && ["localhost", "127.0.0.1", "[::1]"].includes(new URL(assignment.target.url).hostname)) {
188
+ env.PW_TEST_CONNECT_WS_ENDPOINT = (await server.start({})).endpoint;
189
+ }
190
+ // navarch-run's command contract: run the configured shell body and append
191
+ // positional arguments. Keep selection and report paths out of shell text.
192
+ const selection = await qaSelectionArgs(repo, workDir, assignment.items.filter(i => ["queued", "running"].includes(i.status)).map(i => i.case_id));
193
+ const executable = node_path_1.default.join(workDir, "navarch-run");
194
+ await node_fs_1.promises.writeFile(executable, `#!/bin/sh\nset -eu\n[ "$1" = ${JSON.stringify(commandName)} ] || exit 64\nshift\n[ "${"${1:-}"}" != -- ] || shift\n${commandScript}\n`, { mode: 0o700 });
195
+ await run(executable, [commandName, "--", ...selection, "--reporter=json,html", "--retries=1", "--trace=retain-on-failure", "--output", traceDir], env, command.timeout_s * 1000);
196
+ }
197
+ catch {
198
+ failure = timedOut ? "runner_timeout" : "runner_error";
199
+ }
200
+ if (leaseLost)
201
+ return;
202
+ try {
203
+ report = JSON.parse(await node_fs_1.promises.readFile(jsonFile, "utf8"));
204
+ }
205
+ catch {
206
+ if (!timedOut)
207
+ failure ??= "runner_error";
208
+ }
209
+ let results;
210
+ try {
211
+ results = parseQaReport(report, assignment, timedOut ? "runner_timeout" : failure ?? "automation_missing");
212
+ }
213
+ catch {
214
+ results = parseQaReport({ suites: [] }, assignment, timedOut ? "runner_timeout" : "runner_error");
215
+ }
216
+ const evidenceUrls = [];
217
+ const upload = async (file, mime) => {
218
+ if (leaseLost)
219
+ throw new Error("Runner lease lost");
220
+ const resolved = await node_fs_1.promises.realpath(file);
221
+ // Reports may contain arbitrary attachment paths; never upload host files.
222
+ const roots = await Promise.all([htmlDir, traceDir].map(dir => node_fs_1.promises.realpath(dir)));
223
+ if (!roots.some(root => resolved.startsWith(root + node_path_1.default.sep)))
224
+ throw new Error("Artifact outside runner workspace");
225
+ const stat = await node_fs_1.promises.stat(resolved);
226
+ if (!stat.isFile() || stat.size > 100 * 1024 * 1024)
227
+ throw new Error("Runner artifact exceeds size limit");
228
+ const bytes = await node_fs_1.promises.readFile(resolved);
229
+ const registered = await api.artifactTool(leaseId, "register_artifact", { file_name: node_path_1.default.basename(file), mime_type: mime,
230
+ size_bytes: bytes.length, checksum_sha256: (0, node_crypto_1.createHash)("sha256").update(bytes).digest("hex") });
231
+ if (typeof registered.upload_url !== "string" || new URL(registered.upload_url).protocol !== "https:" || typeof registered.artifact_version_id !== "string")
232
+ throw new Error("Invalid artifact upload target");
233
+ const uploaded = await (deps.fetchImpl ?? fetch)(registered.upload_url, { method: "PUT",
234
+ headers: { "content-type": mime, "if-none-match": "*" }, body: new Uint8Array(bytes), signal: AbortSignal.timeout(60_000) });
235
+ if (!uploaded.ok)
236
+ throw new Error("Runner artifact upload failed");
237
+ if (leaseLost)
238
+ throw new Error("Runner lease lost");
239
+ const final = await api.artifactTool(leaseId, "finalize_artifact", { artifact_version_id: registered.artifact_version_id });
240
+ if (final.artifact_version_id !== registered.artifact_version_id || typeof final.artifact_id !== "string" || typeof final.public_url !== "string")
241
+ throw new Error("Runner artifact finalization failed");
242
+ evidenceUrls.push(final.public_url);
243
+ return final.artifact_id;
244
+ };
245
+ let htmlId;
246
+ for (const result of results) {
247
+ if (result.status !== "failed")
248
+ continue;
249
+ htmlId ??= await upload(node_path_1.default.join(htmlDir, "index.html"), "text/html");
250
+ result.artifact_ids = [htmlId];
251
+ for (const trace of result.traces.slice(0, 49))
252
+ result.artifact_ids.push(await upload(node_path_1.default.resolve(repo, trace), "application/zip"));
253
+ }
254
+ // Posting and completing remain separate: any failed upload or result post
255
+ // leaves the lease incomplete, so QT-5's unreported-case gate stays effective.
256
+ for (let offset = 0; offset < results.length; offset += 100) {
257
+ if (leaseLost)
258
+ return;
259
+ await api.postQaResults(leaseId, results.slice(offset, offset + 100).map(({ traces: _traces, ...item }) => item));
260
+ }
261
+ if (leaseLost)
262
+ return;
263
+ await api.completeLease(leaseId, { status: "completed", report: `QA runner (${assignment.target.commit_sha}):\n${results.map(item => `${item.case_id}: ${item.status}${item.flaky ? " (flaky)" : ""}${item.failure_summary ? ` — ${item.failure_summary}` : ""}`).join("\n")}`,
264
+ evidence_urls: evidenceUrls, cost: { tokens_in: 0, tokens_out: 0, cost_usd: 0 }, exit_status: "completed", sandbox_profile: "host" });
265
+ }
266
+ finally {
267
+ if (timer)
268
+ clearTimeout(timer);
269
+ clearInterval(heartbeat);
270
+ guard.stop();
271
+ deps.signal?.removeEventListener("abort", shutdown);
272
+ controller.abort();
273
+ await server.close();
274
+ }
275
+ }
package/dist/session.cjs CHANGED
@@ -7,6 +7,7 @@ exports.runSession = runSession;
7
7
  exports.gitGrantCredentialHelper = gitGrantCredentialHelper;
8
8
  exports.toEnvMap = toEnvMap;
9
9
  const muse_cjs_1 = require("./adapters/muse.cjs");
10
+ const qa_runner_cjs_1 = require("./qa-runner.cjs");
10
11
  const node_crypto_1 = require("node:crypto");
11
12
  const node_path_1 = __importDefault(require("node:path"));
12
13
  const node_perf_hooks_1 = require("node:perf_hooks");
@@ -336,6 +337,7 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
336
337
  // `navarch/...` branch. PR-continuation tasks are the exception: their agent
337
338
  // must check out and push the reviewed PR's existing head branch.
338
339
  const allowBranchRename = Boolean(task.review_of_task_id);
340
+ let runnerPreparationSignal;
339
341
  const gitWorktree = new git_worktree_cjs_1.GitWorktree({
340
342
  workspaceRoot: config.workspaceRoot,
341
343
  projectId: task.project_id,
@@ -344,6 +346,9 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
344
346
  taskType: task.task_type,
345
347
  prContinuation: allowBranchRename,
346
348
  sessionId,
349
+ ...(task.skill_inputs?.execution_mode === "runner" ? { runner: {
350
+ run: (cmd, args, opts) => sandbox_cjs_1.nodeCommandRunner.run(cmd, args, { ...opts, signal: runnerPreparationSignal ?? opts?.signal }),
351
+ } } : {}),
347
352
  cloneUrl,
348
353
  githubToken,
349
354
  githubTokenProvider: githubTokenRefresher ? () => githubTokenRefresher.current : undefined,
@@ -362,6 +367,38 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
362
367
  ...(commitIdentity ? { ownershipCommitIdentity: commitIdentity.committer } : {}),
363
368
  });
364
369
  credentialConsumer.worktree = gitWorktree;
370
+ if (task.skill_inputs?.execution_mode === "runner") {
371
+ try {
372
+ if (config.sandboxMode !== "host")
373
+ throw new Error("QA runner requires host execution mode");
374
+ await (0, qa_runner_cjs_1.executeQaRunner)({ api, claimed, workDir, repo: gitWorktree.worktreePath,
375
+ workspaceRoot: config.workspaceRoot, maxRuntimeMs: task.max_runtime_ms ?? config.sessionTimeoutMs,
376
+ heartbeatMs: config.leaseHeartbeatIntervalMs, signal: deps.shutdownSignal,
377
+ prepare: async (signal) => {
378
+ runnerPreparationSignal = signal;
379
+ await gitWorktree.prepare(signal);
380
+ signal.throwIfAborted();
381
+ const sha = bundle.qa_run_assignment?.target.commit_sha;
382
+ if (!sha || !/^[a-f0-9]{40}$/i.test(sha))
383
+ throw new Error("Invalid QA run commit");
384
+ for (const args of [["fetch", "origin", sha], ["checkout", "--detach", sha]]) {
385
+ const result = await sandbox_cjs_1.nodeCommandRunner.run("git", args, { cwd: gitWorktree.worktreePath, env: { ...process.env, ...sessionEnv }, signal });
386
+ if (result.code !== 0)
387
+ throw new Error("QA run commit checkout failed");
388
+ }
389
+ },
390
+ });
391
+ }
392
+ finally {
393
+ runnerPreparationSignal = undefined;
394
+ await gitGrantRefresher?.stopAndClean();
395
+ await githubTokenRefresher?.stopAndClean();
396
+ await (0, session_processes_cjs_1.reapSessionProcesses)(workDir);
397
+ await gitWorktree.cleanup();
398
+ await node_fs_1.promises.rm(workDir, { recursive: true, force: true }).catch(() => undefined);
399
+ }
400
+ return;
401
+ }
365
402
  const knownGuidanceIds = new Set((bundle.guidance ?? []).map((entry) => entry.id));
366
403
  const deliveredGuidance = [...(bundle.guidance ?? [])];
367
404
  let guidanceCursor = bundle.guidance_cursor ?? null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sagentlab/navarch-runtime",
3
- "version": "0.1.155",
3
+ "version": "0.1.158",
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",