@code-sentinel-cli/code-sentinel-cli 3.0.3 → 3.0.5

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.
Files changed (133) hide show
  1. package/README.md +1 -1
  2. package/dist/bin.js +1191 -816
  3. package/dist/builtin-rules/ai/angular/api-service-contract-risk.prompt.md +71 -0
  4. package/dist/builtin-rules/ai/angular/api-service-contract-risk.rule.yaml +22 -0
  5. package/dist/builtin-rules/ai/angular/component-state-flow.prompt.md +79 -0
  6. package/dist/builtin-rules/ai/angular/component-state-flow.rule.yaml +26 -0
  7. package/dist/builtin-rules/ai/angular/cross-feature-api-drift.prompt.md +70 -0
  8. package/dist/builtin-rules/ai/angular/cross-feature-api-drift.rule.yaml +42 -0
  9. package/dist/builtin-rules/ai/angular/cross-feature-route-permission-drift.prompt.md +73 -0
  10. package/dist/builtin-rules/ai/angular/cross-feature-route-permission-drift.rule.yaml +50 -0
  11. package/dist/builtin-rules/ai/angular/reactive-form-flow.prompt.md +82 -0
  12. package/dist/builtin-rules/ai/angular/reactive-form-flow.rule.yaml +23 -0
  13. package/dist/builtin-rules/ai/angular/route-permission-flow.prompt.md +80 -0
  14. package/dist/builtin-rules/ai/angular/route-permission-flow.rule.yaml +23 -0
  15. package/dist/builtin-rules/ai/angular/rxjs-flow-risk.prompt.md +82 -0
  16. package/dist/builtin-rules/ai/angular/rxjs-flow-risk.rule.yaml +24 -0
  17. package/dist/builtin-rules/ai/angular/template-contract-risk.prompt.md +80 -0
  18. package/dist/builtin-rules/ai/angular/template-contract-risk.rule.yaml +25 -0
  19. package/dist/builtin-rules/ai/flutter/dynamic-content-risk.prompt.md +55 -0
  20. package/dist/builtin-rules/ai/flutter/dynamic-content-risk.rule.yaml +18 -0
  21. package/dist/builtin-rules/ai/flutter/feature-state-flow-risk.prompt.md +58 -0
  22. package/dist/builtin-rules/ai/flutter/feature-state-flow-risk.rule.yaml +18 -0
  23. package/dist/builtin-rules/ai/flutter/native-platform-consistency-risk.prompt.md +56 -0
  24. package/dist/builtin-rules/ai/flutter/native-platform-consistency-risk.rule.yaml +18 -0
  25. package/dist/builtin-rules/ai/flutter/network-auth-flow-risk.prompt.md +57 -0
  26. package/dist/builtin-rules/ai/flutter/network-auth-flow-risk.rule.yaml +19 -0
  27. package/dist/builtin-rules/ai/flutter/ui-responsive-accessibility-risk.prompt.md +60 -0
  28. package/dist/builtin-rules/ai/flutter/ui-responsive-accessibility-risk.rule.yaml +18 -0
  29. package/dist/builtin-rules/ai/general/code-clarity.prompt.md +57 -0
  30. package/dist/builtin-rules/ai/general/code-clarity.rule.yaml +20 -0
  31. package/dist/builtin-rules/ai/spring-boot/business-invariant-risk.prompt.md +86 -0
  32. package/dist/builtin-rules/ai/spring-boot/business-invariant-risk.rule.yaml +25 -0
  33. package/dist/builtin-rules/ai/spring-boot/cache-consistency-risk.prompt.md +80 -0
  34. package/dist/builtin-rules/ai/spring-boot/cache-consistency-risk.rule.yaml +25 -0
  35. package/dist/builtin-rules/ai/spring-boot/cross-feature-error-handling-drift.prompt.md +76 -0
  36. package/dist/builtin-rules/ai/spring-boot/cross-feature-error-handling-drift.rule.yaml +63 -0
  37. package/dist/builtin-rules/ai/spring-boot/cross-feature-transaction-boundary-drift.prompt.md +85 -0
  38. package/dist/builtin-rules/ai/spring-boot/cross-feature-transaction-boundary-drift.rule.yaml +68 -0
  39. package/dist/builtin-rules/ai/spring-boot/error-handling-completeness.prompt.md +121 -0
  40. package/dist/builtin-rules/ai/spring-boot/error-handling-completeness.rule.yaml +84 -0
  41. package/dist/builtin-rules/ai/spring-boot/event-publishing-risk.prompt.md +80 -0
  42. package/dist/builtin-rules/ai/spring-boot/event-publishing-risk.rule.yaml +25 -0
  43. package/dist/builtin-rules/ai/spring-boot/io-boundary-risk.prompt.md +78 -0
  44. package/dist/builtin-rules/ai/spring-boot/io-boundary-risk.rule.yaml +25 -0
  45. package/dist/builtin-rules/ai/spring-boot/ownership-scope-risk.prompt.md +83 -0
  46. package/dist/builtin-rules/ai/spring-boot/ownership-scope-risk.rule.yaml +25 -0
  47. package/dist/builtin-rules/ai/spring-boot/pagination-risk.prompt.md +81 -0
  48. package/dist/builtin-rules/ai/spring-boot/pagination-risk.rule.yaml +25 -0
  49. package/dist/builtin-rules/ai/spring-boot/security-authorization-risk.prompt.md +75 -0
  50. package/dist/builtin-rules/ai/spring-boot/security-authorization-risk.rule.yaml +26 -0
  51. package/dist/builtin-rules/ai/spring-boot/security-mass-assignment-risk.prompt.md +75 -0
  52. package/dist/builtin-rules/ai/spring-boot/security-mass-assignment-risk.rule.yaml +24 -0
  53. package/dist/builtin-rules/ai/spring-boot/security-redirect-risk.prompt.md +74 -0
  54. package/dist/builtin-rules/ai/spring-boot/security-redirect-risk.rule.yaml +24 -0
  55. package/dist/builtin-rules/ai/spring-boot/security-sensitive-data-risk.prompt.md +75 -0
  56. package/dist/builtin-rules/ai/spring-boot/security-sensitive-data-risk.rule.yaml +25 -0
  57. package/dist/builtin-rules/ai/spring-boot/transaction-loop-risk.prompt.md +78 -0
  58. package/dist/builtin-rules/ai/spring-boot/transaction-loop-risk.rule.yaml +25 -0
  59. package/dist/builtin-rules/static/angular/component-prefix.rule.js +78 -0
  60. package/dist/builtin-rules/static/angular/image-control-alt-required.rule.js +105 -0
  61. package/dist/builtin-rules/static/angular/img-alt-required.rule.js +96 -0
  62. package/dist/builtin-rules/static/angular/inject-pattern.rule.js +47 -0
  63. package/dist/builtin-rules/static/angular/lifecycle-method-required.rule.js +59 -0
  64. package/dist/builtin-rules/static/angular/no-any-type.rule.yaml +55 -0
  65. package/dist/builtin-rules/static/angular/no-direct-dom-access.rule.js +191 -0
  66. package/dist/builtin-rules/static/angular/no-dom-xss.rule.js +48 -0
  67. package/dist/builtin-rules/static/angular/no-leaky-subscription.rule.js +197 -0
  68. package/dist/builtin-rules/static/angular/no-ngmodule.rule.yaml +44 -0
  69. package/dist/builtin-rules/static/angular/no-non-null-asserted-optional-chain.rule.js +53 -0
  70. package/dist/builtin-rules/static/angular/no-uncalled-signal-in-condition.rule.js +112 -0
  71. package/dist/builtin-rules/static/angular/observable-naming.rule.js +85 -0
  72. package/dist/builtin-rules/static/angular/onpush-required.rule.js +70 -0
  73. package/dist/builtin-rules/static/angular/standalone-component-required.rule.js +65 -0
  74. package/dist/builtin-rules/static/angular/template-dom-xss.rule.js +112 -0
  75. package/dist/builtin-rules/static/angular/template-syntax-modern.rule.js +154 -0
  76. package/dist/builtin-rules/static/angular/trackby-required.rule.js +66 -0
  77. package/dist/builtin-rules/static/flutter/android-exported-component.rule.js +75 -0
  78. package/dist/builtin-rules/static/flutter/android-manifest-hardening.rule.js +117 -0
  79. package/dist/builtin-rules/static/flutter/android-sensitive-permissions.rule.js +87 -0
  80. package/dist/builtin-rules/static/flutter/debug-tooling-release-risk.rule.js +90 -0
  81. package/dist/builtin-rules/static/flutter/dynamic-archive-risk.rule.js +96 -0
  82. package/dist/builtin-rules/static/flutter/hive-sensitive-storage.rule.js +77 -0
  83. package/dist/builtin-rules/static/flutter/ios-privacy-hardening.rule.js +119 -0
  84. package/dist/builtin-rules/static/flutter/packaged-env-risk.rule.js +95 -0
  85. package/dist/builtin-rules/static/flutter/sensitive-log-leak.rule.js +94 -0
  86. package/dist/builtin-rules/static/flutter/webview-bridge-guard.rule.js +102 -0
  87. package/dist/builtin-rules/static/general/file-too-long.rule.js +41 -0
  88. package/dist/builtin-rules/static/general/function-too-long.rule.js +72 -0
  89. package/dist/builtin-rules/static/general/no-circular-import.rule.js +39 -0
  90. package/dist/builtin-rules/static/general/no-code-injection.rule.js +48 -0
  91. package/dist/builtin-rules/static/general/no-console-log.rule.js +110 -0
  92. package/dist/builtin-rules/static/general/no-empty-catch.rule.yaml +56 -0
  93. package/dist/builtin-rules/static/general/no-hardcoded-secret.rule.js +517 -0
  94. package/dist/builtin-rules/static/general/no-magic-number.rule.js +78 -0
  95. package/dist/builtin-rules/static/general/no-open-redirect.rule.js +46 -0
  96. package/dist/builtin-rules/static/general/no-todo-comment.rule.yaml +30 -0
  97. package/dist/builtin-rules/static/general/no-unresolved-import-symbol.rule.js +80 -0
  98. package/dist/builtin-rules/static/general/no-unused-export.rule.js +140 -0
  99. package/dist/builtin-rules/static/spring-boot/no-autowired-field.rule.js +162 -0
  100. package/dist/builtin-rules/static/spring-boot/no-business-logic-in-controller.rule.js +94 -0
  101. package/dist/builtin-rules/static/spring-boot/no-command-injection.rule.js +47 -0
  102. package/dist/builtin-rules/static/spring-boot/no-entity-in-controller.rule.yaml +52 -0
  103. package/dist/builtin-rules/static/spring-boot/no-nplus1-query-in-loop.rule.js +106 -0
  104. package/dist/builtin-rules/static/spring-boot/no-path-traversal.rule.js +47 -0
  105. package/dist/builtin-rules/static/spring-boot/no-spel-injection.rule.js +41 -0
  106. package/dist/builtin-rules/static/spring-boot/no-sql-string-concat.rule.js +194 -0
  107. package/dist/builtin-rules/static/spring-boot/no-ssrf.rule.js +49 -0
  108. package/dist/builtin-rules/static/spring-boot/no-transactional-self-invocation.rule.js +142 -0
  109. package/dist/builtin-rules/static/spring-boot/no-unclosed-resource.rule.js +108 -0
  110. package/dist/builtin-rules/static/spring-boot/no-unsafe-shared-formatter.rule.js +118 -0
  111. package/dist/builtin-rules/static/spring-boot/repository-naming.rule.yaml +42 -0
  112. package/dist/builtin-rules/static/spring-boot/restful-naming.rule.yaml +39 -0
  113. package/dist/builtin-rules/static/spring-boot/transaction-on-service.rule.yaml +58 -0
  114. package/dist/builtin-rules/static/spring-boot/validate-input.rule.js +123 -0
  115. package/dist/builtin-rules/vauthz/static/spring-boot/require-authz-check.rule.js +101 -0
  116. package/dist/index.d.ts +225 -48
  117. package/dist/index.js +1190 -815
  118. package/node_modules/@code-sentinel/core/index.js +55 -0
  119. package/node_modules/@code-sentinel/core/package.json +6 -0
  120. package/node_modules/@code-sentinel/parsers/index.js +13 -0
  121. package/node_modules/@code-sentinel/parsers/package.json +6 -0
  122. package/package.json +34 -29
  123. package/src/migrations/0000_initial.sql +62 -0
  124. package/src/migrations/0001_add_confidence.sql +7 -0
  125. package/src/migrations/0002_add_ai_stats.sql +21 -0
  126. package/src/migrations/0003_add_fix_recipe.sql +29 -0
  127. package/src/migrations/0004_add_ast_graph.sql +61 -0
  128. package/src/migrations/0005_add_project_id.sql +1 -0
  129. package/src/migrations/0006_add_ai_model.sql +5 -0
  130. package/src/migrations/0006_add_rule_results.sql +1 -0
  131. package/src/migrations/0007_add_finding_metadata.sql +4 -0
  132. package/src/migrations/0008_add_coverage.sql +2 -0
  133. package/src/migrations/0009_run_provenance.sql +5 -0
package/dist/index.js CHANGED
@@ -30,6 +30,8 @@ import Spinner from 'ink-spinner';
30
30
  import { createElement } from 'react';
31
31
  import { EventEmitter } from 'events';
32
32
  import { Readable } from 'stream';
33
+ import { stdout, stdin } from 'process';
34
+ import { createInterface } from 'readline/promises';
33
35
  import { parse as parse$1 } from 'dotenv';
34
36
  import { createServer } from 'http';
35
37
 
