@sagentlab/navarch-runtime 0.1.149 → 0.1.151

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.
@@ -5,6 +5,14 @@ const exit_conditions_cjs_1 = require("./exit-conditions.cjs");
5
5
  const DEFAULT_CAPACITY_COOLDOWN_MS = 15 * 60 * 1000;
6
6
  const RESET_GRACE_MS = 30 * 1000;
7
7
  const MAX_RESET_SEARCH_MINUTES = 48 * 60;
8
+ /**
9
+ * Account capacity wording. Claude Code says "You've hit your session limit"
10
+ * or "You've hit your weekly limit · resets 11am (America/New_York)"; OpenCode
11
+ * and Codex say "usage limit" or "rate limit".
12
+ */
13
+ const CAPACITY_PATTERN = /\b(?:session|usage|rate|weekly|daily|monthly|hourly|5-hour)\s+limit\b|\bhit your (?:[\w.-]+ ){0,3}limit\b|\btoo many requests\b/i;
14
+ /** Claude Code's account-limit lead: "You've hit your weekly limit". */
15
+ const CLAUDE_ACCOUNT_LIMIT = /^you(?:'|’)ve hit your (?:[\w.-]+ ){0,3}limit\b/i;
8
16
  /**
9
17
  * Detects a provider-side capacity response that applies beyond one task
10
18
  * lease. Claude Code reports account session exhaustion as a successful CLI
@@ -14,15 +22,22 @@ const MAX_RESET_SEARCH_MINUTES = 48 * 60;
14
22
  function detectAdapterCapacityLimit(result, nowMs = Date.now()) {
15
23
  const parsed = (0, exit_conditions_cjs_1.parseClaudeJsonResult)(result.stdout) ??
16
24
  (0, exit_conditions_cjs_1.parseClaudeJsonResult)(result.stderr);
17
- if (!result.capacityError && parsed?.api_error_status !== 429)
25
+ // A structured error result is written by the CLI, not the agent. Claude
26
+ // Code does not mark every account limit with a 429 status, so a structured
27
+ // error result with no API status also counts when its text is Claude
28
+ // Code's own "You've hit your … limit". Another explicit status (401, 403)
29
+ // is a different failure.
30
+ const detail = (result.capacityError ?? (typeof parsed?.result === "string" ? parsed.result : "")).trim();
31
+ const structured = parsed?.api_error_status === 429 ||
32
+ (parsed?.is_error === true && parsed.api_error_status == null && CLAUDE_ACCOUNT_LIMIT.test(detail));
33
+ if (!result.capacityError && !structured)
18
34
  return null;
19
- const detail = result.capacityError ?? parsed?.result ?? "";
20
- if (!/\b(?:session|usage|rate)\s+limit\b|\btoo many requests\b/i.test(detail)) {
35
+ if (!CAPACITY_PATTERN.test(detail))
21
36
  return null;
22
- }
23
37
  return {
24
38
  retryAtMs: parseResetTime(detail, nowMs) ??
25
39
  nowMs + DEFAULT_CAPACITY_COOLDOWN_MS,
40
+ detail: detail.length > 300 ? `${detail.slice(0, 299)}…` : detail,
26
41
  };
27
42
  }
28
43
  /**
@@ -39,7 +39,7 @@ function operatorOwnsSession(extraArgs) {
39
39
  * the same result object (`type: "result"`, `usage`, `total_cost_usd`) that
40
40
  * `--output-format json` prints alone; parseClaudeJsonResult() reads that
41
41
  * last record. If the real shape differs, parseClaudeJsonResult() returns null and
42
- * tokensIn/tokensOut/costUsd fall back to 0 (session.cts's existing
42
+ * tokensIn/tokensOut/costUsd remain unset (session.cts's existing
43
43
  * default) rather than throwing -- see runtime/README.md.
44
44
  */
45
45
  async function runClaudeCodeAdapter(options) {
@@ -95,7 +95,11 @@ async function runClaudeCodeAdapter(options) {
95
95
  tokensIn: addUsage(primary.tokensIn, fallback.tokensIn),
96
96
  tokensOut: addUsage(primary.tokensOut, fallback.tokensOut),
97
97
  cacheHitTokensIn: addUsage(primary.cacheHitTokensIn, fallback.cacheHitTokensIn),
98
- costUsd: addUsage(primary.costUsd, fallback.costUsd),
98
+ // A resumed result is cumulative for the same conversation. Fresh
99
+ // conversations require both reports; missing is never a zero addend.
100
+ costUsd: canResume ? fallback.costUsd
101
+ : primary.costUsd === undefined || fallback.costUsd === undefined ? undefined
102
+ : primary.costUsd + fallback.costUsd,
99
103
  };
100
104
  }
101
105
  function addUsage(first, second) {
@@ -10,7 +10,12 @@ const exit_conditions_cjs_1 = require("./exit-conditions.cjs");
10
10
  *
11
11
  * - Claude Code: "Failed to authenticate: OAuth session expired and could not
12
12
  * be refreshed", "OAuth token has expired", "Invalid API key · Please run
13
- * /login", "Not logged in · Please run /login", 401 authentication_error.
13
+ * /login", "Not logged in · Please run /login", 401 authentication_error,
14
+ * and an organization that turned subscription access off: "Your
15
+ * organization has disabled Claude subscription access for Claude Code · Use
16
+ * an Anthropic API key instead, or ask your admin to enable access". No
17
+ * retry on the same machine can fix that either; a person must change the
18
+ * account or the login.
14
19
  * - Codex: "Your access token could not be refreshed because your refresh
15
20
  * token has expired/was already used", "Not logged in", "Please run `codex
16
21
  * login`", token_expired / refresh_token_* error codes.
@@ -25,6 +30,7 @@ const AGENT_AUTH_PATTERNS = [
25
30
  /\brefresh token (?:has expired|was already used|is invalid|expired)\b/i,
26
31
  /\b(?:refresh_token_(?:expired|reused|invalidated)|token_expired)\b/i,
27
32
  /\bauthentication_error\b/i,
33
+ /\bhas disabled claude subscription access\b/i,
28
34
  ];
29
35
  function matchingLine(text) {
30
36
  for (const line of text.split("\n")) {
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AGENT_MODEL_UNAVAILABLE_PREFIX = exports.AGENT_AUTH_FAILURE_PREFIX = void 0;
3
+ exports.AGENT_MODEL_UNAVAILABLE_PREFIX = exports.AGENT_CAPACITY_FAILURE_PREFIX = exports.AGENT_AUTH_FAILURE_PREFIX = void 0;
4
+ exports.capacityFailureReport = capacityFailureReport;
4
5
  exports.agentAuthFailureReport = agentAuthFailureReport;
5
6
  exports.agentModelUnavailableReport = agentModelUnavailableReport;
6
7
  exports.parseClaudeJsonResult = parseClaudeJsonResult;
@@ -22,6 +23,20 @@ exports.mapExitCondition = mapExitCondition;
22
23
  * `provider.agent_auth`).
23
24
  */
24
25
  exports.AGENT_AUTH_FAILURE_PREFIX = "Coding agent authentication failed";
26
+ /**
27
+ * Leading text of every report for a turn the provider refused because the
28
+ * account is out of capacity (a session, weekly or usage limit). The control
29
+ * plane recognizes it, requeues the task without spending a retry and pauses
30
+ * this machine's claims until the time after "until"
31
+ * (lib/navarch/failure-attribution.ts `provider.agent_capacity`).
32
+ */
33
+ exports.AGENT_CAPACITY_FAILURE_PREFIX = "Session stopped: provider capacity exhausted";
34
+ function capacityFailureReport(detail, retryAtMs) {
35
+ const until = retryAtMs !== undefined && Number.isFinite(retryAtMs)
36
+ ? ` until ${new Date(retryAtMs).toISOString()}`
37
+ : "";
38
+ return `${exports.AGENT_CAPACITY_FAILURE_PREFIX}${until}. ${detail}`;
39
+ }
25
40
  function agentAuthFailureReport(detail) {
26
41
  return `${exports.AGENT_AUTH_FAILURE_PREFIX}: ${detail} ` +
27
42
  "Log the coding agent in again on this machine (`claude /login`, `codex login`, an interactive `agy` session, or open `muse` and run `/login`), then resume the agent.";
@@ -98,7 +113,9 @@ function extractUsageFromClaudeJson(parsed) {
98
113
  (usage.cache_creation_input_tokens ?? 0) +
99
114
  (usage.cache_read_input_tokens ?? 0);
100
115
  const tokensOut = usage.output_tokens ?? 0;
101
- const costUsd = parsed.total_cost_usd ?? parsed.cost_usd ?? 0;
116
+ const reportedCost = parsed.total_cost_usd ?? parsed.cost_usd;
117
+ const costUsd = typeof reportedCost === "number" && Number.isFinite(reportedCost) && reportedCost >= 0
118
+ ? reportedCost : undefined;
102
119
  return { tokensIn, tokensOut, cacheHitTokensIn: usage.cache_read_input_tokens ?? 0, costUsd };
103
120
  }
104
121
  /**
@@ -248,7 +265,7 @@ const REVIEW_FIX_MARKER_LINE = /^[ \t]*Review fix delivered: [a-f0-9]{40}(?=\s|$
248
265
  * this package cannot import it. A report without a marker is unchanged.
249
266
  */
250
267
  function leadWithReviewFixMarker(report) {
251
- const marker = REVIEW_FIX_MARKER_LINE.exec(report);
268
+ const marker = REVIEW_FIX_MARKER_LINE.exec(report) ?? /^[ \t]*Review metadata delivered: [a-f0-9]{40} [1-9][0-9]*(?=\s|$)/im.exec(report);
252
269
  if (!marker || !report.slice(0, marker.index).trim())
253
270
  return report;
254
271
  const lineEnd = report.indexOf("\n", marker.index);
@@ -386,7 +403,7 @@ function mapExitCondition(result) {
386
403
  return {
387
404
  leaseOutcome: "failed",
388
405
  exitStatus: "failed",
389
- reportSummary: summarize(`Session stopped: provider capacity exhausted. ${result.capacityError}`) +
406
+ reportSummary: summarize(capacityFailureReport(result.capacityError, result.capacityRetryAtMs)) +
390
407
  (result.checkpointPath ? ` Local recovery checkpoint: ${result.checkpointPath}` : "") +
391
408
  (result.retainedWorktreePath ? ` Recovery worktree retained: ${result.retainedWorktreePath}` : ""),
392
409
  evidenceUrls,
package/dist/session.cjs CHANGED
@@ -864,6 +864,10 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
864
864
  // Running usage totals the resumable conversation last reported, for the
865
865
  // fields its adapter reports cumulatively (AgentAdapter.cumulativeResumeUsage).
866
866
  let conversationUsage = {};
867
+ // Claude costs are cumulative per conversation, including resumed turns.
868
+ const claudeCosts = new Map();
869
+ const missingClaudeCosts = new Set();
870
+ let claudeConversation = 0;
867
871
  // Claim-time guidance is part of the brief (task_context's "Human
868
872
  // guidance" section, lib/navarch/context.ts), so guidance turns carry only
869
873
  // what arrived after the claim.
@@ -1027,6 +1031,17 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
1027
1031
  antigravityResume = turnResult.antigravityResume;
1028
1032
  if (runtime === "muse")
1029
1033
  museSessionId = turnResult.agentSessionId;
1034
+ if (runtime === "claude-code") {
1035
+ if (!resumed)
1036
+ claudeConversation += 1;
1037
+ const cost = turnResult.costUsd;
1038
+ if (typeof cost === "number" && Number.isFinite(cost) && cost >= 0) {
1039
+ claudeCosts.set(claudeConversation, Math.max(claudeCosts.get(claudeConversation) ?? 0, cost));
1040
+ missingClaudeCosts.delete(claudeConversation);
1041
+ }
1042
+ else
1043
+ missingClaudeCosts.add(claudeConversation);
1044
+ }
1030
1045
  if (adapter.cumulativeResumeUsage) {
1031
1046
  // A resumed run reports the conversation's running total: record only
1032
1047
  // this turn's increase. A fresh conversation starts its own total.
@@ -1066,6 +1081,14 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
1066
1081
  reportActivity("finishing");
1067
1082
  const capacityLimit = (0, adapter_capacity_cjs_1.detectAdapterCapacityLimit)(turnResult);
1068
1083
  if (capacityLimit) {
1084
+ // Claude Code reports an account limit as a structured result, not as
1085
+ // an adapter capacity error. Name it in the report with the reset
1086
+ // time, so the control plane requeues the task without spending a
1087
+ // retry and pauses this machine until then.
1088
+ turnResult.capacityError ??= capacityLimit.detail;
1089
+ turnResult.capacityRetryAtMs = capacityLimit.retryAtMs;
1090
+ log.warn(`session ${leaseId}: provider capacity exhausted until ` +
1091
+ `${new Date(capacityLimit.retryAtMs).toISOString()}: ${capacityLimit.detail}`);
1069
1092
  await checkpointForRecovery(turnResult);
1070
1093
  sessionOutcome.claimCooldownUntil = Math.max(sessionOutcome.claimCooldownUntil ?? 0, capacityLimit.retryAtMs);
1071
1094
  }
@@ -1136,7 +1159,10 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
1136
1159
  tokensIn: sumReportedUsage(attempts, "tokensIn", runtime === "muse"),
1137
1160
  tokensOut: sumReportedUsage(attempts, "tokensOut", runtime === "muse"),
1138
1161
  cacheHitTokensIn: sumReportedUsage(attempts, "cacheHitTokensIn", runtime === "muse"),
1139
- costUsd: runtime === "muse" ? (0, muse_cjs_1.sumMuseSessionCost)(attempts) : sumReportedUsage(attempts, "costUsd"),
1162
+ costUsd: runtime === "claude-code"
1163
+ ? missingClaudeCosts.size > 0 || claudeCosts.size === 0 ? undefined
1164
+ : [...claudeCosts.values()].reduce((sum, cost) => sum + cost, 0)
1165
+ : runtime === "muse" ? (0, muse_cjs_1.sumMuseSessionCost)(attempts) : sumReportedUsage(attempts, "costUsd"),
1140
1166
  };
1141
1167
  const mapping = (0, exit_conditions_cjs_1.mapExitCondition)({
1142
1168
  ...result,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sagentlab/navarch-runtime",
3
- "version": "0.1.149",
3
+ "version": "0.1.151",
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",