@sagentlab/navarch-runtime 0.1.150 → 0.1.152

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.
@@ -269,19 +269,23 @@ function quotedSpanAt(command, index) {
269
269
  * plain-quoted word in a shell segment whose command word is `jq`, or is `gh`
270
270
  * with the word given to `--jq`/`-q`. Unquoted tokens (`find // -x`),
271
271
  * quoted bare roots (`ls "//"`) and `//` in other quoted text stay screened.
272
+ * As in isJqProgramText, only a gh command that evaluates jq itself
273
+ * (GH_JQ_COMMAND_RE) qualifies, and a command that could redefine `jq` or
274
+ * `gh` (mayRedefineCommands) or that the scanner cannot follow gets no
275
+ * exemption.
272
276
  */
273
- function isJqAlternativeOperator(command, start, token) {
277
+ function isJqAlternativeOperator(command, start, token, heredocs) {
274
278
  if (token !== "//" && token !== "//=") return false;
275
279
  const next = command[start + token.length];
276
280
  if (!/\s/.test(command[start - 1] ?? "") || next === undefined || !/\s/.test(next)) return false;
277
281
  const span = quotedSpanAt(command, start);
278
282
  if (!span) return false;
279
283
  const segment = command.slice(span[2], span[0]);
280
- const commandWord = /^\s*\(?\s*(?:[A-Za-z_]\w*=\S*\s+)*/;
281
- if (new RegExp(commandWord.source + "jq\\s").test(segment)) return true;
282
- return (
283
- new RegExp(commandWord.source + "gh\\s").test(segment) && /\s(?:--jq|-q)(?:=|\s+)$/.test(segment)
284
- );
284
+ const rest = segment.replace(/^\s*\(?\s*(?:[A-Za-z_]\w*=\S*\s+)*/, "");
285
+ const isJq = /^jq\s/.test(rest) || (GH_JQ_COMMAND_RE.test(rest) && /\s(?:--jq|-q)(?:=|\s+)$/.test(segment));
286
+ if (!isJq) return false;
287
+ const { ok, bodies } = heredocs();
288
+ return ok && !mayRedefineCommands(command, bodies);
285
289
  }
286
290
 
287
291
  /**
@@ -296,11 +300,11 @@ function isJqAlternativeOperator(command, start, token) {
296
300
  * program is exempt under the separate, narrower rule in
297
301
  * isJqAlternativeOperator.
298
302
  */
299
- function isCommentOrMarkupToken(command, start, token) {
303
+ function isCommentOrMarkupToken(command, start, token, heredocs) {
300
304
  const end = start + token.length;
301
305
  const next = command[end];
302
306
 
303
- if (isJqAlternativeOperator(command, start, token)) return true;
307
+ if (isJqAlternativeOperator(command, start, token, heredocs)) return true;
304
308
 
305
309
  if (command[start - 1] === "<" && next === ">" && /^\/[A-Za-z][\w:.-]*$/.test(token)) {
306
310
  return !fs.existsSync(token);
@@ -629,10 +633,11 @@ function scanHeredocs(command) {
629
633
  while (command[j] === " " || command[j] === "\t") j++;
630
634
  const word = /^[^\s;|&<>()]+/.exec(command.slice(j));
631
635
  if (!word) return failed;
632
- const delimiter = word[0].replace(/['"\\]/g, "");
633
- if (!delimiter || delimiter.includes("$")) return failed;
634
- if ((word[0].split("'").length - 1) % 2 !== 0) return failed;
635
- if ((word[0].split('"').length - 1) % 2 !== 0) return failed;
636
+ // Accept only complete identifier words with at most one matching
637
+ // outer quote pair. Other shell quote forms can change body boundaries.
638
+ const identifier = /^(?:([A-Za-z0-9_]+)|'([A-Za-z0-9_]+)'|"([A-Za-z0-9_]+)")$/.exec(word[0]);
639
+ if (!identifier) return failed;
640
+ const delimiter = identifier[1] ?? identifier[2] ?? identifier[3];
636
641
  const lineEnd = command.indexOf("\n", i);
637
642
  pending.push({
638
643
  delimiter,
@@ -656,6 +661,9 @@ function scanHeredocs(command) {
656
661
  const lineEnd = newline === -1 ? n : newline;
657
662
  let line = command.slice(i, lineEnd);
658
663
  if (doc.stripTabs) line = line.replace(/^\t+/, "");
664
+ // In an unquoted body the shell joins a line that ends in `\` with
665
+ // the next line before it compares the delimiter.
666
+ if (!doc.quoted && /(?:^|[^\\])(?:\\\\)*\\$/.test(command.slice(i, lineEnd))) return failed;
659
667
  const lineStart = i;
660
668
  i = newline === -1 ? n + 1 : newline + 1;
661
669
  if (line === doc.delimiter) {
@@ -692,6 +700,8 @@ function scanHeredocs(command) {
692
700
  */
693
701
  function readsAsText(segment, text, isMessage) {
694
702
  const word = commandWordOf(segment);
703
+ // A jq module directive reads a file from its `search` path (isJqProgramText).
704
+ if (word === "jq" && /\b(?:import|include)\b/.test(text)) return false;
695
705
  if (TEXT_COMMANDS.has(word)) return true;
696
706
  if (PROGRAM_COMMANDS.has(word)) return !PROGRAM_SHELL_RE.test(text);
697
707
  return MESSAGE_SUBCOMMAND_RE.test(segment.replace(ASSIGNMENTS_RE, "")) && isMessage;
@@ -700,24 +710,295 @@ function readsAsText(segment, text, isMessage) {
700
710
  /** Reserved words that may precede a command word (`do jq ...`, `then gh ...`). */
701
711
  const SHELL_KEYWORDS_RE = /^\s*(?:(?:do|then|else|elif|if|while|until|time|!|\{)\s+)*/;
702
712
 
713
+ /**
714
+ * gh commands whose `-q`/`--jq` value is a jq filter that gh evaluates
715
+ * itself. Any other gh command, such as an extension or a `--shell` alias,
716
+ * gets its arguments raw and can run them. gh global flags (`-R`/`--repo`)
717
+ * may come before the command.
718
+ */
719
+ const GH_JQ_COMMAND_RE = new RegExp(
720
+ "^gh(?:\\s+(?:-R|--repo)(?:=|\\s+)[^\\s;|&<>()'\"`$]+)*\\s+(?:api|" +
721
+ "(?:pr|issue)\\s+(?:list|view|status|checks)|" +
722
+ "(?:run|release|repo|workflow|cache|label|variable|secret|ruleset)\\s+(?:list|view)|" +
723
+ "search\\s+(?:repos|issues|prs|commits|code))\\s",
724
+ );
725
+
726
+ /**
727
+ * Command words that a reader exemption may share a command with. Each one
728
+ * is an external program, or a builtin that cannot define a function or
729
+ * alias, read definitions, or set a variable (`printf` only with a literal
730
+ * format that is not an option and uses only `%s`, `%b` and `%%`, so
731
+ * `printf -v` and zsh math arguments such as `printf %d x=1` refuse). `cd`
732
+ * changes which program runs only when the inherited PATH holds a relative
733
+ * entry, which is outside this check like any other shell snapshot state.
734
+ */
735
+ // `$name`, `${name}` or a special parameter, without a zsh subscript.
736
+ const PLAIN_PARAMETER_RE = /^(?:[A-Za-z_]\w*|\{[A-Za-z_]\w*\}|[0-9?#@*!$-])(?!\[)/;
737
+ // printf directives that never read an argument as a number.
738
+ const PLAIN_PRINTF_DIRECTIVES_RE = /%(?:%|[-+ #0]*\d*(?:\.\d*)?[sb])/g;
739
+ const MAX_PLAIN_DEPTH = 32;
740
+
741
+ const PLAIN_COMMANDS = new Set([...LITERAL_PATTERN_COMMANDS, ...PROGRAM_COMMANDS, "false", "gh", "git", "rm"]);
742
+
743
+ // Variables and zsh special arrays that change command lookup, aliases or
744
+ // functions (`PATH=.:$PATH`, `path=(. $path)`, `functions[jq]=...`,
745
+ // `BASH_CMDS[jq]=./x`), and loader variables that inject code into any
746
+ // program (`LD_PRELOAD`, `DYLD_INSERT_LIBRARIES`). These count anywhere, so
747
+ // `export PATH` and `echo $PATH` do too. zsh math allows `path = 5`.
748
+ const LOOKUP_VARIABLE_RE =
749
+ /\b(?:PATH|BASH_ALIASES|BASH_CMDS|FPATH|(?:LD|DYLD)_\w+)\b|\b(?:path|fpath|functions|aliases|galiases|saliases|commands|builtins|dis_\w+)(?:\[[^\]]*\])?\s*\+?=/;
750
+
751
+ /**
752
+ * True unless every simple command outside the heredoc bodies is positively
753
+ * recognised as plain words with a PLAIN_COMMANDS command word. Every rule
754
+ * that trusts a reader's command word (`jq`, `cat`, `gh`, `node`) needs this,
755
+ * because an earlier command in the same shell could redefine that word.
756
+ *
757
+ * The parser accepts only this grammar; anything else refuses the exemption:
758
+ * - Commands separated by `;`, `&`, `&&`, `|`, `||`, `|&` or a newline.
759
+ * - A command word of plain characters (`[A-Za-z0-9_.-]`) in PLAIN_COMMANDS.
760
+ * So leading assignments of any form, leading redirects, here-strings,
761
+ * keywords and compound syntax (`if`, `for`, `case`, `{`, `(`, `!`, `time`),
762
+ * precommands, function definitions, unknown command words and quoted,
763
+ * escaped or expanded command words all refuse.
764
+ * - Argument words built from plain characters, `\` escapes, single quotes,
765
+ * double quotes, `$name`, `${name}`, special parameters, and `$(...)` whose
766
+ * content passes the same parser. Backticks, `$'...'`, `${...}` operators,
767
+ * `$[...]`, arithmetic and an unquoted `(` refuse.
768
+ * - Redirects after the command word (`>f`, `2>&1`, `<<'EOF'`), except a
769
+ * here-string or a word directly before `<` or `>` (`{fd}>f`, `a>b`).
770
+ * - Comments without separators, quotes, escapes or expansions.
771
+ * Expansions refuse when a subscript follows (`$a[x]`), and `$(` nesting
772
+ * deeper than MAX_PLAIN_DEPTH refuses. An unquoted heredoc body expands in
773
+ * this shell, so it may hold only `$name`, `${name}` and special
774
+ * parameters. LOOKUP_VARIABLE_RE refuses even a read.
775
+ *
776
+ * This check is syntactic. A function, alias or PATH entry that the user's
777
+ * shell snapshot already defines before the command runs is out of its
778
+ * reach.
779
+ */
780
+ function mayRedefineCommands(command, bodies) {
781
+ let text = command;
782
+ for (const { start, end, quoted } of bodies) {
783
+ if (!quoted && !bodyExpansionsArePlain(command.slice(start, end))) return true;
784
+ // Blank the closing delimiter line too, so it does not read as a command.
785
+ const lineEnd = command.indexOf("\n", end);
786
+ const stop = lineEnd === -1 ? command.length : lineEnd;
787
+ text = text.slice(0, start) + " ".repeat(stop - start) + text.slice(stop);
788
+ }
789
+ if (LOOKUP_VARIABLE_RE.test(text.replace(/['"\\]/g, ""))) return true;
790
+ const parser = { text, i: 0, depth: 0 };
791
+ return !(parsePlainList(parser, false) && parser.i === text.length);
792
+ }
793
+
794
+ /** True when an unquoted heredoc body expands only plain parameters. */
795
+ function bodyExpansionsArePlain(body) {
796
+ for (let i = 0; i < body.length; i++) {
797
+ const ch = body[i];
798
+ if (ch === "`") return false;
799
+ if (ch === "\\") {
800
+ i++;
801
+ continue;
802
+ }
803
+ if (ch !== "$") continue;
804
+ const plain = PLAIN_PARAMETER_RE.exec(body.slice(i + 1));
805
+ if (plain) i += plain[0].length;
806
+ else if (!/^(?:\s|"|$)/.test(body.slice(i + 1))) return false;
807
+ }
808
+ return true;
809
+ }
810
+
811
+ /** Skips blanks and `\` line continuations. */
812
+ function skipPlainBlanks(p) {
813
+ for (;;) {
814
+ const ch = p.text[p.i];
815
+ if (ch === " " || ch === "\t") p.i++;
816
+ else if (ch === "\\" && p.text[p.i + 1] === "\n") p.i += 2;
817
+ else return;
818
+ }
819
+ }
820
+
821
+ /**
822
+ * Skips a comment that starts at a word boundary, up to its newline. A shell
823
+ * without comment support (zsh without INTERACTIVE_COMMENTS) reads it as
824
+ * words, so it may hold no separator, quote, escape or expansion.
825
+ */
826
+ function skipPlainComment(p) {
827
+ const comment = /^#[^\n;&|<>()`$\\'"]*/.exec(p.text.slice(p.i))[0];
828
+ p.i += comment.length;
829
+ return p.i === p.text.length || p.text[p.i] === "\n";
830
+ }
831
+
832
+ /**
833
+ * Parses commands up to the end of the text or, in a `$(` substitution, up to
834
+ * and including its `)`. Returns false on anything outside the grammar.
835
+ */
836
+ function parsePlainList(p, inSubstitution) {
837
+ for (;;) {
838
+ skipPlainBlanks(p);
839
+ const ch = p.text[p.i];
840
+ if (ch === undefined) return !inSubstitution;
841
+ if (ch === ")") {
842
+ if (!inSubstitution) return false;
843
+ p.i++;
844
+ return true;
845
+ }
846
+ if (ch === "&" && p.text[p.i + 1] === ">") return false;
847
+ if (/[;&|\n]/.test(ch)) {
848
+ p.i++;
849
+ continue;
850
+ }
851
+ if (!parsePlainCommand(p)) return false;
852
+ }
853
+ }
854
+
855
+ /** Parses one simple command: a PLAIN_COMMANDS word, then words and redirects. */
856
+ function parsePlainCommand(p) {
857
+ if (p.text[p.i] === "#") return skipPlainComment(p);
858
+ const word = readPlainWord(p);
859
+ if (!word || !word.plain || !PLAIN_COMMANDS.has(word.value)) return false;
860
+ const args = [];
861
+ for (;;) {
862
+ skipPlainBlanks(p);
863
+ const ch = p.text[p.i];
864
+ if (ch === undefined || /[;|\n)]/.test(ch) || (ch === "&" && p.text[p.i + 1] !== ">")) break;
865
+ if (ch === "#") {
866
+ if (!skipPlainComment(p)) return false;
867
+ break;
868
+ }
869
+ const rest = p.text.slice(p.i);
870
+ const redirect = /^(?:\d*(?:<<-|<<|<>|<&|>&|>>|>\||<|>)|&>>|&>)/.exec(rest);
871
+ if (redirect) {
872
+ if (rest.startsWith("<<<")) return false;
873
+ p.i += redirect[0].length;
874
+ skipPlainBlanks(p);
875
+ const duplicate = /&$/.test(redirect[0]) && /^(?:\d+|-)(?=[\s;&|)]|$)/.exec(p.text.slice(p.i));
876
+ if (duplicate) p.i += duplicate[0].length;
877
+ else if (!readPlainWord(p)) return false;
878
+ continue;
879
+ }
880
+ const arg = readPlainWord(p);
881
+ if (!arg) return false;
882
+ // `{fd}>file` assigns a variable; refuse every word glued to a redirect.
883
+ if (p.text[p.i] === "<" || p.text[p.i] === ">") return false;
884
+ args.push(arg);
885
+ }
886
+ if (word.value !== "printf") return true;
887
+ // `printf -v name` assigns a variable, and zsh evaluates numeric arguments
888
+ // as math, which can assign too. Allow only a literal text-only format.
889
+ const format = args[0];
890
+ if (!format || !format.literal || format.value.startsWith("-")) return false;
891
+ return !format.value.replace(PLAIN_PRINTF_DIRECTIVES_RE, "").includes("%");
892
+ return true;
893
+ }
894
+
895
+ /**
896
+ * Reads one shell word. Returns {value, plain, literal}, or null when the word
897
+ * is empty or uses syntax outside the grammar. `plain` means only
898
+ * `[A-Za-z0-9_.-]` characters; `literal` means no expansion, so `value` is the
899
+ * word after quote removal.
900
+ */
901
+ function readPlainWord(p) {
902
+ const start = p.i;
903
+ let value = "";
904
+ let plain = true;
905
+ let literal = true;
906
+ for (;;) {
907
+ const ch = p.text[p.i];
908
+ if (ch === undefined || /[\s;&|<>()]/.test(ch)) break;
909
+ if (ch === "`") return null;
910
+ plain = plain && /[A-Za-z0-9_.-]/.test(ch);
911
+ if (ch === "\\") {
912
+ const next = p.text[p.i + 1];
913
+ if (next === undefined) return null;
914
+ if (next !== "\n") value += next;
915
+ p.i += 2;
916
+ } else if (ch === "'") {
917
+ const close = p.text.indexOf("'", p.i + 1);
918
+ if (close === -1) return null;
919
+ value += p.text.slice(p.i + 1, close);
920
+ p.i = close + 1;
921
+ } else if (ch === '"') {
922
+ p.i++;
923
+ for (;;) {
924
+ const inner = p.text[p.i];
925
+ if (inner === undefined || inner === "`") return null;
926
+ if (inner === '"') {
927
+ p.i++;
928
+ break;
929
+ }
930
+ if (inner === "\\") {
931
+ value += p.text[p.i + 1] ?? "";
932
+ p.i += 2;
933
+ } else if (inner === "$") {
934
+ if (!readPlainExpansion(p)) return null;
935
+ literal = false;
936
+ } else {
937
+ value += inner;
938
+ p.i++;
939
+ }
940
+ }
941
+ } else if (ch === "$") {
942
+ if (!readPlainExpansion(p)) return null;
943
+ literal = false;
944
+ } else {
945
+ value += ch;
946
+ p.i++;
947
+ }
948
+ }
949
+ return p.i === start ? null : { value, plain, literal };
950
+ }
951
+
952
+ /**
953
+ * Reads a `$` expansion: `$name`, `${name}`, a special parameter, or `$(...)`
954
+ * whose content parses as a plain list. A `$` before a blank, a closing
955
+ * double quote or the end stays literal. Anything else returns false.
956
+ */
957
+ function readPlainExpansion(p) {
958
+ const rest = p.text.slice(p.i + 1);
959
+ if (rest.startsWith("(")) {
960
+ if (rest.startsWith("((") || p.depth >= MAX_PLAIN_DEPTH) return false;
961
+ p.i += 2;
962
+ p.depth++;
963
+ const ok = parsePlainList(p, true);
964
+ p.depth--;
965
+ return ok;
966
+ }
967
+ // zsh evaluates `$a[expr]` as a subscript, which can assign, so refuse `[`.
968
+ const plain = PLAIN_PARAMETER_RE.exec(rest);
969
+ if (plain) {
970
+ p.i += 1 + plain[0].length;
971
+ return true;
972
+ }
973
+ if (!/^(?:\s|"|$)/.test(rest)) return false;
974
+ p.i++;
975
+ return true;
976
+ }
977
+
703
978
  /**
704
979
  * True when bare root text sits inside a single-quoted jq program: a filter
705
- * argument of `jq`, or the `--jq`/`-q` value of `gh`
706
- * (`--jq '"\(.url|split("/")|last)"'`, `--jq '.a // "none"'`). The shell
707
- * passes single-quoted text through unchanged, and jq cannot open a path or
708
- * start a process from a filter, so `/`, `//` or `/*` there is jq syntax. The
709
- * command word must be a bare `jq` or `gh` (not `./jq`), and the word must
710
- * hold more than the token, so `jq . '/'` stays screened. Only bare root text
711
- * qualifies: `jq 'include "/home/x"; .'` and every unquoted path argument
712
- * stay candidates.
980
+ * argument of `jq`, or the `--jq`/`-q` value of a gh command that evaluates
981
+ * jq itself (GH_JQ_COMMAND_RE: `gh api x --jq '.a // "none"'`,
982
+ * `gh pr view 1 -q '.url|split("/")|last'`). The shell passes single-quoted
983
+ * text through unchanged, and a jq filter cannot start a process, so `/`,
984
+ * `//` or `/*` there is jq syntax. A filter can read files through
985
+ * `import`/`include` (with a `search` path or `-L`), so a program that names
986
+ * either gets no exemption. The command word must be a bare `jq` or `gh` (not
987
+ * `./jq`), and the word must hold more than the token, so `jq . '/'` stays
988
+ * screened. Only bare root text qualifies: every unquoted path argument stays
989
+ * a candidate. The caller refuses this exemption when the command could
990
+ * redefine `jq` or `gh` (mayRedefineCommands).
713
991
  */
714
992
  function isJqProgramText(command, start, token, singleQuoted, segments) {
715
993
  const span = singleQuoted.find(({ open, close }) => start > open && start < close);
716
994
  if (!span) return false;
717
- if (command.slice(span.open + 1, span.close).trim() === token) return false;
995
+ const program = command.slice(span.open + 1, span.close);
996
+ if (program.trim() === token || /\b(?:import|include)\b/.test(program)) return false;
718
997
  const prefix = command.slice(span.segmentStart, span.open).replace(SHELL_KEYWORDS_RE, "");
719
998
  const rest = prefix.replace(ASSIGNMENTS_RE, "");
720
- const isJq = /^jq\s/.test(rest) || (/^gh\s/.test(rest) && /\s(?:--jq|-q)(?:=|\s+)$/.test(prefix));
999
+ const isJq =
1000
+ rest === prefix.trimStart() &&
1001
+ (/^jq\s/.test(rest) || (GH_JQ_COMMAND_RE.test(rest) && /\s(?:--jq|-q)(?:=|\s+)$/.test(prefix)));
721
1002
  return isJq && outputStaysText(command, span.segmentStart, segments, singleQuoted);
722
1003
  }
723
1004
 
@@ -880,7 +1161,9 @@ function isProgramFileBody(command, body, segments) {
880
1161
  * command cannot run that text (exemptionContextIsSafe), except for a
881
1162
  * single-quoted jq program whose output stays text (isJqProgramText), and a
882
1163
  * quoted heredoc body that reaches only its reader (isSealedBody) or runs only
883
- * as a program file (isProgramFileBody). The two heredoc rules look for hook
1164
+ * as a program file (isProgramFileBody). Every rule trusts the reader's
1165
+ * command word (`jq`, `cat`, `gh`, `node`), so none applies when the command
1166
+ * could redefine it (mayRedefineCommands). The two heredoc rules look for hook
884
1167
  * locations (HOOK_PATH_RE) only outside the bodies, so body prose that
885
1168
  * mentions `hooks` stays exempt. The jq rule needs no hook check, because jq
886
1169
  * output never reaches a hook file when it reaches no other command.
@@ -889,6 +1172,7 @@ function isProgramTextRootToken(command, start, token, heredocs) {
889
1172
  if (!isBareRootText(token)) return false;
890
1173
  const { ok, bodies, segments, singleQuoted } = heredocs();
891
1174
  if (!ok) return false;
1175
+ if (mayRedefineCommands(command, bodies)) return false;
892
1176
  if (isJqProgramText(command, start, token, singleQuoted, segments)) return true;
893
1177
  const body = bodies.find((doc) => start >= doc.start && start < doc.end);
894
1178
  const outside = body && body.quoted ? textOutsideBodies(command, bodies) : "";
@@ -940,7 +1224,7 @@ function extractBashPathCandidates(command) {
940
1224
  let match;
941
1225
  while ((match = absoluteRe.exec(command))) {
942
1226
  const start = match.index + match[0].length - match[1].length;
943
- if (isCommentOrMarkupToken(command, start, match[1])) continue;
1227
+ if (isCommentOrMarkupToken(command, start, match[1], getHeredocs)) continue;
944
1228
  const token = clean(match[1]);
945
1229
  // Quotes keep `$`, `(` and `{` literal only for a command that does not
946
1230
  // hand the word to a shell, such as `sed '/^$/d'`; `sh -c '... /$D'` expands.
@@ -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) {
@@ -113,7 +113,9 @@ function extractUsageFromClaudeJson(parsed) {
113
113
  (usage.cache_creation_input_tokens ?? 0) +
114
114
  (usage.cache_read_input_tokens ?? 0);
115
115
  const tokensOut = usage.output_tokens ?? 0;
116
- 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;
117
119
  return { tokensIn, tokensOut, cacheHitTokensIn: usage.cache_read_input_tokens ?? 0, costUsd };
118
120
  }
119
121
  /**
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.
@@ -1144,7 +1159,10 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
1144
1159
  tokensIn: sumReportedUsage(attempts, "tokensIn", runtime === "muse"),
1145
1160
  tokensOut: sumReportedUsage(attempts, "tokensOut", runtime === "muse"),
1146
1161
  cacheHitTokensIn: sumReportedUsage(attempts, "cacheHitTokensIn", runtime === "muse"),
1147
- 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"),
1148
1166
  };
1149
1167
  const mapping = (0, exit_conditions_cjs_1.mapExitCondition)({
1150
1168
  ...result,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sagentlab/navarch-runtime",
3
- "version": "0.1.150",
3
+ "version": "0.1.152",
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",