@sagentlab/navarch-runtime 0.1.179 → 0.1.181

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.
@@ -47,8 +47,12 @@ async function runClaudeCodeAdapter(options) {
47
47
  if (options.signal?.aborted) {
48
48
  return { exitCode: null, timedOut: false, killedByLeaseLoss: true, stdout: "", stderr: "" };
49
49
  }
50
- const model = options.model ?? DEFAULT_CLAUDE_MODEL;
51
- const automaticFallback = ["claude-fable-5-1", "fable"].includes(model) &&
50
+ const endpointModel = options.env.ANTHROPIC_BASE_URL ? options.env.ANTHROPIC_MODEL : undefined;
51
+ const model = endpointModel ?? options.model ?? DEFAULT_CLAUDE_MODEL;
52
+ if (endpointModel && ["--model", "-m", "--fallback-model"].some((flag) => hasFlag(options.extraArgs, flag))) {
53
+ throw new Error("custom endpoint model cannot be overridden by Claude arguments");
54
+ }
55
+ const automaticFallback = !endpointModel && ["claude-fable-5-1", "fable"].includes(model) &&
52
56
  !hasFlag(options.extraArgs, "--fallback-model");
53
57
  const startedAt = Date.now();
54
58
  const primary = await runClaudeAttempt({ ...options, model }, automaticFallback);
package/dist/delivery.cjs CHANGED
@@ -21,6 +21,8 @@
21
21
  // gate existed. A verification mechanism that fails good sessions when its own
22
22
  // dependency is unavailable is worse than no mechanism.
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.codeupBuildStopLine = codeupBuildStopLine;
25
+ exports.evaluateCodeupDelivery = evaluateCodeupDelivery;
24
26
  exports.captureDeliveryBaseline = captureDeliveryBaseline;
25
27
  exports.probeWorktreeDelivery = probeWorktreeDelivery;
26
28
  exports.evaluateDelivery = evaluateDelivery;
@@ -29,6 +31,32 @@ exports.renderResumedDeliveryCorrectionPrompt = renderResumedDeliveryCorrectionP
29
31
  const sandbox_cjs_1 = require("./sandbox.cjs");
30
32
  const prompt_cjs_1 = require("./prompt.cjs");
31
33
  const GIT_TIMEOUT_MS = 30_000;
34
+ /** Match the root-build stop markers accepted by lib/navarch/build-outcome.ts. */
35
+ function codeupBuildStopLine(report) {
36
+ return report.split(/\r?\n/).map((line) => line.trim()).find((line) => /^Build outcome:[*_`~]*\s*[*_`~]*(?:SUPERSEDED|PLATFORM[ _-]CONFIG)(?![a-z0-9])/i.test(line.replace(/^(?:#{1,6}\s+|>\s*|[*_`~]+\s*)+/, "")));
37
+ }
38
+ async function evaluateCodeupDelivery(probe, requiredBranch) {
39
+ if (probe.dirty) {
40
+ return { status: "incomplete", reason: "the worktree still has uncommitted changes" };
41
+ }
42
+ if (!requiredBranch)
43
+ return { status: "no_changes" };
44
+ const { name, headSha, readRemoteTip } = requiredBranch;
45
+ if (!headSha) {
46
+ return { status: "incomplete", reason: `the local HEAD of Codeup task branch \`${name}\` could not be resolved` };
47
+ }
48
+ let remoteSha;
49
+ try {
50
+ remoteSha = await readRemoteTip();
51
+ }
52
+ catch {
53
+ return { status: "incomplete", reason: `the remote tip of Codeup task branch \`${name}\` could not be read` };
54
+ }
55
+ if (remoteSha !== headSha.toLowerCase()) {
56
+ return { status: "incomplete", reason: `push Codeup task branch \`${name}\` to origin so it points to local HEAD ${headSha}` };
57
+ }
58
+ return { status: "branch_delivered", evidence: `Pushed branch: ${name}\nPushed commit: ${remoteSha}` };
59
+ }
32
60
  /** Empty ownership commits carry no task changes and may disappear on rebase. */
33
61
  async function captureDeliveryBaseline(worktreePath, runner = sandbox_cjs_1.nodeCommandRunner) {
34
62
  const read = async (...args) => {
@@ -805,6 +805,17 @@ class GitWorktree {
805
805
  }
806
806
  return { branch: this.branch, sha: head.sha };
807
807
  }
808
+ /** Read the allocated branch on the repository configured for this lease. */
809
+ async readRemoteTaskBranchTip() {
810
+ const ref = `refs/heads/${this.branch}`;
811
+ const { stdout } = await this.runGit(["-C", this.worktreePath, "ls-remote", "--refs", this.cloneUrl, ref], true, { timeoutMs: 30_000 });
812
+ for (const line of stdout.trimEnd().split("\n")) {
813
+ const [sha, name] = line.split("\t");
814
+ if (name === ref && sha && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(sha))
815
+ return sha.toLowerCase();
816
+ }
817
+ return null;
818
+ }
808
819
  /** Save recoverable code, never the repository config or broker credentials. */
809
820
  async saveCheckpoint() {
810
821
  await node_fs_1.promises.mkdir(this.checkpointRoot, { recursive: true, mode: 0o700 });
package/dist/session.cjs CHANGED
@@ -24,6 +24,8 @@ const prompt_cjs_1 = require("./prompt.cjs");
24
24
  const mcp_config_cjs_1 = require("./mcp-config.cjs");
25
25
  const user_mcp_servers_cjs_1 = require("./user-mcp-servers.cjs");
26
26
  const logger_cjs_1 = require("./logger.cjs");
27
+ const provider_endpoint_cjs_1 = require("./provider-endpoint.cjs");
28
+ const provider_secret_names_cjs_1 = require("./provider-secret-names.cjs");
27
29
  const secret_env_names_cjs_1 = require("./secret-env-names.cjs");
28
30
  const git_worktree_cjs_1 = require("./git-worktree.cjs");
29
31
  const dependency_cache_cjs_1 = require("./dependency-cache.cjs");
@@ -198,6 +200,8 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
198
200
  // the machine token or a GitHub token in these modes.
199
201
  const credentialUsername = bundle.repository?.credential_username;
200
202
  const codeup = credentialUsername !== undefined;
203
+ const codeupBuild = codeup && task.task_type === "build" && !task.review_of_task_id &&
204
+ (task.deliverable_kind == null || task.deliverable_kind === "code" || task.deliverable_kind === "video");
201
205
  const cloneUrl = (0, github_credential_cjs_1.repositoryCloneUrl)(bundle.repository, task.repo);
202
206
  const bundleGitMode = bundle.repository?.git_proxy_mode;
203
207
  // Codex's worktree guard is an OS sandbox around the whole agent, git's
@@ -253,9 +257,14 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
253
257
  const secretNames = bundle.secret_manifest
254
258
  .map((s) => s.name)
255
259
  .filter((name) => !(gitGrantMode && githubSecretNames.has(name)));
260
+ let byoEndpointBinding;
256
261
  if (secretNames.length > 0) {
257
262
  const issued = await api.issueSecrets({ lease_id: leaseId, secret_names: secretNames });
258
263
  secrets = issued.secrets;
264
+ byoEndpointBinding = issued.byo_endpoint;
265
+ if (secretNames.includes("anthropic-api-key") && !Object.hasOwn(secrets, "anthropic-api-key")) {
266
+ throw new Error("requested anthropic-api-key was not issued");
267
+ }
259
268
  managedGithubCredential = issued.github_app_issued === true;
260
269
  registry.registerAll(secrets);
261
270
  const credentialDenial = (0, github_credential_cjs_1.githubCredentialDenialSummary)(issued.denied);
@@ -293,7 +302,11 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
293
302
  await githubTokenRefresher.start(secrets["github-pat"]);
294
303
  gitCredentialRefresh = { helperPath, tokenFile };
295
304
  }
296
- const sessionEnv = toEnvMap(secrets, gitCredentialRefresh, config.gitAuthorName, config.gitAuthorEmail, gitGrantEnv, codeup ? { username: credentialUsername, secretName: bundle.repository.credential_secret_name } : undefined);
305
+ const sessionEnv = toEnvMap(secrets, gitCredentialRefresh, config.gitAuthorName, config.gitAuthorEmail, gitGrantEnv, codeup ? { username: credentialUsername, secretName: bundle.repository.credential_secret_name } : undefined, { binding: byoEndpointBinding, projectId: task.project_id, leaseId, agentType: runtime });
306
+ if (byoEndpointBinding) {
307
+ execution.model = sessionEnv.ANTHROPIC_MODEL;
308
+ executionReport = { ...executionReport, model: execution.model };
309
+ }
297
310
  // Proxied projects (CX-3.7): the control-plane identity replaces the
298
311
  // NAVARCH_GIT_AUTHOR_* default for this session; mode `off` sends none.
299
312
  const commitIdentity = (0, commit_attribution_cjs_1.parseCommitIdentity)(bundle.repository?.commit_identity);
@@ -963,7 +976,7 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
963
976
  const resumedTask = { id: task.id, summary: task.summary };
964
977
  let completionRemediationRetries = 0;
965
978
  let deliveryCorrectionRetries = 0;
966
- let deliveredPullRequest = false;
979
+ let delivered = false;
967
980
  let antigravityResume;
968
981
  let museSessionId;
969
982
  while (true) {
@@ -1272,7 +1285,7 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
1272
1285
  log.warn(`worktree HEAD lookup failed for ${leaseId}: ${String(err)}`);
1273
1286
  }
1274
1287
  let pullRequestUrl = null;
1275
- let pullRequestLookupFailed = codeup;
1288
+ let pullRequestLookupFailed = false;
1276
1289
  try {
1277
1290
  if (!codeup)
1278
1291
  pullRequestUrl = await (0, github_pr_cjs_1.findHeadBranchPullRequestUrl)({
@@ -1322,7 +1335,7 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
1322
1335
  try {
1323
1336
  const probe = await (0, delivery_cjs_1.probeWorktreeDelivery)({
1324
1337
  worktreePath: gitWorktree.worktreePath,
1325
- baseRef: await gitWorktree.resolveDeliveryBase(),
1338
+ baseRef: codeup ? undefined : await gitWorktree.resolveDeliveryBase(),
1326
1339
  claimBaselineSha: deliveryBaselineSha,
1327
1340
  // A verify or review agent may check the reviewed PR's head out,
1328
1341
  // onto its task branch or the PR's own branch. Those commits are
@@ -1335,12 +1348,32 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
1335
1348
  ? { inheritRemoteCommitsExcept: gitWorktree.branch }
1336
1349
  : {}),
1337
1350
  });
1338
- delivery = (0, delivery_cjs_1.evaluateDelivery)({ ...probe, pullRequestUrl, pullRequestLookupFailed }, deliveryBinding);
1351
+ if (codeup) {
1352
+ const stopLine = codeupBuild ? (0, delivery_cjs_1.codeupBuildStopLine)(previousTurnReport()) : undefined;
1353
+ delivery = await (0, delivery_cjs_1.evaluateCodeupDelivery)(probe, codeupBuild && !stopLine ? {
1354
+ name: gitWorktree.branch,
1355
+ headSha: headBranch === gitWorktree.branch ? headSha : undefined,
1356
+ readRemoteTip: () => gitWorktree.readRemoteTaskBranchTip(),
1357
+ } : undefined);
1358
+ if (delivery.status === "branch_delivered") {
1359
+ // The control plane parses these lines before storing the summary.
1360
+ mapping.reportSummary = `${delivery.evidence}\n\n${mapping.reportSummary}`;
1361
+ }
1362
+ else if (stopLine && delivery.status === "no_changes") {
1363
+ mapping.reportSummary = `${stopLine.slice(0, 500)}\n\n${mapping.reportSummary}`;
1364
+ }
1365
+ }
1366
+ else {
1367
+ delivery = (0, delivery_cjs_1.evaluateDelivery)({ ...probe, pullRequestUrl, pullRequestLookupFailed }, deliveryBinding);
1368
+ }
1339
1369
  }
1340
1370
  catch (err) {
1341
- delivery = { status: deliveryBinding ? "incomplete" : "unknown", reason: `the delivery probe failed: ${String(err)}` };
1371
+ delivery = {
1372
+ status: deliveryBinding || codeupBuild ? "incomplete" : "unknown",
1373
+ reason: `the delivery probe failed: ${String(err)}`,
1374
+ };
1342
1375
  }
1343
- deliveredPullRequest = delivery.status === "delivered";
1376
+ delivered = delivery.status === "delivered" || delivery.status === "branch_delivered";
1344
1377
  if (delivery.status === "unknown") {
1345
1378
  log.warn(`delivery for ${leaseId} could not be verified: ${delivery.reason}; completing anyway.`);
1346
1379
  }
@@ -1468,8 +1501,8 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
1468
1501
  completingLease = true;
1469
1502
  if (await sendCompletion() === "steering_turn")
1470
1503
  continue;
1471
- if (deliveredPullRequest && completion.status === "completed" && gitWorktree.restoredHostedCheckpoint) {
1472
- // The pull request carries the hosted attempt's work now; a later
1504
+ if (delivered && completion.status === "completed" && gitWorktree.restoredHostedCheckpoint) {
1505
+ // The remote carries the hosted attempt's work now; a later
1473
1506
  // hosted attempt must not resume the stale snapshot.
1474
1507
  await gitWorktree.deleteRestoredHostedCheckpoint().catch((err) => {
1475
1508
  log.warn(`hosted checkpoint cleanup failed for ${leaseId}: ${(0, redact_cjs_1.redactText)(String(err), knownSecrets)}`);
@@ -1796,7 +1829,7 @@ function gitGrantCredentialHelper(config) {
1796
1829
  /** Secret names (lowercased, non-alphanumerics as `_`) that are raw GitHub credentials. */
1797
1830
  const GITHUB_CREDENTIAL_SECRETS = new Set(["github_pat", "github_token", "gh_token"]);
1798
1831
  /** Uppercases + sanitizes secret names into shell-safe env var names for injectEnv(). */
1799
- function toEnvMap(secrets, credentialRefreshOrAuthorName, gitAuthorNameOrEmail = "sagentlab", gitAuthorEmail = "z@sagentlab.com", gitGrant, repositoryCredential) {
1832
+ function toEnvMap(secrets, credentialRefreshOrAuthorName, gitAuthorNameOrEmail = "sagentlab", gitAuthorEmail = "z@sagentlab.com", gitGrant, repositoryCredential, endpointContext) {
1800
1833
  // Keep the existing `(secrets, authorName, authorEmail)` call shape while
1801
1834
  // accepting a refresh config before the author identity for managed repos.
1802
1835
  const gitCredentialRefresh = typeof credentialRefreshOrAuthorName === "string"
@@ -1809,7 +1842,34 @@ function toEnvMap(secrets, credentialRefreshOrAuthorName, gitAuthorNameOrEmail =
1809
1842
  ? gitAuthorNameOrEmail
1810
1843
  : gitAuthorEmail;
1811
1844
  const out = {};
1845
+ const companionNames = new Set();
1846
+ const binding = endpointContext?.binding;
1847
+ if (binding) {
1848
+ if (!binding.secret_id || binding.project_id !== endpointContext.projectId || binding.lease_id !== endpointContext.leaseId ||
1849
+ endpointContext.agentType !== "claude-code")
1850
+ throw new Error("custom endpoint binding refused");
1851
+ const baseUrl = secrets["anthropic-base-url"];
1852
+ const model = secrets["anthropic-model"];
1853
+ const checked = (0, provider_endpoint_cjs_1.validateProviderEndpointUrl)(baseUrl, "anthropic_messages");
1854
+ if (!checked.ok || checked.url !== baseUrl)
1855
+ throw new Error(`custom endpoint refused: ${checked.ok ? "not normalized" : checked.code}`);
1856
+ if (!model || !/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,199}$/.test(model))
1857
+ throw new Error("custom endpoint model refused");
1858
+ const bearer = secrets["anthropic-auth-token"];
1859
+ const key = secrets["anthropic-api-key"];
1860
+ if (bearer ? key !== "" : !key)
1861
+ throw new Error("custom endpoint key pair refused");
1862
+ if (!Object.hasOwn(secrets, "anthropic-api-key"))
1863
+ throw new Error("custom endpoint key missing");
1864
+ companionNames.add("anthropic-base-url");
1865
+ companionNames.add("anthropic-model");
1866
+ if (bearer)
1867
+ companionNames.add("anthropic-auth-token");
1868
+ }
1812
1869
  for (const [name, value] of Object.entries(secrets)) {
1870
+ if ((0, provider_secret_names_cjs_1.isProtectedProviderSecret)(name) && !companionNames.has(name)) {
1871
+ throw new Error(`reserved provider secret: ${(0, provider_secret_names_cjs_1.providerSecretEnvName)(name)}`);
1872
+ }
1813
1873
  if ((gitGrant || repositoryCredential) && GITHUB_CREDENTIAL_SECRETS.has(name.toLowerCase().replace(/[^a-z0-9]/g, "_")))
1814
1874
  continue;
1815
1875
  // A project secret must not set a proxy, TLS-trust or loader variable:
@@ -1819,7 +1879,14 @@ function toEnvMap(secrets, credentialRefreshOrAuthorName, gitAuthorNameOrEmail =
1819
1879
  log.warn(`dropped project secret ${JSON.stringify(name)}: it maps to the reserved environment variable ${(0, secret_env_names_cjs_1.secretEnvName)(name)}`);
1820
1880
  continue;
1821
1881
  }
1822
- out[(0, secret_env_names_cjs_1.secretEnvName)(name)] = value;
1882
+ out[(0, provider_secret_names_cjs_1.providerSecretEnvName)(name)] = value;
1883
+ }
1884
+ if (binding) {
1885
+ out.ANTHROPIC_API_KEY = secrets["anthropic-api-key"];
1886
+ out.ANTHROPIC_AUTH_TOKEN = secrets["anthropic-auth-token"] ?? "";
1887
+ out.CLAUDE_CODE_OAUTH_TOKEN = "";
1888
+ for (const tier of ["HAIKU", "SONNET", "OPUS"])
1889
+ out[`ANTHROPIC_DEFAULT_${tier}_MODEL`] = out.ANTHROPIC_MODEL;
1823
1890
  }
1824
1891
  if (gitGrant) {
1825
1892
  // Grant modes: git and gh authenticate with the grant file. No machine
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sagentlab/navarch-runtime",
3
- "version": "0.1.179",
3
+ "version": "0.1.181",
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",