@@ -70,8 +72,8 @@ var require_picocolors = __commonJS({
70
72
  var argv = p.argv || [];
71
73
  var env = p.env || {};
72
74
  var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
73
- var formatter = (open2, close, replace = open2) => (input3) => {
74
- let string = "" + input3, index2 = string.indexOf(close, open2.length);
75
+ var formatter = (open2, close, replace = open2) => (input4) => {
76
+ let string = "" + input4, index2 = string.indexOf(close, open2.length);
75
77
  return ~index2 ? open2 + replaceClose(string, close, replace, index2) + close : open2 + string + close;
76
78
  };
77
79
  var replaceClose = (string, close, replace, index2) => {
@@ -365,28 +367,28 @@ var require_utils = __commonJS({
365
367
  return match === "\\" ? "" : match;
366
368
  });
367
369
  };
368
- exports.escapeLast = (input3, char, lastIdx) => {
369
- const idx = input3.lastIndexOf(char, lastIdx);
370
- if (idx === -1) return input3;
371
- if (input3[idx - 1] === "\\") return exports.escapeLast(input3, char, idx - 1);
372
- return `${input3.slice(0, idx)}\\${input3.slice(idx)}`;
370
+ exports.escapeLast = (input4, char, lastIdx) => {
371
+ const idx = input4.lastIndexOf(char, lastIdx);
372
+ if (idx === -1) return input4;
373
+ if (input4[idx - 1] === "\\") return exports.escapeLast(input4, char, idx - 1);
374
+ return `${input4.slice(0, idx)}\\${input4.slice(idx)}`;
373
375
  };
374
- exports.removePrefix = (input3, state = {}) => {
375
- let output = input3;
376
- if (output.startsWith("./")) {
377
- output = output.slice(2);
376
+ exports.removePrefix = (input4, state = {}) => {
377
+ let output2 = input4;
378
+ if (output2.startsWith("./")) {
379
+ output2 = output2.slice(2);
378
380
  state.prefix = "./";
379
381
  }
380
- return output;
382
+ return output2;
381
383
  };
382
- exports.wrapOutput = (input3, state = {}, options = {}) => {
384
+ exports.wrapOutput = (input4, state = {}, options = {}) => {
383
385
  const prepend = options.contains ? "" : "^";
384
386
  const append = options.contains ? "" : "$";
385
- let output = `${prepend}(?:${input3})${append}`;
387
+ let output2 = `${prepend}(?:${input4})${append}`;
386
388
  if (state.negated === true) {
387
- output = `(?:^(?!${output}).*$)`;
389
+ output2 = `(?:^(?!${output2}).*$)`;
388
390
  }
389
- return output;
391
+ return output2;
390
392
  };
391
393
  exports.basename = (path, { windows } = {}) => {
392
394
  const segs = path.split(windows ? /[\\/]/ : "/");
@@ -443,14 +445,14 @@ var require_scan = __commonJS({
443
445
  token.depth = token.isGlobstar ? Infinity : 1;
444
446
  }
445
447
  };
446
- var scan = (input3, options) => {
448
+ var scan = (input4, options) => {
447
449
  const opts = options || {};
448
- const length = input3.length - 1;
450
+ const length = input4.length - 1;
449
451
  const scanToEnd = opts.parts === true || opts.scanToEnd === true;
450
452
  const slashes = [];
451
453
  const tokens = [];
452
454
  const parts = [];
453
- let str = input3;
455
+ let str = input4;
454
456
  let index2 = -1;
455
457
  let start = 0;
456
458
  let lastIndex = 0;
@@ -670,7 +672,7 @@ var require_scan = __commonJS({
670
672
  }
671
673
  const state = {
672
674
  prefix,
673
- input: input3,
675
+ input: input4,
674
676
  start,
675
677
  base,
676
678
  glob: glob2,
@@ -694,7 +696,7 @@ var require_scan = __commonJS({
694
696
  for (let idx = 0; idx < slashes.length; idx++) {
695
697
  const n = prevIndex ? prevIndex + 1 : start;
696
698
  const i = slashes[idx];
697
- const value = input3.slice(n, i);
699
+ const value = input4.slice(n, i);
698
700
  if (opts.tokens) {
699
701
  if (idx === 0 && start !== 0) {
700
702
  tokens[idx].isPrefix = true;
@@ -710,8 +712,8 @@ var require_scan = __commonJS({
710
712
  }
711
713
  prevIndex = i;
712
714
  }
713
- if (prevIndex && prevIndex + 1 < input3.length) {
714
- const value = input3.slice(prevIndex + 1);
715
+ if (prevIndex && prevIndex + 1 < input4.length) {
716
+ const value = input4.slice(prevIndex + 1);
715
717
  parts.push(value);
716
718
  if (opts.tokens) {
717
719
  tokens[tokens.length - 1].value = value;
@@ -756,14 +758,14 @@ var require_parse = __commonJS({
756
758
  var syntaxError = (type, char) => {
757
759
  return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
758
760
  };
759
- var splitTopLevel = (input3) => {
761
+ var splitTopLevel = (input4) => {
760
762
  const parts = [];
761
763
  let bracket = 0;
762
764
  let paren = 0;
763
765
  let quote = 0;
764
766
  let value = "";
765
767
  let escaped = false;
766
- for (const ch of input3) {
768
+ for (const ch of input4) {
767
769
  if (escaped === true) {
768
770
  value += ch;
769
771
  escaped = false;
@@ -963,14 +965,14 @@ var require_parse = __commonJS({
963
965
  }
964
966
  return { risky: false };
965
967
  };
966
- var parse2 = (input3, options) => {
967
- if (typeof input3 !== "string") {
968
+ var parse2 = (input4, options) => {
969
+ if (typeof input4 !== "string") {
968
970
  throw new TypeError("Expected a string");
969
971
  }
970
- input3 = REPLACEMENTS[input3] || input3;
972
+ input4 = REPLACEMENTS[input4] || input4;
971
973
  const opts = { ...options };
972
974
  const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
973
- let len = input3.length;
975
+ let len = input4.length;
974
976
  if (len > max) {
975
977
  throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
976
978
  }
@@ -1006,7 +1008,7 @@ var require_parse = __commonJS({
1006
1008
  opts.noextglob = opts.noext;
1007
1009
  }
1008
1010
  const state = {
1009
- input: input3,
1011
+ input: input4,
1010
1012
  index: -1,
1011
1013
  start: 0,
1012
1014
  dot: opts.dot === true,
@@ -1022,17 +1024,17 @@ var require_parse = __commonJS({
1022
1024
  globstar: false,
1023
1025
  tokens
1024
1026
  };
1025
- input3 = utils.removePrefix(input3, state);
1026
- len = input3.length;
1027
+ input4 = utils.removePrefix(input4, state);
1028
+ len = input4.length;
1027
1029
  const extglobs = [];
1028
1030
  const braces = [];
1029
1031
  const stack = [];
1030
1032
  let prev = bos;
1031
1033
  let value;
1032
1034
  const eos = () => state.index === len - 1;
1033
- const peek = state.peek = (n = 1) => input3[state.index + n];
1034
- const advance = state.advance = () => input3[++state.index] || "";
1035
- const remaining = () => input3.slice(state.index + 1);
1035
+ const peek = state.peek = (n = 1) => input4[state.index + n];
1036
+ const advance = state.advance = () => input4[++state.index] || "";
1037
+ const remaining = () => input4.slice(state.index + 1);
1036
1038
  const consume = (value2 = "", num = 0) => {
1037
1039
  state.consumed += value2;
1038
1040
  state.index += num;
@@ -1095,15 +1097,15 @@ var require_parse = __commonJS({
1095
1097
  token.output = state.output;
1096
1098
  token.startIndex = state.index;
1097
1099
  token.tokensIndex = tokens.length;
1098
- const output = (opts.capture ? "(" : "") + token.open;
1100
+ const output2 = (opts.capture ? "(" : "") + token.open;
1099
1101
  increment("parens");
1100
1102
  push({ type, value: value2, output: state.output ? "" : ONE_CHAR });
1101
- push({ type: "paren", extglob: true, value: advance(), output });
1103
+ push({ type: "paren", extglob: true, value: advance(), output: output2 });
1102
1104
  extglobs.push(token);
1103
1105
  };
1104
1106
  const extglobClose = (token) => {
1105
- const literal = input3.slice(token.startIndex, state.index + 1);
1106
- const body = input3.slice(token.startIndex + 2, state.index);
1107
+ const literal = input4.slice(token.startIndex, state.index + 1);
1108
+ const body = input4.slice(token.startIndex + 2, state.index);
1107
1109
  const analysis = analyzeRepeatedExtglob(body, opts);
1108
1110
  if ((token.type === "plus" || token.type === "star") && analysis.risky) {
1109
1111
  const safeOutput = analysis.safeOutput ? (token.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : void 0;
@@ -1122,7 +1124,7 @@ var require_parse = __commonJS({
1122
1124
  decrement("parens");
1123
1125
  return;
1124
1126
  }
1125
- let output = token.close + (opts.capture ? ")" : "");
1127
+ let output2 = token.close + (opts.capture ? ")" : "");
1126
1128
  let rest;
1127
1129
  if (token.type === "negate") {
1128
1130
  let extglobStar = star;
@@ -1130,22 +1132,22 @@ var require_parse = __commonJS({
1130
1132
  extglobStar = globstar(opts);
1131
1133
  }
1132
1134
  if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
1133
- output = token.close = `)$))${extglobStar}`;
1135
+ output2 = token.close = `)$))${extglobStar}`;
1134
1136
  }
1135
1137
  if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
1136
1138
  const expression = parse2(rest, { ...options, fastpaths: false }).output;
1137
- output = token.close = `)${expression})${extglobStar})`;
1139
+ output2 = token.close = `)${expression})${extglobStar})`;
1138
1140
  }
1139
1141
  if (token.prev.type === "bos") {
1140
1142
  state.negatedExtglob = true;
1141
1143
  }
1142
1144
  }
1143
- push({ type: "paren", extglob: true, value, output });
1145
+ push({ type: "paren", extglob: true, value, output: output2 });
1144
1146
  decrement("parens");
1145
1147
  };
1146
- if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input3)) {
1148
+ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input4)) {
1147
1149
  let backslashes = false;
1148
- let output = input3.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index2) => {
1150
+ let output2 = input4.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index2) => {
1149
1151
  if (first === "\\") {
1150
1152
  backslashes = true;
1151
1153
  return m;
@@ -1172,18 +1174,18 @@ var require_parse = __commonJS({
1172
1174
  });
1173
1175
  if (backslashes === true) {
1174
1176
  if (opts.unescape === true) {
1175
- output = output.replace(/\\/g, "");
1177
+ output2 = output2.replace(/\\/g, "");
1176
1178
  } else {
1177
- output = output.replace(/\\+/g, (m) => {
1179
+ output2 = output2.replace(/\\+/g, (m) => {
1178
1180
  return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
1179
1181
  });
1180
1182
  }
1181
1183
  }
1182
- if (output === input3 && opts.contains === true) {
1183
- state.output = input3;
1184
+ if (output2 === input4 && opts.contains === true) {
1185
+ state.output = input4;
1184
1186
  return state;
1185
1187
  }
1186
- state.output = utils.wrapOutput(output, state, options);
1188
+ state.output = utils.wrapOutput(output2, state, options);
1187
1189
  return state;
1188
1190
  }
1189
1191
  while (!eos()) {
@@ -1353,7 +1355,7 @@ var require_parse = __commonJS({
1353
1355
  push({ type: "text", value, output: value });
1354
1356
  continue;
1355
1357
  }
1356
- let output = ")";
1358
+ let output2 = ")";
1357
1359
  if (brace.dots === true) {
1358
1360
  const arr = tokens.slice();
1359
1361
  const range = [];
@@ -1366,20 +1368,20 @@ var require_parse = __commonJS({
1366
1368
  range.unshift(arr[i].value);
1367
1369
  }
1368
1370
  }
1369
- output = expandRange(range, opts);
1371
+ output2 = expandRange(range, opts);
1370
1372
  state.backtrack = true;
1371
1373
  }
1372
1374
  if (brace.comma !== true && brace.dots !== true) {
1373
1375
  const out = state.output.slice(0, brace.outputIndex);
1374
1376
  const toks = state.tokens.slice(brace.tokensIndex);
1375
1377
  brace.value = brace.output = "\\{";
1376
- value = output = "\\}";
1378
+ value = output2 = "\\}";
1377
1379
  state.output = out;
1378
1380
  for (const t of toks) {
1379
1381
  state.output += t.output || t.value;
1380
1382
  }
1381
1383
  }
1382
- push({ type: "brace", value, output });
1384
+ push({ type: "brace", value, output: output2 });
1383
1385
  decrement("braces");
1384
1386
  braces.pop();
1385
1387
  continue;
@@ -1392,13 +1394,13 @@ var require_parse = __commonJS({
1392
1394
  continue;
1393
1395
  }
1394
1396
  if (value === ",") {
1395
- let output = value;
1397
+ let output2 = value;
1396
1398
  const brace = braces[braces.length - 1];
1397
1399
  if (brace && stack[stack.length - 1] === "braces") {
1398
1400
  brace.comma = true;
1399
- output = "|";
1401
+ output2 = "|";
1400
1402
  }
1401
- push({ type: "comma", value, output });
1403
+ push({ type: "comma", value, output: output2 });
1402
1404
  continue;
1403
1405
  }
1404
1406
  if (value === "/") {
@@ -1438,11 +1440,11 @@ var require_parse = __commonJS({
1438
1440
  }
1439
1441
  if (prev && prev.type === "paren") {
1440
1442
  const next = peek();
1441
- let output = value;
1443
+ let output2 = value;
1442
1444
  if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) {
1443
- output = `\\${value}`;
1445
+ output2 = `\\${value}`;
1444
1446
  }
1445
- push({ type: "text", value, output });
1447
+ push({ type: "text", value, output: output2 });
1446
1448
  continue;
1447
1449
  }
1448
1450
  if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
@@ -1535,7 +1537,7 @@ var require_parse = __commonJS({
1535
1537
  continue;
1536
1538
  }
1537
1539
  while (rest.slice(0, 3) === "/**") {
1538
- const after = input3[state.index + 4];
1540
+ const after = input4[state.index + 4];
1539
1541
  if (after && after !== "/") {
1540
1542
  break;
1541
1543
  }
@@ -1655,14 +1657,14 @@ var require_parse = __commonJS({
1655
1657
  }
1656
1658
  return state;
1657
1659
  };
1658
- parse2.fastpaths = (input3, options) => {
1660
+ parse2.fastpaths = (input4, options) => {
1659
1661
  const opts = { ...options };
1660
1662
  const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
1661
- const len = input3.length;
1663
+ const len = input4.length;
1662
1664
  if (len > max) {
1663
1665
  throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
1664
1666
  }
1665
- input3 = REPLACEMENTS[input3] || input3;
1667
+ input4 = REPLACEMENTS[input4] || input4;
1666
1668
  const {
1667
1669
  DOT_LITERAL,
1668
1670
  SLASH_LITERAL,
@@ -1713,8 +1715,8 @@ var require_parse = __commonJS({
1713
1715
  }
1714
1716
  }
1715
1717
  };
1716
- const output = utils.removePrefix(input3, state);
1717
- let source = create(output);
1718
+ const output2 = utils.removePrefix(input4, state);
1719
+ let source = create(output2);
1718
1720
  if (source && opts.strictSlashes !== true) {
1719
1721
  source += `${SLASH_LITERAL}?`;
1720
1722
  }
@@ -1734,7 +1736,7 @@ var require_picomatch = __commonJS({
1734
1736
  var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
1735
1737
  var picomatch2 = (glob2, options, returnState = false) => {
1736
1738
  if (Array.isArray(glob2)) {
1737
- const fns = glob2.map((input3) => picomatch2(input3, options, returnState));
1739
+ const fns = glob2.map((input4) => picomatch2(input4, options, returnState));
1738
1740
  const arrayMatcher = (str) => {
1739
1741
  for (const isMatch of fns) {
1740
1742
  const state2 = isMatch(str);
@@ -1758,9 +1760,9 @@ var require_picomatch = __commonJS({
1758
1760
  const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
1759
1761
  isIgnored = picomatch2(opts.ignore, ignoreOpts, returnState);
1760
1762
  }
1761
- const matcher = (input3, returnObject = false) => {
1762
- const { isMatch, match, output } = picomatch2.test(input3, regex, options, { glob: glob2, posix: posix3 });
1763
- const result = { glob: glob2, state, regex, posix: posix3, input: input3, output, match, isMatch };
1763
+ const matcher = (input4, returnObject = false) => {
1764
+ const { isMatch, match, output: output2 } = picomatch2.test(input4, regex, options, { glob: glob2, posix: posix3 });
1765
+ const result = { glob: glob2, state, regex, posix: posix3, input: input4, output: output2, match, isMatch };
1764
1766
  if (typeof opts.onResult === "function") {
1765
1767
  opts.onResult(result);
1766
1768
  }
@@ -1768,7 +1770,7 @@ var require_picomatch = __commonJS({
1768
1770
  result.isMatch = false;
1769
1771
  return returnObject ? result : false;
1770
1772
  }
1771
- if (isIgnored(input3)) {
1773
+ if (isIgnored(input4)) {
1772
1774
  if (typeof opts.onIgnore === "function") {
1773
1775
  opts.onIgnore(result);
1774
1776
  }
@@ -1785,40 +1787,40 @@ var require_picomatch = __commonJS({
1785
1787
  }
1786
1788
  return matcher;
1787
1789
  };
1788
- picomatch2.test = (input3, regex, options, { glob: glob2, posix: posix3 } = {}) => {
1789
- if (typeof input3 !== "string") {
1790
+ picomatch2.test = (input4, regex, options, { glob: glob2, posix: posix3 } = {}) => {
1791
+ if (typeof input4 !== "string") {
1790
1792
  throw new TypeError("Expected input to be a string");
1791
1793
  }
1792
- if (input3 === "") {
1794
+ if (input4 === "") {
1793
1795
  return { isMatch: false, output: "" };
1794
1796
  }
1795
1797
  const opts = options || {};
1796
1798
  const format = opts.format || (posix3 ? utils.toPosixSlashes : null);
1797
- let match = input3 === glob2;
1798
- let output = match && format ? format(input3) : input3;
1799
+ let match = input4 === glob2;
1800
+ let output2 = match && format ? format(input4) : input4;
1799
1801
  if (match === false) {
1800
- output = format ? format(input3) : input3;
1801
- match = output === glob2;
1802
+ output2 = format ? format(input4) : input4;
1803
+ match = output2 === glob2;
1802
1804
  }
1803
1805
  if (match === false || opts.capture === true) {
1804
1806
  if (opts.matchBase === true || opts.basename === true) {
1805
- match = picomatch2.matchBase(input3, regex, options, posix3);
1807
+ match = picomatch2.matchBase(input4, regex, options, posix3);
1806
1808
  } else {
1807
- match = regex.exec(output);
1809
+ match = regex.exec(output2);
1808
1810
  }
1809
1811
  }
1810
- return { isMatch: Boolean(match), match, output };
1812
+ return { isMatch: Boolean(match), match, output: output2 };
1811
1813
  };
1812
- picomatch2.matchBase = (input3, glob2, options) => {
1814
+ picomatch2.matchBase = (input4, glob2, options) => {
1813
1815
  const regex = glob2 instanceof RegExp ? glob2 : picomatch2.makeRe(glob2, options);
1814
- return regex.test(utils.basename(input3));
1816
+ return regex.test(utils.basename(input4));
1815
1817
  };
1816
1818
  picomatch2.isMatch = (str, patterns, options) => picomatch2(patterns, options)(str);
1817
1819
  picomatch2.parse = (pattern, options) => {
1818
1820
  if (Array.isArray(pattern)) return pattern.map((p) => picomatch2.parse(p, options));
1819
1821
  return parse2(pattern, { ...options, fastpaths: false });
1820
1822
  };
1821
- picomatch2.scan = (input3, options) => scan(input3, options);
1823
+ picomatch2.scan = (input4, options) => scan(input4, options);
1822
1824
  picomatch2.compileRe = (state, options, returnOutput = false, returnState = false) => {
1823
1825
  if (returnOutput === true) {
1824
1826
  return state.output;
@@ -1836,16 +1838,16 @@ var require_picomatch = __commonJS({
1836
1838
  }
1837
1839
  return regex;
1838
1840
  };
1839
- picomatch2.makeRe = (input3, options = {}, returnOutput = false, returnState = false) => {
1840
- if (!input3 || typeof input3 !== "string") {
1841
+ picomatch2.makeRe = (input4, options = {}, returnOutput = false, returnState = false) => {
1842
+ if (!input4 || typeof input4 !== "string") {
1841
1843
  throw new TypeError("Expected a non-empty string");
1842
1844
  }
1843
1845
  let parsed = { negated: false, fastpaths: true };
1844
- if (options.fastpaths !== false && (input3[0] === "." || input3[0] === "*")) {
1845
- parsed.output = parse2.fastpaths(input3, options);
1846
+ if (options.fastpaths !== false && (input4[0] === "." || input4[0] === "*")) {
1847
+ parsed.output = parse2.fastpaths(input4, options);
1846
1848
  }
1847
1849
  if (!parsed.output) {
1848
- parsed = parse2(input3, options);
1850
+ parsed = parse2(input4, options);
1849
1851
  }
1850
1852
  return picomatch2.compileRe(parsed, options, returnOutput, returnState);
1851
1853
  };
@@ -2002,7 +2004,7 @@ var newId = (seedTime) => {
2002
2004
  if (seedTime) return ulid(seedTime.getTime());
2003
2005
  return ulid();
2004
2006
  };
2005
- var sha256 = (input3) => createHash("sha256").update(input3).digest("hex");
2007
+ var sha256 = (input4) => createHash("sha256").update(input4).digest("hex");
2006
2008
  var compositeKey = (...parts) => sha256(parts.map(String).join("|"));
2007
2009
  var SystemClock = class {
2008
2010
  now() {
@@ -2280,45 +2282,45 @@ var buildRuleResults = (rules, files, findings2, aiEnabled, aiStats, pendingRule
2280
2282
  };
2281
2283
  });
2282
2284
  };
2283
- var reviewProject = async (deps, input3) => {
2285
+ var reviewProject = async (deps, input4) => {
2284
2286
  const { executor, store, clock, logger } = deps;
2285
- const runId = input3.runId ?? newId(clock.now());
2286
- const startedAt = input3.startedAt ?? clock.now();
2287
- const executionRules = input3.executionRules ?? input3.rules;
2288
- const status = input3.status ?? "completed";
2289
- const ruleSetHash = computeRuleSetHash(input3.rules);
2287
+ const runId = input4.runId ?? newId(clock.now());
2288
+ const startedAt = input4.startedAt ?? clock.now();
2289
+ const executionRules = input4.executionRules ?? input4.rules;
2290
+ const status = input4.status ?? "completed";
2291
+ const ruleSetHash = computeRuleSetHash(input4.rules);
2290
2292
  logger.info(
2291
2293
  {
2292
2294
  runId,
2293
- projectPath: input3.projectPath,
2294
- files: input3.files.length,
2295
+ projectPath: input4.projectPath,
2296
+ files: input4.files.length,
2295
2297
  rules: executionRules.length,
2296
2298
  ruleSetHash: ruleSetHash.slice(0, 8),
2297
2299
  status
2298
2300
  },
2299
2301
  "review.started"
2300
2302
  );
2301
- const findings2 = [...input3.initialFindings ?? []];
2303
+ const findings2 = [...input4.initialFindings ?? []];
2302
2304
  const findingKeys = new Set(
2303
2305
  findings2.map(
2304
2306
  (finding) => `${finding.ruleId}\0${finding.file}\0${finding.range.line}\0${finding.range.endLine ?? ""}\0${finding.message}\0${finding.suggestion ?? ""}`
2305
2307
  )
2306
2308
  );
2307
- for await (const finding of executor.execute(executionRules, input3.files, {
2309
+ for await (const finding of executor.execute(executionRules, input4.files, {
2308
2310
  runId,
2309
- projectRoot: input3.projectPath,
2310
- ...input3.minSeverity !== void 0 ? { minSeverity: input3.minSeverity } : {},
2311
- ...input3.aiEnabled !== void 0 ? { aiEnabled: input3.aiEnabled } : {},
2312
- ...input3.aiConcurrency !== void 0 ? { aiConcurrency: input3.aiConcurrency } : {},
2313
- ...input3.contextFiles !== void 0 ? { contextFiles: input3.contextFiles } : {},
2314
- ...input3.initialFindings !== void 0 ? { seedFindings: input3.initialFindings } : {},
2315
- ...input3.minConfidence !== void 0 ? { minConfidence: input3.minConfidence } : {},
2311
+ projectRoot: input4.projectPath,
2312
+ ...input4.minSeverity !== void 0 ? { minSeverity: input4.minSeverity } : {},
2313
+ ...input4.aiEnabled !== void 0 ? { aiEnabled: input4.aiEnabled } : {},
2314
+ ...input4.aiConcurrency !== void 0 ? { aiConcurrency: input4.aiConcurrency } : {},
2315
+ ...input4.contextFiles !== void 0 ? { contextFiles: input4.contextFiles } : {},
2316
+ ...input4.initialFindings !== void 0 ? { seedFindings: input4.initialFindings } : {},
2317
+ ...input4.minConfidence !== void 0 ? { minConfidence: input4.minConfidence } : {},
2316
2318
  // Phase 14.1.3 — forward live-progress callbacks to the executor.
2317
2319
  // Each is optional; passing them conditionally keeps Zod's
2318
2320
  // strict-undefined contract happy when the executor's options
2319
2321
  // pass through a schema check downstream.
2320
- ...input3.onFinding !== void 0 ? { onFinding: input3.onFinding } : {},
2321
- ...input3.onFileComplete !== void 0 ? { onFileComplete: input3.onFileComplete } : {}
2322
+ ...input4.onFinding !== void 0 ? { onFinding: input4.onFinding } : {},
2323
+ ...input4.onFileComplete !== void 0 ? { onFileComplete: input4.onFileComplete } : {}
2322
2324
  })) {
2323
2325
  const key = `${finding.ruleId}\0${finding.file}\0${finding.range.line}\0${finding.range.endLine ?? ""}\0${finding.message}\0${finding.suggestion ?? ""}`;
2324
2326
  if (findingKeys.has(key)) continue;
@@ -2326,34 +2328,34 @@ var reviewProject = async (deps, input3) => {
2326
2328
  findings2.push(finding);
2327
2329
  }
2328
2330
  const finishedAt = status === "completed" ? clock.now() : null;
2329
- const aiStats = input3.aiEnabled === false ? void 0 : deps.aiTracker ? deps.aiTracker.snapshot() : void 0;
2330
- const effectiveAiProvider = input3.aiEnabled === false ? null : input3.aiProvider;
2331
- const effectiveAiModel = input3.aiEnabled === false ? null : input3.aiModel;
2331
+ const aiStats = input4.aiEnabled === false ? void 0 : deps.aiTracker ? deps.aiTracker.snapshot() : void 0;
2332
+ const effectiveAiProvider = input4.aiEnabled === false ? null : input4.aiProvider;
2333
+ const effectiveAiModel = input4.aiEnabled === false ? null : input4.aiModel;
2332
2334
  const ruleResults = buildRuleResults(
2333
- input3.rules,
2334
- input3.files,
2335
+ input4.rules,
2336
+ input4.files,
2335
2337
  findings2,
2336
- input3.aiEnabled,
2338
+ input4.aiEnabled,
2337
2339
  aiStats,
2338
- input3.pendingRuleKinds ?? []
2340
+ input4.pendingRuleKinds ?? []
2339
2341
  );
2340
2342
  const run = {
2341
2343
  id: runId,
2342
- projectId: input3.projectId ?? "local-project",
2343
- projectPath: input3.projectPath,
2344
+ projectId: input4.projectId ?? "local-project",
2345
+ projectPath: input4.projectPath,
2344
2346
  startedAt,
2345
2347
  finishedAt,
2346
2348
  status,
2347
- totalFiles: input3.files.length,
2349
+ totalFiles: input4.files.length,
2348
2350
  totalFindings: findings2.length,
2349
2351
  ruleSetHash,
2350
2352
  ruleResults,
2351
2353
  findings: findings2,
2352
- ...input3.gitRef !== void 0 ? { gitRef: input3.gitRef } : {},
2354
+ ...input4.gitRef !== void 0 ? { gitRef: input4.gitRef } : {},
2353
2355
  ...effectiveAiProvider !== void 0 ? { aiProvider: effectiveAiProvider } : {},
2354
2356
  ...effectiveAiModel !== void 0 ? { aiModel: effectiveAiModel } : {},
2355
2357
  ...aiStats !== void 0 ? { aiStats } : {},
2356
- ...input3.coverage !== void 0 ? { coverage: input3.coverage } : {}
2358
+ ...input4.coverage !== void 0 ? { coverage: input4.coverage } : {}
2357
2359
  };
2358
2360
  const saveResult = await store.save(run);
2359
2361
  if (!saveResult.ok) {
@@ -2380,11 +2382,11 @@ var definedBuildValue = (value, fallback) => typeof value === "string" && value.
2380
2382
  var getCliBuildMetadata = (version2) => ({
2381
2383
  version: version2,
2382
2384
  gitSha: definedBuildValue(
2383
- "db0ad7eaf9c6" ,
2385
+ "73d6e7b299a5" ,
2384
2386
  "unknown"
2385
2387
  ),
2386
2388
  buildTimestamp: definedBuildValue(
2387
- "2026-08-07T03:32:56.496Z" ,
2389
+ "2026-08-10T07:21:32.211Z" ,
2388
2390
  "unknown"
2389
2391
  ),
2390
2392
  configSchemaRange: definedBuildValue(
@@ -2425,16 +2427,36 @@ var pollDeviceAuthorization = async (serverUrl, deviceCode, fetchFn = fetch) =>
2425
2427
  if (response.status === 429)
2426
2428
  return { status: "slow_down", interval: response.body.interval ?? 5 };
2427
2429
  if (response.status === 410) return { status: "expired" };
2428
- if (response.status === 200 && typeof response.body.accessToken === "string" && typeof response.body.subject === "string" && typeof response.body.expiresIn === "number") {
2430
+ if (response.status === 200 && typeof response.body.accessToken === "string" && typeof response.body.refreshToken === "string" && typeof response.body.subject === "string" && typeof response.body.expiresIn === "number") {
2429
2431
  return {
2430
2432
  status: "approved",
2431
2433
  accessToken: response.body.accessToken,
2434
+ refreshToken: response.body.refreshToken,
2432
2435
  subject: response.body.subject,
2433
2436
  expiresIn: response.body.expiresIn
2434
2437
  };
2435
2438
  }
2436
2439
  throw new Error("Authorization polling failed.");
2437
2440
  };
2441
+ var refreshDeviceCredential = async (serverUrl, refreshToken, fetchFn = fetch) => {
2442
+ const response = await requestJson(
2443
+ serverUrl,
2444
+ "/api/cli/auth/refresh",
2445
+ { method: "POST", body: JSON.stringify({ refreshToken }) },
2446
+ fetchFn
2447
+ );
2448
+ if (response.status === 401) return { status: "invalid" };
2449
+ if (response.status === 200 && typeof response.body.accessToken === "string" && typeof response.body.refreshToken === "string" && typeof response.body.subject === "string" && typeof response.body.expiresIn === "number") {
2450
+ return {
2451
+ status: "approved",
2452
+ accessToken: response.body.accessToken,
2453
+ refreshToken: response.body.refreshToken,
2454
+ subject: response.body.subject,
2455
+ expiresIn: response.body.expiresIn
2456
+ };
2457
+ }
2458
+ throw new Error("Credential refresh failed.");
2459
+ };
2438
2460
  var revokeDeviceCredential = async (serverUrl, accessToken, fetchFn = fetch) => {
2439
2461
  await requestJson(
2440
2462
  serverUrl,
@@ -2572,7 +2594,7 @@ var SecretCommandError = class extends Error {
2572
2594
  code;
2573
2595
  };
2574
2596
  var nativeRunner = {
2575
- run: (command, args, input3) => new Promise((resolve40, reject) => {
2597
+ run: (command, args, input4) => new Promise((resolve40, reject) => {
2576
2598
  const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] });
2577
2599
  let stdout = "";
2578
2600
  let stderr = "";
@@ -2589,7 +2611,7 @@ var nativeRunner = {
2589
2611
  if (code === 0) resolve40(stdout);
2590
2612
  else reject(new SecretCommandError(command, code, stderr.trim() || `${command} failed`));
2591
2613
  });
2592
- if (input3 !== void 0) child.stdin.end(input3);
2614
+ if (input4 !== void 0) child.stdin.end(input4);
2593
2615
  else child.stdin.end();
2594
2616
  })
2595
2617
  };
@@ -2669,7 +2691,7 @@ var WindowsCredentialManagerStore = class {
2669
2691
  this.commands = commands;
2670
2692
  }
2671
2693
  commands;
2672
- run(target, body, input3) {
2694
+ run(target, body, input4) {
2673
2695
  return this.commands.run(
2674
2696
  "powershell.exe",
2675
2697
  [
@@ -2678,11 +2700,11 @@ var WindowsCredentialManagerStore = class {
2678
2700
  "-EncodedCommand",
2679
2701
  encodedPowerShell(powershellPrelude(target) + body)
2680
2702
  ],
2681
- input3
2703
+ input4
2682
2704
  );
2683
2705
  }
2684
2706
  async read(service, account) {
2685
- const output = await this.run(
2707
+ const output2 = await this.run(
2686
2708
  powerShellTarget(service, account),
2687
2709
  `
2688
2710
  $credentialPtr = [IntPtr]::Zero
@@ -2698,7 +2720,7 @@ try {
2698
2720
  } finally { [CodeSentinelCredentialNative]::CredFree($credentialPtr) }
2699
2721
  `
2700
2722
  );
2701
- return output.trim() ? Buffer.from(output.trim(), "base64").toString("utf8") : null;
2723
+ return output2.trim() ? Buffer.from(output2.trim(), "base64").toString("utf8") : null;
2702
2724
  }
2703
2725
  async write(service, account, value) {
2704
2726
  await this.run(
@@ -2749,6 +2771,41 @@ var createPlatformCredentialStore = (platform = process.platform) => new SecretB
2749
2771
  var createPlatformAiCredentialStore = (platform = process.platform) => new SecretBackedAiCredentialStore(createPlatformSecretStore(platform));
2750
2772
  var createPlatformRetryKeyProvider = (platform = process.platform) => new SecretBackedRetryKeyProvider(createPlatformSecretStore(platform));
2751
2773
 
2774
+ // src/auth/session.ts
2775
+ var REFRESH_BEFORE_EXPIRY_MS = 3e4;
2776
+ var accessTokenNeedsRefresh = (credential, now = Date.now()) => {
2777
+ if (!credential.expiresAt) return false;
2778
+ const expiresAt = Date.parse(credential.expiresAt);
2779
+ return !Number.isFinite(expiresAt) || expiresAt <= now + REFRESH_BEFORE_EXPIRY_MS;
2780
+ };
2781
+ var getAuthenticatedCredential = async (options) => {
2782
+ const serverUrl = new URL(options.server).origin;
2783
+ const credential = await options.store.read(serverUrl);
2784
+ if (!credential) throw new Error("Not authenticated. Run `cs auth login --server <url>`.");
2785
+ const now = options.now ?? Date.now;
2786
+ if (!options.forceRefresh && !accessTokenNeedsRefresh(credential, now())) return credential;
2787
+ if (!credential.refreshToken) {
2788
+ throw new Error("Credential expired. Run `cs auth login --server <url>`.");
2789
+ }
2790
+ const refreshed = await (options.refresh ?? refreshDeviceCredential)(
2791
+ serverUrl,
2792
+ credential.refreshToken
2793
+ );
2794
+ if (refreshed.status === "invalid") {
2795
+ await options.store.remove(serverUrl);
2796
+ throw new Error("Credential expired. Run `cs auth login --server <url>`.");
2797
+ }
2798
+ const updated = {
2799
+ serverUrl,
2800
+ subject: refreshed.subject,
2801
+ accessToken: refreshed.accessToken,
2802
+ refreshToken: refreshed.refreshToken,
2803
+ expiresAt: new Date(now() + refreshed.expiresIn * 1e3).toISOString()
2804
+ };
2805
+ await options.store.write(updated);
2806
+ return updated;
2807
+ };
2808
+
2752
2809
  // src/exit-codes.ts
2753
2810
  var EXIT = {
2754
2811
  /** Success — no findings of severity 'error' or 'blocker'. */
@@ -2775,9 +2832,9 @@ var FileProtectedRetryStore = class {
2775
2832
  }
2776
2833
  keys;
2777
2834
  #directory;
2778
- async enqueue(input3) {
2835
+ async enqueue(input4) {
2779
2836
  const entry = {
2780
- ...input3,
2837
+ ...input4,
2781
2838
  schemaVersion: 1,
2782
2839
  expiresAt: new Date(Date.now() + TTL_MS).toISOString()
2783
2840
  };
@@ -2869,6 +2926,7 @@ var defaults = () => ({
2869
2926
  store: credentialStore(),
2870
2927
  start: startDeviceAuthorization,
2871
2928
  poll: pollDeviceAuthorization,
2929
+ refresh: refreshDeviceCredential,
2872
2930
  revoke: revokeDeviceCredential,
2873
2931
  openBrowser,
2874
2932
  sleep,
@@ -2917,6 +2975,7 @@ var runAuthLogin = async (options) => {
2917
2975
  serverUrl: new URL(options.server).origin,
2918
2976
  subject: poll.subject,
2919
2977
  accessToken: poll.accessToken,
2978
+ refreshToken: poll.refreshToken,
2920
2979
  expiresAt: new Date(deps.now() + poll.expiresIn * 1e3).toISOString()
2921
2980
  });
2922
2981
  write(`Authenticated as ${poll.subject}. Credential saved to the system keychain.`);
@@ -2930,28 +2989,30 @@ var runAuthLogin = async (options) => {
2930
2989
  writeError("Browser authorization expired. Run `cs auth login` again.");
2931
2990
  return EXIT.RUNTIME;
2932
2991
  };
2933
- var runAuthStatus = async (input3) => {
2934
- const store = input3.dependencies?.store ?? credentialStore();
2935
- const now = input3.dependencies?.now ?? Date.now;
2936
- const write = input3.write ?? console.log;
2937
- const server = new URL(input3.server).origin;
2938
- const credential = await store.read(server);
2939
- if (!credential) {
2940
- write("Not authenticated. Run `cs auth login --server <url>`.");
2941
- return EXIT.USAGE;
2942
- }
2943
- if (credential.expiresAt && Date.parse(credential.expiresAt) <= now()) {
2944
- write("Credential expired. Run `cs auth login --server <url>`.");
2992
+ var runAuthStatus = async (input4) => {
2993
+ const store = input4.dependencies?.store ?? credentialStore();
2994
+ const now = input4.dependencies?.now ?? Date.now;
2995
+ const write = input4.write ?? console.log;
2996
+ const server = new URL(input4.server).origin;
2997
+ try {
2998
+ const credential = await getAuthenticatedCredential({
2999
+ server,
3000
+ store,
3001
+ now,
3002
+ refresh: input4.dependencies?.refresh
3003
+ });
3004
+ write(`Authenticated as ${credential.subject} at ${server}.`);
3005
+ return EXIT.SUCCESS;
3006
+ } catch (error) {
3007
+ write(error instanceof Error ? error.message : "Unable to check authentication status.");
2945
3008
  return EXIT.USAGE;
2946
3009
  }
2947
- write(`Authenticated as ${credential.subject} at ${server}.`);
2948
- return EXIT.SUCCESS;
2949
3010
  };
2950
- var runAuthLogout = async (input3) => {
2951
- const store = input3.dependencies?.store ?? credentialStore();
2952
- const revoke = input3.dependencies?.revoke ?? revokeDeviceCredential;
2953
- const write = input3.write ?? console.log;
2954
- const server = new URL(input3.server).origin;
3011
+ var runAuthLogout = async (input4) => {
3012
+ const store = input4.dependencies?.store ?? credentialStore();
3013
+ const revoke = input4.dependencies?.revoke ?? revokeDeviceCredential;
3014
+ const write = input4.write ?? console.log;
3015
+ const server = new URL(input4.server).origin;
2955
3016
  const credential = await store.read(server);
2956
3017
  if (credential) {
2957
3018
  try {
@@ -2962,7 +3023,7 @@ var runAuthLogout = async (input3) => {
2962
3023
  if (credential) {
2963
3024
  try {
2964
3025
  await new FileProtectedRetryStore(
2965
- input3.path ?? process.cwd(),
3026
+ input4.path ?? process.cwd(),
2966
3027
  createPlatformRetryKeyProvider()
2967
3028
  ).removeIdentity(server, credential.subject);
2968
3029
  } catch {
@@ -3632,41 +3693,41 @@ var ZodType = class {
3632
3693
  get description() {
3633
3694
  return this._def.description;
3634
3695
  }
3635
- _getType(input3) {
3636
- return getParsedType(input3.data);
3696
+ _getType(input4) {
3697
+ return getParsedType(input4.data);
3637
3698
  }
3638
- _getOrReturnCtx(input3, ctx) {
3699
+ _getOrReturnCtx(input4, ctx) {
3639
3700
  return ctx || {
3640
- common: input3.parent.common,
3641
- data: input3.data,
3642
- parsedType: getParsedType(input3.data),
3701
+ common: input4.parent.common,
3702
+ data: input4.data,
3703
+ parsedType: getParsedType(input4.data),
3643
3704
  schemaErrorMap: this._def.errorMap,
3644
- path: input3.path,
3645
- parent: input3.parent
3705
+ path: input4.path,
3706
+ parent: input4.parent
3646
3707
  };
3647
3708
  }
3648
- _processInputParams(input3) {
3709
+ _processInputParams(input4) {
3649
3710
  return {
3650
3711
  status: new ParseStatus(),
3651
3712
  ctx: {
3652
- common: input3.parent.common,
3653
- data: input3.data,
3654
- parsedType: getParsedType(input3.data),
3713
+ common: input4.parent.common,
3714
+ data: input4.data,
3715
+ parsedType: getParsedType(input4.data),
3655
3716
  schemaErrorMap: this._def.errorMap,
3656
- path: input3.path,
3657
- parent: input3.parent
3717
+ path: input4.path,
3718
+ parent: input4.parent
3658
3719
  }
3659
3720
  };
3660
3721
  }
3661
- _parseSync(input3) {
3662
- const result = this._parse(input3);
3722
+ _parseSync(input4) {
3723
+ const result = this._parse(input4);
3663
3724
  if (isAsync(result)) {
3664
3725
  throw new Error("Synchronous parse encountered promise.");
3665
3726
  }
3666
3727
  return result;
3667
3728
  }
3668
- _parseAsync(input3) {
3669
- const result = this._parse(input3);
3729
+ _parseAsync(input4) {
3730
+ const result = this._parse(input4);
3670
3731
  return Promise.resolve(result);
3671
3732
  }
3672
3733
  parse(data, params) {
@@ -3992,13 +4053,13 @@ function isValidCidr(ip, version2) {
3992
4053
  return false;
3993
4054
  }
3994
4055
  var ZodString = class _ZodString extends ZodType {
3995
- _parse(input3) {
4056
+ _parse(input4) {
3996
4057
  if (this._def.coerce) {
3997
- input3.data = String(input3.data);
4058
+ input4.data = String(input4.data);
3998
4059
  }
3999
- const parsedType = this._getType(input3);
4060
+ const parsedType = this._getType(input4);
4000
4061
  if (parsedType !== ZodParsedType.string) {
4001
- const ctx2 = this._getOrReturnCtx(input3);
4062
+ const ctx2 = this._getOrReturnCtx(input4);
4002
4063
  addIssueToContext(ctx2, {
4003
4064
  code: ZodIssueCode.invalid_type,
4004
4065
  expected: ZodParsedType.string,
@@ -4010,8 +4071,8 @@ var ZodString = class _ZodString extends ZodType {
4010
4071
  let ctx = void 0;
4011
4072
  for (const check of this._def.checks) {
4012
4073
  if (check.kind === "min") {
4013
- if (input3.data.length < check.value) {
4014
- ctx = this._getOrReturnCtx(input3, ctx);
4074
+ if (input4.data.length < check.value) {
4075
+ ctx = this._getOrReturnCtx(input4, ctx);
4015
4076
  addIssueToContext(ctx, {
4016
4077
  code: ZodIssueCode.too_small,
4017
4078
  minimum: check.value,
@@ -4023,8 +4084,8 @@ var ZodString = class _ZodString extends ZodType {
4023
4084
  status.dirty();
4024
4085
  }
4025
4086
  } else if (check.kind === "max") {
4026
- if (input3.data.length > check.value) {
4027
- ctx = this._getOrReturnCtx(input3, ctx);
4087
+ if (input4.data.length > check.value) {
4088
+ ctx = this._getOrReturnCtx(input4, ctx);
4028
4089
  addIssueToContext(ctx, {
4029
4090
  code: ZodIssueCode.too_big,
4030
4091
  maximum: check.value,
@@ -4036,10 +4097,10 @@ var ZodString = class _ZodString extends ZodType {
4036
4097
  status.dirty();
4037
4098
  }
4038
4099
  } else if (check.kind === "length") {
4039
- const tooBig = input3.data.length > check.value;
4040
- const tooSmall = input3.data.length < check.value;
4100
+ const tooBig = input4.data.length > check.value;
4101
+ const tooSmall = input4.data.length < check.value;
4041
4102
  if (tooBig || tooSmall) {
4042
- ctx = this._getOrReturnCtx(input3, ctx);
4103
+ ctx = this._getOrReturnCtx(input4, ctx);
4043
4104
  if (tooBig) {
4044
4105
  addIssueToContext(ctx, {
4045
4106
  code: ZodIssueCode.too_big,
@@ -4062,8 +4123,8 @@ var ZodString = class _ZodString extends ZodType {
4062
4123
  status.dirty();
4063
4124
  }
4064
4125
  } else if (check.kind === "email") {
4065
- if (!emailRegex.test(input3.data)) {
4066
- ctx = this._getOrReturnCtx(input3, ctx);
4126
+ if (!emailRegex.test(input4.data)) {
4127
+ ctx = this._getOrReturnCtx(input4, ctx);
4067
4128
  addIssueToContext(ctx, {
4068
4129
  validation: "email",
4069
4130
  code: ZodIssueCode.invalid_string,
@@ -4075,8 +4136,8 @@ var ZodString = class _ZodString extends ZodType {
4075
4136
  if (!emojiRegex) {
4076
4137
  emojiRegex = new RegExp(_emojiRegex, "u");
4077
4138
  }
4078
- if (!emojiRegex.test(input3.data)) {
4079
- ctx = this._getOrReturnCtx(input3, ctx);
4139
+ if (!emojiRegex.test(input4.data)) {
4140
+ ctx = this._getOrReturnCtx(input4, ctx);
4080
4141
  addIssueToContext(ctx, {
4081
4142
  validation: "emoji",
4082
4143
  code: ZodIssueCode.invalid_string,
@@ -4085,8 +4146,8 @@ var ZodString = class _ZodString extends ZodType {
4085
4146
  status.dirty();
4086
4147
  }
4087
4148
  } else if (check.kind === "uuid") {
4088
- if (!uuidRegex.test(input3.data)) {
4089
- ctx = this._getOrReturnCtx(input3, ctx);
4149
+ if (!uuidRegex.test(input4.data)) {
4150
+ ctx = this._getOrReturnCtx(input4, ctx);
4090
4151
  addIssueToContext(ctx, {
4091
4152
  validation: "uuid",
4092
4153
  code: ZodIssueCode.invalid_string,
@@ -4095,8 +4156,8 @@ var ZodString = class _ZodString extends ZodType {
4095
4156
  status.dirty();
4096
4157
  }
4097
4158
  } else if (check.kind === "nanoid") {
4098
- if (!nanoidRegex.test(input3.data)) {
4099
- ctx = this._getOrReturnCtx(input3, ctx);
4159
+ if (!nanoidRegex.test(input4.data)) {
4160
+ ctx = this._getOrReturnCtx(input4, ctx);
4100
4161
  addIssueToContext(ctx, {
4101
4162
  validation: "nanoid",
4102
4163
  code: ZodIssueCode.invalid_string,
@@ -4105,8 +4166,8 @@ var ZodString = class _ZodString extends ZodType {
4105
4166
  status.dirty();
4106
4167
  }
4107
4168
  } else if (check.kind === "cuid") {
4108
- if (!cuidRegex.test(input3.data)) {
4109
- ctx = this._getOrReturnCtx(input3, ctx);
4169
+ if (!cuidRegex.test(input4.data)) {
4170
+ ctx = this._getOrReturnCtx(input4, ctx);
4110
4171
  addIssueToContext(ctx, {
4111
4172
  validation: "cuid",
4112
4173
  code: ZodIssueCode.invalid_string,
@@ -4115,8 +4176,8 @@ var ZodString = class _ZodString extends ZodType {
4115
4176
  status.dirty();
4116
4177
  }
4117
4178
  } else if (check.kind === "cuid2") {
4118
- if (!cuid2Regex.test(input3.data)) {
4119
- ctx = this._getOrReturnCtx(input3, ctx);
4179
+ if (!cuid2Regex.test(input4.data)) {
4180
+ ctx = this._getOrReturnCtx(input4, ctx);
4120
4181
  addIssueToContext(ctx, {
4121
4182
  validation: "cuid2",
4122
4183
  code: ZodIssueCode.invalid_string,
@@ -4125,8 +4186,8 @@ var ZodString = class _ZodString extends ZodType {
4125
4186
  status.dirty();
4126
4187
  }
4127
4188
  } else if (check.kind === "ulid") {
4128
- if (!ulidRegex.test(input3.data)) {
4129
- ctx = this._getOrReturnCtx(input3, ctx);
4189
+ if (!ulidRegex.test(input4.data)) {
4190
+ ctx = this._getOrReturnCtx(input4, ctx);
4130
4191
  addIssueToContext(ctx, {
4131
4192
  validation: "ulid",
4132
4193
  code: ZodIssueCode.invalid_string,
@@ -4136,9 +4197,9 @@ var ZodString = class _ZodString extends ZodType {
4136
4197
  }
4137
4198
  } else if (check.kind === "url") {
4138
4199
  try {
4139
- new URL(input3.data);
4200
+ new URL(input4.data);
4140
4201
  } catch {
4141
- ctx = this._getOrReturnCtx(input3, ctx);
4202
+ ctx = this._getOrReturnCtx(input4, ctx);
4142
4203
  addIssueToContext(ctx, {
4143
4204
  validation: "url",
4144
4205
  code: ZodIssueCode.invalid_string,
@@ -4148,9 +4209,9 @@ var ZodString = class _ZodString extends ZodType {
4148
4209
  }
4149
4210
  } else if (check.kind === "regex") {
4150
4211
  check.regex.lastIndex = 0;
4151
- const testResult = check.regex.test(input3.data);
4212
+ const testResult = check.regex.test(input4.data);
4152
4213
  if (!testResult) {
4153
- ctx = this._getOrReturnCtx(input3, ctx);
4214
+ ctx = this._getOrReturnCtx(input4, ctx);
4154
4215
  addIssueToContext(ctx, {
4155
4216
  validation: "regex",
4156
4217
  code: ZodIssueCode.invalid_string,
@@ -4159,10 +4220,10 @@ var ZodString = class _ZodString extends ZodType {
4159
4220
  status.dirty();
4160
4221
  }
4161
4222
  } else if (check.kind === "trim") {
4162
- input3.data = input3.data.trim();
4223
+ input4.data = input4.data.trim();
4163
4224
  } else if (check.kind === "includes") {
4164
- if (!input3.data.includes(check.value, check.position)) {
4165
- ctx = this._getOrReturnCtx(input3, ctx);
4225
+ if (!input4.data.includes(check.value, check.position)) {
4226
+ ctx = this._getOrReturnCtx(input4, ctx);
4166
4227
  addIssueToContext(ctx, {
4167
4228
  code: ZodIssueCode.invalid_string,
4168
4229
  validation: { includes: check.value, position: check.position },
@@ -4171,12 +4232,12 @@ var ZodString = class _ZodString extends ZodType {
4171
4232
  status.dirty();
4172
4233
  }
4173
4234
  } else if (check.kind === "toLowerCase") {
4174
- input3.data = input3.data.toLowerCase();
4235
+ input4.data = input4.data.toLowerCase();
4175
4236
  } else if (check.kind === "toUpperCase") {
4176
- input3.data = input3.data.toUpperCase();
4237
+ input4.data = input4.data.toUpperCase();
4177
4238
  } else if (check.kind === "startsWith") {
4178
- if (!input3.data.startsWith(check.value)) {
4179
- ctx = this._getOrReturnCtx(input3, ctx);
4239
+ if (!input4.data.startsWith(check.value)) {
4240
+ ctx = this._getOrReturnCtx(input4, ctx);
4180
4241
  addIssueToContext(ctx, {
4181
4242
  code: ZodIssueCode.invalid_string,
4182
4243
  validation: { startsWith: check.value },
@@ -4185,8 +4246,8 @@ var ZodString = class _ZodString extends ZodType {
4185
4246
  status.dirty();
4186
4247
  }
4187
4248
  } else if (check.kind === "endsWith") {
4188
- if (!input3.data.endsWith(check.value)) {
4189
- ctx = this._getOrReturnCtx(input3, ctx);
4249
+ if (!input4.data.endsWith(check.value)) {
4250
+ ctx = this._getOrReturnCtx(input4, ctx);
4190
4251
  addIssueToContext(ctx, {
4191
4252
  code: ZodIssueCode.invalid_string,
4192
4253
  validation: { endsWith: check.value },
@@ -4196,8 +4257,8 @@ var ZodString = class _ZodString extends ZodType {
4196
4257
  }
4197
4258
  } else if (check.kind === "datetime") {
4198
4259
  const regex = datetimeRegex(check);
4199
- if (!regex.test(input3.data)) {
4200
- ctx = this._getOrReturnCtx(input3, ctx);
4260
+ if (!regex.test(input4.data)) {
4261
+ ctx = this._getOrReturnCtx(input4, ctx);
4201
4262
  addIssueToContext(ctx, {
4202
4263
  code: ZodIssueCode.invalid_string,
4203
4264
  validation: "datetime",
@@ -4207,8 +4268,8 @@ var ZodString = class _ZodString extends ZodType {
4207
4268
  }
4208
4269
  } else if (check.kind === "date") {
4209
4270
  const regex = dateRegex;
4210
- if (!regex.test(input3.data)) {
4211
- ctx = this._getOrReturnCtx(input3, ctx);
4271
+ if (!regex.test(input4.data)) {
4272
+ ctx = this._getOrReturnCtx(input4, ctx);
4212
4273
  addIssueToContext(ctx, {
4213
4274
  code: ZodIssueCode.invalid_string,
4214
4275
  validation: "date",
@@ -4218,8 +4279,8 @@ var ZodString = class _ZodString extends ZodType {
4218
4279
  }
4219
4280
  } else if (check.kind === "time") {
4220
4281
  const regex = timeRegex(check);
4221
- if (!regex.test(input3.data)) {
4222
- ctx = this._getOrReturnCtx(input3, ctx);
4282
+ if (!regex.test(input4.data)) {
4283
+ ctx = this._getOrReturnCtx(input4, ctx);
4223
4284
  addIssueToContext(ctx, {
4224
4285
  code: ZodIssueCode.invalid_string,
4225
4286
  validation: "time",
@@ -4228,8 +4289,8 @@ var ZodString = class _ZodString extends ZodType {
4228
4289
  status.dirty();
4229
4290
  }
4230
4291
  } else if (check.kind === "duration") {
4231
- if (!durationRegex.test(input3.data)) {
4232
- ctx = this._getOrReturnCtx(input3, ctx);
4292
+ if (!durationRegex.test(input4.data)) {
4293
+ ctx = this._getOrReturnCtx(input4, ctx);
4233
4294
  addIssueToContext(ctx, {
4234
4295
  validation: "duration",
4235
4296
  code: ZodIssueCode.invalid_string,
@@ -4238,8 +4299,8 @@ var ZodString = class _ZodString extends ZodType {
4238
4299
  status.dirty();
4239
4300
  }
4240
4301
  } else if (check.kind === "ip") {
4241
- if (!isValidIP(input3.data, check.version)) {
4242
- ctx = this._getOrReturnCtx(input3, ctx);
4302
+ if (!isValidIP(input4.data, check.version)) {
4303
+ ctx = this._getOrReturnCtx(input4, ctx);
4243
4304
  addIssueToContext(ctx, {
4244
4305
  validation: "ip",
4245
4306
  code: ZodIssueCode.invalid_string,
@@ -4248,8 +4309,8 @@ var ZodString = class _ZodString extends ZodType {
4248
4309
  status.dirty();
4249
4310
  }
4250
4311
  } else if (check.kind === "jwt") {
4251
- if (!isValidJWT(input3.data, check.alg)) {
4252
- ctx = this._getOrReturnCtx(input3, ctx);
4312
+ if (!isValidJWT(input4.data, check.alg)) {
4313
+ ctx = this._getOrReturnCtx(input4, ctx);
4253
4314
  addIssueToContext(ctx, {
4254
4315
  validation: "jwt",
4255
4316
  code: ZodIssueCode.invalid_string,
@@ -4258,8 +4319,8 @@ var ZodString = class _ZodString extends ZodType {
4258
4319
  status.dirty();
4259
4320
  }
4260
4321
  } else if (check.kind === "cidr") {
4261
- if (!isValidCidr(input3.data, check.version)) {
4262
- ctx = this._getOrReturnCtx(input3, ctx);
4322
+ if (!isValidCidr(input4.data, check.version)) {
4323
+ ctx = this._getOrReturnCtx(input4, ctx);
4263
4324
  addIssueToContext(ctx, {
4264
4325
  validation: "cidr",
4265
4326
  code: ZodIssueCode.invalid_string,
@@ -4268,8 +4329,8 @@ var ZodString = class _ZodString extends ZodType {
4268
4329
  status.dirty();
4269
4330
  }
4270
4331
  } else if (check.kind === "base64") {
4271
- if (!base64Regex.test(input3.data)) {
4272
- ctx = this._getOrReturnCtx(input3, ctx);
4332
+ if (!base64Regex.test(input4.data)) {
4333
+ ctx = this._getOrReturnCtx(input4, ctx);
4273
4334
  addIssueToContext(ctx, {
4274
4335
  validation: "base64",
4275
4336
  code: ZodIssueCode.invalid_string,
@@ -4278,8 +4339,8 @@ var ZodString = class _ZodString extends ZodType {
4278
4339
  status.dirty();
4279
4340
  }
4280
4341
  } else if (check.kind === "base64url") {
4281
- if (!base64urlRegex.test(input3.data)) {
4282
- ctx = this._getOrReturnCtx(input3, ctx);
4342
+ if (!base64urlRegex.test(input4.data)) {
4343
+ ctx = this._getOrReturnCtx(input4, ctx);
4283
4344
  addIssueToContext(ctx, {
4284
4345
  validation: "base64url",
4285
4346
  code: ZodIssueCode.invalid_string,
@@ -4291,7 +4352,7 @@ var ZodString = class _ZodString extends ZodType {
4291
4352
  util.assertNever(check);
4292
4353
  }
4293
4354
  }
4294
- return { status: status.value, value: input3.data };
4355
+ return { status: status.value, value: input4.data };
4295
4356
  }
4296
4357
  _regex(regex, validation, message) {
4297
4358
  return this.refinement((data) => regex.test(data), {
@@ -4552,13 +4613,13 @@ var ZodNumber = class _ZodNumber extends ZodType {
4552
4613
  this.max = this.lte;
4553
4614
  this.step = this.multipleOf;
4554
4615
  }
4555
- _parse(input3) {
4616
+ _parse(input4) {
4556
4617
  if (this._def.coerce) {
4557
- input3.data = Number(input3.data);
4618
+ input4.data = Number(input4.data);
4558
4619
  }
4559
- const parsedType = this._getType(input3);
4620
+ const parsedType = this._getType(input4);
4560
4621
  if (parsedType !== ZodParsedType.number) {
4561
- const ctx2 = this._getOrReturnCtx(input3);
4622
+ const ctx2 = this._getOrReturnCtx(input4);
4562
4623
  addIssueToContext(ctx2, {
4563
4624
  code: ZodIssueCode.invalid_type,
4564
4625
  expected: ZodParsedType.number,
@@ -4570,8 +4631,8 @@ var ZodNumber = class _ZodNumber extends ZodType {
4570
4631
  const status = new ParseStatus();
4571
4632
  for (const check of this._def.checks) {
4572
4633
  if (check.kind === "int") {
4573
- if (!util.isInteger(input3.data)) {
4574
- ctx = this._getOrReturnCtx(input3, ctx);
4634
+ if (!util.isInteger(input4.data)) {
4635
+ ctx = this._getOrReturnCtx(input4, ctx);
4575
4636
  addIssueToContext(ctx, {
4576
4637
  code: ZodIssueCode.invalid_type,
4577
4638
  expected: "integer",
@@ -4581,9 +4642,9 @@ var ZodNumber = class _ZodNumber extends ZodType {
4581
4642
  status.dirty();
4582
4643
  }
4583
4644
  } else if (check.kind === "min") {
4584
- const tooSmall = check.inclusive ? input3.data < check.value : input3.data <= check.value;
4645
+ const tooSmall = check.inclusive ? input4.data < check.value : input4.data <= check.value;
4585
4646
  if (tooSmall) {
4586
- ctx = this._getOrReturnCtx(input3, ctx);
4647
+ ctx = this._getOrReturnCtx(input4, ctx);
4587
4648
  addIssueToContext(ctx, {
4588
4649
  code: ZodIssueCode.too_small,
4589
4650
  minimum: check.value,
@@ -4595,9 +4656,9 @@ var ZodNumber = class _ZodNumber extends ZodType {
4595
4656
  status.dirty();
4596
4657
  }
4597
4658
  } else if (check.kind === "max") {
4598
- const tooBig = check.inclusive ? input3.data > check.value : input3.data >= check.value;
4659
+ const tooBig = check.inclusive ? input4.data > check.value : input4.data >= check.value;
4599
4660
  if (tooBig) {
4600
- ctx = this._getOrReturnCtx(input3, ctx);
4661
+ ctx = this._getOrReturnCtx(input4, ctx);
4601
4662
  addIssueToContext(ctx, {
4602
4663
  code: ZodIssueCode.too_big,
4603
4664
  maximum: check.value,
@@ -4609,8 +4670,8 @@ var ZodNumber = class _ZodNumber extends ZodType {
4609
4670
  status.dirty();
4610
4671
  }
4611
4672
  } else if (check.kind === "multipleOf") {
4612
- if (floatSafeRemainder(input3.data, check.value) !== 0) {
4613
- ctx = this._getOrReturnCtx(input3, ctx);
4673
+ if (floatSafeRemainder(input4.data, check.value) !== 0) {
4674
+ ctx = this._getOrReturnCtx(input4, ctx);
4614
4675
  addIssueToContext(ctx, {
4615
4676
  code: ZodIssueCode.not_multiple_of,
4616
4677
  multipleOf: check.value,
@@ -4619,8 +4680,8 @@ var ZodNumber = class _ZodNumber extends ZodType {
4619
4680
  status.dirty();
4620
4681
  }
4621
4682
  } else if (check.kind === "finite") {
4622
- if (!Number.isFinite(input3.data)) {
4623
- ctx = this._getOrReturnCtx(input3, ctx);
4683
+ if (!Number.isFinite(input4.data)) {
4684
+ ctx = this._getOrReturnCtx(input4, ctx);
4624
4685
  addIssueToContext(ctx, {
4625
4686
  code: ZodIssueCode.not_finite,
4626
4687
  message: check.message
@@ -4631,7 +4692,7 @@ var ZodNumber = class _ZodNumber extends ZodType {
4631
4692
  util.assertNever(check);
4632
4693
  }
4633
4694
  }
4634
- return { status: status.value, value: input3.data };
4695
+ return { status: status.value, value: input4.data };
4635
4696
  }
4636
4697
  gte(value, message) {
4637
4698
  return this.setLimit("min", value, true, errorUtil.toString(message));
@@ -4783,25 +4844,25 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
4783
4844
  this.min = this.gte;
4784
4845
  this.max = this.lte;
4785
4846
  }
4786
- _parse(input3) {
4847
+ _parse(input4) {
4787
4848
  if (this._def.coerce) {
4788
4849
  try {
4789
- input3.data = BigInt(input3.data);
4850
+ input4.data = BigInt(input4.data);
4790
4851
  } catch {
4791
- return this._getInvalidInput(input3);
4852
+ return this._getInvalidInput(input4);
4792
4853
  }
4793
4854
  }
4794
- const parsedType = this._getType(input3);
4855
+ const parsedType = this._getType(input4);
4795
4856
  if (parsedType !== ZodParsedType.bigint) {
4796
- return this._getInvalidInput(input3);
4857
+ return this._getInvalidInput(input4);
4797
4858
  }
4798
4859
  let ctx = void 0;
4799
4860
  const status = new ParseStatus();
4800
4861
  for (const check of this._def.checks) {
4801
4862
  if (check.kind === "min") {
4802
- const tooSmall = check.inclusive ? input3.data < check.value : input3.data <= check.value;
4863
+ const tooSmall = check.inclusive ? input4.data < check.value : input4.data <= check.value;
4803
4864
  if (tooSmall) {
4804
- ctx = this._getOrReturnCtx(input3, ctx);
4865
+ ctx = this._getOrReturnCtx(input4, ctx);
4805
4866
  addIssueToContext(ctx, {
4806
4867
  code: ZodIssueCode.too_small,
4807
4868
  type: "bigint",
@@ -4812,9 +4873,9 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
4812
4873
  status.dirty();
4813
4874
  }
4814
4875
  } else if (check.kind === "max") {
4815
- const tooBig = check.inclusive ? input3.data > check.value : input3.data >= check.value;
4876
+ const tooBig = check.inclusive ? input4.data > check.value : input4.data >= check.value;
4816
4877
  if (tooBig) {
4817
- ctx = this._getOrReturnCtx(input3, ctx);
4878
+ ctx = this._getOrReturnCtx(input4, ctx);
4818
4879
  addIssueToContext(ctx, {
4819
4880
  code: ZodIssueCode.too_big,
4820
4881
  type: "bigint",
@@ -4825,8 +4886,8 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
4825
4886
  status.dirty();
4826
4887
  }
4827
4888
  } else if (check.kind === "multipleOf") {
4828
- if (input3.data % check.value !== BigInt(0)) {
4829
- ctx = this._getOrReturnCtx(input3, ctx);
4889
+ if (input4.data % check.value !== BigInt(0)) {
4890
+ ctx = this._getOrReturnCtx(input4, ctx);
4830
4891
  addIssueToContext(ctx, {
4831
4892
  code: ZodIssueCode.not_multiple_of,
4832
4893
  multipleOf: check.value,
@@ -4838,10 +4899,10 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
4838
4899
  util.assertNever(check);
4839
4900
  }
4840
4901
  }
4841
- return { status: status.value, value: input3.data };
4902
+ return { status: status.value, value: input4.data };
4842
4903
  }
4843
- _getInvalidInput(input3) {
4844
- const ctx = this._getOrReturnCtx(input3);
4904
+ _getInvalidInput(input4) {
4905
+ const ctx = this._getOrReturnCtx(input4);
4845
4906
  addIssueToContext(ctx, {
4846
4907
  code: ZodIssueCode.invalid_type,
4847
4908
  expected: ZodParsedType.bigint,
@@ -4950,13 +5011,13 @@ ZodBigInt.create = (params) => {
4950
5011
  });
4951
5012
  };
4952
5013
  var ZodBoolean = class extends ZodType {
4953
- _parse(input3) {
5014
+ _parse(input4) {
4954
5015
  if (this._def.coerce) {
4955
- input3.data = Boolean(input3.data);
5016
+ input4.data = Boolean(input4.data);
4956
5017
  }
4957
- const parsedType = this._getType(input3);
5018
+ const parsedType = this._getType(input4);
4958
5019
  if (parsedType !== ZodParsedType.boolean) {
4959
- const ctx = this._getOrReturnCtx(input3);
5020
+ const ctx = this._getOrReturnCtx(input4);
4960
5021
  addIssueToContext(ctx, {
4961
5022
  code: ZodIssueCode.invalid_type,
4962
5023
  expected: ZodParsedType.boolean,
@@ -4964,7 +5025,7 @@ var ZodBoolean = class extends ZodType {
4964
5025
  });
4965
5026
  return INVALID;
4966
5027
  }
4967
- return OK(input3.data);
5028
+ return OK(input4.data);
4968
5029
  }
4969
5030
  };
4970
5031
  ZodBoolean.create = (params) => {
@@ -4975,13 +5036,13 @@ ZodBoolean.create = (params) => {
4975
5036
  });
4976
5037
  };
4977
5038
  var ZodDate = class _ZodDate extends ZodType {
4978
- _parse(input3) {
5039
+ _parse(input4) {
4979
5040
  if (this._def.coerce) {
4980
- input3.data = new Date(input3.data);
5041
+ input4.data = new Date(input4.data);
4981
5042
  }
4982
- const parsedType = this._getType(input3);
5043
+ const parsedType = this._getType(input4);
4983
5044
  if (parsedType !== ZodParsedType.date) {
4984
- const ctx2 = this._getOrReturnCtx(input3);
5045
+ const ctx2 = this._getOrReturnCtx(input4);
4985
5046
  addIssueToContext(ctx2, {
4986
5047
  code: ZodIssueCode.invalid_type,
4987
5048
  expected: ZodParsedType.date,
@@ -4989,8 +5050,8 @@ var ZodDate = class _ZodDate extends ZodType {
4989
5050
  });
4990
5051
  return INVALID;
4991
5052
  }
4992
- if (Number.isNaN(input3.data.getTime())) {
4993
- const ctx2 = this._getOrReturnCtx(input3);
5053
+ if (Number.isNaN(input4.data.getTime())) {
5054
+ const ctx2 = this._getOrReturnCtx(input4);
4994
5055
  addIssueToContext(ctx2, {
4995
5056
  code: ZodIssueCode.invalid_date
4996
5057
  });
@@ -5000,8 +5061,8 @@ var ZodDate = class _ZodDate extends ZodType {
5000
5061
  let ctx = void 0;
5001
5062
  for (const check of this._def.checks) {
5002
5063
  if (check.kind === "min") {
5003
- if (input3.data.getTime() < check.value) {
5004
- ctx = this._getOrReturnCtx(input3, ctx);
5064
+ if (input4.data.getTime() < check.value) {
5065
+ ctx = this._getOrReturnCtx(input4, ctx);
5005
5066
  addIssueToContext(ctx, {
5006
5067
  code: ZodIssueCode.too_small,
5007
5068
  message: check.message,
@@ -5013,8 +5074,8 @@ var ZodDate = class _ZodDate extends ZodType {
5013
5074
  status.dirty();
5014
5075
  }
5015
5076
  } else if (check.kind === "max") {
5016
- if (input3.data.getTime() > check.value) {
5017
- ctx = this._getOrReturnCtx(input3, ctx);
5077
+ if (input4.data.getTime() > check.value) {
5078
+ ctx = this._getOrReturnCtx(input4, ctx);
5018
5079
  addIssueToContext(ctx, {
5019
5080
  code: ZodIssueCode.too_big,
5020
5081
  message: check.message,
@@ -5031,7 +5092,7 @@ var ZodDate = class _ZodDate extends ZodType {
5031
5092
  }
5032
5093
  return {
5033
5094
  status: status.value,
5034
- value: new Date(input3.data.getTime())
5095
+ value: new Date(input4.data.getTime())
5035
5096
  };
5036
5097
  }
5037
5098
  _addCheck(check) {
@@ -5084,10 +5145,10 @@ ZodDate.create = (params) => {
5084
5145
  });
5085
5146
  };
5086
5147
  var ZodSymbol = class extends ZodType {
5087
- _parse(input3) {
5088
- const parsedType = this._getType(input3);
5148
+ _parse(input4) {
5149
+ const parsedType = this._getType(input4);
5089
5150
  if (parsedType !== ZodParsedType.symbol) {
5090
- const ctx = this._getOrReturnCtx(input3);
5151
+ const ctx = this._getOrReturnCtx(input4);
5091
5152
  addIssueToContext(ctx, {
5092
5153
  code: ZodIssueCode.invalid_type,
5093
5154
  expected: ZodParsedType.symbol,
@@ -5095,7 +5156,7 @@ var ZodSymbol = class extends ZodType {
5095
5156
  });
5096
5157
  return INVALID;
5097
5158
  }
5098
- return OK(input3.data);
5159
+ return OK(input4.data);
5099
5160
  }
5100
5161
  };
5101
5162
  ZodSymbol.create = (params) => {
@@ -5105,10 +5166,10 @@ ZodSymbol.create = (params) => {
5105
5166
  });
5106
5167
  };
5107
5168
  var ZodUndefined = class extends ZodType {
5108
- _parse(input3) {
5109
- const parsedType = this._getType(input3);
5169
+ _parse(input4) {
5170
+ const parsedType = this._getType(input4);
5110
5171
  if (parsedType !== ZodParsedType.undefined) {
5111
- const ctx = this._getOrReturnCtx(input3);
5172
+ const ctx = this._getOrReturnCtx(input4);
5112
5173
  addIssueToContext(ctx, {
5113
5174
  code: ZodIssueCode.invalid_type,
5114
5175
  expected: ZodParsedType.undefined,
@@ -5116,7 +5177,7 @@ var ZodUndefined = class extends ZodType {
5116
5177
  });
5117
5178
  return INVALID;
5118
5179
  }
5119
- return OK(input3.data);
5180
+ return OK(input4.data);
5120
5181
  }
5121
5182
  };
5122
5183
  ZodUndefined.create = (params) => {
@@ -5126,10 +5187,10 @@ ZodUndefined.create = (params) => {
5126
5187
  });
5127
5188
  };
5128
5189
  var ZodNull = class extends ZodType {
5129
- _parse(input3) {
5130
- const parsedType = this._getType(input3);
5190
+ _parse(input4) {
5191
+ const parsedType = this._getType(input4);
5131
5192
  if (parsedType !== ZodParsedType.null) {
5132
- const ctx = this._getOrReturnCtx(input3);
5193
+ const ctx = this._getOrReturnCtx(input4);
5133
5194
  addIssueToContext(ctx, {
5134
5195
  code: ZodIssueCode.invalid_type,
5135
5196
  expected: ZodParsedType.null,
@@ -5137,7 +5198,7 @@ var ZodNull = class extends ZodType {
5137
5198
  });
5138
5199
  return INVALID;
5139
5200
  }
5140
- return OK(input3.data);
5201
+ return OK(input4.data);
5141
5202
  }
5142
5203
  };
5143
5204
  ZodNull.create = (params) => {
@@ -5151,8 +5212,8 @@ var ZodAny = class extends ZodType {
5151
5212
  super(...arguments);
5152
5213
  this._any = true;
5153
5214
  }
5154
- _parse(input3) {
5155
- return OK(input3.data);
5215
+ _parse(input4) {
5216
+ return OK(input4.data);
5156
5217
  }
5157
5218
  };
5158
5219
  ZodAny.create = (params) => {
@@ -5166,8 +5227,8 @@ var ZodUnknown = class extends ZodType {
5166
5227
  super(...arguments);
5167
5228
  this._unknown = true;
5168
5229
  }
5169
- _parse(input3) {
5170
- return OK(input3.data);
5230
+ _parse(input4) {
5231
+ return OK(input4.data);
5171
5232
  }
5172
5233
  };
5173
5234
  ZodUnknown.create = (params) => {
@@ -5177,8 +5238,8 @@ ZodUnknown.create = (params) => {
5177
5238
  });
5178
5239
  };
5179
5240
  var ZodNever = class extends ZodType {
5180
- _parse(input3) {
5181
- const ctx = this._getOrReturnCtx(input3);
5241
+ _parse(input4) {
5242
+ const ctx = this._getOrReturnCtx(input4);
5182
5243
  addIssueToContext(ctx, {
5183
5244
  code: ZodIssueCode.invalid_type,
5184
5245
  expected: ZodParsedType.never,
@@ -5194,10 +5255,10 @@ ZodNever.create = (params) => {
5194
5255
  });
5195
5256
  };
5196
5257
  var ZodVoid = class extends ZodType {
5197
- _parse(input3) {
5198
- const parsedType = this._getType(input3);
5258
+ _parse(input4) {
5259
+ const parsedType = this._getType(input4);
5199
5260
  if (parsedType !== ZodParsedType.undefined) {
5200
- const ctx = this._getOrReturnCtx(input3);
5261
+ const ctx = this._getOrReturnCtx(input4);
5201
5262
  addIssueToContext(ctx, {
5202
5263
  code: ZodIssueCode.invalid_type,
5203
5264
  expected: ZodParsedType.void,
@@ -5205,7 +5266,7 @@ var ZodVoid = class extends ZodType {
5205
5266
  });
5206
5267
  return INVALID;
5207
5268
  }
5208
- return OK(input3.data);
5269
+ return OK(input4.data);
5209
5270
  }
5210
5271
  };
5211
5272
  ZodVoid.create = (params) => {
@@ -5215,8 +5276,8 @@ ZodVoid.create = (params) => {
5215
5276
  });
5216
5277
  };
5217
5278
  var ZodArray = class _ZodArray extends ZodType {
5218
- _parse(input3) {
5219
- const { ctx, status } = this._processInputParams(input3);
5279
+ _parse(input4) {
5280
+ const { ctx, status } = this._processInputParams(input4);
5220
5281
  const def = this._def;
5221
5282
  if (ctx.parsedType !== ZodParsedType.array) {
5222
5283
  addIssueToContext(ctx, {
@@ -5356,10 +5417,10 @@ var ZodObject = class _ZodObject extends ZodType {
5356
5417
  this._cached = { shape, keys };
5357
5418
  return this._cached;
5358
5419
  }
5359
- _parse(input3) {
5360
- const parsedType = this._getType(input3);
5420
+ _parse(input4) {
5421
+ const parsedType = this._getType(input4);
5361
5422
  if (parsedType !== ZodParsedType.object) {
5362
- const ctx2 = this._getOrReturnCtx(input3);
5423
+ const ctx2 = this._getOrReturnCtx(input4);
5363
5424
  addIssueToContext(ctx2, {
5364
5425
  code: ZodIssueCode.invalid_type,
5365
5426
  expected: ZodParsedType.object,
@@ -5367,7 +5428,7 @@ var ZodObject = class _ZodObject extends ZodType {
5367
5428
  });
5368
5429
  return INVALID;
5369
5430
  }
5370
- const { status, ctx } = this._processInputParams(input3);
5431
+ const { status, ctx } = this._processInputParams(input4);
5371
5432
  const { shape, keys: shapeKeys } = this._getCached();
5372
5433
  const extraKeys = [];
5373
5434
  if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
@@ -5679,8 +5740,8 @@ ZodObject.lazycreate = (shape, params) => {
5679
5740
  });
5680
5741
  };
5681
5742
  var ZodUnion = class extends ZodType {
5682
- _parse(input3) {
5683
- const { ctx } = this._processInputParams(input3);
5743
+ _parse(input4) {
5744
+ const { ctx } = this._processInputParams(input4);
5684
5745
  const options = this._def.options;
5685
5746
  function handleResults(results) {
5686
5747
  for (const result of results) {
@@ -5801,8 +5862,8 @@ var getDiscriminator = (type) => {
5801
5862
  }
5802
5863
  };
5803
5864
  var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
5804
- _parse(input3) {
5805
- const { ctx } = this._processInputParams(input3);
5865
+ _parse(input4) {
5866
+ const { ctx } = this._processInputParams(input4);
5806
5867
  if (ctx.parsedType !== ZodParsedType.object) {
5807
5868
  addIssueToContext(ctx, {
5808
5869
  code: ZodIssueCode.invalid_type,
@@ -5915,8 +5976,8 @@ function mergeValues(a, b) {
5915
5976
  }
5916
5977
  }
5917
5978
  var ZodIntersection = class extends ZodType {
5918
- _parse(input3) {
5919
- const { status, ctx } = this._processInputParams(input3);
5979
+ _parse(input4) {
5980
+ const { status, ctx } = this._processInputParams(input4);
5920
5981
  const handleParsed = (parsedLeft, parsedRight) => {
5921
5982
  if (isAborted(parsedLeft) || isAborted(parsedRight)) {
5922
5983
  return INVALID;
@@ -5968,8 +6029,8 @@ ZodIntersection.create = (left, right, params) => {
5968
6029
  });
5969
6030
  };
5970
6031
  var ZodTuple = class _ZodTuple extends ZodType {
5971
- _parse(input3) {
5972
- const { status, ctx } = this._processInputParams(input3);
6032
+ _parse(input4) {
6033
+ const { status, ctx } = this._processInputParams(input4);
5973
6034
  if (ctx.parsedType !== ZodParsedType.array) {
5974
6035
  addIssueToContext(ctx, {
5975
6036
  code: ZodIssueCode.invalid_type,
@@ -6041,8 +6102,8 @@ var ZodRecord = class _ZodRecord extends ZodType {
6041
6102
  get valueSchema() {
6042
6103
  return this._def.valueType;
6043
6104
  }
6044
- _parse(input3) {
6045
- const { status, ctx } = this._processInputParams(input3);
6105
+ _parse(input4) {
6106
+ const { status, ctx } = this._processInputParams(input4);
6046
6107
  if (ctx.parsedType !== ZodParsedType.object) {
6047
6108
  addIssueToContext(ctx, {
6048
6109
  code: ZodIssueCode.invalid_type,
@@ -6094,8 +6155,8 @@ var ZodMap = class extends ZodType {
6094
6155
  get valueSchema() {
6095
6156
  return this._def.valueType;
6096
6157
  }
6097
- _parse(input3) {
6098
- const { status, ctx } = this._processInputParams(input3);
6158
+ _parse(input4) {
6159
+ const { status, ctx } = this._processInputParams(input4);
6099
6160
  if (ctx.parsedType !== ZodParsedType.map) {
6100
6161
  addIssueToContext(ctx, {
6101
6162
  code: ZodIssueCode.invalid_type,
@@ -6154,8 +6215,8 @@ ZodMap.create = (keyType, valueType, params) => {
6154
6215
  });
6155
6216
  };
6156
6217
  var ZodSet = class _ZodSet extends ZodType {
6157
- _parse(input3) {
6158
- const { status, ctx } = this._processInputParams(input3);
6218
+ _parse(input4) {
6219
+ const { status, ctx } = this._processInputParams(input4);
6159
6220
  if (ctx.parsedType !== ZodParsedType.set) {
6160
6221
  addIssueToContext(ctx, {
6161
6222
  code: ZodIssueCode.invalid_type,
@@ -6243,8 +6304,8 @@ var ZodFunction = class _ZodFunction extends ZodType {
6243
6304
  super(...arguments);
6244
6305
  this.validate = this.implement;
6245
6306
  }
6246
- _parse(input3) {
6247
- const { ctx } = this._processInputParams(input3);
6307
+ _parse(input4) {
6308
+ const { ctx } = this._processInputParams(input4);
6248
6309
  if (ctx.parsedType !== ZodParsedType.function) {
6249
6310
  addIssueToContext(ctx, {
6250
6311
  code: ZodIssueCode.invalid_type,
@@ -6347,8 +6408,8 @@ var ZodLazy = class extends ZodType {
6347
6408
  get schema() {
6348
6409
  return this._def.getter();
6349
6410
  }
6350
- _parse(input3) {
6351
- const { ctx } = this._processInputParams(input3);
6411
+ _parse(input4) {
6412
+ const { ctx } = this._processInputParams(input4);
6352
6413
  const lazySchema = this._def.getter();
6353
6414
  return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
6354
6415
  }
@@ -6361,9 +6422,9 @@ ZodLazy.create = (getter, params) => {
6361
6422
  });
6362
6423
  };
6363
6424
  var ZodLiteral = class extends ZodType {
6364
- _parse(input3) {
6365
- if (input3.data !== this._def.value) {
6366
- const ctx = this._getOrReturnCtx(input3);
6425
+ _parse(input4) {
6426
+ if (input4.data !== this._def.value) {
6427
+ const ctx = this._getOrReturnCtx(input4);
6367
6428
  addIssueToContext(ctx, {
6368
6429
  received: ctx.data,
6369
6430
  code: ZodIssueCode.invalid_literal,
@@ -6371,7 +6432,7 @@ var ZodLiteral = class extends ZodType {
6371
6432
  });
6372
6433
  return INVALID;
6373
6434
  }
6374
- return { status: "valid", value: input3.data };
6435
+ return { status: "valid", value: input4.data };
6375
6436
  }
6376
6437
  get value() {
6377
6438
  return this._def.value;
@@ -6392,9 +6453,9 @@ function createZodEnum(values, params) {
6392
6453
  });
6393
6454
  }
6394
6455
  var ZodEnum = class _ZodEnum extends ZodType {
6395
- _parse(input3) {
6396
- if (typeof input3.data !== "string") {
6397
- const ctx = this._getOrReturnCtx(input3);
6456
+ _parse(input4) {
6457
+ if (typeof input4.data !== "string") {
6458
+ const ctx = this._getOrReturnCtx(input4);
6398
6459
  const expectedValues = this._def.values;
6399
6460
  addIssueToContext(ctx, {
6400
6461
  expected: util.joinValues(expectedValues),
@@ -6406,8 +6467,8 @@ var ZodEnum = class _ZodEnum extends ZodType {
6406
6467
  if (!this._cache) {
6407
6468
  this._cache = new Set(this._def.values);
6408
6469
  }
6409
- if (!this._cache.has(input3.data)) {
6410
- const ctx = this._getOrReturnCtx(input3);
6470
+ if (!this._cache.has(input4.data)) {
6471
+ const ctx = this._getOrReturnCtx(input4);
6411
6472
  const expectedValues = this._def.values;
6412
6473
  addIssueToContext(ctx, {
6413
6474
  received: ctx.data,
@@ -6416,7 +6477,7 @@ var ZodEnum = class _ZodEnum extends ZodType {
6416
6477
  });
6417
6478
  return INVALID;
6418
6479
  }
6419
- return OK(input3.data);
6480
+ return OK(input4.data);
6420
6481
  }
6421
6482
  get options() {
6422
6483
  return this._def.values;
@@ -6457,9 +6518,9 @@ var ZodEnum = class _ZodEnum extends ZodType {
6457
6518
  };
6458
6519
  ZodEnum.create = createZodEnum;
6459
6520
  var ZodNativeEnum = class extends ZodType {
6460
- _parse(input3) {
6521
+ _parse(input4) {
6461
6522
  const nativeEnumValues = util.getValidEnumValues(this._def.values);
6462
- const ctx = this._getOrReturnCtx(input3);
6523
+ const ctx = this._getOrReturnCtx(input4);
6463
6524
  if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
6464
6525
  const expectedValues = util.objectValues(nativeEnumValues);
6465
6526
  addIssueToContext(ctx, {
@@ -6472,7 +6533,7 @@ var ZodNativeEnum = class extends ZodType {
6472
6533
  if (!this._cache) {
6473
6534
  this._cache = new Set(util.getValidEnumValues(this._def.values));
6474
6535
  }
6475
- if (!this._cache.has(input3.data)) {
6536
+ if (!this._cache.has(input4.data)) {
6476
6537
  const expectedValues = util.objectValues(nativeEnumValues);
6477
6538
  addIssueToContext(ctx, {
6478
6539
  received: ctx.data,
@@ -6481,7 +6542,7 @@ var ZodNativeEnum = class extends ZodType {
6481
6542
  });
6482
6543
  return INVALID;
6483
6544
  }
6484
- return OK(input3.data);
6545
+ return OK(input4.data);
6485
6546
  }
6486
6547
  get enum() {
6487
6548
  return this._def.values;
@@ -6498,8 +6559,8 @@ var ZodPromise = class extends ZodType {
6498
6559
  unwrap() {
6499
6560
  return this._def.type;
6500
6561
  }
6501
- _parse(input3) {
6502
- const { ctx } = this._processInputParams(input3);
6562
+ _parse(input4) {
6563
+ const { ctx } = this._processInputParams(input4);
6503
6564
  if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
6504
6565
  addIssueToContext(ctx, {
6505
6566
  code: ZodIssueCode.invalid_type,
@@ -6531,8 +6592,8 @@ var ZodEffects = class extends ZodType {
6531
6592
  sourceType() {
6532
6593
  return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
6533
6594
  }
6534
- _parse(input3) {
6535
- const { status, ctx } = this._processInputParams(input3);
6595
+ _parse(input4) {
6596
+ const { status, ctx } = this._processInputParams(input4);
6536
6597
  const effect = this._def.effect || null;
6537
6598
  const checkCtx = {
6538
6599
  addIssue: (arg) => {
@@ -6664,12 +6725,12 @@ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
6664
6725
  });
6665
6726
  };
6666
6727
  var ZodOptional = class extends ZodType {
6667
- _parse(input3) {
6668
- const parsedType = this._getType(input3);
6728
+ _parse(input4) {
6729
+ const parsedType = this._getType(input4);
6669
6730
  if (parsedType === ZodParsedType.undefined) {
6670
6731
  return OK(void 0);
6671
6732
  }
6672
- return this._def.innerType._parse(input3);
6733
+ return this._def.innerType._parse(input4);
6673
6734
  }
6674
6735
  unwrap() {
6675
6736
  return this._def.innerType;
@@ -6683,12 +6744,12 @@ ZodOptional.create = (type, params) => {
6683
6744
  });
6684
6745
  };
6685
6746
  var ZodNullable = class extends ZodType {
6686
- _parse(input3) {
6687
- const parsedType = this._getType(input3);
6747
+ _parse(input4) {
6748
+ const parsedType = this._getType(input4);
6688
6749
  if (parsedType === ZodParsedType.null) {
6689
6750
  return OK(null);
6690
6751
  }
6691
- return this._def.innerType._parse(input3);
6752
+ return this._def.innerType._parse(input4);
6692
6753
  }
6693
6754
  unwrap() {
6694
6755
  return this._def.innerType;
@@ -6702,8 +6763,8 @@ ZodNullable.create = (type, params) => {
6702
6763
  });
6703
6764
  };
6704
6765
  var ZodDefault = class extends ZodType {
6705
- _parse(input3) {
6706
- const { ctx } = this._processInputParams(input3);
6766
+ _parse(input4) {
6767
+ const { ctx } = this._processInputParams(input4);
6707
6768
  let data = ctx.data;
6708
6769
  if (ctx.parsedType === ZodParsedType.undefined) {
6709
6770
  data = this._def.defaultValue();
@@ -6727,8 +6788,8 @@ ZodDefault.create = (type, params) => {
6727
6788
  });
6728
6789
  };
6729
6790
  var ZodCatch = class extends ZodType {
6730
- _parse(input3) {
6731
- const { ctx } = this._processInputParams(input3);
6791
+ _parse(input4) {
6792
+ const { ctx } = this._processInputParams(input4);
6732
6793
  const newCtx = {
6733
6794
  ...ctx,
6734
6795
  common: {
@@ -6780,10 +6841,10 @@ ZodCatch.create = (type, params) => {
6780
6841
  });
6781
6842
  };
6782
6843
  var ZodNaN = class extends ZodType {
6783
- _parse(input3) {
6784
- const parsedType = this._getType(input3);
6844
+ _parse(input4) {
6845
+ const parsedType = this._getType(input4);
6785
6846
  if (parsedType !== ZodParsedType.nan) {
6786
- const ctx = this._getOrReturnCtx(input3);
6847
+ const ctx = this._getOrReturnCtx(input4);
6787
6848
  addIssueToContext(ctx, {
6788
6849
  code: ZodIssueCode.invalid_type,
6789
6850
  expected: ZodParsedType.nan,
@@ -6791,7 +6852,7 @@ var ZodNaN = class extends ZodType {
6791
6852
  });
6792
6853
  return INVALID;
6793
6854
  }
6794
- return { status: "valid", value: input3.data };
6855
+ return { status: "valid", value: input4.data };
6795
6856
  }
6796
6857
  };
6797
6858
  ZodNaN.create = (params) => {
@@ -6802,8 +6863,8 @@ ZodNaN.create = (params) => {
6802
6863
  };
6803
6864
  var BRAND = /* @__PURE__ */ Symbol("zod_brand");
6804
6865
  var ZodBranded = class extends ZodType {
6805
- _parse(input3) {
6806
- const { ctx } = this._processInputParams(input3);
6866
+ _parse(input4) {
6867
+ const { ctx } = this._processInputParams(input4);
6807
6868
  const data = ctx.data;
6808
6869
  return this._def.type._parse({
6809
6870
  data,
@@ -6816,8 +6877,8 @@ var ZodBranded = class extends ZodType {
6816
6877
  }
6817
6878
  };
6818
6879
  var ZodPipeline = class _ZodPipeline extends ZodType {
6819
- _parse(input3) {
6820
- const { status, ctx } = this._processInputParams(input3);
6880
+ _parse(input4) {
6881
+ const { status, ctx } = this._processInputParams(input4);
6821
6882
  if (ctx.common.async) {
6822
6883
  const handleAsync = async () => {
6823
6884
  const inResult = await this._def.in._parseAsync({
@@ -6871,8 +6932,8 @@ var ZodPipeline = class _ZodPipeline extends ZodType {
6871
6932
  }
6872
6933
  };
6873
6934
  var ZodReadonly = class extends ZodType {
6874
- _parse(input3) {
6875
- const result = this._def.innerType._parse(input3);
6935
+ _parse(input4) {
6936
+ const result = this._def.innerType._parse(input4);
6876
6937
  const freeze = (data) => {
6877
6938
  if (isValid(data)) {
6878
6939
  data.value = Object.freeze(data.value);
@@ -7339,23 +7400,40 @@ var createCliApiClient = (options) => {
7339
7400
  const fetchFn = options.fetchFn ?? fetch;
7340
7401
  const timeoutMs = options.timeoutMs ?? 1e4;
7341
7402
  const projectPageLimit = 100;
7342
- const request = async (path, init, parse2) => {
7343
- const controller = new AbortController();
7344
- const timer = setTimeout(() => controller.abort(), timeoutMs);
7345
- const requestId = (options.requestId ?? defaultRequestId)();
7346
- try {
7403
+ const requestWithAuthorization = async (path, init, accept, controller, requestId) => {
7404
+ const send = () => {
7347
7405
  const authorization = options.getAuthorization?.();
7348
- const response = await fetchFn(new URL(path, baseUrl).toString(), {
7406
+ return fetchFn(new URL(path, baseUrl).toString(), {
7349
7407
  ...init,
7350
7408
  signal: controller.signal,
7351
7409
  headers: {
7352
- accept: "application/json",
7410
+ accept,
7353
7411
  "x-request-id": requestId,
7354
7412
  ...authorization ? { authorization } : {},
7355
7413
  ...init.body ? { "content-type": "application/json" } : {},
7356
7414
  ...init.headers
7357
7415
  }
7358
7416
  });
7417
+ };
7418
+ let response = await send();
7419
+ if (response.status === 401 && options.onUnauthorized) {
7420
+ const refreshed = await options.onUnauthorized();
7421
+ if (refreshed) response = await send();
7422
+ }
7423
+ return response;
7424
+ };
7425
+ const request = async (path, init, parse2) => {
7426
+ const controller = new AbortController();
7427
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
7428
+ const requestId = (options.requestId ?? defaultRequestId)();
7429
+ try {
7430
+ const response = await requestWithAuthorization(
7431
+ path,
7432
+ init,
7433
+ "application/json",
7434
+ controller,
7435
+ requestId
7436
+ );
7359
7437
  if (!response.ok) throw await asError(response, requestId);
7360
7438
  return parse2(await response.json());
7361
7439
  } catch (error) {
@@ -7376,17 +7454,13 @@ var createCliApiClient = (options) => {
7376
7454
  const timer = setTimeout(() => controller.abort(), timeoutMs);
7377
7455
  const requestId = (options.requestId ?? defaultRequestId)();
7378
7456
  try {
7379
- const authorization = options.getAuthorization?.();
7380
- const response = await fetchFn(new URL(path, baseUrl).toString(), {
7381
- ...init,
7382
- signal: controller.signal,
7383
- headers: {
7384
- accept: "application/json, text/plain, text/markdown, application/sarif+json",
7385
- "x-request-id": requestId,
7386
- ...authorization ? { authorization } : {},
7387
- ...init.headers
7388
- }
7389
- });
7457
+ const response = await requestWithAuthorization(
7458
+ path,
7459
+ init,
7460
+ "application/json, text/plain, text/markdown, application/sarif+json",
7461
+ controller,
7462
+ requestId
7463
+ );
7390
7464
  if (!response.ok) throw await asError(response, requestId);
7391
7465
  return { content: await response.text(), contentType: response.headers.get("content-type") };
7392
7466
  } catch (error) {
@@ -7406,16 +7480,16 @@ var createCliApiClient = (options) => {
7406
7480
  );
7407
7481
  return result.codebases;
7408
7482
  },
7409
- linkWorkspace: async (input3) => {
7410
- const parsed = workspaceLinkCandidateSchema.parse(input3);
7483
+ linkWorkspace: async (input4) => {
7484
+ const parsed = workspaceLinkCandidateSchema.parse(input4);
7411
7485
  await request(
7412
7486
  `/api/cli/workspaces/${encodeURIComponent(parsed.fingerprint)}`,
7413
7487
  { method: "PUT", body: JSON.stringify(parsed) },
7414
7488
  () => void 0
7415
7489
  );
7416
7490
  },
7417
- resolveConfig: async (input3) => {
7418
- const parsed = repositoryConfigInputSchema.parse(input3);
7491
+ resolveConfig: async (input4) => {
7492
+ const parsed = repositoryConfigInputSchema.parse(input4);
7419
7493
  return request(
7420
7494
  "/api/cli/config/resolve",
7421
7495
  { method: "POST", body: JSON.stringify(parsed) },
@@ -7449,8 +7523,8 @@ var createCliApiClient = (options) => {
7449
7523
  offset: 0
7450
7524
  };
7451
7525
  },
7452
- createProject: (input3) => {
7453
- const parsed = createProjectRequestSchema.parse(input3);
7526
+ createProject: (input4) => {
7527
+ const parsed = createProjectRequestSchema.parse(input4);
7454
7528
  return request(
7455
7529
  "/api/projects",
7456
7530
  { method: "POST", body: JSON.stringify(parsed) },
@@ -7462,8 +7536,8 @@ var createCliApiClient = (options) => {
7462
7536
  { method: "GET" },
7463
7537
  (payload) => projectCodebaseListSchema.parse(payload)
7464
7538
  ),
7465
- createProjectCodebase: (projectId, input3) => {
7466
- const parsed = projectCodebaseInputSchema.parse(input3);
7539
+ createProjectCodebase: (projectId, input4) => {
7540
+ const parsed = projectCodebaseInputSchema.parse(input4);
7467
7541
  return request(
7468
7542
  `/api/projects/${encodeURIComponent(projectId)}/repositories`,
7469
7543
  { method: "POST", body: JSON.stringify(parsed) },
@@ -7501,8 +7575,8 @@ var createCliApiClient = (options) => {
7501
7575
  { method: "GET" },
7502
7576
  (payload) => automationTokenListSchema.parse(payload)
7503
7577
  ),
7504
- createAutomationToken: (projectId, input3) => {
7505
- const parsed = createAutomationTokenRequestSchema.parse(input3);
7578
+ createAutomationToken: (projectId, input4) => {
7579
+ const parsed = createAutomationTokenRequestSchema.parse(input4);
7506
7580
  return request(
7507
7581
  `/api/projects/${encodeURIComponent(projectId)}/tokens`,
7508
7582
  { method: "POST", body: JSON.stringify(parsed) },
@@ -7579,10 +7653,39 @@ external_exports.object({
7579
7653
  });
7580
7654
 
7581
7655
  // src/config/remote-client.ts
7582
- var createRemoteConfigClient = (input3) => createCliApiClient({
7583
- serverUrl: input3.serverUrl,
7584
- getAuthorization: () => input3.token ? `Bearer ${input3.token}` : void 0
7656
+ var createRemoteConfigClient = (input4) => createCliApiClient({
7657
+ serverUrl: input4.serverUrl,
7658
+ getAuthorization: () => {
7659
+ const token = input4.getToken?.() ?? input4.token;
7660
+ return token ? `Bearer ${token}` : void 0;
7661
+ },
7662
+ onUnauthorized: input4.onUnauthorized
7585
7663
  });
7664
+
7665
+ // src/auth/authenticated-remote-client.ts
7666
+ var createAuthenticatedRemoteClient = async (input4) => {
7667
+ const serverUrl = new URL(input4.server).origin;
7668
+ let credential = await getAuthenticatedCredential({
7669
+ server: serverUrl,
7670
+ store: input4.store
7671
+ });
7672
+ return createRemoteConfigClient({
7673
+ serverUrl,
7674
+ getToken: () => credential.accessToken,
7675
+ onUnauthorized: async () => {
7676
+ try {
7677
+ credential = await getAuthenticatedCredential({
7678
+ server: serverUrl,
7679
+ store: input4.store,
7680
+ forceRefresh: true
7681
+ });
7682
+ return true;
7683
+ } catch {
7684
+ return false;
7685
+ }
7686
+ }
7687
+ });
7688
+ };
7586
7689
  var workspaceLinkStateSchema = workspaceLinkCandidateSchema.extend({
7587
7690
  serverUrl: external_exports.string().url(),
7588
7691
  configCache: external_exports.object({ expiresAt: external_exports.string().datetime({ offset: true }), effectiveConfigHash: external_exports.string() }).strict().optional()
@@ -7636,12 +7739,7 @@ var FileWorkspaceLinkStore = class {
7636
7739
  // src/commands/automation.command.ts
7637
7740
  var authenticatedClient = async (server, store) => {
7638
7741
  const origin = new URL(server).origin;
7639
- const credential = await store.read(origin);
7640
- if (!credential) throw new Error("Not authenticated. Run `cs auth login`.");
7641
- if (credential.expiresAt && Date.parse(credential.expiresAt) <= Date.now()) {
7642
- throw new Error("Credential expired. Run `cs auth login`.");
7643
- }
7644
- return createRemoteConfigClient({ serverUrl: origin, token: credential.accessToken });
7742
+ return createAuthenticatedRemoteClient({ server: origin, store });
7645
7743
  };
7646
7744
  var projectIdFor = async (path, projectId) => {
7647
7745
  if (projectId) return projectId;
@@ -8864,9 +8962,9 @@ var groupsAsync = (state, error, callback$1) => {
8864
8962
  report(error, callback$1, state.groups, state.options.suppressErrors);
8865
8963
  return null;
8866
8964
  };
8867
- function report(error, callback$1, output, suppressErrors) {
8868
- if (error && !suppressErrors) callback$1(error, output);
8869
- else callback$1(null, output);
8965
+ function report(error, callback$1, output2, suppressErrors) {
8966
+ if (error && !suppressErrors) callback$1(error, output2);
8967
+ else callback$1(null, output2);
8870
8968
  }
8871
8969
  function build$1(options, isSynchronous) {
8872
8970
  const { onlyCounts, group, maxFiles } = options;
@@ -8912,11 +9010,11 @@ var Queue = class {
8912
9010
  this.count++;
8913
9011
  return this.count;
8914
9012
  }
8915
- dequeue(error, output) {
9013
+ dequeue(error, output2) {
8916
9014
  if (this.onQueueEmpty && (--this.count <= 0 || error)) {
8917
- this.onQueueEmpty(error, output);
9015
+ this.onQueueEmpty(error, output2);
8918
9016
  if (error) {
8919
- output.controller.abort();
9017
+ output2.controller.abort();
8920
9018
  this.onQueueEmpty = void 0;
8921
9019
  }
8922
9020
  }
@@ -9028,9 +9126,9 @@ var Walker = class {
9028
9126
  };
9029
9127
  function promise(root, options) {
9030
9128
  return new Promise((resolve$1, reject) => {
9031
- callback(root, options, (err2, output) => {
9129
+ callback(root, options, (err2, output2) => {
9032
9130
  if (err2) return reject(err2);
9033
- resolve$1(output);
9131
+ resolve$1(output2);
9034
9132
  });
9035
9133
  });
9036
9134
  }
@@ -9204,9 +9302,9 @@ function getPartialMatcher(patterns, options = {}) {
9204
9302
  for (j = 0; j < partsCount; j++) partMatchers[j] = (0, import_picomatch.default)(parts[j], options);
9205
9303
  matchers[i] = partMatchers;
9206
9304
  }
9207
- return (input3) => {
9208
- const inputParts = input3.split("/");
9209
- if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input3)) return true;
9305
+ return (input4) => {
9306
+ const inputParts = input4.split("/");
9307
+ if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input4)) return true;
9210
9308
  for (i = 0; i < patternsCount; i++) {
9211
9309
  const patternParts = patternsParts[i];
9212
9310
  const matcher = matchers[i];
@@ -13508,8 +13606,7 @@ var providerDetails = {
13508
13606
  gemini: { displayName: "Google Gemini", envName: "GEMINI_API_KEY" },
13509
13607
  groq: { displayName: "Groq", envName: "GROQ_API_KEY" },
13510
13608
  "viettel-netmind": { displayName: "Viettel Netmind", envName: "LLM_API_KEY" },
13511
- "opencode-go": { displayName: "OpenCode Go", envName: "OPENCODE_GO_API_KEY" },
13512
- freemodel: { displayName: "FreeModel", envName: "FREEMODEL_API_KEY" }
13609
+ "opencode-go": { displayName: "OpenCode Go", envName: "OPENCODE_GO_API_KEY" }
13513
13610
  };
13514
13611
  var providerNeedsApiKey = (provider) => provider in providerDetails;
13515
13612
  var providerHasApiKey = (config, provider) => {
@@ -13542,9 +13639,8 @@ var withAiApiKey = (config, credential, apiKey) => {
13542
13639
  };
13543
13640
  };
13544
13641
  var OLLAMA_DEFAULT_BASE = "http://localhost:11434";
13545
- var NETMIND_DEFAULT_BASE = "https://netmind.viettel.vn/gateway/v1";
13642
+ var NETMIND_DEFAULT_BASE = "https://example.invalid/netmind/v1";
13546
13643
  var OPENCODE_GO_DEFAULT_BASE = "https://opencode.ai/zen/go/v1";
13547
- var FREEMODEL_DEFAULT_BASE = "https://api.freemodel.dev";
13548
13644
  var stripTrailingSlash = (s) => s.replace(/\/+$/, "");
13549
13645
  var buildLanguageModel = (config, modelOverride) => {
13550
13646
  const modelId = modelOverride ?? config.defaultModel;
@@ -13588,16 +13684,6 @@ var buildLanguageModel = (config, modelOverride) => {
13588
13684
  apiKey: config.apiKey
13589
13685
  }).chatModel(modelId);
13590
13686
  }
13591
- case "freemodel": {
13592
- if (!config.apiKey) {
13593
- throw new Error('createAiSdkProvider({providerType:"freemodel"}) requires apiKey');
13594
- }
13595
- return createOpenAICompatible({
13596
- name: "freemodel",
13597
- baseURL: stripTrailingSlash(config.baseUrl ?? FREEMODEL_DEFAULT_BASE),
13598
- apiKey: config.apiKey
13599
- }).chatModel(modelId);
13600
- }
13601
13687
  case "openai-compatible": {
13602
13688
  if (!config.baseUrl) {
13603
13689
  throw new Error('createAiSdkProvider({providerType:"openai-compatible"}) requires baseUrl');
@@ -13656,9 +13742,6 @@ var pingTarget = (config) => {
13656
13742
  headers: config.apiKey ? { authorization: `Bearer ${config.apiKey}` } : {}
13657
13743
  };
13658
13744
  }
13659
- case "freemodel": {
13660
- return null;
13661
- }
13662
13745
  case "openai-compatible": {
13663
13746
  if (!config.baseUrl) return null;
13664
13747
  return {
@@ -13731,9 +13814,9 @@ var completeRawOpenAICompatibleJsonChat = async (options) => {
13731
13814
  })
13732
13815
  );
13733
13816
  }
13734
- const input3 = body.usage?.prompt_tokens;
13735
- const output = body.usage?.completion_tokens;
13736
- const tokensUsed = input3 !== void 0 && output !== void 0 ? { prompt: input3, completion: output } : void 0;
13817
+ const input4 = body.usage?.prompt_tokens;
13818
+ const output2 = body.usage?.completion_tokens;
13819
+ const tokensUsed = input4 !== void 0 && output2 !== void 0 ? { prompt: input4, completion: output2 } : void 0;
13737
13820
  return ok({
13738
13821
  text: text2,
13739
13822
  ...tokensUsed !== void 0 ? { tokensUsed } : {},
@@ -13741,10 +13824,7 @@ var completeRawOpenAICompatibleJsonChat = async (options) => {
13741
13824
  });
13742
13825
  };
13743
13826
  var createAiSdkProvider = (config) => {
13744
- if (config.providerType === "freemodel" && !config.apiKey) {
13745
- throw new Error('createAiSdkProvider({providerType:"freemodel"}) requires apiKey');
13746
- }
13747
- const model = config.providerType === "freemodel" ? null : buildLanguageModel(config);
13827
+ const model = buildLanguageModel(config);
13748
13828
  const name = config.providerName ?? config.providerType;
13749
13829
  const defaultTimeoutMs = config.defaultTimeoutMs ?? 18e4;
13750
13830
  const probe = pingTarget(config);
@@ -13800,57 +13880,6 @@ var createAiSdkProvider = (config) => {
13800
13880
  signal: ctrl.signal
13801
13881
  });
13802
13882
  }
13803
- if (config.providerType === "freemodel") {
13804
- if (!config.apiKey) {
13805
- return err(
13806
- new AIProviderError(`${name} request failed: missing apiKey`, {
13807
- context: { provider: name, model: reportedModel }
13808
- })
13809
- );
13810
- }
13811
- const base = stripTrailingSlash(config.baseUrl ?? FREEMODEL_DEFAULT_BASE);
13812
- const res = await fetch(`${base}/responses`, {
13813
- method: "POST",
13814
- headers: {
13815
- authorization: `Bearer ${config.apiKey}`,
13816
- "content-type": "application/json"
13817
- },
13818
- body: JSON.stringify({
13819
- model: reportedModel,
13820
- ...request.system ? { instructions: request.system } : {},
13821
- input: request.user,
13822
- store: false,
13823
- temperature: request.temperature ?? 0.1,
13824
- ...request.maxTokens !== void 0 ? { max_output_tokens: request.maxTokens } : {}
13825
- }),
13826
- signal: ctrl.signal
13827
- });
13828
- if (!res.ok) {
13829
- const body2 = await res.text().catch(() => "");
13830
- return err(
13831
- new AIProviderError(`${name} request failed: HTTP ${res.status} ${body2}`.trim(), {
13832
- context: { provider: name, model: reportedModel }
13833
- })
13834
- );
13835
- }
13836
- const body = await res.json();
13837
- const text22 = body.output?.flatMap((item) => item.content ?? []).map((part) => part.type === "output_text" ? part.text : void 0).filter((part) => part !== void 0 && part.length > 0).join("\n") ?? "";
13838
- if (!text22) {
13839
- return err(
13840
- new AIProviderError(`${name} returned empty content`, {
13841
- context: { provider: name, model: reportedModel }
13842
- })
13843
- );
13844
- }
13845
- const input22 = body.usage?.input_tokens;
13846
- const output2 = body.usage?.output_tokens;
13847
- const tokensUsed2 = input22 !== void 0 && output2 !== void 0 ? { prompt: input22, completion: output2 } : void 0;
13848
- return ok({
13849
- text: text22,
13850
- ...tokensUsed2 !== void 0 ? { tokensUsed: tokensUsed2 } : {},
13851
- cached: false
13852
- });
13853
- }
13854
13883
  const callModel = override === null ? model : buildLanguageModel(config, override);
13855
13884
  if (!callModel) {
13856
13885
  return err(
@@ -13881,9 +13910,9 @@ var createAiSdkProvider = (config) => {
13881
13910
  })
13882
13911
  );
13883
13912
  }
13884
- const input3 = result.usage.inputTokens;
13885
- const output = result.usage.outputTokens;
13886
- const tokensUsed = input3 !== void 0 && output !== void 0 ? { prompt: input3, completion: output } : void 0;
13913
+ const input4 = result.usage.inputTokens;
13914
+ const output2 = result.usage.outputTokens;
13915
+ const tokensUsed = input4 !== void 0 && output2 !== void 0 ? { prompt: input4, completion: output2 } : void 0;
13887
13916
  return ok({
13888
13917
  text: text2,
13889
13918
  ...tokensUsed !== void 0 ? { tokensUsed } : {},
@@ -13922,7 +13951,10 @@ var createFallbackClient = (options) => {
13922
13951
  for (const p of providers) {
13923
13952
  const reachable = await p.ping();
13924
13953
  if (!reachable) {
13925
- logger.debug({ provider: p.name }, "provider unreachable, trying next");
13954
+ logger.debug(
13955
+ { event: "ai_provider_unreachable", provider: p.name, model: request.model },
13956
+ "provider unreachable, trying next"
13957
+ );
13926
13958
  lastError = new AIProviderError(`${p.name} is unreachable`, {
13927
13959
  context: { provider: p.name }
13928
13960
  });
@@ -13936,7 +13968,12 @@ var createFallbackClient = (options) => {
13936
13968
  return r;
13937
13969
  }
13938
13970
  logger.warn(
13939
- { provider: p.name, code: r.error.code },
13971
+ {
13972
+ event: "ai_provider_error",
13973
+ provider: p.name,
13974
+ model: request.model,
13975
+ code: r.error.code
13976
+ },
13940
13977
  `provider failed: ${r.error.message}`
13941
13978
  );
13942
13979
  lastError = r.error;
@@ -14082,6 +14119,11 @@ var formatTokenWarning = (ruleId, promptTokens, budgetTokens) => {
14082
14119
  var CACHE_NAMESPACE = "ai";
14083
14120
  var DEFAULT_PROVIDER_RETRY_MAX_RETRIES = 1;
14084
14121
  var DEFAULT_PROVIDER_RETRY_MAX_DELAY_MS = 75e3;
14122
+ var DEFAULT_ADAPTIVE_RETRY_MAX_RETRIES = 1;
14123
+ var DEFAULT_ADAPTIVE_CONTEXT_REDUCTION_FACTOR = 0.75;
14124
+ var DEFAULT_ADAPTIVE_TIMEOUT_MULTIPLIER = 1.5;
14125
+ var DEFAULT_ADAPTIVE_MAX_DELAY_MS = 5e3;
14126
+ var DEFAULT_PROVIDER_TIMEOUT_MS = 18e4;
14085
14127
  var sleep2 = (ms) => new Promise((resolveSleep) => setTimeout(resolveSleep, ms));
14086
14128
  var parseRetryDelayMs = (message) => {
14087
14129
  const resetMatch = message.match(/limit resets at:\s*([^"}\n]+)/i);
@@ -14116,6 +14158,34 @@ var providerRetryDelayMs = (message, maxDelayMs) => {
14116
14158
  if (hintedDelay === null) return null;
14117
14159
  return Math.min(hintedDelay, maxDelayMs);
14118
14160
  };
14161
+ var adaptiveFailureKind = (message) => {
14162
+ if (/context(?: length| window)|maximum context|too many tokens|prompt too long|input too long|token limit|context_length_exceeded|\b413\b/i.test(
14163
+ message
14164
+ )) {
14165
+ return "context-limit";
14166
+ }
14167
+ if (/timeout|timed out|deadline exceeded|abort(?:ed|error)?|ETIMEDOUT/i.test(message)) {
14168
+ return "timeout";
14169
+ }
14170
+ if (/(?:HTTP\s+)(?:408|425|429|500|502|503|504)\b|temporarily unavailable|overloaded|fetch failed|ECONN(?:RESET|REFUSED)|ENETUNREACH|EAI_AGAIN|socket hang up/i.test(
14171
+ message
14172
+ )) {
14173
+ return "transient";
14174
+ }
14175
+ return null;
14176
+ };
14177
+ var compactClusterContext = (context, keepFraction) => {
14178
+ if (!context || context.supportFiles.length === 0) return void 0;
14179
+ const keepCount = Math.max(
14180
+ 0,
14181
+ Math.min(
14182
+ context.supportFiles.length - 1,
14183
+ Math.floor(context.supportFiles.length * keepFraction)
14184
+ )
14185
+ );
14186
+ if (keepCount >= context.supportFiles.length) return context;
14187
+ return { ...context, supportFiles: context.supportFiles.slice(0, keepCount) };
14188
+ };
14119
14189
  var findingDedupeKey2 = (finding) => finding.rootCauseKey ? ["root", finding.file, finding.rootCauseKey].join("\0") : [
14120
14190
  "line",
14121
14191
  finding.file,
@@ -14171,6 +14241,26 @@ var createAiExecutor = (options) => {
14171
14241
  Math.floor(options.providerRetry?.maxDelayMs ?? DEFAULT_PROVIDER_RETRY_MAX_DELAY_MS)
14172
14242
  );
14173
14243
  const providerRetrySleep = options.providerRetry?.sleep ?? sleep2;
14244
+ const adaptiveRetryMaxRetries = Math.max(
14245
+ 0,
14246
+ Math.floor(options.adaptiveRetry?.maxRetries ?? DEFAULT_ADAPTIVE_RETRY_MAX_RETRIES)
14247
+ );
14248
+ const adaptiveContextReductionFactor = Math.min(
14249
+ 0.95,
14250
+ Math.max(
14251
+ 0.25,
14252
+ options.adaptiveRetry?.contextReductionFactor ?? DEFAULT_ADAPTIVE_CONTEXT_REDUCTION_FACTOR
14253
+ )
14254
+ );
14255
+ const adaptiveTimeoutMultiplier = Math.min(
14256
+ 3,
14257
+ Math.max(1.1, options.adaptiveRetry?.timeoutMultiplier ?? DEFAULT_ADAPTIVE_TIMEOUT_MULTIPLIER)
14258
+ );
14259
+ const adaptiveRetryMaxDelayMs = Math.max(
14260
+ 0,
14261
+ Math.floor(options.adaptiveRetry?.maxDelayMs ?? DEFAULT_ADAPTIVE_MAX_DELAY_MS)
14262
+ );
14263
+ const adaptiveRetrySleep = options.adaptiveRetry?.sleep ?? sleep2;
14174
14264
  const extraText = extraInstructions?.trim() ?? "";
14175
14265
  const extraDiscriminator = extraText.length === 0 ? "" : `xi:${extraText.length}:${extraText.slice(0, 32)}`;
14176
14266
  return async function executeAiRule(rule, file, _parsed, clusterContext, moduleContext) {
@@ -14236,74 +14326,134 @@ var createAiExecutor = (options) => {
14236
14326
  })
14237
14327
  );
14238
14328
  }
14239
- const clusterFilesVar = scope === "per-cluster" && clusterContext ? clusterContext.supportFiles.map((m) => m.path).join("\n") : "";
14240
- const clusterSummaryVar = scope === "per-cluster" && clusterContext ? clusterContext.supportFiles.map((m) => `--- ${m.path} (layer=${m.layer}) ---
14329
+ const renderUserPrompt = (currentClusterContext2) => {
14330
+ const clusterFilesVar = scope === "per-cluster" && currentClusterContext2 ? currentClusterContext2.supportFiles.map((m) => m.path).join("\n") : "";
14331
+ const clusterSummaryVar = scope === "per-cluster" && currentClusterContext2 ? currentClusterContext2.supportFiles.map((m) => `--- ${m.path} (layer=${m.layer}) ---
14241
14332
  ${m.content}`).join("\n\n") : "";
14242
- const moduleFeaturesVar = scope === "per-module" && moduleContext ? moduleContext.features.map((f) => `- ${f.primaryPath} (findings=${f.findingCount})`).join("\n") : "";
14243
- const moduleFindingsVar = scope === "per-module" && moduleContext ? moduleContext.findings.map(
14244
- (f) => `- ${f.file}:${f.line} [${f.ruleId}] (${f.severity}) ${f.message}${f.suggestion ? ` \u2014 ${f.suggestion}` : ""}`
14245
- ).join("\n") : "";
14246
- const moduleSummaryVar = scope === "per-module" && moduleContext ? `Module ${moduleContext.moduleRootPath} \u2014 ${moduleContext.members.length} file(s):
14333
+ const moduleFeaturesVar = scope === "per-module" && moduleContext ? moduleContext.features.map((f) => `- ${f.primaryPath} (findings=${f.findingCount})`).join("\n") : "";
14334
+ const moduleFindingsVar = scope === "per-module" && moduleContext ? moduleContext.findings.map(
14335
+ (f) => `- ${f.file}:${f.line} [${f.ruleId}] (${f.severity}) ${f.message}${f.suggestion ? ` \u2014 ${f.suggestion}` : ""}`
14336
+ ).join("\n") : "";
14337
+ const moduleSummaryVar = scope === "per-module" && moduleContext ? `Module ${moduleContext.moduleRootPath} \u2014 ${moduleContext.members.length} file(s):
14247
14338
  ${moduleContext.members.map((p) => ` ${p}`).join("\n")}` : "";
14248
- const moduleTransactionBoundariesVar = scope === "per-module" && moduleContext?.transactionBoundaries ? moduleContext.transactionBoundaries.map(
14249
- (t) => `- ${t.file}:${t.line} @Transactional on ${t.scope} ${t.target}${t.scope === "method" ? "()" : ""} | readOnly=${t.readOnly} | rollbackFor=${t.rollbackFor ?? "default"} | propagation=${t.propagation ?? "default"}${t.isolation ? ` | isolation=${t.isolation}` : ""} | writes\u2248${t.mutationHint}`
14250
- ).join("\n") : "";
14251
- const promptFilePath = scope === "per-module" && moduleContext ? moduleContext.moduleRootPath : file.path;
14252
- const promptCode = scope === "per-module" && moduleContext ? "" : file.content;
14253
- const baseRendered = renderPrompt(tmplResult.value, {
14254
- file: promptFilePath,
14255
- language: file.language,
14256
- code: promptCode,
14257
- cluster_files: clusterFilesVar,
14258
- cluster_summary: clusterSummaryVar,
14259
- module_features: moduleFeaturesVar,
14260
- module_findings: moduleFindingsVar,
14261
- module_summary: moduleSummaryVar,
14262
- module_transaction_boundaries: moduleTransactionBoundariesVar
14263
- });
14264
- const rendered = extraText.length === 0 ? baseRendered : `${baseRendered}
14339
+ const moduleTransactionBoundariesVar = scope === "per-module" && moduleContext?.transactionBoundaries ? moduleContext.transactionBoundaries.map(
14340
+ (t) => `- ${t.file}:${t.line} @Transactional on ${t.scope} ${t.target}${t.scope === "method" ? "()" : ""} | readOnly=${t.readOnly} | rollbackFor=${t.rollbackFor ?? "default"} | propagation=${t.propagation ?? "default"}${t.isolation ? ` | isolation=${t.isolation}` : ""} | writes\u2248${t.mutationHint}`
14341
+ ).join("\n") : "";
14342
+ const promptFilePath = scope === "per-module" && moduleContext ? moduleContext.moduleRootPath : file.path;
14343
+ const promptCode = scope === "per-module" && moduleContext ? "" : file.content;
14344
+ const baseRendered = renderPrompt(tmplResult.value, {
14345
+ file: promptFilePath,
14346
+ language: file.language,
14347
+ code: promptCode,
14348
+ cluster_files: clusterFilesVar,
14349
+ cluster_summary: clusterSummaryVar,
14350
+ module_features: moduleFeaturesVar,
14351
+ module_findings: moduleFindingsVar,
14352
+ module_summary: moduleSummaryVar,
14353
+ module_transaction_boundaries: moduleTransactionBoundariesVar
14354
+ });
14355
+ return extraText.length === 0 ? baseRendered : `${baseRendered}
14265
14356
 
14266
14357
  --- Additional reviewer instructions ---
14267
14358
  ${extraText}
14268
14359
  `;
14269
- const promptTokens = estimateTokens(rendered);
14270
- if (promptTokens > tokenBudgetWarn) {
14360
+ };
14361
+ const initialRendered = renderUserPrompt(clusterContext);
14362
+ const initialPromptTokens = estimateTokens(initialRendered);
14363
+ if (initialPromptTokens > tokenBudgetWarn) {
14271
14364
  logger.warn(
14272
- { ruleId: rule.id, file: file.path, promptTokens, tokenBudgetWarn },
14273
- formatTokenWarning(rule.id, promptTokens, tokenBudgetWarn)
14365
+ {
14366
+ event: "ai_prompt_budget_warning",
14367
+ ruleId: rule.id,
14368
+ file: file.path,
14369
+ promptTokens: initialPromptTokens,
14370
+ tokenBudgetWarn
14371
+ },
14372
+ formatTokenWarning(rule.id, initialPromptTokens, tokenBudgetWarn)
14274
14373
  );
14275
14374
  }
14276
- const request = {
14277
- user: rendered,
14375
+ let currentClusterContext = clusterContext;
14376
+ let currentRendered = initialRendered;
14377
+ let currentTimeoutMs = timeoutMs;
14378
+ let currentMaxTokens = rule.maxTokens;
14379
+ const buildRequest = () => ({
14380
+ user: currentRendered,
14278
14381
  model,
14279
14382
  temperature,
14280
14383
  responseFormat: "json",
14281
- ...rule.maxTokens !== void 0 ? { maxTokens: rule.maxTokens } : {},
14282
- ...timeoutMs !== void 0 ? { timeoutMs } : {},
14384
+ ...currentMaxTokens !== void 0 ? { maxTokens: currentMaxTokens } : {},
14385
+ ...currentTimeoutMs !== void 0 ? { timeoutMs: currentTimeoutMs } : {},
14283
14386
  ...tier !== void 0 ? { tier } : {}
14387
+ });
14388
+ const completeWithProviderRetry = async (request) => {
14389
+ let result = await client.complete(request);
14390
+ for (let attempt = 0; !result.ok && attempt < providerRetryMaxRetries; attempt += 1) {
14391
+ const retryDelayMs = providerRetryDelayMs(result.error.message, providerRetryMaxDelayMs);
14392
+ if (retryDelayMs === null) break;
14393
+ logger.warn(
14394
+ {
14395
+ event: "ai_provider_retry",
14396
+ ruleId: rule.id,
14397
+ file: file.path,
14398
+ code: result.error.code,
14399
+ retryDelayMs,
14400
+ retryAttempt: attempt + 1,
14401
+ retryMaxRetries: providerRetryMaxRetries
14402
+ },
14403
+ `AI provider retry in ${retryDelayMs}ms`
14404
+ );
14405
+ await providerRetrySleep(retryDelayMs);
14406
+ result = await client.complete(request);
14407
+ }
14408
+ return result;
14284
14409
  };
14285
- let aiResult = await client.complete(request);
14286
- for (let attempt = 0; !aiResult.ok && attempt < providerRetryMaxRetries; attempt += 1) {
14287
- const retryDelayMs = providerRetryDelayMs(aiResult.error.message, providerRetryMaxDelayMs);
14288
- if (retryDelayMs === null) break;
14410
+ let aiResult = await completeWithProviderRetry(buildRequest());
14411
+ for (let attempt = 0; !aiResult.ok && attempt < adaptiveRetryMaxRetries; attempt += 1) {
14412
+ const failureKind = adaptiveFailureKind(aiResult.error.message);
14413
+ const nextContext = failureKind === "context-limit" ? compactClusterContext(currentClusterContext, adaptiveContextReductionFactor) : currentClusterContext;
14414
+ const nextTimeoutMs = failureKind === "timeout" ? Math.ceil((currentTimeoutMs ?? DEFAULT_PROVIDER_TIMEOUT_MS) * adaptiveTimeoutMultiplier) : currentTimeoutMs;
14415
+ const nextMaxTokens = failureKind === "context-limit" && currentMaxTokens !== void 0 ? Math.max(256, Math.floor(currentMaxTokens * adaptiveContextReductionFactor)) : currentMaxTokens;
14416
+ const contextChanged = nextContext !== currentClusterContext;
14417
+ const timeoutChanged = nextTimeoutMs !== currentTimeoutMs;
14418
+ const maxTokensChanged = nextMaxTokens !== currentMaxTokens;
14419
+ const canAdapt = failureKind === "transient" || failureKind !== null && (contextChanged || timeoutChanged || maxTokensChanged);
14420
+ if (!canAdapt) break;
14421
+ const backoffMs = failureKind === "transient" ? Math.min(adaptiveRetryMaxDelayMs, 250 * 2 ** attempt) : 0;
14422
+ if (backoffMs > 0) await adaptiveRetrySleep(backoffMs);
14423
+ currentClusterContext = nextContext;
14424
+ currentTimeoutMs = nextTimeoutMs;
14425
+ currentMaxTokens = nextMaxTokens;
14426
+ currentRendered = renderUserPrompt(currentClusterContext);
14289
14427
  logger.warn(
14290
14428
  {
14429
+ event: "ai_adaptive_retry",
14291
14430
  ruleId: rule.id,
14292
14431
  file: file.path,
14293
- code: aiResult.error.code,
14294
- retryDelayMs,
14295
- retryAttempt: attempt + 1,
14296
- retryMaxRetries: providerRetryMaxRetries
14432
+ failureKind,
14433
+ adaptiveAttempt: attempt + 1,
14434
+ adaptiveMaxRetries: adaptiveRetryMaxRetries,
14435
+ supportFiles: currentClusterContext?.supportFiles.length ?? 0,
14436
+ promptTokens: estimateTokens(currentRendered),
14437
+ timeoutMs: currentTimeoutMs,
14438
+ maxTokens: currentMaxTokens,
14439
+ backoffMs
14297
14440
  },
14298
- `AI provider transient failure; retrying in ${retryDelayMs}ms`
14441
+ `AI request adapted after ${failureKind}; retrying`
14299
14442
  );
14300
- await providerRetrySleep(retryDelayMs);
14301
- aiResult = await client.complete(request);
14443
+ aiResult = await completeWithProviderRetry(buildRequest());
14302
14444
  }
14303
14445
  if (!aiResult.ok) {
14304
14446
  onOutcome?.(rule.id, "skipped", "provider-error");
14305
14447
  logger.warn(
14306
- { ruleId: rule.id, file: file.path, code: aiResult.error.code },
14448
+ {
14449
+ event: "ai_rule_error",
14450
+ provider: client.name,
14451
+ model,
14452
+ ruleId: rule.id,
14453
+ file: file.path,
14454
+ code: aiResult.error.code,
14455
+ failureKind: adaptiveFailureKind(aiResult.error.message) ?? "provider"
14456
+ },
14307
14457
  `AI rule skipped: ${aiResult.error.message}`
14308
14458
  );
14309
14459
  return ok([]);
@@ -14311,8 +14461,8 @@ ${extraText}
14311
14461
  let parsedResp = parseAiResponse(aiResult.value.text);
14312
14462
  if (!parsedResp.ok) {
14313
14463
  const repairRequest = {
14314
- ...request,
14315
- user: `${rendered}
14464
+ ...buildRequest(),
14465
+ user: `${currentRendered}
14316
14466
 
14317
14467
  --- Response repair ---
14318
14468
  Your previous response was invalid: ${parsedResp.error.message}
@@ -14329,7 +14479,14 @@ ${aiResult.value.text.slice(0, 4e3)}`
14329
14479
  if (!parsedResp.ok) {
14330
14480
  onOutcome?.(rule.id, "skipped", "invalid-response");
14331
14481
  logger.warn(
14332
- { ruleId: rule.id, file: file.path },
14482
+ {
14483
+ event: "ai_response_error",
14484
+ provider: client.name,
14485
+ model,
14486
+ ruleId: rule.id,
14487
+ file: file.path,
14488
+ code: parsedResp.error.code
14489
+ },
14333
14490
  `AI rule produced invalid response: ${parsedResp.error.message}`
14334
14491
  );
14335
14492
  return ok([]);
@@ -15236,12 +15393,12 @@ var extractTransactionBoundaries = (files) => {
15236
15393
  facts.sort((a, b) => a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1);
15237
15394
  return facts;
15238
15395
  };
15239
- var renderPrDiffPrompt = (input3) => {
15396
+ var renderPrDiffPrompt = (input4) => {
15240
15397
  const parts = [
15241
15398
  "# Merge request",
15242
- `Title: ${input3.title}`,
15243
- input3.description ? `Description:
15244
- ${input3.description}` : "Description: <empty>",
15399
+ `Title: ${input4.title}`,
15400
+ input4.description ? `Description:
15401
+ ${input4.description}` : "Description: <empty>",
15245
15402
  "",
15246
15403
  "# Review rules",
15247
15404
  "- Report only issues introduced by this merge request.",
@@ -15250,20 +15407,20 @@ ${input3.description}` : "Description: <empty>",
15250
15407
  "- Return strict JSON with a top-level `violations` array.",
15251
15408
  "",
15252
15409
  "# Diff hunks",
15253
- input3.hunks.join("\n\n---\n\n")
15410
+ input4.hunks.join("\n\n---\n\n")
15254
15411
  ];
15255
- if (input3.staticFindings && input3.staticFindings.length > 0) {
15412
+ if (input4.staticFindings && input4.staticFindings.length > 0) {
15256
15413
  parts.push(
15257
15414
  "",
15258
15415
  "# Nearby static findings",
15259
- input3.staticFindings.map((f) => `- ${f.ruleId} ${f.file}:${f.line} ${f.message}`).join("\n")
15416
+ input4.staticFindings.map((f) => `- ${f.ruleId} ${f.file}:${f.line} ${f.message}`).join("\n")
15260
15417
  );
15261
15418
  }
15262
- if (input3.supportFiles.length > 0) {
15419
+ if (input4.supportFiles.length > 0) {
15263
15420
  parts.push(
15264
15421
  "",
15265
15422
  "# Support files",
15266
- input3.supportFiles.map((f) => `## ${f.path}
15423
+ input4.supportFiles.map((f) => `## ${f.path}
15267
15424
  \`\`\`
15268
15425
  ${f.content}
15269
15426
  \`\`\``).join("\n\n")
@@ -15300,10 +15457,10 @@ var prDiffResponseSchema = external_exports.object({
15300
15457
  )
15301
15458
  });
15302
15459
  var createPrDiffReviewer = (options) => ({
15303
- async review(input3) {
15460
+ async review(input4) {
15304
15461
  const response = await options.client.complete({
15305
15462
  system: "You are Code Sentinel PR diff reviewer. Output strict JSON only. Report only issues introduced by the diff.",
15306
- user: renderPrDiffPrompt(input3),
15463
+ user: renderPrDiffPrompt(input4),
15307
15464
  model: options.model ?? "",
15308
15465
  responseFormat: "json",
15309
15466
  temperature: options.temperature ?? 0.1,
@@ -15337,14 +15494,14 @@ var createPrDiffReviewer = (options) => ({
15337
15494
  );
15338
15495
  }
15339
15496
  });
15340
- var renderGroupedRulePrompt = (input3) => {
15497
+ var renderGroupedRulePrompt = (input4) => {
15341
15498
  const parts = [
15342
15499
  "# PR grouped rule review",
15343
- `Primary file: ${input3.primaryFile.path}`,
15344
- `Language: ${input3.primaryFile.language}`,
15500
+ `Primary file: ${input4.primaryFile.path}`,
15501
+ `Language: ${input4.primaryFile.language}`,
15345
15502
  "",
15346
15503
  "# Rules to evaluate",
15347
- input3.rules.map(
15504
+ input4.rules.map(
15348
15505
  (rule) => [
15349
15506
  `## ${rule.ruleId}`,
15350
15507
  `Title: ${rule.title}`,
@@ -15363,17 +15520,17 @@ ${rule.description}` : "Description: <empty>"
15363
15520
  "",
15364
15521
  "# Primary file",
15365
15522
  "```",
15366
- input3.primaryFile.content,
15523
+ input4.primaryFile.content,
15367
15524
  "```",
15368
15525
  "",
15369
15526
  "# Diff hunks",
15370
- input3.diffHunks.join("\n\n---\n\n")
15527
+ input4.diffHunks.join("\n\n---\n\n")
15371
15528
  ];
15372
- if (input3.supportFiles.length > 0) {
15529
+ if (input4.supportFiles.length > 0) {
15373
15530
  parts.push(
15374
15531
  "",
15375
15532
  "# Support files",
15376
- input3.supportFiles.map((file) => `## ${file.path}
15533
+ input4.supportFiles.map((file) => `## ${file.path}
15377
15534
  \`\`\`
15378
15535
  ${file.content}
15379
15536
  \`\`\``).join("\n\n")
@@ -15440,11 +15597,11 @@ var labelToConfidence = (label) => {
15440
15597
  }
15441
15598
  };
15442
15599
  var createGroupedRuleReviewer = (options) => ({
15443
- async review(input3) {
15444
- const allowedRuleIds = new Set(input3.rules.map((rule) => rule.ruleId));
15600
+ async review(input4) {
15601
+ const allowedRuleIds = new Set(input4.rules.map((rule) => rule.ruleId));
15445
15602
  const response = await options.client.complete({
15446
15603
  system: "You are Code Sentinel grouped PR rule reviewer. Output strict JSON only. Map every finding to one provided ruleId.",
15447
- user: renderGroupedRulePrompt(input3),
15604
+ user: renderGroupedRulePrompt(input4),
15448
15605
  model: options.model ?? "",
15449
15606
  responseFormat: "json",
15450
15607
  temperature: options.temperature ?? 0.1,
@@ -15475,7 +15632,7 @@ var createGroupedRuleReviewer = (options) => ({
15475
15632
  findings2.push({
15476
15633
  ruleId: ruleResult.ruleId,
15477
15634
  message: finding.title,
15478
- file: input3.primaryFile.path,
15635
+ file: input4.primaryFile.path,
15479
15636
  range: {
15480
15637
  line: finding.lineStart,
15481
15638
  column: 1,
@@ -15490,19 +15647,19 @@ var createGroupedRuleReviewer = (options) => ({
15490
15647
  return ok(findings2);
15491
15648
  }
15492
15649
  });
15493
- var renderPerRulePrompt = (input3) => {
15650
+ var renderPerRulePrompt = (input4) => {
15494
15651
  const parts = [
15495
15652
  "# PR targeted review",
15496
- `Primary file: ${input3.primaryFile.path}`,
15497
- `Language: ${input3.primaryFile.language}`,
15653
+ `Primary file: ${input4.primaryFile.path}`,
15654
+ `Language: ${input4.primaryFile.language}`,
15498
15655
  "",
15499
15656
  "# Rule to evaluate",
15500
- `Rule id: ${input3.rule.ruleId}`,
15501
- `Title: ${input3.rule.title}`,
15502
- `Category: ${input3.rule.category}`,
15503
- `Default severity: ${input3.rule.severity}`,
15504
- input3.rule.description ? `Description:
15505
- ${input3.rule.description}` : "Description: <empty>",
15657
+ `Rule id: ${input4.rule.ruleId}`,
15658
+ `Title: ${input4.rule.title}`,
15659
+ `Category: ${input4.rule.category}`,
15660
+ `Default severity: ${input4.rule.severity}`,
15661
+ input4.rule.description ? `Description:
15662
+ ${input4.rule.description}` : "Description: <empty>",
15506
15663
  "",
15507
15664
  "# Review constraints",
15508
15665
  "- Report only issues introduced by this merge request.",
@@ -15511,21 +15668,21 @@ ${input3.rule.description}` : "Description: <empty>",
15511
15668
  "- Return strict JSON with a top-level `violations` array.",
15512
15669
  "",
15513
15670
  "# Rule prompt",
15514
- input3.renderedRulePrompt,
15671
+ input4.renderedRulePrompt,
15515
15672
  "",
15516
15673
  "# Primary file",
15517
15674
  "```",
15518
- input3.primaryFile.content,
15675
+ input4.primaryFile.content,
15519
15676
  "```",
15520
15677
  "",
15521
15678
  "# Diff hunks",
15522
- input3.diffHunks.join("\n\n---\n\n")
15679
+ input4.diffHunks.join("\n\n---\n\n")
15523
15680
  ];
15524
- if (input3.supportFiles.length > 0) {
15681
+ if (input4.supportFiles.length > 0) {
15525
15682
  parts.push(
15526
15683
  "",
15527
15684
  "# Support files",
15528
- input3.supportFiles.map((file) => `## ${file.path}
15685
+ input4.supportFiles.map((file) => `## ${file.path}
15529
15686
  \`\`\`
15530
15687
  ${file.content}
15531
15688
  \`\`\``).join("\n\n")
@@ -15537,7 +15694,7 @@ ${file.content}
15537
15694
  JSON.stringify({
15538
15695
  violations: [
15539
15696
  {
15540
- file: input3.primaryFile.path,
15697
+ file: input4.primaryFile.path,
15541
15698
  line: 123,
15542
15699
  message: "Concrete issue introduced by the PR",
15543
15700
  suggestion: "Short fix suggestion",
@@ -15549,8 +15706,8 @@ ${file.content}
15549
15706
  return parts.join("\n");
15550
15707
  };
15551
15708
  var createPerRuleReviewer = (options) => ({
15552
- async review(input3) {
15553
- const template = await loadPromptTemplate(input3.promptPath);
15709
+ async review(input4) {
15710
+ const template = await loadPromptTemplate(input4.promptPath);
15554
15711
  if (!template.ok) {
15555
15712
  return err(
15556
15713
  new AIProviderError(`Failed to load PR targeted prompt: ${template.error.message}`, {
@@ -15559,16 +15716,16 @@ var createPerRuleReviewer = (options) => ({
15559
15716
  );
15560
15717
  }
15561
15718
  const renderedRulePrompt = renderPrompt(template.value, {
15562
- file: input3.primaryFile.path,
15563
- language: input3.primaryFile.language,
15564
- code: input3.primaryFile.content,
15565
- cluster_files: input3.supportFiles.map((file) => file.path).join("\n"),
15566
- cluster_summary: input3.supportFiles.map((file) => `--- ${file.path} ---
15719
+ file: input4.primaryFile.path,
15720
+ language: input4.primaryFile.language,
15721
+ code: input4.primaryFile.content,
15722
+ cluster_files: input4.supportFiles.map((file) => file.path).join("\n"),
15723
+ cluster_summary: input4.supportFiles.map((file) => `--- ${file.path} ---
15567
15724
  ${file.content}`).join("\n\n")
15568
15725
  });
15569
15726
  const response = await options.client.complete({
15570
15727
  system: "You are Code Sentinel PR targeted reviewer. Output strict JSON only. Report only issues introduced by the diff.",
15571
- user: renderPerRulePrompt({ ...input3, renderedRulePrompt }),
15728
+ user: renderPerRulePrompt({ ...input4, renderedRulePrompt }),
15572
15729
  model: options.model ?? "",
15573
15730
  responseFormat: "json",
15574
15731
  temperature: options.temperature ?? 0.1,
@@ -15583,9 +15740,9 @@ ${file.content}`).join("\n\n")
15583
15740
  }
15584
15741
  return ok(
15585
15742
  parsed.value.violations.map((violation) => ({
15586
- ruleId: input3.rule.ruleId,
15743
+ ruleId: input4.rule.ruleId,
15587
15744
  message: violation.message,
15588
- file: input3.primaryFile.path,
15745
+ file: input4.primaryFile.path,
15589
15746
  range: {
15590
15747
  line: violation.line,
15591
15748
  column: 1,
@@ -17658,19 +17815,19 @@ var SQLiteDeleteBase = class extends QueryPromise {
17658
17815
  };
17659
17816
 
17660
17817
  // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@libsql+client@0.14.0_@opentelemetry+api@1.9.1_@types+better-sqlite3_308d9e3fe54e7589396665df270c63bc/node_modules/drizzle-orm/casing.js
17661
- function toSnakeCase(input3) {
17662
- const words = input3.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
17818
+ function toSnakeCase(input4) {
17819
+ const words = input4.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
17663
17820
  return words.map((word) => word.toLowerCase()).join("_");
17664
17821
  }
17665
- function toCamelCase(input3) {
17666
- const words = input3.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
17822
+ function toCamelCase(input4) {
17823
+ const words = input4.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
17667
17824
  return words.reduce((acc, word, i) => {
17668
17825
  const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`;
17669
17826
  return acc + formattedWord;
17670
17827
  }, "");
17671
17828
  }
17672
- function noopCase(input3) {
17673
- return input3;
17829
+ function noopCase(input4) {
17830
+ return input4;
17674
17831
  }
17675
17832
  var CasingCache = class {
17676
17833
  static [entityKind] = "CasingCache";
@@ -22232,6 +22389,103 @@ var migration0025 = {
22232
22389
  "ALTER TABLE review_runs ADD COLUMN IF NOT EXISTS duration_ms BIGINT NULL"
22233
22390
  ]
22234
22391
  };
22392
+ var migration0026 = {
22393
+ version: 26,
22394
+ name: "cli-refresh-tokens",
22395
+ statements: [
22396
+ `ALTER TABLE cli_access_tokens
22397
+ ADD COLUMN IF NOT EXISTS session_id CHAR(32) NULL AFTER user_id`,
22398
+ `CREATE INDEX IF NOT EXISTS cli_access_tokens_session_idx
22399
+ ON cli_access_tokens (session_id, expires_at)`,
22400
+ `CREATE TABLE IF NOT EXISTS cli_refresh_tokens (
22401
+ token_hash CHAR(64) PRIMARY KEY,
22402
+ user_id VARCHAR(384) NOT NULL,
22403
+ session_id CHAR(32) NOT NULL,
22404
+ expires_at BIGINT NOT NULL,
22405
+ created_at BIGINT NOT NULL,
22406
+ last_used_at BIGINT NULL,
22407
+ revoked_at BIGINT NULL,
22408
+ replaced_by_hash CHAR(64) NULL,
22409
+ CONSTRAINT cli_refresh_tokens_user_fk
22410
+ FOREIGN KEY (user_id) REFERENCES dashboard_users(id) ON DELETE CASCADE,
22411
+ INDEX cli_refresh_tokens_session_idx (session_id, expires_at),
22412
+ INDEX cli_refresh_tokens_user_idx (user_id, expires_at DESC),
22413
+ INDEX cli_refresh_tokens_expiry_idx (expires_at)
22414
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`
22415
+ ]
22416
+ };
22417
+ var migration0027 = {
22418
+ version: 27,
22419
+ name: "run-ai-insights",
22420
+ statements: [
22421
+ `CREATE TABLE IF NOT EXISTS run_ai_insights (
22422
+ run_id VARCHAR(384) PRIMARY KEY,
22423
+ project_id VARCHAR(255) NOT NULL,
22424
+ provider VARCHAR(128) NOT NULL,
22425
+ model VARCHAR(255) NOT NULL,
22426
+ status VARCHAR(32) NOT NULL,
22427
+ summary_json LONGTEXT NULL,
22428
+ error_message TEXT NULL,
22429
+ generated_by VARCHAR(384) NULL,
22430
+ created_at BIGINT NOT NULL,
22431
+ updated_at BIGINT NOT NULL,
22432
+ CONSTRAINT run_ai_insights_run_fk
22433
+ FOREIGN KEY (run_id) REFERENCES review_runs(id) ON DELETE CASCADE,
22434
+ CONSTRAINT run_ai_insights_project_fk
22435
+ FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
22436
+ CONSTRAINT run_ai_insights_status_check
22437
+ CHECK (status IN ('running', 'completed', 'failed')),
22438
+ INDEX run_ai_insights_project_idx (project_id),
22439
+ INDEX run_ai_insights_status_idx (status, updated_at DESC),
22440
+ INDEX run_ai_insights_generated_by_idx (generated_by)
22441
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`
22442
+ ]
22443
+ };
22444
+ var migration0028 = {
22445
+ version: 28,
22446
+ name: "site-ai-config",
22447
+ statements: [
22448
+ `CREATE TABLE IF NOT EXISTS site_ai_configs (
22449
+ config_key VARCHAR(64) PRIMARY KEY,
22450
+ config_json LONGTEXT NOT NULL,
22451
+ updated_by VARCHAR(384) NULL,
22452
+ updated_at BIGINT NOT NULL,
22453
+ CONSTRAINT site_ai_configs_updated_by_fk
22454
+ FOREIGN KEY (updated_by) REFERENCES dashboard_users(id) ON DELETE SET NULL,
22455
+ INDEX site_ai_configs_updated_idx (updated_at DESC)
22456
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`
22457
+ ]
22458
+ };
22459
+ var migration0029 = {
22460
+ version: 29,
22461
+ name: "audit-events",
22462
+ statements: [
22463
+ `CREATE TABLE IF NOT EXISTS audit_events (
22464
+ id VARCHAR(384) PRIMARY KEY,
22465
+ event_type VARCHAR(96) NOT NULL,
22466
+ actor_user_id VARCHAR(384) NULL,
22467
+ target_user_id VARCHAR(384) NULL,
22468
+ project_id VARCHAR(255) NULL,
22469
+ resource_type VARCHAR(96) NULL,
22470
+ resource_id VARCHAR(384) NULL,
22471
+ before_json LONGTEXT NULL,
22472
+ after_json LONGTEXT NULL,
22473
+ ip_address VARCHAR(128) NULL,
22474
+ user_agent TEXT NULL,
22475
+ created_at BIGINT NOT NULL,
22476
+ CONSTRAINT audit_events_actor_fk
22477
+ FOREIGN KEY (actor_user_id) REFERENCES dashboard_users(id) ON DELETE SET NULL,
22478
+ CONSTRAINT audit_events_target_fk
22479
+ FOREIGN KEY (target_user_id) REFERENCES dashboard_users(id) ON DELETE SET NULL,
22480
+ CONSTRAINT audit_events_project_fk
22481
+ FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE SET NULL,
22482
+ INDEX audit_events_created_idx (created_at DESC),
22483
+ INDEX audit_events_type_idx (event_type, created_at DESC),
22484
+ INDEX audit_events_actor_idx (actor_user_id, created_at DESC),
22485
+ INDEX audit_events_project_idx (project_id, created_at DESC)
22486
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`
22487
+ ]
22488
+ };
22235
22489
  var MARIADB_MIGRATIONS = [
22236
22490
  migration0001,
22237
22491
  migration0002,
@@ -22257,7 +22511,11 @@ var MARIADB_MIGRATIONS = [
22257
22511
  migration0022,
22258
22512
  migration0023,
22259
22513
  migration0024,
22260
- migration0025
22514
+ migration0025,
22515
+ migration0026,
22516
+ migration0027,
22517
+ migration0028,
22518
+ migration0029
22261
22519
  ];
22262
22520
  MARIADB_MIGRATIONS[MARIADB_MIGRATIONS.length - 1]?.version ?? 0;
22263
22521
 
@@ -22376,18 +22634,6 @@ var buildOneProvider = (name, config, logger) => {
22376
22634
  defaultModel: config.ai.opencodeGo.model,
22377
22635
  defaultTimeoutMs: config.ai.timeoutMs
22378
22636
  });
22379
- case "freemodel":
22380
- if (!config.ai.freemodel.apiKey) {
22381
- logger.warn("freemodel provider requested but no apiKey \u2014 skipping");
22382
- return null;
22383
- }
22384
- return createAiSdkProvider({
22385
- providerType: "freemodel",
22386
- baseUrl: config.ai.freemodel.baseUrl,
22387
- apiKey: config.ai.freemodel.apiKey,
22388
- defaultModel: config.ai.freemodel.model,
22389
- defaultTimeoutMs: config.ai.timeoutMs
22390
- });
22391
22637
  case "openai-compatible": {
22392
22638
  const c = config.ai.openaiCompatible;
22393
22639
  if (!c.baseUrl || !c.model) {
@@ -22403,6 +22649,8 @@ var buildOneProvider = (name, config, logger) => {
22403
22649
  ...c.apiKey ? { apiKey: c.apiKey } : {}
22404
22650
  });
22405
22651
  }
22652
+ default:
22653
+ throw new Error(`Unsupported AI provider: ${String(name)}`);
22406
22654
  }
22407
22655
  };
22408
22656
  var resolveActiveModel = (config) => {
@@ -22417,12 +22665,12 @@ var resolveActiveModel = (config) => {
22417
22665
  return config.ai.viettelNetmind.model;
22418
22666
  case "opencode-go":
22419
22667
  return config.ai.opencodeGo.model;
22420
- case "freemodel":
22421
- return config.ai.freemodel.model;
22422
22668
  case "openai-compatible":
22423
22669
  return config.ai.openaiCompatible.model ?? "openai-compatible";
22424
22670
  case "none":
22425
22671
  return "";
22672
+ default:
22673
+ throw new Error(`Unsupported AI provider: ${String(config.ai.provider)}`);
22426
22674
  }
22427
22675
  };
22428
22676
  var buildAiClient = (config, logger) => {
@@ -22481,7 +22729,8 @@ var buildContainer = async (options) => {
22481
22729
  ...options.aiOverrides?.numMaxFindings !== void 0 ? { numMaxFindings: options.aiOverrides.numMaxFindings } : {},
22482
22730
  timeoutMs: config.ai.timeoutMs,
22483
22731
  temperature: config.ai.temperature,
22484
- tokenBudgetWarn: config.ai.tokenBudgetWarn
22732
+ tokenBudgetWarn: config.ai.tokenBudgetWarn,
22733
+ adaptiveRetry: config.ai.adaptiveRetry
22485
22734
  });
22486
22735
  return async (rule, file, parsed, clusterContext, moduleContext) => aiExec(rule, file, parsed, clusterContext, moduleContext);
22487
22736
  })() : void 0;
@@ -22562,7 +22811,34 @@ var prReviewLayerSchema = external_exports.enum([
22562
22811
  ]);
22563
22812
  var ruleIdPattern = /^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/;
22564
22813
  var ruleIdSchema2 = external_exports.string().regex(ruleIdPattern, "Rule id must match `<scope>/<kebab-id>` (e.g. general/no-console-log)");
22565
- var codeReviewConfigSchema = external_exports.object({
22814
+ var migrateLegacyFreemodel = (value) => {
22815
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
22816
+ const root = value;
22817
+ const ai = typeof root.ai === "object" && root.ai !== null && !Array.isArray(root.ai) ? { ...root.ai } : null;
22818
+ const provider = typeof ai?.provider === "string" ? ai.provider : typeof root.aiProvider === "string" ? root.aiProvider : null;
22819
+ if (provider !== "freemodel") return value;
22820
+ const legacy = typeof ai?.freemodel === "object" && ai.freemodel !== null && !Array.isArray(ai.freemodel) ? ai.freemodel : {};
22821
+ const custom2 = typeof ai?.openaiCompatible === "object" && ai.openaiCompatible !== null && !Array.isArray(ai.openaiCompatible) ? ai.openaiCompatible : {};
22822
+ const fallback = Array.isArray(ai?.fallback) ? ai.fallback.map((item) => item === "freemodel" ? "openai-compatible" : item) : ai?.fallback;
22823
+ const { freemodel: _legacyFreemodel, ...aiWithoutLegacyProvider } = ai ?? {};
22824
+ return {
22825
+ ...root,
22826
+ aiProvider: "openai-compatible",
22827
+ ai: {
22828
+ ...aiWithoutLegacyProvider,
22829
+ provider: "openai-compatible",
22830
+ ...fallback !== void 0 ? { fallback } : {},
22831
+ openaiCompatible: {
22832
+ ...legacy,
22833
+ ...custom2,
22834
+ baseUrl: custom2.baseUrl ?? legacy.baseUrl ?? "https://api.freemodel.dev",
22835
+ model: custom2.model ?? legacy.model ?? "gpt-5.5",
22836
+ name: custom2.name ?? "freemodel-legacy"
22837
+ }
22838
+ }
22839
+ };
22840
+ };
22841
+ var codeReviewConfigObjectSchema = external_exports.object({
22566
22842
  mode: external_exports.enum(["auto", "economy", "balanced", "performance"]).default("auto"),
22567
22843
  include: external_exports.array(external_exports.string()).default([
22568
22844
  "**/*.ts",
@@ -22753,7 +23029,6 @@ var codeReviewConfigSchema = external_exports.object({
22753
23029
  "groq",
22754
23030
  "viettel-netmind",
22755
23031
  "opencode-go",
22756
- "freemodel",
22757
23032
  "openai-compatible",
22758
23033
  "none"
22759
23034
  ]).default("ollama"),
@@ -22764,7 +23039,6 @@ var codeReviewConfigSchema = external_exports.object({
22764
23039
  "groq",
22765
23040
  "viettel-netmind",
22766
23041
  "opencode-go",
22767
- "freemodel",
22768
23042
  "openai-compatible"
22769
23043
  ])
22770
23044
  ).default([]),
@@ -22772,6 +23046,17 @@ var codeReviewConfigSchema = external_exports.object({
22772
23046
  timeoutMs: external_exports.number().int().positive().default(18e4),
22773
23047
  tokenBudgetWarn: external_exports.number().int().positive().default(3e4),
22774
23048
  clusterTokenBudget: external_exports.number().int().positive().default(3e4),
23049
+ adaptiveRetry: external_exports.object({
23050
+ maxRetries: external_exports.number().int().min(0).max(3).default(1),
23051
+ contextReductionFactor: external_exports.number().min(0.25).max(0.95).default(0.75),
23052
+ timeoutMultiplier: external_exports.number().min(1.1).max(3).default(1.5),
23053
+ maxDelayMs: external_exports.number().int().min(0).max(3e4).default(5e3)
23054
+ }).default({
23055
+ maxRetries: 1,
23056
+ contextReductionFactor: 0.75,
23057
+ timeoutMultiplier: 1.5,
23058
+ maxDelayMs: 5e3
23059
+ }),
22775
23060
  /**
22776
23061
  * AI-resilience re-run ([ADR-0029]). After the main pass, AI rules whose
22777
23062
  * invocations were skipped for a RETRYABLE reason (provider down / parse
@@ -22811,7 +23096,7 @@ var codeReviewConfigSchema = external_exports.object({
22811
23096
  * default until M3 passes the repository's finding-quality gate.
22812
23097
  */
22813
23098
  viettelNetmind: external_exports.object({
22814
- baseUrl: external_exports.string().url().default("https://netmind.viettel.vn/gateway/v1"),
23099
+ baseUrl: external_exports.string().url().default("https://example.invalid/netmind/v1"),
22815
23100
  apiKey: external_exports.string().optional(),
22816
23101
  // Model access is team-scoped; `/models` is the source of truth.
22817
23102
  // M2.7 is the measured fast option but under-detected per-module
@@ -22819,7 +23104,7 @@ var codeReviewConfigSchema = external_exports.object({
22819
23104
  // remains opt-in until the same gate has measured its recall.
22820
23105
  model: external_exports.string().default("zai-org/GLM-4.7-cc")
22821
23106
  }).default({
22822
- baseUrl: "https://netmind.viettel.vn/gateway/v1",
23107
+ baseUrl: "https://example.invalid/netmind/v1",
22823
23108
  model: "zai-org/GLM-4.7-cc"
22824
23109
  }),
22825
23110
  opencodeGo: external_exports.object({
@@ -22830,14 +23115,6 @@ var codeReviewConfigSchema = external_exports.object({
22830
23115
  baseUrl: "https://opencode.ai/zen/go/v1",
22831
23116
  model: "qwen3.6-plus"
22832
23117
  }),
22833
- freemodel: external_exports.object({
22834
- baseUrl: external_exports.string().url().default("https://api.freemodel.dev"),
22835
- apiKey: external_exports.string().optional(),
22836
- model: external_exports.string().default("gpt-5.5")
22837
- }).default({
22838
- baseUrl: "https://api.freemodel.dev",
22839
- model: "gpt-5.5"
22840
- }),
22841
23118
  /**
22842
23119
  * Generic OpenAI-compatible escape hatch (LM Studio, vLLM, custom
22843
23120
  * self-hosted gateways, OpenRouter, Together, Anyscale, ...).
@@ -22857,16 +23134,21 @@ var codeReviewConfigSchema = external_exports.object({
22857
23134
  timeoutMs: 18e4,
22858
23135
  tokenBudgetWarn: 3e4,
22859
23136
  clusterTokenBudget: 3e4,
23137
+ adaptiveRetry: {
23138
+ maxRetries: 1,
23139
+ contextReductionFactor: 0.75,
23140
+ timeoutMultiplier: 1.5,
23141
+ maxDelayMs: 5e3
23142
+ },
22860
23143
  skipRerun: { maxPasses: 1, delayMs: 2e3 },
22861
23144
  ollama: { baseUrl: "http://localhost:11434", model: "qwen2.5-coder:7b", temperature: 0.1 },
22862
23145
  gemini: { model: "gemini-2.0-flash" },
22863
23146
  groq: { model: "llama-3.3-70b-versatile" },
22864
23147
  viettelNetmind: {
22865
- baseUrl: "https://netmind.viettel.vn/gateway/v1",
23148
+ baseUrl: "https://example.invalid/netmind/v1",
22866
23149
  model: "zai-org/GLM-4.7-cc"
22867
23150
  },
22868
23151
  opencodeGo: { baseUrl: "https://opencode.ai/zen/go/v1", model: "qwen3.6-plus" },
22869
- freemodel: { baseUrl: "https://api.freemodel.dev", model: "gpt-5.5" },
22870
23152
  openaiCompatible: { name: "openai-compatible" }
22871
23153
  }),
22872
23154
  report: external_exports.object({
@@ -23168,7 +23450,7 @@ var codeReviewConfigSchema = external_exports.object({
23168
23450
  * `${ENV_VAR}` interpolation for the token so secrets stay out of the file.
23169
23451
  */
23170
23452
  dashboard: external_exports.object({
23171
- /** Base URL of the @code-sentinel/server instance, e.g. `https://codesentinel.vtscloud.vn`. */
23453
+ /** Base URL of the @code-sentinel/server instance, e.g. `https://example.invalid/code-sentinel-dashboard`. */
23172
23454
  serverUrl: external_exports.string().url().optional(),
23173
23455
  /** Project-scoped bearer token for `POST /api/runs`. */
23174
23456
  token: external_exports.string().optional(),
@@ -23176,6 +23458,10 @@ var codeReviewConfigSchema = external_exports.object({
23176
23458
  projectId: external_exports.string().min(1).optional()
23177
23459
  }).default({})
23178
23460
  });
23461
+ var codeReviewConfigSchema = external_exports.preprocess(
23462
+ migrateLegacyFreemodel,
23463
+ codeReviewConfigObjectSchema
23464
+ );
23179
23465
 
23180
23466
  // src/config/load.ts
23181
23467
  var MODULE_NAME = "codereview";
@@ -23508,24 +23794,31 @@ var pathMatchesAnyGlob = (path, patterns) => {
23508
23794
  };
23509
23795
 
23510
23796
  // src/config/dashboard-defaults.ts
23511
- var DEFAULT_DASHBOARD_SERVER_URL = "https://codesentinel.vtscloud.vn";
23797
+ var DEFAULT_DASHBOARD_SERVER_URL = "https://example.invalid/code-sentinel-dashboard";
23512
23798
  var getDefaultDashboardServerUrl = () => process.env.CODE_SENTINEL_DASHBOARD_URL?.trim() || DEFAULT_DASHBOARD_SERVER_URL;
23513
23799
 
23514
23800
  // src/commands/push.command.ts
23515
23801
  var pushRunToServer = async (args) => {
23516
23802
  const doFetch = args.fetchFn ?? fetch;
23517
23803
  const url = `${args.serverUrl.replace(/\/+$/, "")}/api/runs`;
23518
- let res;
23519
- try {
23520
- res = await doFetch(url, {
23804
+ const send = () => {
23805
+ const token = args.getToken?.() ?? args.token;
23806
+ return doFetch(url, {
23521
23807
  method: "POST",
23522
23808
  headers: {
23523
23809
  "content-type": "application/json",
23524
- ...args.token !== void 0 ? { authorization: `Bearer ${args.token}` } : {},
23810
+ ...token !== void 0 ? { authorization: `Bearer ${token}` } : {},
23525
23811
  ...args.dto.status === "completed" ? { "idempotency-key": args.idempotencyKey ?? args.dto.id } : {}
23526
23812
  },
23527
23813
  body: JSON.stringify(args.dto)
23528
23814
  });
23815
+ };
23816
+ let res;
23817
+ try {
23818
+ res = await send();
23819
+ if (res.status === 401 && args.onUnauthorized && await args.onUnauthorized()) {
23820
+ res = await send();
23821
+ }
23529
23822
  } catch (e) {
23530
23823
  return err(new Error(`network error posting to ${url}: ${e.message}`));
23531
23824
  }
@@ -23568,6 +23861,8 @@ var pushReviewRunToServer = async (args) => {
23568
23861
  dto: finalDto,
23569
23862
  serverUrl: args.serverUrl,
23570
23863
  ...args.token !== void 0 ? { token: args.token } : {},
23864
+ ...args.getToken !== void 0 ? { getToken: args.getToken } : {},
23865
+ ...args.onUnauthorized !== void 0 ? { onUnauthorized: args.onUnauthorized } : {},
23571
23866
  ...args.run.status === "completed" ? { idempotencyKey: args.run.id } : {},
23572
23867
  ...args.fetchFn !== void 0 ? { fetchFn: args.fetchFn } : {}
23573
23868
  });
@@ -23593,12 +23888,28 @@ var runPush = async (options = {}, deps = {}) => {
23593
23888
  return EXIT.USAGE;
23594
23889
  }
23595
23890
  let token = options.token ?? config.dashboard.token ?? process.env.CODE_SENTINEL_DASHBOARD_TOKEN;
23891
+ let refreshDashboardCredential;
23596
23892
  if (!token && link && serverUrl === link.serverUrl) {
23597
23893
  try {
23598
- const credential = await createPlatformCredentialStore().read(link.serverUrl);
23599
- if (credential && (!credential.expiresAt || Date.parse(credential.expiresAt) > Date.now())) {
23600
- token = credential.accessToken;
23601
- }
23894
+ const store = createPlatformCredentialStore();
23895
+ const credential = await getAuthenticatedCredential({
23896
+ server: link.serverUrl,
23897
+ store
23898
+ });
23899
+ token = credential.accessToken;
23900
+ refreshDashboardCredential = async () => {
23901
+ try {
23902
+ const refreshed = await getAuthenticatedCredential({
23903
+ server: link.serverUrl,
23904
+ store,
23905
+ forceRefresh: true
23906
+ });
23907
+ token = refreshed.accessToken;
23908
+ return true;
23909
+ } catch {
23910
+ return false;
23911
+ }
23912
+ };
23602
23913
  } catch (error) {
23603
23914
  console.error(
23604
23915
  red(
@@ -23656,6 +23967,7 @@ var runPush = async (options = {}, deps = {}) => {
23656
23967
  projectId,
23657
23968
  serverUrl,
23658
23969
  ...token !== void 0 ? { token } : {},
23970
+ ...refreshDashboardCredential ? { getToken: () => token, onUnauthorized: refreshDashboardCredential } : {},
23659
23971
  ...link?.codebaseId ? { repositoryId: link.codebaseId } : {},
23660
23972
  ...reviewRequestId ? { reviewRequestId } : {},
23661
23973
  ...deps.fetchFn !== void 0 ? { fetchFn: deps.fetchFn } : {}
@@ -24101,13 +24413,13 @@ var createInkProgressRenderer = (opts) => {
24101
24413
  };
24102
24414
 
24103
24415
  // src/ui/ink/should-use-ink.ts
24104
- var shouldUseInkUi = (input3) => {
24105
- if (input3.noUi) return false;
24106
- if (input3.silent) return false;
24107
- if (!input3.isTty) return false;
24108
- const ci = (input3.ci ?? "").trim().toLowerCase();
24416
+ var shouldUseInkUi = (input4) => {
24417
+ if (input4.noUi) return false;
24418
+ if (input4.silent) return false;
24419
+ if (!input4.isTty) return false;
24420
+ const ci = (input4.ci ?? "").trim().toLowerCase();
24109
24421
  if (ci === "true" || ci === "1") return false;
24110
- if (input3.outputToStdout) return false;
24422
+ if (input4.outputToStdout) return false;
24111
24423
  return true;
24112
24424
  };
24113
24425
 
@@ -24305,23 +24617,23 @@ var isReviewableDiffPacket = (packet, excludes = DEFAULT_EXCLUDES) => {
24305
24617
  };
24306
24618
 
24307
24619
  // src/pr/hunk-chunker.ts
24308
- var chunkDiffHunks = (input3) => {
24309
- if (input3.maxChunks <= 0 || input3.hunks.length === 0) return [];
24620
+ var chunkDiffHunks = (input4) => {
24621
+ if (input4.maxChunks <= 0 || input4.hunks.length === 0) return [];
24310
24622
  const chunks = [];
24311
24623
  let current = [];
24312
24624
  let currentTokens = 0;
24313
- for (const hunk of input3.hunks) {
24314
- const tokens = input3.estimateTokens(hunk);
24315
- if (current.length > 0 && currentTokens + tokens > input3.tokenBudget) {
24625
+ for (const hunk of input4.hunks) {
24626
+ const tokens = input4.estimateTokens(hunk);
24627
+ if (current.length > 0 && currentTokens + tokens > input4.tokenBudget) {
24316
24628
  chunks.push(current);
24317
24629
  current = [];
24318
24630
  currentTokens = 0;
24319
- if (chunks.length >= input3.maxChunks) break;
24631
+ if (chunks.length >= input4.maxChunks) break;
24320
24632
  }
24321
24633
  current.push(hunk);
24322
24634
  currentTokens += tokens;
24323
24635
  }
24324
- if (current.length > 0 && chunks.length < input3.maxChunks) {
24636
+ if (current.length > 0 && chunks.length < input4.maxChunks) {
24325
24637
  chunks.push(current);
24326
24638
  }
24327
24639
  return chunks.map((hunks) => ({ hunks }));
@@ -24452,17 +24764,17 @@ var selectRulesForGroup = (group, profile, maxRules) => group.rules.filter((rule
24452
24764
  var strategyIncludesDiffReview = (strategy) => strategy === "adaptive" || strategy === "diff-only";
24453
24765
  var strategyIncludesGroupedReview = (strategy) => strategy === "adaptive" || strategy === "grouped";
24454
24766
  var strategyIncludesPerRuleReview = (strategy) => strategy === "targeted";
24455
- var buildAiReviewPlan = (input3) => {
24456
- const { config } = input3;
24767
+ var buildAiReviewPlan = (input4) => {
24768
+ const { config } = input4;
24457
24769
  const diffCalls = config.diffReview.enabled && strategyIncludesDiffReview(config.aiStrategy) ? chunkDiffHunks({
24458
- hunks: input3.packets.map(renderPrAgentHunks),
24770
+ hunks: input4.packets.map(renderPrAgentHunks),
24459
24771
  tokenBudget: config.diffChunkTokenBudget,
24460
24772
  maxChunks: Math.min(config.diffReview.maxChunkCalls, config.maxAiCalls),
24461
- estimateTokens: input3.estimateTokens
24773
+ estimateTokens: input4.estimateTokens
24462
24774
  }) : [];
24463
- const profiles = profilePrFiles(input3.sourceFiles, input3.packets, input3.diffFindings, config);
24775
+ const profiles = profilePrFiles(input4.sourceFiles, input4.packets, input4.diffFindings, config);
24464
24776
  const primaryProfiles = selectPrimaryProfiles(profiles, config);
24465
- const groups = collectPrRuleGroups(input3.rules);
24777
+ const groups = collectPrRuleGroups(input4.rules);
24466
24778
  const groupedCalls = [];
24467
24779
  const specializedCalls = [];
24468
24780
  let remaining = Math.max(0, config.maxAiCalls - diffCalls.length);
@@ -24543,8 +24855,8 @@ var renderGitLabCodeQualityReport = (findings2) => findings2.map((finding) => ({
24543
24855
  }
24544
24856
  }
24545
24857
  }));
24546
- var writeGitLabCodeQualityReport = async (findings2, root, output) => {
24547
- const path = resolve(root, output);
24858
+ var writeGitLabCodeQualityReport = async (findings2, root, output2) => {
24859
+ const path = resolve(root, output2);
24548
24860
  await mkdir(dirname(path), { recursive: true });
24549
24861
  await writeFile(path, JSON.stringify(renderGitLabCodeQualityReport(findings2), null, 2), "utf8");
24550
24862
  return path;
@@ -24663,15 +24975,15 @@ var decodePath = (segments) => {
24663
24975
  }
24664
24976
  };
24665
24977
  var isValidProjectPath = (value) => decodePath(value.split("/").filter((segment) => segment.length > 0)) === value;
24666
- var parseGitLabMrUrl = (input3) => {
24978
+ var parseGitLabMrUrl = (input4) => {
24667
24979
  let url;
24668
24980
  try {
24669
- url = new URL(input3);
24981
+ url = new URL(input4);
24670
24982
  } catch (e) {
24671
24983
  return err(
24672
24984
  new IOError(`Invalid GitLab MR URL: ${e.message}`, {
24673
24985
  cause: e,
24674
- context: { input: input3 }
24986
+ context: { input: input4 }
24675
24987
  })
24676
24988
  );
24677
24989
  }
@@ -24682,31 +24994,31 @@ var parseGitLabMrUrl = (input3) => {
24682
24994
  if (dashIndex <= 0) {
24683
24995
  return err(
24684
24996
  new IOError("Invalid GitLab MR URL: expected /<group>/<project>/-/merge_requests/<iid>", {
24685
- context: { input: input3 }
24997
+ context: { input: input4 }
24686
24998
  })
24687
24999
  );
24688
25000
  }
24689
25001
  const iidRaw = segments[dashIndex + 2];
24690
25002
  if (!iidRaw || !/^[1-9]\d*$/.test(iidRaw)) {
24691
25003
  return err(
24692
- new IOError(`Invalid GitLab MR iid: ${iidRaw ?? "<missing>"}`, { context: { input: input3 } })
25004
+ new IOError(`Invalid GitLab MR iid: ${iidRaw ?? "<missing>"}`, { context: { input: input4 } })
24693
25005
  );
24694
25006
  }
24695
25007
  const iid = Number.parseInt(iidRaw ?? "", 10);
24696
25008
  if (!Number.isInteger(iid) || iid < 1) {
24697
25009
  return err(
24698
- new IOError(`Invalid GitLab MR iid: ${iidRaw ?? "<missing>"}`, { context: { input: input3 } })
25010
+ new IOError(`Invalid GitLab MR iid: ${iidRaw ?? "<missing>"}`, { context: { input: input4 } })
24699
25011
  );
24700
25012
  }
24701
25013
  const projectPath = decodePath(segments.slice(0, dashIndex));
24702
25014
  if (!projectPath) {
24703
- return err(new IOError("Invalid GitLab project path encoding", { context: { input: input3 } }));
25015
+ return err(new IOError("Invalid GitLab project path encoding", { context: { input: input4 } }));
24704
25016
  }
24705
25017
  return ok({
24706
25018
  baseUrl: cleanBaseUrl(url.origin),
24707
25019
  projectPath,
24708
25020
  iid,
24709
- webUrl: input3
25021
+ webUrl: input4
24710
25022
  });
24711
25023
  };
24712
25024
  var resolveGitLabAutoTarget = (env = process.env) => {
@@ -25670,23 +25982,23 @@ var runWithConcurrency2 = async (tasks, limit) => {
25670
25982
  await Promise.all(workers);
25671
25983
  return results;
25672
25984
  };
25673
- var runDiffAiReview = async (input3) => {
25985
+ var runDiffAiReview = async (input4) => {
25674
25986
  const found = [];
25675
25987
  let succeeded = 0;
25676
25988
  let skipped = 0;
25677
- for (const [index2, call] of input3.calls.entries()) {
25678
- input3.onProgress?.({
25989
+ for (const [index2, call] of input4.calls.entries()) {
25990
+ input4.onProgress?.({
25679
25991
  phase: "PR AI diff review",
25680
25992
  detail: `chunk ${index2 + 1}`,
25681
25993
  done: index2,
25682
- total: input3.calls.length
25994
+ total: input4.calls.length
25683
25995
  });
25684
- const result = await input3.reviewer.review({
25685
- title: input3.mr.title,
25686
- description: input3.mr.description,
25996
+ const result = await input4.reviewer.review({
25997
+ title: input4.mr.title,
25998
+ description: input4.mr.description,
25687
25999
  hunks: call.hunks,
25688
- supportFiles: input3.supportFiles,
25689
- staticFindings: input3.staticFindings.slice(0, MAX_STATIC_FINDINGS_IN_DIFF_PROMPT).map((finding) => ({
26000
+ supportFiles: input4.supportFiles,
26001
+ staticFindings: input4.staticFindings.slice(0, MAX_STATIC_FINDINGS_IN_DIFF_PROMPT).map((finding) => ({
25690
26002
  ruleId: finding.ruleId,
25691
26003
  file: finding.file,
25692
26004
  line: finding.range.line,
@@ -25695,28 +26007,28 @@ var runDiffAiReview = async (input3) => {
25695
26007
  });
25696
26008
  if (!result.ok) {
25697
26009
  skipped += 1;
25698
- input3.logger.warn({ err: result.error.message }, "PR AI diff review skipped for one chunk");
25699
- input3.onProgress?.({
26010
+ input4.logger.warn({ err: result.error.message }, "PR AI diff review skipped for one chunk");
26011
+ input4.onProgress?.({
25700
26012
  phase: "PR AI diff review",
25701
26013
  detail: `chunk ${index2 + 1}`,
25702
26014
  done: index2 + 1,
25703
- total: input3.calls.length
26015
+ total: input4.calls.length
25704
26016
  });
25705
26017
  continue;
25706
26018
  }
25707
26019
  succeeded += 1;
25708
- found.push(...result.value.map((raw) => toAiFinding(input3.runId, raw)));
25709
- input3.onProgress?.({
26020
+ found.push(...result.value.map((raw) => toAiFinding(input4.runId, raw)));
26021
+ input4.onProgress?.({
25710
26022
  phase: "PR AI diff review",
25711
26023
  detail: `chunk ${index2 + 1}`,
25712
26024
  done: index2 + 1,
25713
- total: input3.calls.length
26025
+ total: input4.calls.length
25714
26026
  });
25715
26027
  }
25716
26028
  return { findings: found, succeeded, skipped };
25717
26029
  };
25718
26030
  var diffHunksForFile = (packets, filePath) => packets.filter((packet) => packet.newPath === filePath).map(renderPrAgentHunks);
25719
- var runGroupedAiReview = async (input3) => {
26031
+ var runGroupedAiReview = async (input4) => {
25720
26032
  const found = [];
25721
26033
  const stats = {};
25722
26034
  const record = (ruleIds, outcome) => {
@@ -25728,22 +26040,22 @@ var runGroupedAiReview = async (input3) => {
25728
26040
  };
25729
26041
  }
25730
26042
  };
25731
- for (const [index2, call] of input3.calls.entries()) {
26043
+ for (const [index2, call] of input4.calls.entries()) {
25732
26044
  const ruleIds = call.rules.map((rule) => rule.id);
25733
- input3.onProgress?.({
26045
+ input4.onProgress?.({
25734
26046
  phase: "PR AI grouped review",
25735
26047
  detail: call.profile.file.path,
25736
26048
  done: index2,
25737
- total: input3.calls.length
26049
+ total: input4.calls.length
25738
26050
  });
25739
- const result = await input3.reviewer.review({
26051
+ const result = await input4.reviewer.review({
25740
26052
  primaryFile: {
25741
26053
  path: call.profile.file.path,
25742
26054
  language: call.profile.file.language,
25743
26055
  content: call.profile.file.content
25744
26056
  },
25745
- diffHunks: diffHunksForFile(input3.packets, call.profile.file.path),
25746
- supportFiles: input3.supportFiles,
26057
+ diffHunks: diffHunksForFile(input4.packets, call.profile.file.path),
26058
+ supportFiles: input4.supportFiles,
25747
26059
  rules: call.rules.map((rule) => ({
25748
26060
  ruleId: rule.id,
25749
26061
  title: rule.title,
@@ -25753,34 +26065,34 @@ var runGroupedAiReview = async (input3) => {
25753
26065
  });
25754
26066
  if (!result.ok) {
25755
26067
  record(ruleIds, "skipped");
25756
- input3.logger.warn(
26068
+ input4.logger.warn(
25757
26069
  { groupId: call.groupId, file: call.profile.file.path, err: result.error.message },
25758
26070
  "PR grouped AI review skipped for one call"
25759
26071
  );
25760
- input3.onProgress?.({
26072
+ input4.onProgress?.({
25761
26073
  phase: "PR AI grouped review",
25762
26074
  detail: call.profile.file.path,
25763
26075
  done: index2 + 1,
25764
- total: input3.calls.length
26076
+ total: input4.calls.length
25765
26077
  });
25766
26078
  continue;
25767
26079
  }
25768
26080
  record(ruleIds, "succeeded");
25769
26081
  found.push(
25770
26082
  ...result.value.filter(
25771
- (raw) => raw.file === call.profile.file.path && getDiffLinePosition(input3.lineMap, raw.file, raw.range.line) !== void 0
25772
- ).map((raw) => toGroupedFinding(input3.runId, raw, input3.ruleById))
26083
+ (raw) => raw.file === call.profile.file.path && getDiffLinePosition(input4.lineMap, raw.file, raw.range.line) !== void 0
26084
+ ).map((raw) => toGroupedFinding(input4.runId, raw, input4.ruleById))
25773
26085
  );
25774
- input3.onProgress?.({
26086
+ input4.onProgress?.({
25775
26087
  phase: "PR AI grouped review",
25776
26088
  detail: call.profile.file.path,
25777
26089
  done: index2 + 1,
25778
- total: input3.calls.length
26090
+ total: input4.calls.length
25779
26091
  });
25780
26092
  }
25781
26093
  return { findings: found, stats };
25782
26094
  };
25783
- var runPerRuleAiReview = async (input3) => {
26095
+ var runPerRuleAiReview = async (input4) => {
25784
26096
  const found = [];
25785
26097
  const stats = {};
25786
26098
  let completed = 0;
@@ -25791,21 +26103,21 @@ var runPerRuleAiReview = async (input3) => {
25791
26103
  skipped: current.skipped + (outcome === "skipped" ? 1 : 0)
25792
26104
  };
25793
26105
  };
25794
- input3.onProgress?.({
26106
+ input4.onProgress?.({
25795
26107
  phase: "PR AI targeted review",
25796
- detail: input3.calls.length === 0 ? "no calls" : input3.calls[0]?.profile.file.path ?? "",
26108
+ detail: input4.calls.length === 0 ? "no calls" : input4.calls[0]?.profile.file.path ?? "",
25797
26109
  done: 0,
25798
- total: input3.calls.length
26110
+ total: input4.calls.length
25799
26111
  });
25800
- const tasks = input3.calls.map((call) => async () => {
25801
- const result = await input3.reviewer.review({
26112
+ const tasks = input4.calls.map((call) => async () => {
26113
+ const result = await input4.reviewer.review({
25802
26114
  primaryFile: {
25803
26115
  path: call.profile.file.path,
25804
26116
  language: call.profile.file.language,
25805
26117
  content: call.profile.file.content
25806
26118
  },
25807
- diffHunks: diffHunksForFile(input3.packets, call.profile.file.path),
25808
- supportFiles: input3.supportFiles,
26119
+ diffHunks: diffHunksForFile(input4.packets, call.profile.file.path),
26120
+ supportFiles: input4.supportFiles,
25809
26121
  rule: {
25810
26122
  ruleId: call.rule.id,
25811
26123
  title: call.rule.title,
@@ -25816,15 +26128,15 @@ var runPerRuleAiReview = async (input3) => {
25816
26128
  promptPath: call.rule.prompt
25817
26129
  });
25818
26130
  completed += 1;
25819
- input3.onProgress?.({
26131
+ input4.onProgress?.({
25820
26132
  phase: "PR AI targeted review",
25821
26133
  detail: `${call.profile.file.path} \xB7 ${call.rule.id}`,
25822
26134
  done: completed,
25823
- total: input3.calls.length
26135
+ total: input4.calls.length
25824
26136
  });
25825
26137
  if (!result.ok) {
25826
26138
  record(call.rule.id, "skipped");
25827
- input3.logger.warn(
26139
+ input4.logger.warn(
25828
26140
  { ruleId: call.rule.id, file: call.profile.file.path, err: result.error.message },
25829
26141
  "PR targeted AI review skipped for one call"
25830
26142
  );
@@ -25832,10 +26144,10 @@ var runPerRuleAiReview = async (input3) => {
25832
26144
  }
25833
26145
  record(call.rule.id, "succeeded");
25834
26146
  return result.value.filter(
25835
- (raw) => raw.file === call.profile.file.path && getDiffLinePosition(input3.lineMap, raw.file, raw.range.line) !== void 0
25836
- ).map((raw) => toPerRuleFinding(input3.runId, raw, input3.ruleById));
26147
+ (raw) => raw.file === call.profile.file.path && getDiffLinePosition(input4.lineMap, raw.file, raw.range.line) !== void 0
26148
+ ).map((raw) => toPerRuleFinding(input4.runId, raw, input4.ruleById));
25837
26149
  });
25838
- const settled = await runWithConcurrency2(tasks, input3.concurrency);
26150
+ const settled = await runWithConcurrency2(tasks, input4.concurrency);
25839
26151
  for (const findings2 of settled) found.push(...findings2);
25840
26152
  return { findings: found, stats };
25841
26153
  };
@@ -26497,9 +26809,9 @@ var runPrReview = async (options) => {
26497
26809
  };
26498
26810
 
26499
26811
  // src/review-profile.ts
26500
- var resolveReviewProfile = (input3) => {
26501
- const name = input3.requested ?? input3.configured.name;
26502
- const configured = input3.configured;
26812
+ var resolveReviewProfile = (input4) => {
26813
+ const name = input4.requested ?? input4.configured.name;
26814
+ const configured = input4.configured;
26503
26815
  if (name === "fast" && configured.name === "fast" && configured.ai !== "disabled") {
26504
26816
  return {
26505
26817
  ok: false,
@@ -26507,7 +26819,7 @@ var resolveReviewProfile = (input3) => {
26507
26819
  };
26508
26820
  }
26509
26821
  if (name === "fast") {
26510
- const gitFilter = input3.explicitGitFilter ?? { mode: "staged" };
26822
+ const gitFilter = input4.explicitGitFilter ?? { mode: "staged" };
26511
26823
  const scope = gitFilter.mode === "staged" ? "staged" : gitFilter.mode === "changed" ? "changed" : "range";
26512
26824
  return {
26513
26825
  ok: true,
@@ -26519,29 +26831,29 @@ var resolveReviewProfile = (input3) => {
26519
26831
  ai: "disabled",
26520
26832
  maxBudgetMs: configured.name === "fast" ? configured.maxBudgetMs : 5e3,
26521
26833
  gateCoverageLabel: "deterministic checks on selected changes; AI intentionally not run",
26522
- aiSkipReason: input3.aiOff ? "explicit --ai-off" : "fast profile policy"
26834
+ aiSkipReason: input4.aiOff ? "explicit --ai-off" : "fast profile policy"
26523
26835
  },
26524
26836
  gitFilter,
26525
26837
  noGraphCache: false,
26526
26838
  aiOff: true
26527
26839
  };
26528
26840
  }
26529
- if (input3.explicitGitFilter) {
26841
+ if (input4.explicitGitFilter) {
26530
26842
  return {
26531
26843
  ok: true,
26532
26844
  profile: {
26533
26845
  name: "deep",
26534
- fileScope: input3.explicitGitFilter.mode === "staged" ? "staged" : "range",
26846
+ fileScope: input4.explicitGitFilter.mode === "staged" ? "staged" : "range",
26535
26847
  deterministicRules: "required",
26536
26848
  graph: "full",
26537
- ai: input3.aiOff ? "disabled" : configured.ai,
26849
+ ai: input4.aiOff ? "disabled" : configured.ai,
26538
26850
  ...configured.maxBudgetMs ? { maxBudgetMs: configured.maxBudgetMs } : {},
26539
26851
  gateCoverageLabel: "configured deterministic checks on selected scope",
26540
- ...input3.aiOff ? { aiSkipReason: "explicit --ai-off" } : {}
26852
+ ...input4.aiOff ? { aiSkipReason: "explicit --ai-off" } : {}
26541
26853
  },
26542
- gitFilter: input3.explicitGitFilter,
26854
+ gitFilter: input4.explicitGitFilter,
26543
26855
  noGraphCache: true,
26544
- aiOff: input3.aiOff
26856
+ aiOff: input4.aiOff
26545
26857
  };
26546
26858
  }
26547
26859
  return {
@@ -26551,13 +26863,13 @@ var resolveReviewProfile = (input3) => {
26551
26863
  fileScope: "repository",
26552
26864
  deterministicRules: "required",
26553
26865
  graph: "full",
26554
- ai: input3.aiOff ? "disabled" : configured.ai,
26866
+ ai: input4.aiOff ? "disabled" : configured.ai,
26555
26867
  ...configured.maxBudgetMs ? { maxBudgetMs: configured.maxBudgetMs } : {},
26556
26868
  gateCoverageLabel: "configured deterministic checks across the repository",
26557
- ...input3.aiOff ? { aiSkipReason: "explicit --ai-off" } : {}
26869
+ ...input4.aiOff ? { aiSkipReason: "explicit --ai-off" } : {}
26558
26870
  },
26559
26871
  noGraphCache: true,
26560
- aiOff: input3.aiOff
26872
+ aiOff: input4.aiOff
26561
26873
  };
26562
26874
  };
26563
26875
 
@@ -28382,10 +28694,10 @@ var repositoryConfigFromLocalConfig = (config) => ({
28382
28694
  review: config.review,
28383
28695
  prReview: config.prReview
28384
28696
  });
28385
- var getLocalEffectiveConfig = async (input3) => {
28386
- const cwd = resolve(input3.path ?? process.cwd());
28697
+ var getLocalEffectiveConfig = async (input4) => {
28698
+ const cwd = resolve(input4.path ?? process.cwd());
28387
28699
  const loaded = await loadConfig(
28388
- input3.configPath === void 0 ? { cwd } : { cwd, configPath: input3.configPath }
28700
+ input4.configPath === void 0 ? { cwd } : { cwd, configPath: input4.configPath }
28389
28701
  );
28390
28702
  if (!loaded.ok) return { error: loaded.error.message };
28391
28703
  const effectiveConfig = repositoryConfigFromLocalConfig(loaded.value.config);
@@ -28424,17 +28736,10 @@ var runConfigEffective = async (options = {}) => {
28424
28736
  return EXIT.USAGE;
28425
28737
  }
28426
28738
  try {
28427
- const credential = await createPlatformCredentialStore().read(link.serverUrl);
28428
- if (!credential || credential.expiresAt && Date.parse(credential.expiresAt) <= Date.now()) {
28429
- writeError(
28430
- `Not authenticated with ${link.serverUrl}. Run \`cs auth login --server ${link.serverUrl}\`.`
28431
- );
28432
- return EXIT.USAGE;
28433
- }
28434
- const response = await createRemoteConfigClient({
28435
- serverUrl: link.serverUrl,
28436
- token: credential.accessToken
28437
- }).resolveConfig({
28739
+ const response = await (await createAuthenticatedRemoteClient({
28740
+ server: link.serverUrl,
28741
+ store: createPlatformCredentialStore()
28742
+ })).resolveConfig({
28438
28743
  schemaVersion: 1,
28439
28744
  projectId: link.projectId,
28440
28745
  codebaseId: link.codebaseId,
@@ -29649,15 +29954,15 @@ var decodeSegment = (value) => {
29649
29954
  return null;
29650
29955
  }
29651
29956
  };
29652
- var parseGitHubPullUrl = (input3) => {
29957
+ var parseGitHubPullUrl = (input4) => {
29653
29958
  let url;
29654
29959
  try {
29655
- url = new URL(input3);
29960
+ url = new URL(input4);
29656
29961
  } catch (e) {
29657
29962
  return err(
29658
29963
  new IOError(`Invalid GitHub PR URL: ${e.message}`, {
29659
29964
  cause: e,
29660
- context: { input: input3 }
29965
+ context: { input: input4 }
29661
29966
  })
29662
29967
  );
29663
29968
  }
@@ -29665,7 +29970,7 @@ var parseGitHubPullUrl = (input3) => {
29665
29970
  if (segments.length < 4 || segments[2] !== "pull") {
29666
29971
  return err(
29667
29972
  new IOError("Invalid GitHub PR URL: expected /<owner>/<repo>/pull/<number>", {
29668
- context: { input: input3 }
29973
+ context: { input: input4 }
29669
29974
  })
29670
29975
  );
29671
29976
  }
@@ -29673,18 +29978,18 @@ var parseGitHubPullUrl = (input3) => {
29673
29978
  const repo = decodeSegment(segments[1] ?? "");
29674
29979
  const pullNumberRaw = segments[3];
29675
29980
  if (!owner || !repo) {
29676
- return err(new IOError("Invalid GitHub repository path encoding", { context: { input: input3 } }));
29981
+ return err(new IOError("Invalid GitHub repository path encoding", { context: { input: input4 } }));
29677
29982
  }
29678
29983
  if (!pullNumberRaw || !/^[1-9]\d*$/.test(pullNumberRaw)) {
29679
29984
  return err(
29680
29985
  new IOError(`Invalid GitHub PR number: ${pullNumberRaw ?? "<missing>"}`, {
29681
- context: { input: input3 }
29986
+ context: { input: input4 }
29682
29987
  })
29683
29988
  );
29684
29989
  }
29685
29990
  const pullNumber = Number.parseInt(pullNumberRaw, 10);
29686
29991
  if (!Number.isInteger(pullNumber) || pullNumber < 1) {
29687
- return err(new IOError(`Invalid GitHub PR number: ${pullNumberRaw}`, { context: { input: input3 } }));
29992
+ return err(new IOError(`Invalid GitHub PR number: ${pullNumberRaw}`, { context: { input: input4 } }));
29688
29993
  }
29689
29994
  const baseUrl = cleanBaseUrl2(url.origin);
29690
29995
  return ok({
@@ -29693,7 +29998,7 @@ var parseGitHubPullUrl = (input3) => {
29693
29998
  repo,
29694
29999
  pullNumber,
29695
30000
  cloneUrl: `${baseUrl}/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}.git`,
29696
- webUrl: input3
30001
+ webUrl: input4
29697
30002
  });
29698
30003
  };
29699
30004
 
@@ -30767,12 +31072,7 @@ var runProjectStatus = async (options = {}) => {
30767
31072
  var credentialStore2 = () => createPlatformCredentialStore();
30768
31073
  var authenticatedClient2 = async (server, store) => {
30769
31074
  const origin = new URL(server).origin;
30770
- const credential = await store.read(origin);
30771
- if (!credential) throw new Error("Not authenticated. Run `cs auth login --server <url>`.");
30772
- if (credential.expiresAt && Date.parse(credential.expiresAt) <= Date.now()) {
30773
- throw new Error("Credential expired. Run `cs auth login --server <url>`.");
30774
- }
30775
- return createRemoteConfigClient({ serverUrl: origin, token: credential.accessToken });
31075
+ return createAuthenticatedRemoteClient({ server: origin, store });
30776
31076
  };
30777
31077
  var runProjectList = async (options) => {
30778
31078
  const write = options.write ?? console.log;
@@ -30803,7 +31103,7 @@ var canonicalRepositoryUrl = (value) => {
30803
31103
  return null;
30804
31104
  }
30805
31105
  };
30806
- var workspaceFingerprint = (input3) => createHash("sha256").update(JSON.stringify(input3)).digest("hex");
31106
+ var workspaceFingerprint = (input4) => createHash("sha256").update(JSON.stringify(input4)).digest("hex");
30807
31107
  var suggestedIdentifier = (canonicalRemote) => {
30808
31108
  const lastPath = canonicalRemote.split("/").filter(Boolean).at(-1) ?? "project";
30809
31109
  return lastPath.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}", "gu"), "").replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 128) || "project";
@@ -30944,19 +31244,12 @@ var aiProviderConfigKey = (provider) => {
30944
31244
  case "ollama":
30945
31245
  case "gemini":
30946
31246
  case "groq":
30947
- case "freemodel":
30948
31247
  return provider;
30949
31248
  default:
30950
31249
  return null;
30951
31250
  }
30952
31251
  };
30953
- var LOCAL_API_KEY_PROVIDERS = /* @__PURE__ */ new Set([
30954
- "gemini",
30955
- "groq",
30956
- "viettel-netmind",
30957
- "opencode-go",
30958
- "freemodel"
30959
- ]);
31252
+ var LOCAL_API_KEY_PROVIDERS = /* @__PURE__ */ new Set(["gemini", "groq", "viettel-netmind", "opencode-go"]);
30960
31253
  var providerUsesLocalApiKey = (provider) => LOCAL_API_KEY_PROVIDERS.has(provider);
30961
31254
  var mergeIfMissing = (target, key, value) => {
30962
31255
  if (value !== void 0 && target[key] === void 0) target[key] = value;
@@ -30994,8 +31287,8 @@ var materializeDashboardRuntimeConfig = (config) => {
30994
31287
  mergeIfMissing(report2, "output", config.reportOutput);
30995
31288
  if (Object.keys(report2).length > 0) config.report = report2;
30996
31289
  };
30997
- var dashboardPolicyToLocalConfig = (input3) => {
30998
- const config = { ...unwrapProjectReviewConfig(input3.value) };
31290
+ var dashboardPolicyToLocalConfig = (input4) => {
31291
+ const config = { ...unwrapProjectReviewConfig(input4.value) };
30999
31292
  materializeDashboardRuntimeConfig(config);
31000
31293
  for (const key of [
31001
31294
  "schemaVersion",
@@ -31017,8 +31310,8 @@ var dashboardPolicyToLocalConfig = (input3) => {
31017
31310
  }
31018
31311
  return {
31019
31312
  dashboard: {
31020
- projectId: input3.projectId,
31021
- serverUrl: new URL(input3.server).origin
31313
+ projectId: input4.projectId,
31314
+ serverUrl: new URL(input4.server).origin
31022
31315
  },
31023
31316
  ...config
31024
31317
  };
@@ -31297,14 +31590,14 @@ var hasGitRepository = async (cwd) => {
31297
31590
  return false;
31298
31591
  }
31299
31592
  };
31300
- var getLocalReadiness = async (input3 = {}) => {
31301
- const root = resolve(input3.path ?? process.cwd());
31593
+ var getLocalReadiness = async (input4 = {}) => {
31594
+ const root = resolve(input4.path ?? process.cwd());
31302
31595
  const [project, isGitRepository, config] = await Promise.all([
31303
- input3.projectStatus ? input3.projectStatus() : getLocalProjectStatus(root),
31304
- input3.gitRepository ? input3.gitRepository() : hasGitRepository(root),
31596
+ input4.projectStatus ? input4.projectStatus() : getLocalProjectStatus(root),
31597
+ input4.gitRepository ? input4.gitRepository() : hasGitRepository(root),
31305
31598
  getLocalEffectiveConfig({
31306
31599
  path: root,
31307
- ...input3.configPath ? { configPath: input3.configPath } : {}
31600
+ ...input4.configPath ? { configPath: input4.configPath } : {}
31308
31601
  })
31309
31602
  ]);
31310
31603
  const checks = [
@@ -31513,12 +31806,10 @@ var runReport = async (options) => {
31513
31806
  };
31514
31807
  var remoteClient = async (server) => {
31515
31808
  const origin = new URL(server).origin;
31516
- const credential = await createPlatformCredentialStore().read(origin);
31517
- if (!credential) throw new Error("Not authenticated. Run `cs auth login`.");
31518
- if (credential.expiresAt && Date.parse(credential.expiresAt) <= Date.now()) {
31519
- throw new Error("Credential expired. Run `cs auth login`.");
31520
- }
31521
- return createRemoteConfigClient({ serverUrl: origin, token: credential.accessToken });
31809
+ return createAuthenticatedRemoteClient({
31810
+ server: origin,
31811
+ store: createPlatformCredentialStore()
31812
+ });
31522
31813
  };
31523
31814
  var linkedContext = async (path) => {
31524
31815
  const link = await new FileWorkspaceLinkStore(resolve(path ?? process.cwd())).read();
@@ -31580,9 +31871,9 @@ var runResultsExport = async (options) => {
31580
31871
  const client = options.client ?? await remoteClient(server);
31581
31872
  const exported = await client.exportRun(options.runId, options.format);
31582
31873
  if (options.output) {
31583
- const output = resolve(options.path ?? process.cwd(), options.output);
31584
- await writeFile(output, exported.content, "utf8");
31585
- write(`Exported Dashboard run ${options.runId} to ${output}.`);
31874
+ const output2 = resolve(options.path ?? process.cwd(), options.output);
31875
+ await writeFile(output2, exported.content, "utf8");
31876
+ write(`Exported Dashboard run ${options.runId} to ${output2}.`);
31586
31877
  } else {
31587
31878
  process.stdout.write(exported.content);
31588
31879
  }
@@ -31963,12 +32254,12 @@ var createRunnerLogPoster = (serverUrl, job) => {
31963
32254
  };
31964
32255
  return { log: log3, flush };
31965
32256
  };
31966
- var forwardChildOutput = (stream, output, logPoster, logStream) => {
32257
+ var forwardChildOutput = (stream, output2, logPoster, logStream) => {
31967
32258
  if (!stream) return;
31968
32259
  let buffered = "";
31969
32260
  stream.on("data", (chunk) => {
31970
32261
  const text2 = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
31971
- output.write(text2);
32262
+ output2.write(text2);
31972
32263
  buffered += text2;
31973
32264
  const lines = buffered.split(/\r?\n/);
31974
32265
  buffered = lines.pop() ?? "";
@@ -32158,7 +32449,7 @@ var RUNNER_PROCESS_ENV_ALLOWLIST = [
32158
32449
  "NO_COLOR",
32159
32450
  "CODE_SENTINEL_NETMIND_MIN_REQUEST_INTERVAL_MS"
32160
32451
  ];
32161
- var createRunnerChildEnv = (parentEnv, input3) => {
32452
+ var createRunnerChildEnv = (parentEnv, input4) => {
32162
32453
  const env = {};
32163
32454
  for (const key of RUNNER_PROCESS_ENV_ALLOWLIST) {
32164
32455
  if (parentEnv[key] !== void 0) env[key] = parentEnv[key];
@@ -32167,15 +32458,15 @@ var createRunnerChildEnv = (parentEnv, input3) => {
32167
32458
  ...env,
32168
32459
  CI: parentEnv.CI ?? "true",
32169
32460
  CODE_SENTINEL_CONFIG_FILE: "",
32170
- CODE_SENTINEL_SOURCE_WORKDIR: input3.workspace,
32171
- CODE_SENTINEL_DASHBOARD_URL: input3.serverUrl,
32172
- CODE_SENTINEL_DASHBOARD_TOKEN: input3.jobToken,
32173
- CODE_SENTINEL_PROJECT_ID: input3.projectId,
32174
- CODE_SENTINEL_REVIEW_REQUEST_ID: input3.requestId,
32175
- CODE_SENTINEL_RUNTIME_DIR: input3.runtimeDir,
32176
- CODE_SENTINEL_RUNTIME_STATE_FILE: join(input3.runtimeDir, "runtime.env"),
32177
- ...input3.runtimeAiConfigB64 ? { CODE_SENTINEL_RUNTIME_AI_CONFIG_B64: input3.runtimeAiConfigB64 } : {},
32178
- ...input3.cacheDbPath ? { CODE_SENTINEL_STORAGE_DB_PATH: input3.cacheDbPath } : {}
32461
+ CODE_SENTINEL_SOURCE_WORKDIR: input4.workspace,
32462
+ CODE_SENTINEL_DASHBOARD_URL: input4.serverUrl,
32463
+ CODE_SENTINEL_DASHBOARD_TOKEN: input4.jobToken,
32464
+ CODE_SENTINEL_PROJECT_ID: input4.projectId,
32465
+ CODE_SENTINEL_REVIEW_REQUEST_ID: input4.requestId,
32466
+ CODE_SENTINEL_RUNTIME_DIR: input4.runtimeDir,
32467
+ CODE_SENTINEL_RUNTIME_STATE_FILE: join(input4.runtimeDir, "runtime.env"),
32468
+ ...input4.runtimeAiConfigB64 ? { CODE_SENTINEL_RUNTIME_AI_CONFIG_B64: input4.runtimeAiConfigB64 } : {},
32469
+ ...input4.cacheDbPath ? { CODE_SENTINEL_STORAGE_DB_PATH: input4.cacheDbPath } : {}
32179
32470
  };
32180
32471
  };
32181
32472
  var runJob = async (serverUrl, job, options) => {
@@ -32288,25 +32579,6 @@ var runServerRunner = async (options = {}) => {
32288
32579
  await Promise.allSettled(active);
32289
32580
  return EXIT.SUCCESS;
32290
32581
  };
32291
- var loadDotenv = (options = {}) => {
32292
- if (options.skipFsLoad) return { loaded: [] };
32293
- const cwd = options.cwd ?? process.cwd();
32294
- const candidates = [resolve(cwd, ".env"), resolve(cwd, ".env.local")];
32295
- const loaded = [];
32296
- const merged = {};
32297
- for (const path of candidates) {
32298
- if (!existsSync(path)) continue;
32299
- const text2 = readFileSync(path, "utf8");
32300
- Object.assign(merged, parse$1(text2));
32301
- loaded.push(path);
32302
- }
32303
- for (const [key, value] of Object.entries(merged)) {
32304
- if (process.env[key] === void 0) {
32305
- process.env[key] = value;
32306
- }
32307
- }
32308
- return { loaded };
32309
- };
32310
32582
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
32311
32583
  var FETCH_TIMEOUT_MS = 1200;
32312
32584
  var truthy = (value) => value === "1" || value === "true" || value === "yes" || value === "on";
@@ -32356,6 +32628,14 @@ var fetchLatestVersion = async (packageName) => {
32356
32628
  clearTimeout(timeout);
32357
32629
  }
32358
32630
  };
32631
+ var checkLatestVersion = async (input4) => {
32632
+ const latest = await fetchLatestVersion(input4.packageName);
32633
+ return {
32634
+ current: input4.currentVersion,
32635
+ latest,
32636
+ updateAvailable: latest ? isNewerVersion(latest, input4.currentVersion) : false
32637
+ };
32638
+ };
32359
32639
  var printUpdateMessage = (packageName, current, latest) => {
32360
32640
  process.stderr.write(
32361
32641
  [
@@ -32398,6 +32678,98 @@ var maybeNotifyUpdate = async (options) => {
32398
32678
  printUpdateMessage(options.packageName, options.currentVersion, latest);
32399
32679
  }
32400
32680
  };
32681
+
32682
+ // src/commands/update.command.ts
32683
+ var updateCommand = (packageName, tag) => {
32684
+ const packageSpec = `${packageName}@${tag}`;
32685
+ const npmExecPath = process.env.npm_execpath;
32686
+ if (npmExecPath) return [process.execPath, [npmExecPath, "install", "-g", packageSpec]];
32687
+ return ["npm", ["install", "-g", packageSpec]];
32688
+ };
32689
+ var runProcess = (command, args) => new Promise((resolveRun) => {
32690
+ const child = spawn(command, args, { stdio: "inherit" });
32691
+ child.on("error", () => resolveRun(EXIT.RUNTIME));
32692
+ child.on("close", (code) => resolveRun(code ?? EXIT.RUNTIME));
32693
+ });
32694
+ var askYes = async (question) => {
32695
+ const rl = createInterface({ input: stdin, output: stdout });
32696
+ try {
32697
+ const answer = (await rl.question(`${question} [y/N]: `)).trim().toLowerCase();
32698
+ return answer === "y" || answer === "yes";
32699
+ } finally {
32700
+ rl.close();
32701
+ }
32702
+ };
32703
+ var runUpdate = async (options) => {
32704
+ const tag = options.tag ?? "latest";
32705
+ if (options.privatePackage || !options.packageName || options.packageName === "@code-sentinel/cli") {
32706
+ if (options.json) {
32707
+ console.log(
32708
+ JSON.stringify({
32709
+ ok: false,
32710
+ error: "update_not_available",
32711
+ packageName: options.packageName
32712
+ })
32713
+ );
32714
+ } else {
32715
+ console.error(
32716
+ "This build is not an installable npm CLI package. Update from the release source you used."
32717
+ );
32718
+ }
32719
+ return EXIT.USAGE;
32720
+ }
32721
+ const latest = await checkLatestVersion({
32722
+ packageName: options.packageName,
32723
+ currentVersion: options.currentVersion
32724
+ });
32725
+ if (options.json) {
32726
+ console.log(
32727
+ JSON.stringify({
32728
+ packageName: options.packageName,
32729
+ current: latest.current,
32730
+ latest: latest.latest,
32731
+ updateAvailable: latest.updateAvailable
32732
+ })
32733
+ );
32734
+ } else if (!latest.latest) {
32735
+ console.log(`Could not check npm for ${options.packageName}.`);
32736
+ } else if (latest.updateAvailable) {
32737
+ console.log(`${options.packageName} ${latest.current} -> ${latest.latest} is available.`);
32738
+ } else {
32739
+ console.log(`${options.packageName} is up to date (${latest.current}).`);
32740
+ }
32741
+ if (options.check) return latest.latest ? EXIT.SUCCESS : EXIT.RUNTIME;
32742
+ if (latest.latest && !isNewerVersion(latest.latest, options.currentVersion)) return EXIT.SUCCESS;
32743
+ if (!options.yes) {
32744
+ if (!process.stdin.isTTY) {
32745
+ console.error("Use --yes to run npm install from a non-interactive shell.");
32746
+ return EXIT.USAGE;
32747
+ }
32748
+ const confirmed = await askYes(`Run npm install -g ${options.packageName}@${tag}?`);
32749
+ if (!confirmed) return EXIT.SUCCESS;
32750
+ }
32751
+ const [command, args] = updateCommand(options.packageName, tag);
32752
+ return runProcess(command, args);
32753
+ };
32754
+ var loadDotenv = (options = {}) => {
32755
+ if (options.skipFsLoad) return { loaded: [] };
32756
+ const cwd = options.cwd ?? process.cwd();
32757
+ const candidates = [resolve(cwd, ".env"), resolve(cwd, ".env.local")];
32758
+ const loaded = [];
32759
+ const merged = {};
32760
+ for (const path of candidates) {
32761
+ if (!existsSync(path)) continue;
32762
+ const text2 = readFileSync(path, "utf8");
32763
+ Object.assign(merged, parse$1(text2));
32764
+ loaded.push(path);
32765
+ }
32766
+ for (const [key, value] of Object.entries(merged)) {
32767
+ if (process.env[key] === void 0) {
32768
+ process.env[key] = value;
32769
+ }
32770
+ }
32771
+ return { loaded };
32772
+ };
32401
32773
  var DEFAULT_HOST = "0.0.0.0";
32402
32774
  var DEFAULT_PORT = 8787;
32403
32775
  var DEFAULT_PATH = "/webhooks/gitlab";
@@ -32418,7 +32790,7 @@ var outputForJob = (reviewRoot, outputRoot, job) => {
32418
32790
  return resolve(reviewRoot, outputRoot, `${eventPart}-${mrPart}`, "code-sentinel.md");
32419
32791
  };
32420
32792
  var toReviewOptions = (job, options) => {
32421
- const output = outputForJob(options.reviewRoot, options.outputRoot ?? DEFAULT_OUTPUT_ROOT, job);
32793
+ const output2 = outputForJob(options.reviewRoot, options.outputRoot ?? DEFAULT_OUTPUT_ROOT, job);
32422
32794
  return {
32423
32795
  invocationRoot: options.reviewRoot,
32424
32796
  pr: job.mrUrl,
@@ -32428,7 +32800,7 @@ var toReviewOptions = (job, options) => {
32428
32800
  silent: true,
32429
32801
  noUi: true,
32430
32802
  reportFormat: options.reportFormat ?? "both",
32431
- output,
32803
+ output: output2,
32432
32804
  ...options.minSeverity ? { minSeverity: options.minSeverity } : {},
32433
32805
  ...options.minConfidence !== void 0 ? { minConfidence: options.minConfidence } : {}
32434
32806
  };
@@ -32861,7 +33233,6 @@ var runWizard = async (deps = {}) => {
32861
33233
  aiProvider = await p.select({
32862
33234
  message: "AI provider:",
32863
33235
  choices: [
32864
- { name: "FreeModel (cloud, gpt-5.5)", value: "freemodel" },
32865
33236
  { name: "Ollama (local)", value: "ollama" },
32866
33237
  { name: "Gemini", value: "gemini" },
32867
33238
  { name: "Groq", value: "groq" },
@@ -32869,7 +33240,7 @@ var runWizard = async (deps = {}) => {
32869
33240
  { name: "OpenCode Go", value: "opencode-go" },
32870
33241
  { name: "OpenAI-compatible custom URL", value: "openai-compatible" }
32871
33242
  ],
32872
- default: "freemodel"
33243
+ default: "ollama"
32873
33244
  });
32874
33245
  const defaults2 = providerDefaults[aiProvider];
32875
33246
  if (defaults2.needsBaseUrl) {
@@ -32952,7 +33323,7 @@ var runWizard = async (deps = {}) => {
32952
33323
  };
32953
33324
  var wizardAnswersToReviewOptions = (answers) => {
32954
33325
  const path = normalizeWizardPath(answers.path);
32955
- const output = normalizeWizardPath(answers.reportOutput);
33326
+ const output2 = normalizeWizardPath(answers.reportOutput);
32956
33327
  const base = {
32957
33328
  path,
32958
33329
  aiOff: !answers.aiOn,
@@ -32960,7 +33331,7 @@ var wizardAnswersToReviewOptions = (answers) => {
32960
33331
  ...answers.aiTimeoutSeconds !== void 0 ? { aiTimeoutMs: answers.aiTimeoutSeconds * 1e3 } : {},
32961
33332
  reportFormat: answers.reportFormat,
32962
33333
  scope: answers.scope,
32963
- ...output.length > 0 ? { output } : {},
33334
+ ...output2.length > 0 ? { output: output2 } : {},
32964
33335
  ...answers.reviewTarget === "gitlab-pr" && answers.pr ? {
32965
33336
  pr: normalizeWizardPath(answers.pr),
32966
33337
  ...answers.post === true ? { post: true } : {},
@@ -32972,7 +33343,7 @@ var wizardAnswersToReviewOptions = (answers) => {
32972
33343
  return answers.reportStyle === "compact" ? { ...base, compact: true } : { ...base, full: true };
32973
33344
  };
32974
33345
  var wizardAnswersToInitConfig = (answers) => {
32975
- const provider = answers.aiOn ? answers.aiProvider ?? "freemodel" : "none";
33346
+ const provider = answers.aiOn ? answers.aiProvider ?? "ollama" : "none";
32976
33347
  const ai = {
32977
33348
  provider,
32978
33349
  fallback: parseFallbackProviders(answers.aiFallback),
@@ -33070,13 +33441,6 @@ var providerDefaults = {
33070
33441
  needsApiKey: false,
33071
33442
  needsBaseUrl: true
33072
33443
  },
33073
- freemodel: {
33074
- model: "gpt-5.5",
33075
- baseUrl: "https://api.freemodel.dev",
33076
- apiKeyEnv: "FREEMODEL_API_KEY",
33077
- needsApiKey: true,
33078
- needsBaseUrl: true
33079
- },
33080
33444
  gemini: {
33081
33445
  model: "gemini-2.0-flash",
33082
33446
  baseUrl: "",
@@ -33093,7 +33457,7 @@ var providerDefaults = {
33093
33457
  },
33094
33458
  "viettel-netmind": {
33095
33459
  model: "zai-org/GLM-4.7-cc",
33096
- baseUrl: "https://netmind.viettel.vn/gateway/v1",
33460
+ baseUrl: "https://example.invalid/netmind/v1",
33097
33461
  apiKeyEnv: "LLM_API_KEY",
33098
33462
  needsApiKey: true,
33099
33463
  needsBaseUrl: true
@@ -33108,8 +33472,8 @@ var providerDefaults = {
33108
33472
  "openai-compatible": {
33109
33473
  model: "mistral-7b-instruct",
33110
33474
  baseUrl: "http://localhost:8080/v1",
33111
- apiKeyEnv: "",
33112
- needsApiKey: false,
33475
+ apiKeyEnv: "CUSTOM_AI_API_KEY",
33476
+ needsApiKey: true,
33113
33477
  needsBaseUrl: true
33114
33478
  }
33115
33479
  };
@@ -33172,6 +33536,17 @@ var buildProgram = () => {
33172
33536
  `Code Sentinel ${BUILD_METADATA.version} (${BUILD_METADATA.gitSha}, ${BUILD_METADATA.buildTimestamp}; config ${BUILD_METADATA.configSchemaRange})`
33173
33537
  );
33174
33538
  });
33539
+ program.command("update").description("Check for or install the latest published CLI version").option("--check", "only check whether an update is available").option("--yes", "skip the confirmation prompt before installing").option("--tag <tag>", "npm dist-tag or version to install", "latest").option("--json", "print stable JSON for automation").action(async (opts) => {
33540
+ process.exitCode = await runUpdate({
33541
+ packageName: pkg.name ?? "code-sentinel",
33542
+ currentVersion: VERSION,
33543
+ privatePackage: pkg.private === true,
33544
+ check: opts.check === true,
33545
+ yes: opts.yes === true,
33546
+ tag: opts.tag,
33547
+ json: opts.json === true
33548
+ });
33549
+ });
33175
33550
  const auth = program.command("auth").description("Authenticate this CLI with Code Sentinel");
33176
33551
  auth.command("login").description("Open the browser approval flow; use --no-browser to open the shown URL manually").option("--server <url>", "Code Sentinel dashboard base URL", getDefaultDashboardServerUrl()).option("--no-browser", "do not open the browser automatically").action(async (opts) => {
33177
33552
  process.exitCode = await runAuthLogin({