@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/bin.js CHANGED
@@ -6,7 +6,7 @@ import { randomBytes, createCipheriv, createDecipheriv, createHash, timingSafeEq
6
6
  import * as sp2 from 'path';
7
7
  import { dirname, resolve, join, isAbsolute, basename, relative, extname, sep, posix, normalize } from 'path';
8
8
  import { Command } from 'commander';
9
- import { execFile as execFile$1, execSync, spawn } from 'child_process';
9
+ import { execFile as execFile$1, spawn, execSync } from 'child_process';
10
10
  import { promisify } from 'util';
11
11
  import { readFile, mkdir, writeFile, rename, access, mkdtemp, stat, readdir, rm, unlink, chmod, lstat, realpath as realpath$1, open } from 'fs/promises';
12
12
  import { password, confirm, input, select } from '@inquirer/prompts';
@@ -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 } 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,
@@ -2555,7 +2577,7 @@ var SecretCommandError = class extends Error {
2555
2577
  code;
2556
2578
  };
2557
2579
  var nativeRunner = {
2558
- run: (command, args, input3) => new Promise((resolve40, reject) => {
2580
+ run: (command, args, input4) => new Promise((resolve40, reject) => {
2559
2581
  const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] });
2560
2582
  let stdout = "";
2561
2583
  let stderr = "";
@@ -2572,7 +2594,7 @@ var nativeRunner = {
2572
2594
  if (code2 === 0) resolve40(stdout);
2573
2595
  else reject(new SecretCommandError(command, code2, stderr.trim() || `${command} failed`));
2574
2596
  });
2575
- if (input3 !== void 0) child.stdin.end(input3);
2597
+ if (input4 !== void 0) child.stdin.end(input4);
2576
2598
  else child.stdin.end();
2577
2599
  })
2578
2600
  };
@@ -2652,7 +2674,7 @@ var WindowsCredentialManagerStore = class {
2652
2674
  this.commands = commands;
2653
2675
  }
2654
2676
  commands;
2655
- run(target, body, input3) {
2677
+ run(target, body, input4) {
2656
2678
  return this.commands.run(
2657
2679
  "powershell.exe",
2658
2680
  [
@@ -2661,11 +2683,11 @@ var WindowsCredentialManagerStore = class {
2661
2683
  "-EncodedCommand",
2662
2684
  encodedPowerShell(powershellPrelude(target) + body)
2663
2685
  ],
2664
- input3
2686
+ input4
2665
2687
  );
2666
2688
  }
2667
2689
  async read(service, account) {
2668
- const output = await this.run(
2690
+ const output2 = await this.run(
2669
2691
  powerShellTarget(service, account),
2670
2692
  `
2671
2693
  $credentialPtr = [IntPtr]::Zero
@@ -2681,7 +2703,7 @@ try {
2681
2703
  } finally { [CodeSentinelCredentialNative]::CredFree($credentialPtr) }
2682
2704
  `
2683
2705
  );
2684
- return output.trim() ? Buffer.from(output.trim(), "base64").toString("utf8") : null;
2706
+ return output2.trim() ? Buffer.from(output2.trim(), "base64").toString("utf8") : null;
2685
2707
  }
2686
2708
  async write(service, account, value) {
2687
2709
  await this.run(
@@ -2732,6 +2754,41 @@ var createPlatformCredentialStore = (platform = process.platform) => new SecretB
2732
2754
  var createPlatformAiCredentialStore = (platform = process.platform) => new SecretBackedAiCredentialStore(createPlatformSecretStore(platform));
2733
2755
  var createPlatformRetryKeyProvider = (platform = process.platform) => new SecretBackedRetryKeyProvider(createPlatformSecretStore(platform));
2734
2756
 
2757
+ // src/auth/session.ts
2758
+ var REFRESH_BEFORE_EXPIRY_MS = 3e4;
2759
+ var accessTokenNeedsRefresh = (credential, now = Date.now()) => {
2760
+ if (!credential.expiresAt) return false;
2761
+ const expiresAt = Date.parse(credential.expiresAt);
2762
+ return !Number.isFinite(expiresAt) || expiresAt <= now + REFRESH_BEFORE_EXPIRY_MS;
2763
+ };
2764
+ var getAuthenticatedCredential = async (options) => {
2765
+ const serverUrl = new URL(options.server).origin;
2766
+ const credential = await options.store.read(serverUrl);
2767
+ if (!credential) throw new Error("Not authenticated. Run `cs auth login --server <url>`.");
2768
+ const now = options.now ?? Date.now;
2769
+ if (!options.forceRefresh && !accessTokenNeedsRefresh(credential, now())) return credential;
2770
+ if (!credential.refreshToken) {
2771
+ throw new Error("Credential expired. Run `cs auth login --server <url>`.");
2772
+ }
2773
+ const refreshed = await (options.refresh ?? refreshDeviceCredential)(
2774
+ serverUrl,
2775
+ credential.refreshToken
2776
+ );
2777
+ if (refreshed.status === "invalid") {
2778
+ await options.store.remove(serverUrl);
2779
+ throw new Error("Credential expired. Run `cs auth login --server <url>`.");
2780
+ }
2781
+ const updated = {
2782
+ serverUrl,
2783
+ subject: refreshed.subject,
2784
+ accessToken: refreshed.accessToken,
2785
+ refreshToken: refreshed.refreshToken,
2786
+ expiresAt: new Date(now() + refreshed.expiresIn * 1e3).toISOString()
2787
+ };
2788
+ await options.store.write(updated);
2789
+ return updated;
2790
+ };
2791
+
2735
2792
  // src/exit-codes.ts
2736
2793
  var EXIT = {
2737
2794
  /** Success — no findings of severity 'error' or 'blocker'. */
@@ -2758,9 +2815,9 @@ var FileProtectedRetryStore = class {
2758
2815
  }
2759
2816
  keys;
2760
2817
  #directory;
2761
- async enqueue(input3) {
2818
+ async enqueue(input4) {
2762
2819
  const entry = {
2763
- ...input3,
2820
+ ...input4,
2764
2821
  schemaVersion: 1,
2765
2822
  expiresAt: new Date(Date.now() + TTL_MS).toISOString()
2766
2823
  };
@@ -2839,6 +2896,7 @@ var defaults = () => ({
2839
2896
  store: credentialStore(),
2840
2897
  start: startDeviceAuthorization,
2841
2898
  poll: pollDeviceAuthorization,
2899
+ refresh: refreshDeviceCredential,
2842
2900
  revoke: revokeDeviceCredential,
2843
2901
  openBrowser,
2844
2902
  sleep,
@@ -2887,6 +2945,7 @@ var runAuthLogin = async (options) => {
2887
2945
  serverUrl: new URL(options.server).origin,
2888
2946
  subject: poll.subject,
2889
2947
  accessToken: poll.accessToken,
2948
+ refreshToken: poll.refreshToken,
2890
2949
  expiresAt: new Date(deps.now() + poll.expiresIn * 1e3).toISOString()
2891
2950
  });
2892
2951
  write(`Authenticated as ${poll.subject}. Credential saved to the system keychain.`);
@@ -2900,28 +2959,30 @@ var runAuthLogin = async (options) => {
2900
2959
  writeError("Browser authorization expired. Run `cs auth login` again.");
2901
2960
  return EXIT.RUNTIME;
2902
2961
  };
2903
- var runAuthStatus = async (input3) => {
2904
- const store = input3.dependencies?.store ?? credentialStore();
2905
- const now = input3.dependencies?.now ?? Date.now;
2906
- const write = input3.write ?? console.log;
2907
- const server = new URL(input3.server).origin;
2908
- const credential = await store.read(server);
2909
- if (!credential) {
2910
- write("Not authenticated. Run `cs auth login --server <url>`.");
2911
- return EXIT.USAGE;
2912
- }
2913
- if (credential.expiresAt && Date.parse(credential.expiresAt) <= now()) {
2914
- write("Credential expired. Run `cs auth login --server <url>`.");
2962
+ var runAuthStatus = async (input4) => {
2963
+ const store = input4.dependencies?.store ?? credentialStore();
2964
+ const now = input4.dependencies?.now ?? Date.now;
2965
+ const write = input4.write ?? console.log;
2966
+ const server = new URL(input4.server).origin;
2967
+ try {
2968
+ const credential = await getAuthenticatedCredential({
2969
+ server,
2970
+ store,
2971
+ now,
2972
+ refresh: input4.dependencies?.refresh
2973
+ });
2974
+ write(`Authenticated as ${credential.subject} at ${server}.`);
2975
+ return EXIT.SUCCESS;
2976
+ } catch (error) {
2977
+ write(error instanceof Error ? error.message : "Unable to check authentication status.");
2915
2978
  return EXIT.USAGE;
2916
2979
  }
2917
- write(`Authenticated as ${credential.subject} at ${server}.`);
2918
- return EXIT.SUCCESS;
2919
2980
  };
2920
- var runAuthLogout = async (input3) => {
2921
- const store = input3.dependencies?.store ?? credentialStore();
2922
- const revoke = input3.dependencies?.revoke ?? revokeDeviceCredential;
2923
- const write = input3.write ?? console.log;
2924
- const server = new URL(input3.server).origin;
2981
+ var runAuthLogout = async (input4) => {
2982
+ const store = input4.dependencies?.store ?? credentialStore();
2983
+ const revoke = input4.dependencies?.revoke ?? revokeDeviceCredential;
2984
+ const write = input4.write ?? console.log;
2985
+ const server = new URL(input4.server).origin;
2925
2986
  const credential = await store.read(server);
2926
2987
  if (credential) {
2927
2988
  try {
@@ -2932,7 +2993,7 @@ var runAuthLogout = async (input3) => {
2932
2993
  if (credential) {
2933
2994
  try {
2934
2995
  await new FileProtectedRetryStore(
2935
- input3.path ?? process.cwd(),
2996
+ input4.path ?? process.cwd(),
2936
2997
  createPlatformRetryKeyProvider()
2937
2998
  ).removeIdentity(server, credential.subject);
2938
2999
  } catch {
@@ -3602,41 +3663,41 @@ var ZodType = class {
3602
3663
  get description() {
3603
3664
  return this._def.description;
3604
3665
  }
3605
- _getType(input3) {
3606
- return getParsedType(input3.data);
3666
+ _getType(input4) {
3667
+ return getParsedType(input4.data);
3607
3668
  }
3608
- _getOrReturnCtx(input3, ctx) {
3669
+ _getOrReturnCtx(input4, ctx) {
3609
3670
  return ctx || {
3610
- common: input3.parent.common,
3611
- data: input3.data,
3612
- parsedType: getParsedType(input3.data),
3671
+ common: input4.parent.common,
3672
+ data: input4.data,
3673
+ parsedType: getParsedType(input4.data),
3613
3674
  schemaErrorMap: this._def.errorMap,
3614
- path: input3.path,
3615
- parent: input3.parent
3675
+ path: input4.path,
3676
+ parent: input4.parent
3616
3677
  };
3617
3678
  }
3618
- _processInputParams(input3) {
3679
+ _processInputParams(input4) {
3619
3680
  return {
3620
3681
  status: new ParseStatus(),
3621
3682
  ctx: {
3622
- common: input3.parent.common,
3623
- data: input3.data,
3624
- parsedType: getParsedType(input3.data),
3683
+ common: input4.parent.common,
3684
+ data: input4.data,
3685
+ parsedType: getParsedType(input4.data),
3625
3686
  schemaErrorMap: this._def.errorMap,
3626
- path: input3.path,
3627
- parent: input3.parent
3687
+ path: input4.path,
3688
+ parent: input4.parent
3628
3689
  }
3629
3690
  };
3630
3691
  }
3631
- _parseSync(input3) {
3632
- const result = this._parse(input3);
3692
+ _parseSync(input4) {
3693
+ const result = this._parse(input4);
3633
3694
  if (isAsync(result)) {
3634
3695
  throw new Error("Synchronous parse encountered promise.");
3635
3696
  }
3636
3697
  return result;
3637
3698
  }
3638
- _parseAsync(input3) {
3639
- const result = this._parse(input3);
3699
+ _parseAsync(input4) {
3700
+ const result = this._parse(input4);
3640
3701
  return Promise.resolve(result);
3641
3702
  }
3642
3703
  parse(data, params) {
@@ -3962,13 +4023,13 @@ function isValidCidr(ip, version2) {
3962
4023
  return false;
3963
4024
  }
3964
4025
  var ZodString = class _ZodString extends ZodType {
3965
- _parse(input3) {
4026
+ _parse(input4) {
3966
4027
  if (this._def.coerce) {
3967
- input3.data = String(input3.data);
4028
+ input4.data = String(input4.data);
3968
4029
  }
3969
- const parsedType = this._getType(input3);
4030
+ const parsedType = this._getType(input4);
3970
4031
  if (parsedType !== ZodParsedType.string) {
3971
- const ctx2 = this._getOrReturnCtx(input3);
4032
+ const ctx2 = this._getOrReturnCtx(input4);
3972
4033
  addIssueToContext(ctx2, {
3973
4034
  code: ZodIssueCode.invalid_type,
3974
4035
  expected: ZodParsedType.string,
@@ -3980,8 +4041,8 @@ var ZodString = class _ZodString extends ZodType {
3980
4041
  let ctx = void 0;
3981
4042
  for (const check of this._def.checks) {
3982
4043
  if (check.kind === "min") {
3983
- if (input3.data.length < check.value) {
3984
- ctx = this._getOrReturnCtx(input3, ctx);
4044
+ if (input4.data.length < check.value) {
4045
+ ctx = this._getOrReturnCtx(input4, ctx);
3985
4046
  addIssueToContext(ctx, {
3986
4047
  code: ZodIssueCode.too_small,
3987
4048
  minimum: check.value,
@@ -3993,8 +4054,8 @@ var ZodString = class _ZodString extends ZodType {
3993
4054
  status.dirty();
3994
4055
  }
3995
4056
  } else if (check.kind === "max") {
3996
- if (input3.data.length > check.value) {
3997
- ctx = this._getOrReturnCtx(input3, ctx);
4057
+ if (input4.data.length > check.value) {
4058
+ ctx = this._getOrReturnCtx(input4, ctx);
3998
4059
  addIssueToContext(ctx, {
3999
4060
  code: ZodIssueCode.too_big,
4000
4061
  maximum: check.value,
@@ -4006,10 +4067,10 @@ var ZodString = class _ZodString extends ZodType {
4006
4067
  status.dirty();
4007
4068
  }
4008
4069
  } else if (check.kind === "length") {
4009
- const tooBig = input3.data.length > check.value;
4010
- const tooSmall = input3.data.length < check.value;
4070
+ const tooBig = input4.data.length > check.value;
4071
+ const tooSmall = input4.data.length < check.value;
4011
4072
  if (tooBig || tooSmall) {
4012
- ctx = this._getOrReturnCtx(input3, ctx);
4073
+ ctx = this._getOrReturnCtx(input4, ctx);
4013
4074
  if (tooBig) {
4014
4075
  addIssueToContext(ctx, {
4015
4076
  code: ZodIssueCode.too_big,
@@ -4032,8 +4093,8 @@ var ZodString = class _ZodString extends ZodType {
4032
4093
  status.dirty();
4033
4094
  }
4034
4095
  } else if (check.kind === "email") {
4035
- if (!emailRegex.test(input3.data)) {
4036
- ctx = this._getOrReturnCtx(input3, ctx);
4096
+ if (!emailRegex.test(input4.data)) {
4097
+ ctx = this._getOrReturnCtx(input4, ctx);
4037
4098
  addIssueToContext(ctx, {
4038
4099
  validation: "email",
4039
4100
  code: ZodIssueCode.invalid_string,
@@ -4045,8 +4106,8 @@ var ZodString = class _ZodString extends ZodType {
4045
4106
  if (!emojiRegex) {
4046
4107
  emojiRegex = new RegExp(_emojiRegex, "u");
4047
4108
  }
4048
- if (!emojiRegex.test(input3.data)) {
4049
- ctx = this._getOrReturnCtx(input3, ctx);
4109
+ if (!emojiRegex.test(input4.data)) {
4110
+ ctx = this._getOrReturnCtx(input4, ctx);
4050
4111
  addIssueToContext(ctx, {
4051
4112
  validation: "emoji",
4052
4113
  code: ZodIssueCode.invalid_string,
@@ -4055,8 +4116,8 @@ var ZodString = class _ZodString extends ZodType {
4055
4116
  status.dirty();
4056
4117
  }
4057
4118
  } else if (check.kind === "uuid") {
4058
- if (!uuidRegex.test(input3.data)) {
4059
- ctx = this._getOrReturnCtx(input3, ctx);
4119
+ if (!uuidRegex.test(input4.data)) {
4120
+ ctx = this._getOrReturnCtx(input4, ctx);
4060
4121
  addIssueToContext(ctx, {
4061
4122
  validation: "uuid",
4062
4123
  code: ZodIssueCode.invalid_string,
@@ -4065,8 +4126,8 @@ var ZodString = class _ZodString extends ZodType {
4065
4126
  status.dirty();
4066
4127
  }
4067
4128
  } else if (check.kind === "nanoid") {
4068
- if (!nanoidRegex.test(input3.data)) {
4069
- ctx = this._getOrReturnCtx(input3, ctx);
4129
+ if (!nanoidRegex.test(input4.data)) {
4130
+ ctx = this._getOrReturnCtx(input4, ctx);
4070
4131
  addIssueToContext(ctx, {
4071
4132
  validation: "nanoid",
4072
4133
  code: ZodIssueCode.invalid_string,
@@ -4075,8 +4136,8 @@ var ZodString = class _ZodString extends ZodType {
4075
4136
  status.dirty();
4076
4137
  }
4077
4138
  } else if (check.kind === "cuid") {
4078
- if (!cuidRegex.test(input3.data)) {
4079
- ctx = this._getOrReturnCtx(input3, ctx);
4139
+ if (!cuidRegex.test(input4.data)) {
4140
+ ctx = this._getOrReturnCtx(input4, ctx);
4080
4141
  addIssueToContext(ctx, {
4081
4142
  validation: "cuid",
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 === "cuid2") {
4088
- if (!cuid2Regex.test(input3.data)) {
4089
- ctx = this._getOrReturnCtx(input3, ctx);
4149
+ if (!cuid2Regex.test(input4.data)) {
4150
+ ctx = this._getOrReturnCtx(input4, ctx);
4090
4151
  addIssueToContext(ctx, {
4091
4152
  validation: "cuid2",
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 === "ulid") {
4098
- if (!ulidRegex.test(input3.data)) {
4099
- ctx = this._getOrReturnCtx(input3, ctx);
4159
+ if (!ulidRegex.test(input4.data)) {
4160
+ ctx = this._getOrReturnCtx(input4, ctx);
4100
4161
  addIssueToContext(ctx, {
4101
4162
  validation: "ulid",
4102
4163
  code: ZodIssueCode.invalid_string,
@@ -4106,9 +4167,9 @@ var ZodString = class _ZodString extends ZodType {
4106
4167
  }
4107
4168
  } else if (check.kind === "url") {
4108
4169
  try {
4109
- new URL(input3.data);
4170
+ new URL(input4.data);
4110
4171
  } catch {
4111
- ctx = this._getOrReturnCtx(input3, ctx);
4172
+ ctx = this._getOrReturnCtx(input4, ctx);
4112
4173
  addIssueToContext(ctx, {
4113
4174
  validation: "url",
4114
4175
  code: ZodIssueCode.invalid_string,
@@ -4118,9 +4179,9 @@ var ZodString = class _ZodString extends ZodType {
4118
4179
  }
4119
4180
  } else if (check.kind === "regex") {
4120
4181
  check.regex.lastIndex = 0;
4121
- const testResult = check.regex.test(input3.data);
4182
+ const testResult = check.regex.test(input4.data);
4122
4183
  if (!testResult) {
4123
- ctx = this._getOrReturnCtx(input3, ctx);
4184
+ ctx = this._getOrReturnCtx(input4, ctx);
4124
4185
  addIssueToContext(ctx, {
4125
4186
  validation: "regex",
4126
4187
  code: ZodIssueCode.invalid_string,
@@ -4129,10 +4190,10 @@ var ZodString = class _ZodString extends ZodType {
4129
4190
  status.dirty();
4130
4191
  }
4131
4192
  } else if (check.kind === "trim") {
4132
- input3.data = input3.data.trim();
4193
+ input4.data = input4.data.trim();
4133
4194
  } else if (check.kind === "includes") {
4134
- if (!input3.data.includes(check.value, check.position)) {
4135
- ctx = this._getOrReturnCtx(input3, ctx);
4195
+ if (!input4.data.includes(check.value, check.position)) {
4196
+ ctx = this._getOrReturnCtx(input4, ctx);
4136
4197
  addIssueToContext(ctx, {
4137
4198
  code: ZodIssueCode.invalid_string,
4138
4199
  validation: { includes: check.value, position: check.position },
@@ -4141,12 +4202,12 @@ var ZodString = class _ZodString extends ZodType {
4141
4202
  status.dirty();
4142
4203
  }
4143
4204
  } else if (check.kind === "toLowerCase") {
4144
- input3.data = input3.data.toLowerCase();
4205
+ input4.data = input4.data.toLowerCase();
4145
4206
  } else if (check.kind === "toUpperCase") {
4146
- input3.data = input3.data.toUpperCase();
4207
+ input4.data = input4.data.toUpperCase();
4147
4208
  } else if (check.kind === "startsWith") {
4148
- if (!input3.data.startsWith(check.value)) {
4149
- ctx = this._getOrReturnCtx(input3, ctx);
4209
+ if (!input4.data.startsWith(check.value)) {
4210
+ ctx = this._getOrReturnCtx(input4, ctx);
4150
4211
  addIssueToContext(ctx, {
4151
4212
  code: ZodIssueCode.invalid_string,
4152
4213
  validation: { startsWith: check.value },
@@ -4155,8 +4216,8 @@ var ZodString = class _ZodString extends ZodType {
4155
4216
  status.dirty();
4156
4217
  }
4157
4218
  } else if (check.kind === "endsWith") {
4158
- if (!input3.data.endsWith(check.value)) {
4159
- ctx = this._getOrReturnCtx(input3, ctx);
4219
+ if (!input4.data.endsWith(check.value)) {
4220
+ ctx = this._getOrReturnCtx(input4, ctx);
4160
4221
  addIssueToContext(ctx, {
4161
4222
  code: ZodIssueCode.invalid_string,
4162
4223
  validation: { endsWith: check.value },
@@ -4166,8 +4227,8 @@ var ZodString = class _ZodString extends ZodType {
4166
4227
  }
4167
4228
  } else if (check.kind === "datetime") {
4168
4229
  const regex = datetimeRegex(check);
4169
- if (!regex.test(input3.data)) {
4170
- ctx = this._getOrReturnCtx(input3, ctx);
4230
+ if (!regex.test(input4.data)) {
4231
+ ctx = this._getOrReturnCtx(input4, ctx);
4171
4232
  addIssueToContext(ctx, {
4172
4233
  code: ZodIssueCode.invalid_string,
4173
4234
  validation: "datetime",
@@ -4177,8 +4238,8 @@ var ZodString = class _ZodString extends ZodType {
4177
4238
  }
4178
4239
  } else if (check.kind === "date") {
4179
4240
  const regex = dateRegex;
4180
- if (!regex.test(input3.data)) {
4181
- ctx = this._getOrReturnCtx(input3, ctx);
4241
+ if (!regex.test(input4.data)) {
4242
+ ctx = this._getOrReturnCtx(input4, ctx);
4182
4243
  addIssueToContext(ctx, {
4183
4244
  code: ZodIssueCode.invalid_string,
4184
4245
  validation: "date",
@@ -4188,8 +4249,8 @@ var ZodString = class _ZodString extends ZodType {
4188
4249
  }
4189
4250
  } else if (check.kind === "time") {
4190
4251
  const regex = timeRegex(check);
4191
- if (!regex.test(input3.data)) {
4192
- ctx = this._getOrReturnCtx(input3, ctx);
4252
+ if (!regex.test(input4.data)) {
4253
+ ctx = this._getOrReturnCtx(input4, ctx);
4193
4254
  addIssueToContext(ctx, {
4194
4255
  code: ZodIssueCode.invalid_string,
4195
4256
  validation: "time",
@@ -4198,8 +4259,8 @@ var ZodString = class _ZodString extends ZodType {
4198
4259
  status.dirty();
4199
4260
  }
4200
4261
  } else if (check.kind === "duration") {
4201
- if (!durationRegex.test(input3.data)) {
4202
- ctx = this._getOrReturnCtx(input3, ctx);
4262
+ if (!durationRegex.test(input4.data)) {
4263
+ ctx = this._getOrReturnCtx(input4, ctx);
4203
4264
  addIssueToContext(ctx, {
4204
4265
  validation: "duration",
4205
4266
  code: ZodIssueCode.invalid_string,
@@ -4208,8 +4269,8 @@ var ZodString = class _ZodString extends ZodType {
4208
4269
  status.dirty();
4209
4270
  }
4210
4271
  } else if (check.kind === "ip") {
4211
- if (!isValidIP(input3.data, check.version)) {
4212
- ctx = this._getOrReturnCtx(input3, ctx);
4272
+ if (!isValidIP(input4.data, check.version)) {
4273
+ ctx = this._getOrReturnCtx(input4, ctx);
4213
4274
  addIssueToContext(ctx, {
4214
4275
  validation: "ip",
4215
4276
  code: ZodIssueCode.invalid_string,
@@ -4218,8 +4279,8 @@ var ZodString = class _ZodString extends ZodType {
4218
4279
  status.dirty();
4219
4280
  }
4220
4281
  } else if (check.kind === "jwt") {
4221
- if (!isValidJWT(input3.data, check.alg)) {
4222
- ctx = this._getOrReturnCtx(input3, ctx);
4282
+ if (!isValidJWT(input4.data, check.alg)) {
4283
+ ctx = this._getOrReturnCtx(input4, ctx);
4223
4284
  addIssueToContext(ctx, {
4224
4285
  validation: "jwt",
4225
4286
  code: ZodIssueCode.invalid_string,
@@ -4228,8 +4289,8 @@ var ZodString = class _ZodString extends ZodType {
4228
4289
  status.dirty();
4229
4290
  }
4230
4291
  } else if (check.kind === "cidr") {
4231
- if (!isValidCidr(input3.data, check.version)) {
4232
- ctx = this._getOrReturnCtx(input3, ctx);
4292
+ if (!isValidCidr(input4.data, check.version)) {
4293
+ ctx = this._getOrReturnCtx(input4, ctx);
4233
4294
  addIssueToContext(ctx, {
4234
4295
  validation: "cidr",
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 === "base64") {
4241
- if (!base64Regex.test(input3.data)) {
4242
- ctx = this._getOrReturnCtx(input3, ctx);
4302
+ if (!base64Regex.test(input4.data)) {
4303
+ ctx = this._getOrReturnCtx(input4, ctx);
4243
4304
  addIssueToContext(ctx, {
4244
4305
  validation: "base64",
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 === "base64url") {
4251
- if (!base64urlRegex.test(input3.data)) {
4252
- ctx = this._getOrReturnCtx(input3, ctx);
4312
+ if (!base64urlRegex.test(input4.data)) {
4313
+ ctx = this._getOrReturnCtx(input4, ctx);
4253
4314
  addIssueToContext(ctx, {
4254
4315
  validation: "base64url",
4255
4316
  code: ZodIssueCode.invalid_string,
@@ -4261,7 +4322,7 @@ var ZodString = class _ZodString extends ZodType {
4261
4322
  util.assertNever(check);
4262
4323
  }
4263
4324
  }
4264
- return { status: status.value, value: input3.data };
4325
+ return { status: status.value, value: input4.data };
4265
4326
  }
4266
4327
  _regex(regex, validation, message) {
4267
4328
  return this.refinement((data) => regex.test(data), {
@@ -4522,13 +4583,13 @@ var ZodNumber = class _ZodNumber extends ZodType {
4522
4583
  this.max = this.lte;
4523
4584
  this.step = this.multipleOf;
4524
4585
  }
4525
- _parse(input3) {
4586
+ _parse(input4) {
4526
4587
  if (this._def.coerce) {
4527
- input3.data = Number(input3.data);
4588
+ input4.data = Number(input4.data);
4528
4589
  }
4529
- const parsedType = this._getType(input3);
4590
+ const parsedType = this._getType(input4);
4530
4591
  if (parsedType !== ZodParsedType.number) {
4531
- const ctx2 = this._getOrReturnCtx(input3);
4592
+ const ctx2 = this._getOrReturnCtx(input4);
4532
4593
  addIssueToContext(ctx2, {
4533
4594
  code: ZodIssueCode.invalid_type,
4534
4595
  expected: ZodParsedType.number,
@@ -4540,8 +4601,8 @@ var ZodNumber = class _ZodNumber extends ZodType {
4540
4601
  const status = new ParseStatus();
4541
4602
  for (const check of this._def.checks) {
4542
4603
  if (check.kind === "int") {
4543
- if (!util.isInteger(input3.data)) {
4544
- ctx = this._getOrReturnCtx(input3, ctx);
4604
+ if (!util.isInteger(input4.data)) {
4605
+ ctx = this._getOrReturnCtx(input4, ctx);
4545
4606
  addIssueToContext(ctx, {
4546
4607
  code: ZodIssueCode.invalid_type,
4547
4608
  expected: "integer",
@@ -4551,9 +4612,9 @@ var ZodNumber = class _ZodNumber extends ZodType {
4551
4612
  status.dirty();
4552
4613
  }
4553
4614
  } else if (check.kind === "min") {
4554
- const tooSmall = check.inclusive ? input3.data < check.value : input3.data <= check.value;
4615
+ const tooSmall = check.inclusive ? input4.data < check.value : input4.data <= check.value;
4555
4616
  if (tooSmall) {
4556
- ctx = this._getOrReturnCtx(input3, ctx);
4617
+ ctx = this._getOrReturnCtx(input4, ctx);
4557
4618
  addIssueToContext(ctx, {
4558
4619
  code: ZodIssueCode.too_small,
4559
4620
  minimum: check.value,
@@ -4565,9 +4626,9 @@ var ZodNumber = class _ZodNumber extends ZodType {
4565
4626
  status.dirty();
4566
4627
  }
4567
4628
  } else if (check.kind === "max") {
4568
- const tooBig = check.inclusive ? input3.data > check.value : input3.data >= check.value;
4629
+ const tooBig = check.inclusive ? input4.data > check.value : input4.data >= check.value;
4569
4630
  if (tooBig) {
4570
- ctx = this._getOrReturnCtx(input3, ctx);
4631
+ ctx = this._getOrReturnCtx(input4, ctx);
4571
4632
  addIssueToContext(ctx, {
4572
4633
  code: ZodIssueCode.too_big,
4573
4634
  maximum: check.value,
@@ -4579,8 +4640,8 @@ var ZodNumber = class _ZodNumber extends ZodType {
4579
4640
  status.dirty();
4580
4641
  }
4581
4642
  } else if (check.kind === "multipleOf") {
4582
- if (floatSafeRemainder(input3.data, check.value) !== 0) {
4583
- ctx = this._getOrReturnCtx(input3, ctx);
4643
+ if (floatSafeRemainder(input4.data, check.value) !== 0) {
4644
+ ctx = this._getOrReturnCtx(input4, ctx);
4584
4645
  addIssueToContext(ctx, {
4585
4646
  code: ZodIssueCode.not_multiple_of,
4586
4647
  multipleOf: check.value,
@@ -4589,8 +4650,8 @@ var ZodNumber = class _ZodNumber extends ZodType {
4589
4650
  status.dirty();
4590
4651
  }
4591
4652
  } else if (check.kind === "finite") {
4592
- if (!Number.isFinite(input3.data)) {
4593
- ctx = this._getOrReturnCtx(input3, ctx);
4653
+ if (!Number.isFinite(input4.data)) {
4654
+ ctx = this._getOrReturnCtx(input4, ctx);
4594
4655
  addIssueToContext(ctx, {
4595
4656
  code: ZodIssueCode.not_finite,
4596
4657
  message: check.message
@@ -4601,7 +4662,7 @@ var ZodNumber = class _ZodNumber extends ZodType {
4601
4662
  util.assertNever(check);
4602
4663
  }
4603
4664
  }
4604
- return { status: status.value, value: input3.data };
4665
+ return { status: status.value, value: input4.data };
4605
4666
  }
4606
4667
  gte(value, message) {
4607
4668
  return this.setLimit("min", value, true, errorUtil.toString(message));
@@ -4753,25 +4814,25 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
4753
4814
  this.min = this.gte;
4754
4815
  this.max = this.lte;
4755
4816
  }
4756
- _parse(input3) {
4817
+ _parse(input4) {
4757
4818
  if (this._def.coerce) {
4758
4819
  try {
4759
- input3.data = BigInt(input3.data);
4820
+ input4.data = BigInt(input4.data);
4760
4821
  } catch {
4761
- return this._getInvalidInput(input3);
4822
+ return this._getInvalidInput(input4);
4762
4823
  }
4763
4824
  }
4764
- const parsedType = this._getType(input3);
4825
+ const parsedType = this._getType(input4);
4765
4826
  if (parsedType !== ZodParsedType.bigint) {
4766
- return this._getInvalidInput(input3);
4827
+ return this._getInvalidInput(input4);
4767
4828
  }
4768
4829
  let ctx = void 0;
4769
4830
  const status = new ParseStatus();
4770
4831
  for (const check of this._def.checks) {
4771
4832
  if (check.kind === "min") {
4772
- const tooSmall = check.inclusive ? input3.data < check.value : input3.data <= check.value;
4833
+ const tooSmall = check.inclusive ? input4.data < check.value : input4.data <= check.value;
4773
4834
  if (tooSmall) {
4774
- ctx = this._getOrReturnCtx(input3, ctx);
4835
+ ctx = this._getOrReturnCtx(input4, ctx);
4775
4836
  addIssueToContext(ctx, {
4776
4837
  code: ZodIssueCode.too_small,
4777
4838
  type: "bigint",
@@ -4782,9 +4843,9 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
4782
4843
  status.dirty();
4783
4844
  }
4784
4845
  } else if (check.kind === "max") {
4785
- const tooBig = check.inclusive ? input3.data > check.value : input3.data >= check.value;
4846
+ const tooBig = check.inclusive ? input4.data > check.value : input4.data >= check.value;
4786
4847
  if (tooBig) {
4787
- ctx = this._getOrReturnCtx(input3, ctx);
4848
+ ctx = this._getOrReturnCtx(input4, ctx);
4788
4849
  addIssueToContext(ctx, {
4789
4850
  code: ZodIssueCode.too_big,
4790
4851
  type: "bigint",
@@ -4795,8 +4856,8 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
4795
4856
  status.dirty();
4796
4857
  }
4797
4858
  } else if (check.kind === "multipleOf") {
4798
- if (input3.data % check.value !== BigInt(0)) {
4799
- ctx = this._getOrReturnCtx(input3, ctx);
4859
+ if (input4.data % check.value !== BigInt(0)) {
4860
+ ctx = this._getOrReturnCtx(input4, ctx);
4800
4861
  addIssueToContext(ctx, {
4801
4862
  code: ZodIssueCode.not_multiple_of,
4802
4863
  multipleOf: check.value,
@@ -4808,10 +4869,10 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
4808
4869
  util.assertNever(check);
4809
4870
  }
4810
4871
  }
4811
- return { status: status.value, value: input3.data };
4872
+ return { status: status.value, value: input4.data };
4812
4873
  }
4813
- _getInvalidInput(input3) {
4814
- const ctx = this._getOrReturnCtx(input3);
4874
+ _getInvalidInput(input4) {
4875
+ const ctx = this._getOrReturnCtx(input4);
4815
4876
  addIssueToContext(ctx, {
4816
4877
  code: ZodIssueCode.invalid_type,
4817
4878
  expected: ZodParsedType.bigint,
@@ -4920,13 +4981,13 @@ ZodBigInt.create = (params) => {
4920
4981
  });
4921
4982
  };
4922
4983
  var ZodBoolean = class extends ZodType {
4923
- _parse(input3) {
4984
+ _parse(input4) {
4924
4985
  if (this._def.coerce) {
4925
- input3.data = Boolean(input3.data);
4986
+ input4.data = Boolean(input4.data);
4926
4987
  }
4927
- const parsedType = this._getType(input3);
4988
+ const parsedType = this._getType(input4);
4928
4989
  if (parsedType !== ZodParsedType.boolean) {
4929
- const ctx = this._getOrReturnCtx(input3);
4990
+ const ctx = this._getOrReturnCtx(input4);
4930
4991
  addIssueToContext(ctx, {
4931
4992
  code: ZodIssueCode.invalid_type,
4932
4993
  expected: ZodParsedType.boolean,
@@ -4934,7 +4995,7 @@ var ZodBoolean = class extends ZodType {
4934
4995
  });
4935
4996
  return INVALID;
4936
4997
  }
4937
- return OK(input3.data);
4998
+ return OK(input4.data);
4938
4999
  }
4939
5000
  };
4940
5001
  ZodBoolean.create = (params) => {
@@ -4945,13 +5006,13 @@ ZodBoolean.create = (params) => {
4945
5006
  });
4946
5007
  };
4947
5008
  var ZodDate = class _ZodDate extends ZodType {
4948
- _parse(input3) {
5009
+ _parse(input4) {
4949
5010
  if (this._def.coerce) {
4950
- input3.data = new Date(input3.data);
5011
+ input4.data = new Date(input4.data);
4951
5012
  }
4952
- const parsedType = this._getType(input3);
5013
+ const parsedType = this._getType(input4);
4953
5014
  if (parsedType !== ZodParsedType.date) {
4954
- const ctx2 = this._getOrReturnCtx(input3);
5015
+ const ctx2 = this._getOrReturnCtx(input4);
4955
5016
  addIssueToContext(ctx2, {
4956
5017
  code: ZodIssueCode.invalid_type,
4957
5018
  expected: ZodParsedType.date,
@@ -4959,8 +5020,8 @@ var ZodDate = class _ZodDate extends ZodType {
4959
5020
  });
4960
5021
  return INVALID;
4961
5022
  }
4962
- if (Number.isNaN(input3.data.getTime())) {
4963
- const ctx2 = this._getOrReturnCtx(input3);
5023
+ if (Number.isNaN(input4.data.getTime())) {
5024
+ const ctx2 = this._getOrReturnCtx(input4);
4964
5025
  addIssueToContext(ctx2, {
4965
5026
  code: ZodIssueCode.invalid_date
4966
5027
  });
@@ -4970,8 +5031,8 @@ var ZodDate = class _ZodDate extends ZodType {
4970
5031
  let ctx = void 0;
4971
5032
  for (const check of this._def.checks) {
4972
5033
  if (check.kind === "min") {
4973
- if (input3.data.getTime() < check.value) {
4974
- ctx = this._getOrReturnCtx(input3, ctx);
5034
+ if (input4.data.getTime() < check.value) {
5035
+ ctx = this._getOrReturnCtx(input4, ctx);
4975
5036
  addIssueToContext(ctx, {
4976
5037
  code: ZodIssueCode.too_small,
4977
5038
  message: check.message,
@@ -4983,8 +5044,8 @@ var ZodDate = class _ZodDate extends ZodType {
4983
5044
  status.dirty();
4984
5045
  }
4985
5046
  } else if (check.kind === "max") {
4986
- if (input3.data.getTime() > check.value) {
4987
- ctx = this._getOrReturnCtx(input3, ctx);
5047
+ if (input4.data.getTime() > check.value) {
5048
+ ctx = this._getOrReturnCtx(input4, ctx);
4988
5049
  addIssueToContext(ctx, {
4989
5050
  code: ZodIssueCode.too_big,
4990
5051
  message: check.message,
@@ -5001,7 +5062,7 @@ var ZodDate = class _ZodDate extends ZodType {
5001
5062
  }
5002
5063
  return {
5003
5064
  status: status.value,
5004
- value: new Date(input3.data.getTime())
5065
+ value: new Date(input4.data.getTime())
5005
5066
  };
5006
5067
  }
5007
5068
  _addCheck(check) {
@@ -5054,10 +5115,10 @@ ZodDate.create = (params) => {
5054
5115
  });
5055
5116
  };
5056
5117
  var ZodSymbol = class extends ZodType {
5057
- _parse(input3) {
5058
- const parsedType = this._getType(input3);
5118
+ _parse(input4) {
5119
+ const parsedType = this._getType(input4);
5059
5120
  if (parsedType !== ZodParsedType.symbol) {
5060
- const ctx = this._getOrReturnCtx(input3);
5121
+ const ctx = this._getOrReturnCtx(input4);
5061
5122
  addIssueToContext(ctx, {
5062
5123
  code: ZodIssueCode.invalid_type,
5063
5124
  expected: ZodParsedType.symbol,
@@ -5065,7 +5126,7 @@ var ZodSymbol = class extends ZodType {
5065
5126
  });
5066
5127
  return INVALID;
5067
5128
  }
5068
- return OK(input3.data);
5129
+ return OK(input4.data);
5069
5130
  }
5070
5131
  };
5071
5132
  ZodSymbol.create = (params) => {
@@ -5075,10 +5136,10 @@ ZodSymbol.create = (params) => {
5075
5136
  });
5076
5137
  };
5077
5138
  var ZodUndefined = class extends ZodType {
5078
- _parse(input3) {
5079
- const parsedType = this._getType(input3);
5139
+ _parse(input4) {
5140
+ const parsedType = this._getType(input4);
5080
5141
  if (parsedType !== ZodParsedType.undefined) {
5081
- const ctx = this._getOrReturnCtx(input3);
5142
+ const ctx = this._getOrReturnCtx(input4);
5082
5143
  addIssueToContext(ctx, {
5083
5144
  code: ZodIssueCode.invalid_type,
5084
5145
  expected: ZodParsedType.undefined,
@@ -5086,7 +5147,7 @@ var ZodUndefined = class extends ZodType {
5086
5147
  });
5087
5148
  return INVALID;
5088
5149
  }
5089
- return OK(input3.data);
5150
+ return OK(input4.data);
5090
5151
  }
5091
5152
  };
5092
5153
  ZodUndefined.create = (params) => {
@@ -5096,10 +5157,10 @@ ZodUndefined.create = (params) => {
5096
5157
  });
5097
5158
  };
5098
5159
  var ZodNull = class extends ZodType {
5099
- _parse(input3) {
5100
- const parsedType = this._getType(input3);
5160
+ _parse(input4) {
5161
+ const parsedType = this._getType(input4);
5101
5162
  if (parsedType !== ZodParsedType.null) {
5102
- const ctx = this._getOrReturnCtx(input3);
5163
+ const ctx = this._getOrReturnCtx(input4);
5103
5164
  addIssueToContext(ctx, {
5104
5165
  code: ZodIssueCode.invalid_type,
5105
5166
  expected: ZodParsedType.null,
@@ -5107,7 +5168,7 @@ var ZodNull = class extends ZodType {
5107
5168
  });
5108
5169
  return INVALID;
5109
5170
  }
5110
- return OK(input3.data);
5171
+ return OK(input4.data);
5111
5172
  }
5112
5173
  };
5113
5174
  ZodNull.create = (params) => {
@@ -5121,8 +5182,8 @@ var ZodAny = class extends ZodType {
5121
5182
  super(...arguments);
5122
5183
  this._any = true;
5123
5184
  }
5124
- _parse(input3) {
5125
- return OK(input3.data);
5185
+ _parse(input4) {
5186
+ return OK(input4.data);
5126
5187
  }
5127
5188
  };
5128
5189
  ZodAny.create = (params) => {
@@ -5136,8 +5197,8 @@ var ZodUnknown = class extends ZodType {
5136
5197
  super(...arguments);
5137
5198
  this._unknown = true;
5138
5199
  }
5139
- _parse(input3) {
5140
- return OK(input3.data);
5200
+ _parse(input4) {
5201
+ return OK(input4.data);
5141
5202
  }
5142
5203
  };
5143
5204
  ZodUnknown.create = (params) => {
@@ -5147,8 +5208,8 @@ ZodUnknown.create = (params) => {
5147
5208
  });
5148
5209
  };
5149
5210
  var ZodNever = class extends ZodType {
5150
- _parse(input3) {
5151
- const ctx = this._getOrReturnCtx(input3);
5211
+ _parse(input4) {
5212
+ const ctx = this._getOrReturnCtx(input4);
5152
5213
  addIssueToContext(ctx, {
5153
5214
  code: ZodIssueCode.invalid_type,
5154
5215
  expected: ZodParsedType.never,
@@ -5164,10 +5225,10 @@ ZodNever.create = (params) => {
5164
5225
  });
5165
5226
  };
5166
5227
  var ZodVoid = class extends ZodType {
5167
- _parse(input3) {
5168
- const parsedType = this._getType(input3);
5228
+ _parse(input4) {
5229
+ const parsedType = this._getType(input4);
5169
5230
  if (parsedType !== ZodParsedType.undefined) {
5170
- const ctx = this._getOrReturnCtx(input3);
5231
+ const ctx = this._getOrReturnCtx(input4);
5171
5232
  addIssueToContext(ctx, {
5172
5233
  code: ZodIssueCode.invalid_type,
5173
5234
  expected: ZodParsedType.void,
@@ -5175,7 +5236,7 @@ var ZodVoid = class extends ZodType {
5175
5236
  });
5176
5237
  return INVALID;
5177
5238
  }
5178
- return OK(input3.data);
5239
+ return OK(input4.data);
5179
5240
  }
5180
5241
  };
5181
5242
  ZodVoid.create = (params) => {
@@ -5185,8 +5246,8 @@ ZodVoid.create = (params) => {
5185
5246
  });
5186
5247
  };
5187
5248
  var ZodArray = class _ZodArray extends ZodType {
5188
- _parse(input3) {
5189
- const { ctx, status } = this._processInputParams(input3);
5249
+ _parse(input4) {
5250
+ const { ctx, status } = this._processInputParams(input4);
5190
5251
  const def = this._def;
5191
5252
  if (ctx.parsedType !== ZodParsedType.array) {
5192
5253
  addIssueToContext(ctx, {
@@ -5326,10 +5387,10 @@ var ZodObject = class _ZodObject extends ZodType {
5326
5387
  this._cached = { shape, keys };
5327
5388
  return this._cached;
5328
5389
  }
5329
- _parse(input3) {
5330
- const parsedType = this._getType(input3);
5390
+ _parse(input4) {
5391
+ const parsedType = this._getType(input4);
5331
5392
  if (parsedType !== ZodParsedType.object) {
5332
- const ctx2 = this._getOrReturnCtx(input3);
5393
+ const ctx2 = this._getOrReturnCtx(input4);
5333
5394
  addIssueToContext(ctx2, {
5334
5395
  code: ZodIssueCode.invalid_type,
5335
5396
  expected: ZodParsedType.object,
@@ -5337,7 +5398,7 @@ var ZodObject = class _ZodObject extends ZodType {
5337
5398
  });
5338
5399
  return INVALID;
5339
5400
  }
5340
- const { status, ctx } = this._processInputParams(input3);
5401
+ const { status, ctx } = this._processInputParams(input4);
5341
5402
  const { shape, keys: shapeKeys } = this._getCached();
5342
5403
  const extraKeys = [];
5343
5404
  if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
@@ -5649,8 +5710,8 @@ ZodObject.lazycreate = (shape, params) => {
5649
5710
  });
5650
5711
  };
5651
5712
  var ZodUnion = class extends ZodType {
5652
- _parse(input3) {
5653
- const { ctx } = this._processInputParams(input3);
5713
+ _parse(input4) {
5714
+ const { ctx } = this._processInputParams(input4);
5654
5715
  const options = this._def.options;
5655
5716
  function handleResults(results) {
5656
5717
  for (const result of results) {
@@ -5771,8 +5832,8 @@ var getDiscriminator = (type) => {
5771
5832
  }
5772
5833
  };
5773
5834
  var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
5774
- _parse(input3) {
5775
- const { ctx } = this._processInputParams(input3);
5835
+ _parse(input4) {
5836
+ const { ctx } = this._processInputParams(input4);
5776
5837
  if (ctx.parsedType !== ZodParsedType.object) {
5777
5838
  addIssueToContext(ctx, {
5778
5839
  code: ZodIssueCode.invalid_type,
@@ -5885,8 +5946,8 @@ function mergeValues(a, b) {
5885
5946
  }
5886
5947
  }
5887
5948
  var ZodIntersection = class extends ZodType {
5888
- _parse(input3) {
5889
- const { status, ctx } = this._processInputParams(input3);
5949
+ _parse(input4) {
5950
+ const { status, ctx } = this._processInputParams(input4);
5890
5951
  const handleParsed = (parsedLeft, parsedRight) => {
5891
5952
  if (isAborted(parsedLeft) || isAborted(parsedRight)) {
5892
5953
  return INVALID;
@@ -5938,8 +5999,8 @@ ZodIntersection.create = (left, right, params) => {
5938
5999
  });
5939
6000
  };
5940
6001
  var ZodTuple = class _ZodTuple extends ZodType {
5941
- _parse(input3) {
5942
- const { status, ctx } = this._processInputParams(input3);
6002
+ _parse(input4) {
6003
+ const { status, ctx } = this._processInputParams(input4);
5943
6004
  if (ctx.parsedType !== ZodParsedType.array) {
5944
6005
  addIssueToContext(ctx, {
5945
6006
  code: ZodIssueCode.invalid_type,
@@ -6011,8 +6072,8 @@ var ZodRecord = class _ZodRecord extends ZodType {
6011
6072
  get valueSchema() {
6012
6073
  return this._def.valueType;
6013
6074
  }
6014
- _parse(input3) {
6015
- const { status, ctx } = this._processInputParams(input3);
6075
+ _parse(input4) {
6076
+ const { status, ctx } = this._processInputParams(input4);
6016
6077
  if (ctx.parsedType !== ZodParsedType.object) {
6017
6078
  addIssueToContext(ctx, {
6018
6079
  code: ZodIssueCode.invalid_type,
@@ -6064,8 +6125,8 @@ var ZodMap = class extends ZodType {
6064
6125
  get valueSchema() {
6065
6126
  return this._def.valueType;
6066
6127
  }
6067
- _parse(input3) {
6068
- const { status, ctx } = this._processInputParams(input3);
6128
+ _parse(input4) {
6129
+ const { status, ctx } = this._processInputParams(input4);
6069
6130
  if (ctx.parsedType !== ZodParsedType.map) {
6070
6131
  addIssueToContext(ctx, {
6071
6132
  code: ZodIssueCode.invalid_type,
@@ -6124,8 +6185,8 @@ ZodMap.create = (keyType, valueType, params) => {
6124
6185
  });
6125
6186
  };
6126
6187
  var ZodSet = class _ZodSet extends ZodType {
6127
- _parse(input3) {
6128
- const { status, ctx } = this._processInputParams(input3);
6188
+ _parse(input4) {
6189
+ const { status, ctx } = this._processInputParams(input4);
6129
6190
  if (ctx.parsedType !== ZodParsedType.set) {
6130
6191
  addIssueToContext(ctx, {
6131
6192
  code: ZodIssueCode.invalid_type,
@@ -6213,8 +6274,8 @@ var ZodFunction = class _ZodFunction extends ZodType {
6213
6274
  super(...arguments);
6214
6275
  this.validate = this.implement;
6215
6276
  }
6216
- _parse(input3) {
6217
- const { ctx } = this._processInputParams(input3);
6277
+ _parse(input4) {
6278
+ const { ctx } = this._processInputParams(input4);
6218
6279
  if (ctx.parsedType !== ZodParsedType.function) {
6219
6280
  addIssueToContext(ctx, {
6220
6281
  code: ZodIssueCode.invalid_type,
@@ -6317,8 +6378,8 @@ var ZodLazy = class extends ZodType {
6317
6378
  get schema() {
6318
6379
  return this._def.getter();
6319
6380
  }
6320
- _parse(input3) {
6321
- const { ctx } = this._processInputParams(input3);
6381
+ _parse(input4) {
6382
+ const { ctx } = this._processInputParams(input4);
6322
6383
  const lazySchema = this._def.getter();
6323
6384
  return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
6324
6385
  }
@@ -6331,9 +6392,9 @@ ZodLazy.create = (getter, params) => {
6331
6392
  });
6332
6393
  };
6333
6394
  var ZodLiteral = class extends ZodType {
6334
- _parse(input3) {
6335
- if (input3.data !== this._def.value) {
6336
- const ctx = this._getOrReturnCtx(input3);
6395
+ _parse(input4) {
6396
+ if (input4.data !== this._def.value) {
6397
+ const ctx = this._getOrReturnCtx(input4);
6337
6398
  addIssueToContext(ctx, {
6338
6399
  received: ctx.data,
6339
6400
  code: ZodIssueCode.invalid_literal,
@@ -6341,7 +6402,7 @@ var ZodLiteral = class extends ZodType {
6341
6402
  });
6342
6403
  return INVALID;
6343
6404
  }
6344
- return { status: "valid", value: input3.data };
6405
+ return { status: "valid", value: input4.data };
6345
6406
  }
6346
6407
  get value() {
6347
6408
  return this._def.value;
@@ -6362,9 +6423,9 @@ function createZodEnum(values, params) {
6362
6423
  });
6363
6424
  }
6364
6425
  var ZodEnum = class _ZodEnum extends ZodType {
6365
- _parse(input3) {
6366
- if (typeof input3.data !== "string") {
6367
- const ctx = this._getOrReturnCtx(input3);
6426
+ _parse(input4) {
6427
+ if (typeof input4.data !== "string") {
6428
+ const ctx = this._getOrReturnCtx(input4);
6368
6429
  const expectedValues = this._def.values;
6369
6430
  addIssueToContext(ctx, {
6370
6431
  expected: util.joinValues(expectedValues),
@@ -6376,8 +6437,8 @@ var ZodEnum = class _ZodEnum extends ZodType {
6376
6437
  if (!this._cache) {
6377
6438
  this._cache = new Set(this._def.values);
6378
6439
  }
6379
- if (!this._cache.has(input3.data)) {
6380
- const ctx = this._getOrReturnCtx(input3);
6440
+ if (!this._cache.has(input4.data)) {
6441
+ const ctx = this._getOrReturnCtx(input4);
6381
6442
  const expectedValues = this._def.values;
6382
6443
  addIssueToContext(ctx, {
6383
6444
  received: ctx.data,
@@ -6386,7 +6447,7 @@ var ZodEnum = class _ZodEnum extends ZodType {
6386
6447
  });
6387
6448
  return INVALID;
6388
6449
  }
6389
- return OK(input3.data);
6450
+ return OK(input4.data);
6390
6451
  }
6391
6452
  get options() {
6392
6453
  return this._def.values;
@@ -6427,9 +6488,9 @@ var ZodEnum = class _ZodEnum extends ZodType {
6427
6488
  };
6428
6489
  ZodEnum.create = createZodEnum;
6429
6490
  var ZodNativeEnum = class extends ZodType {
6430
- _parse(input3) {
6491
+ _parse(input4) {
6431
6492
  const nativeEnumValues = util.getValidEnumValues(this._def.values);
6432
- const ctx = this._getOrReturnCtx(input3);
6493
+ const ctx = this._getOrReturnCtx(input4);
6433
6494
  if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
6434
6495
  const expectedValues = util.objectValues(nativeEnumValues);
6435
6496
  addIssueToContext(ctx, {
@@ -6442,7 +6503,7 @@ var ZodNativeEnum = class extends ZodType {
6442
6503
  if (!this._cache) {
6443
6504
  this._cache = new Set(util.getValidEnumValues(this._def.values));
6444
6505
  }
6445
- if (!this._cache.has(input3.data)) {
6506
+ if (!this._cache.has(input4.data)) {
6446
6507
  const expectedValues = util.objectValues(nativeEnumValues);
6447
6508
  addIssueToContext(ctx, {
6448
6509
  received: ctx.data,
@@ -6451,7 +6512,7 @@ var ZodNativeEnum = class extends ZodType {
6451
6512
  });
6452
6513
  return INVALID;
6453
6514
  }
6454
- return OK(input3.data);
6515
+ return OK(input4.data);
6455
6516
  }
6456
6517
  get enum() {
6457
6518
  return this._def.values;
@@ -6468,8 +6529,8 @@ var ZodPromise = class extends ZodType {
6468
6529
  unwrap() {
6469
6530
  return this._def.type;
6470
6531
  }
6471
- _parse(input3) {
6472
- const { ctx } = this._processInputParams(input3);
6532
+ _parse(input4) {
6533
+ const { ctx } = this._processInputParams(input4);
6473
6534
  if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
6474
6535
  addIssueToContext(ctx, {
6475
6536
  code: ZodIssueCode.invalid_type,
@@ -6501,8 +6562,8 @@ var ZodEffects = class extends ZodType {
6501
6562
  sourceType() {
6502
6563
  return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
6503
6564
  }
6504
- _parse(input3) {
6505
- const { status, ctx } = this._processInputParams(input3);
6565
+ _parse(input4) {
6566
+ const { status, ctx } = this._processInputParams(input4);
6506
6567
  const effect = this._def.effect || null;
6507
6568
  const checkCtx = {
6508
6569
  addIssue: (arg) => {
@@ -6634,12 +6695,12 @@ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
6634
6695
  });
6635
6696
  };
6636
6697
  var ZodOptional = class extends ZodType {
6637
- _parse(input3) {
6638
- const parsedType = this._getType(input3);
6698
+ _parse(input4) {
6699
+ const parsedType = this._getType(input4);
6639
6700
  if (parsedType === ZodParsedType.undefined) {
6640
6701
  return OK(void 0);
6641
6702
  }
6642
- return this._def.innerType._parse(input3);
6703
+ return this._def.innerType._parse(input4);
6643
6704
  }
6644
6705
  unwrap() {
6645
6706
  return this._def.innerType;
@@ -6653,12 +6714,12 @@ ZodOptional.create = (type, params) => {
6653
6714
  });
6654
6715
  };
6655
6716
  var ZodNullable = class extends ZodType {
6656
- _parse(input3) {
6657
- const parsedType = this._getType(input3);
6717
+ _parse(input4) {
6718
+ const parsedType = this._getType(input4);
6658
6719
  if (parsedType === ZodParsedType.null) {
6659
6720
  return OK(null);
6660
6721
  }
6661
- return this._def.innerType._parse(input3);
6722
+ return this._def.innerType._parse(input4);
6662
6723
  }
6663
6724
  unwrap() {
6664
6725
  return this._def.innerType;
@@ -6672,8 +6733,8 @@ ZodNullable.create = (type, params) => {
6672
6733
  });
6673
6734
  };
6674
6735
  var ZodDefault = class extends ZodType {
6675
- _parse(input3) {
6676
- const { ctx } = this._processInputParams(input3);
6736
+ _parse(input4) {
6737
+ const { ctx } = this._processInputParams(input4);
6677
6738
  let data = ctx.data;
6678
6739
  if (ctx.parsedType === ZodParsedType.undefined) {
6679
6740
  data = this._def.defaultValue();
@@ -6697,8 +6758,8 @@ ZodDefault.create = (type, params) => {
6697
6758
  });
6698
6759
  };
6699
6760
  var ZodCatch = class extends ZodType {
6700
- _parse(input3) {
6701
- const { ctx } = this._processInputParams(input3);
6761
+ _parse(input4) {
6762
+ const { ctx } = this._processInputParams(input4);
6702
6763
  const newCtx = {
6703
6764
  ...ctx,
6704
6765
  common: {
@@ -6750,10 +6811,10 @@ ZodCatch.create = (type, params) => {
6750
6811
  });
6751
6812
  };
6752
6813
  var ZodNaN = class extends ZodType {
6753
- _parse(input3) {
6754
- const parsedType = this._getType(input3);
6814
+ _parse(input4) {
6815
+ const parsedType = this._getType(input4);
6755
6816
  if (parsedType !== ZodParsedType.nan) {
6756
- const ctx = this._getOrReturnCtx(input3);
6817
+ const ctx = this._getOrReturnCtx(input4);
6757
6818
  addIssueToContext(ctx, {
6758
6819
  code: ZodIssueCode.invalid_type,
6759
6820
  expected: ZodParsedType.nan,
@@ -6761,7 +6822,7 @@ var ZodNaN = class extends ZodType {
6761
6822
  });
6762
6823
  return INVALID;
6763
6824
  }
6764
- return { status: "valid", value: input3.data };
6825
+ return { status: "valid", value: input4.data };
6765
6826
  }
6766
6827
  };
6767
6828
  ZodNaN.create = (params) => {
@@ -6772,8 +6833,8 @@ ZodNaN.create = (params) => {
6772
6833
  };
6773
6834
  var BRAND = /* @__PURE__ */ Symbol("zod_brand");
6774
6835
  var ZodBranded = class extends ZodType {
6775
- _parse(input3) {
6776
- const { ctx } = this._processInputParams(input3);
6836
+ _parse(input4) {
6837
+ const { ctx } = this._processInputParams(input4);
6777
6838
  const data = ctx.data;
6778
6839
  return this._def.type._parse({
6779
6840
  data,
@@ -6786,8 +6847,8 @@ var ZodBranded = class extends ZodType {
6786
6847
  }
6787
6848
  };
6788
6849
  var ZodPipeline = class _ZodPipeline extends ZodType {
6789
- _parse(input3) {
6790
- const { status, ctx } = this._processInputParams(input3);
6850
+ _parse(input4) {
6851
+ const { status, ctx } = this._processInputParams(input4);
6791
6852
  if (ctx.common.async) {
6792
6853
  const handleAsync = async () => {
6793
6854
  const inResult = await this._def.in._parseAsync({
@@ -6841,8 +6902,8 @@ var ZodPipeline = class _ZodPipeline extends ZodType {
6841
6902
  }
6842
6903
  };
6843
6904
  var ZodReadonly = class extends ZodType {
6844
- _parse(input3) {
6845
- const result = this._def.innerType._parse(input3);
6905
+ _parse(input4) {
6906
+ const result = this._def.innerType._parse(input4);
6846
6907
  const freeze = (data) => {
6847
6908
  if (isValid(data)) {
6848
6909
  data.value = Object.freeze(data.value);
@@ -7309,23 +7370,40 @@ var createCliApiClient = (options) => {
7309
7370
  const fetchFn = options.fetchFn ?? fetch;
7310
7371
  const timeoutMs = options.timeoutMs ?? 1e4;
7311
7372
  const projectPageLimit = 100;
7312
- const request = async (path, init, parse2) => {
7313
- const controller = new AbortController();
7314
- const timer = setTimeout(() => controller.abort(), timeoutMs);
7315
- const requestId = (options.requestId ?? defaultRequestId)();
7316
- try {
7373
+ const requestWithAuthorization = async (path, init, accept, controller, requestId) => {
7374
+ const send = () => {
7317
7375
  const authorization = options.getAuthorization?.();
7318
- const response = await fetchFn(new URL(path, baseUrl).toString(), {
7376
+ return fetchFn(new URL(path, baseUrl).toString(), {
7319
7377
  ...init,
7320
7378
  signal: controller.signal,
7321
7379
  headers: {
7322
- accept: "application/json",
7380
+ accept,
7323
7381
  "x-request-id": requestId,
7324
7382
  ...authorization ? { authorization } : {},
7325
7383
  ...init.body ? { "content-type": "application/json" } : {},
7326
7384
  ...init.headers
7327
7385
  }
7328
7386
  });
7387
+ };
7388
+ let response = await send();
7389
+ if (response.status === 401 && options.onUnauthorized) {
7390
+ const refreshed = await options.onUnauthorized();
7391
+ if (refreshed) response = await send();
7392
+ }
7393
+ return response;
7394
+ };
7395
+ const request = async (path, init, parse2) => {
7396
+ const controller = new AbortController();
7397
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
7398
+ const requestId = (options.requestId ?? defaultRequestId)();
7399
+ try {
7400
+ const response = await requestWithAuthorization(
7401
+ path,
7402
+ init,
7403
+ "application/json",
7404
+ controller,
7405
+ requestId
7406
+ );
7329
7407
  if (!response.ok) throw await asError(response, requestId);
7330
7408
  return parse2(await response.json());
7331
7409
  } catch (error) {
@@ -7346,17 +7424,13 @@ var createCliApiClient = (options) => {
7346
7424
  const timer = setTimeout(() => controller.abort(), timeoutMs);
7347
7425
  const requestId = (options.requestId ?? defaultRequestId)();
7348
7426
  try {
7349
- const authorization = options.getAuthorization?.();
7350
- const response = await fetchFn(new URL(path, baseUrl).toString(), {
7351
- ...init,
7352
- signal: controller.signal,
7353
- headers: {
7354
- accept: "application/json, text/plain, text/markdown, application/sarif+json",
7355
- "x-request-id": requestId,
7356
- ...authorization ? { authorization } : {},
7357
- ...init.headers
7358
- }
7359
- });
7427
+ const response = await requestWithAuthorization(
7428
+ path,
7429
+ init,
7430
+ "application/json, text/plain, text/markdown, application/sarif+json",
7431
+ controller,
7432
+ requestId
7433
+ );
7360
7434
  if (!response.ok) throw await asError(response, requestId);
7361
7435
  return { content: await response.text(), contentType: response.headers.get("content-type") };
7362
7436
  } catch (error) {
@@ -7376,16 +7450,16 @@ var createCliApiClient = (options) => {
7376
7450
  );
7377
7451
  return result.codebases;
7378
7452
  },
7379
- linkWorkspace: async (input3) => {
7380
- const parsed = workspaceLinkCandidateSchema.parse(input3);
7453
+ linkWorkspace: async (input4) => {
7454
+ const parsed = workspaceLinkCandidateSchema.parse(input4);
7381
7455
  await request(
7382
7456
  `/api/cli/workspaces/${encodeURIComponent(parsed.fingerprint)}`,
7383
7457
  { method: "PUT", body: JSON.stringify(parsed) },
7384
7458
  () => void 0
7385
7459
  );
7386
7460
  },
7387
- resolveConfig: async (input3) => {
7388
- const parsed = repositoryConfigInputSchema.parse(input3);
7461
+ resolveConfig: async (input4) => {
7462
+ const parsed = repositoryConfigInputSchema.parse(input4);
7389
7463
  return request(
7390
7464
  "/api/cli/config/resolve",
7391
7465
  { method: "POST", body: JSON.stringify(parsed) },
@@ -7419,8 +7493,8 @@ var createCliApiClient = (options) => {
7419
7493
  offset: 0
7420
7494
  };
7421
7495
  },
7422
- createProject: (input3) => {
7423
- const parsed = createProjectRequestSchema.parse(input3);
7496
+ createProject: (input4) => {
7497
+ const parsed = createProjectRequestSchema.parse(input4);
7424
7498
  return request(
7425
7499
  "/api/projects",
7426
7500
  { method: "POST", body: JSON.stringify(parsed) },
@@ -7432,8 +7506,8 @@ var createCliApiClient = (options) => {
7432
7506
  { method: "GET" },
7433
7507
  (payload) => projectCodebaseListSchema.parse(payload)
7434
7508
  ),
7435
- createProjectCodebase: (projectId, input3) => {
7436
- const parsed = projectCodebaseInputSchema.parse(input3);
7509
+ createProjectCodebase: (projectId, input4) => {
7510
+ const parsed = projectCodebaseInputSchema.parse(input4);
7437
7511
  return request(
7438
7512
  `/api/projects/${encodeURIComponent(projectId)}/repositories`,
7439
7513
  { method: "POST", body: JSON.stringify(parsed) },
@@ -7471,8 +7545,8 @@ var createCliApiClient = (options) => {
7471
7545
  { method: "GET" },
7472
7546
  (payload) => automationTokenListSchema.parse(payload)
7473
7547
  ),
7474
- createAutomationToken: (projectId, input3) => {
7475
- const parsed = createAutomationTokenRequestSchema.parse(input3);
7548
+ createAutomationToken: (projectId, input4) => {
7549
+ const parsed = createAutomationTokenRequestSchema.parse(input4);
7476
7550
  return request(
7477
7551
  `/api/projects/${encodeURIComponent(projectId)}/tokens`,
7478
7552
  { method: "POST", body: JSON.stringify(parsed) },
@@ -7549,10 +7623,39 @@ external_exports.object({
7549
7623
  });
7550
7624
 
7551
7625
  // src/config/remote-client.ts
7552
- var createRemoteConfigClient = (input3) => createCliApiClient({
7553
- serverUrl: input3.serverUrl,
7554
- getAuthorization: () => input3.token ? `Bearer ${input3.token}` : void 0
7626
+ var createRemoteConfigClient = (input4) => createCliApiClient({
7627
+ serverUrl: input4.serverUrl,
7628
+ getAuthorization: () => {
7629
+ const token = input4.getToken?.() ?? input4.token;
7630
+ return token ? `Bearer ${token}` : void 0;
7631
+ },
7632
+ onUnauthorized: input4.onUnauthorized
7555
7633
  });
7634
+
7635
+ // src/auth/authenticated-remote-client.ts
7636
+ var createAuthenticatedRemoteClient = async (input4) => {
7637
+ const serverUrl = new URL(input4.server).origin;
7638
+ let credential = await getAuthenticatedCredential({
7639
+ server: serverUrl,
7640
+ store: input4.store
7641
+ });
7642
+ return createRemoteConfigClient({
7643
+ serverUrl,
7644
+ getToken: () => credential.accessToken,
7645
+ onUnauthorized: async () => {
7646
+ try {
7647
+ credential = await getAuthenticatedCredential({
7648
+ server: serverUrl,
7649
+ store: input4.store,
7650
+ forceRefresh: true
7651
+ });
7652
+ return true;
7653
+ } catch {
7654
+ return false;
7655
+ }
7656
+ }
7657
+ });
7658
+ };
7556
7659
  var workspaceLinkStateSchema = workspaceLinkCandidateSchema.extend({
7557
7660
  serverUrl: external_exports.string().url(),
7558
7661
  configCache: external_exports.object({ expiresAt: external_exports.string().datetime({ offset: true }), effectiveConfigHash: external_exports.string() }).strict().optional()
@@ -7606,12 +7709,7 @@ var FileWorkspaceLinkStore = class {
7606
7709
  // src/commands/automation.command.ts
7607
7710
  var authenticatedClient = async (server, store) => {
7608
7711
  const origin = new URL(server).origin;
7609
- const credential = await store.read(origin);
7610
- if (!credential) throw new Error("Not authenticated. Run `cs auth login`.");
7611
- if (credential.expiresAt && Date.parse(credential.expiresAt) <= Date.now()) {
7612
- throw new Error("Credential expired. Run `cs auth login`.");
7613
- }
7614
- return createRemoteConfigClient({ serverUrl: origin, token: credential.accessToken });
7712
+ return createAuthenticatedRemoteClient({ server: origin, store });
7615
7713
  };
7616
7714
  var projectIdFor = async (path, projectId) => {
7617
7715
  if (projectId) return projectId;
@@ -8834,9 +8932,9 @@ var groupsAsync = (state, error, callback$1) => {
8834
8932
  report(error, callback$1, state.groups, state.options.suppressErrors);
8835
8933
  return null;
8836
8934
  };
8837
- function report(error, callback$1, output, suppressErrors) {
8838
- if (error && !suppressErrors) callback$1(error, output);
8839
- else callback$1(null, output);
8935
+ function report(error, callback$1, output2, suppressErrors) {
8936
+ if (error && !suppressErrors) callback$1(error, output2);
8937
+ else callback$1(null, output2);
8840
8938
  }
8841
8939
  function build$1(options, isSynchronous) {
8842
8940
  const { onlyCounts, group, maxFiles } = options;
@@ -8882,11 +8980,11 @@ var Queue = class {
8882
8980
  this.count++;
8883
8981
  return this.count;
8884
8982
  }
8885
- dequeue(error, output) {
8983
+ dequeue(error, output2) {
8886
8984
  if (this.onQueueEmpty && (--this.count <= 0 || error)) {
8887
- this.onQueueEmpty(error, output);
8985
+ this.onQueueEmpty(error, output2);
8888
8986
  if (error) {
8889
- output.controller.abort();
8987
+ output2.controller.abort();
8890
8988
  this.onQueueEmpty = void 0;
8891
8989
  }
8892
8990
  }
@@ -8998,9 +9096,9 @@ var Walker = class {
8998
9096
  };
8999
9097
  function promise(root, options) {
9000
9098
  return new Promise((resolve$1, reject) => {
9001
- callback(root, options, (err2, output) => {
9099
+ callback(root, options, (err2, output2) => {
9002
9100
  if (err2) return reject(err2);
9003
- resolve$1(output);
9101
+ resolve$1(output2);
9004
9102
  });
9005
9103
  });
9006
9104
  }
@@ -9174,9 +9272,9 @@ function getPartialMatcher(patterns, options = {}) {
9174
9272
  for (j = 0; j < partsCount; j++) partMatchers[j] = (0, import_picomatch.default)(parts[j], options);
9175
9273
  matchers[i] = partMatchers;
9176
9274
  }
9177
- return (input3) => {
9178
- const inputParts = input3.split("/");
9179
- if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input3)) return true;
9275
+ return (input4) => {
9276
+ const inputParts = input4.split("/");
9277
+ if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input4)) return true;
9180
9278
  for (i = 0; i < patternsCount; i++) {
9181
9279
  const patternParts = patternsParts[i];
9182
9280
  const matcher = matchers[i];
@@ -13478,8 +13576,7 @@ var providerDetails = {
13478
13576
  gemini: { displayName: "Google Gemini", envName: "GEMINI_API_KEY" },
13479
13577
  groq: { displayName: "Groq", envName: "GROQ_API_KEY" },
13480
13578
  "viettel-netmind": { displayName: "Viettel Netmind", envName: "LLM_API_KEY" },
13481
- "opencode-go": { displayName: "OpenCode Go", envName: "OPENCODE_GO_API_KEY" },
13482
- freemodel: { displayName: "FreeModel", envName: "FREEMODEL_API_KEY" }
13579
+ "opencode-go": { displayName: "OpenCode Go", envName: "OPENCODE_GO_API_KEY" }
13483
13580
  };
13484
13581
  var providerNeedsApiKey = (provider) => provider in providerDetails;
13485
13582
  var providerHasApiKey = (config, provider) => {
@@ -13512,9 +13609,8 @@ var withAiApiKey = (config, credential, apiKey) => {
13512
13609
  };
13513
13610
  };
13514
13611
  var OLLAMA_DEFAULT_BASE = "http://localhost:11434";
13515
- var NETMIND_DEFAULT_BASE = "https://netmind.viettel.vn/gateway/v1";
13612
+ var NETMIND_DEFAULT_BASE = "https://example.invalid/netmind/v1";
13516
13613
  var OPENCODE_GO_DEFAULT_BASE = "https://opencode.ai/zen/go/v1";
13517
- var FREEMODEL_DEFAULT_BASE = "https://api.freemodel.dev";
13518
13614
  var stripTrailingSlash = (s) => s.replace(/\/+$/, "");
13519
13615
  var buildLanguageModel = (config, modelOverride) => {
13520
13616
  const modelId = modelOverride ?? config.defaultModel;
@@ -13558,16 +13654,6 @@ var buildLanguageModel = (config, modelOverride) => {
13558
13654
  apiKey: config.apiKey
13559
13655
  }).chatModel(modelId);
13560
13656
  }
13561
- case "freemodel": {
13562
- if (!config.apiKey) {
13563
- throw new Error('createAiSdkProvider({providerType:"freemodel"}) requires apiKey');
13564
- }
13565
- return createOpenAICompatible({
13566
- name: "freemodel",
13567
- baseURL: stripTrailingSlash(config.baseUrl ?? FREEMODEL_DEFAULT_BASE),
13568
- apiKey: config.apiKey
13569
- }).chatModel(modelId);
13570
- }
13571
13657
  case "openai-compatible": {
13572
13658
  if (!config.baseUrl) {
13573
13659
  throw new Error('createAiSdkProvider({providerType:"openai-compatible"}) requires baseUrl');
@@ -13626,9 +13712,6 @@ var pingTarget = (config) => {
13626
13712
  headers: config.apiKey ? { authorization: `Bearer ${config.apiKey}` } : {}
13627
13713
  };
13628
13714
  }
13629
- case "freemodel": {
13630
- return null;
13631
- }
13632
13715
  case "openai-compatible": {
13633
13716
  if (!config.baseUrl) return null;
13634
13717
  return {
@@ -13701,9 +13784,9 @@ var completeRawOpenAICompatibleJsonChat = async (options) => {
13701
13784
  })
13702
13785
  );
13703
13786
  }
13704
- const input3 = body.usage?.prompt_tokens;
13705
- const output = body.usage?.completion_tokens;
13706
- const tokensUsed = input3 !== void 0 && output !== void 0 ? { prompt: input3, completion: output } : void 0;
13787
+ const input4 = body.usage?.prompt_tokens;
13788
+ const output2 = body.usage?.completion_tokens;
13789
+ const tokensUsed = input4 !== void 0 && output2 !== void 0 ? { prompt: input4, completion: output2 } : void 0;
13707
13790
  return ok({
13708
13791
  text: text2,
13709
13792
  ...tokensUsed !== void 0 ? { tokensUsed } : {},
@@ -13711,10 +13794,7 @@ var completeRawOpenAICompatibleJsonChat = async (options) => {
13711
13794
  });
13712
13795
  };
13713
13796
  var createAiSdkProvider = (config) => {
13714
- if (config.providerType === "freemodel" && !config.apiKey) {
13715
- throw new Error('createAiSdkProvider({providerType:"freemodel"}) requires apiKey');
13716
- }
13717
- const model = config.providerType === "freemodel" ? null : buildLanguageModel(config);
13797
+ const model = buildLanguageModel(config);
13718
13798
  const name = config.providerName ?? config.providerType;
13719
13799
  const defaultTimeoutMs = config.defaultTimeoutMs ?? 18e4;
13720
13800
  const probe = pingTarget(config);
@@ -13770,57 +13850,6 @@ var createAiSdkProvider = (config) => {
13770
13850
  signal: ctrl.signal
13771
13851
  });
13772
13852
  }
13773
- if (config.providerType === "freemodel") {
13774
- if (!config.apiKey) {
13775
- return err(
13776
- new AIProviderError(`${name} request failed: missing apiKey`, {
13777
- context: { provider: name, model: reportedModel }
13778
- })
13779
- );
13780
- }
13781
- const base = stripTrailingSlash(config.baseUrl ?? FREEMODEL_DEFAULT_BASE);
13782
- const res = await fetch(`${base}/responses`, {
13783
- method: "POST",
13784
- headers: {
13785
- authorization: `Bearer ${config.apiKey}`,
13786
- "content-type": "application/json"
13787
- },
13788
- body: JSON.stringify({
13789
- model: reportedModel,
13790
- ...request.system ? { instructions: request.system } : {},
13791
- input: request.user,
13792
- store: false,
13793
- temperature: request.temperature ?? 0.1,
13794
- ...request.maxTokens !== void 0 ? { max_output_tokens: request.maxTokens } : {}
13795
- }),
13796
- signal: ctrl.signal
13797
- });
13798
- if (!res.ok) {
13799
- const body2 = await res.text().catch(() => "");
13800
- return err(
13801
- new AIProviderError(`${name} request failed: HTTP ${res.status} ${body2}`.trim(), {
13802
- context: { provider: name, model: reportedModel }
13803
- })
13804
- );
13805
- }
13806
- const body = await res.json();
13807
- 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") ?? "";
13808
- if (!text22) {
13809
- return err(
13810
- new AIProviderError(`${name} returned empty content`, {
13811
- context: { provider: name, model: reportedModel }
13812
- })
13813
- );
13814
- }
13815
- const input22 = body.usage?.input_tokens;
13816
- const output2 = body.usage?.output_tokens;
13817
- const tokensUsed2 = input22 !== void 0 && output2 !== void 0 ? { prompt: input22, completion: output2 } : void 0;
13818
- return ok({
13819
- text: text22,
13820
- ...tokensUsed2 !== void 0 ? { tokensUsed: tokensUsed2 } : {},
13821
- cached: false
13822
- });
13823
- }
13824
13853
  const callModel = override === null ? model : buildLanguageModel(config, override);
13825
13854
  if (!callModel) {
13826
13855
  return err(
@@ -13851,9 +13880,9 @@ var createAiSdkProvider = (config) => {
13851
13880
  })
13852
13881
  );
13853
13882
  }
13854
- const input3 = result.usage.inputTokens;
13855
- const output = result.usage.outputTokens;
13856
- const tokensUsed = input3 !== void 0 && output !== void 0 ? { prompt: input3, completion: output } : void 0;
13883
+ const input4 = result.usage.inputTokens;
13884
+ const output2 = result.usage.outputTokens;
13885
+ const tokensUsed = input4 !== void 0 && output2 !== void 0 ? { prompt: input4, completion: output2 } : void 0;
13857
13886
  return ok({
13858
13887
  text: text2,
13859
13888
  ...tokensUsed !== void 0 ? { tokensUsed } : {},
@@ -13892,7 +13921,10 @@ var createFallbackClient = (options) => {
13892
13921
  for (const p of providers) {
13893
13922
  const reachable = await p.ping();
13894
13923
  if (!reachable) {
13895
- logger.debug({ provider: p.name }, "provider unreachable, trying next");
13924
+ logger.debug(
13925
+ { event: "ai_provider_unreachable", provider: p.name, model: request.model },
13926
+ "provider unreachable, trying next"
13927
+ );
13896
13928
  lastError = new AIProviderError(`${p.name} is unreachable`, {
13897
13929
  context: { provider: p.name }
13898
13930
  });
@@ -13906,7 +13938,12 @@ var createFallbackClient = (options) => {
13906
13938
  return r;
13907
13939
  }
13908
13940
  logger.warn(
13909
- { provider: p.name, code: r.error.code },
13941
+ {
13942
+ event: "ai_provider_error",
13943
+ provider: p.name,
13944
+ model: request.model,
13945
+ code: r.error.code
13946
+ },
13910
13947
  `provider failed: ${r.error.message}`
13911
13948
  );
13912
13949
  lastError = r.error;
@@ -14052,6 +14089,11 @@ var formatTokenWarning = (ruleId, promptTokens, budgetTokens) => {
14052
14089
  var CACHE_NAMESPACE = "ai";
14053
14090
  var DEFAULT_PROVIDER_RETRY_MAX_RETRIES = 1;
14054
14091
  var DEFAULT_PROVIDER_RETRY_MAX_DELAY_MS = 75e3;
14092
+ var DEFAULT_ADAPTIVE_RETRY_MAX_RETRIES = 1;
14093
+ var DEFAULT_ADAPTIVE_CONTEXT_REDUCTION_FACTOR = 0.75;
14094
+ var DEFAULT_ADAPTIVE_TIMEOUT_MULTIPLIER = 1.5;
14095
+ var DEFAULT_ADAPTIVE_MAX_DELAY_MS = 5e3;
14096
+ var DEFAULT_PROVIDER_TIMEOUT_MS = 18e4;
14055
14097
  var sleep2 = (ms) => new Promise((resolveSleep) => setTimeout(resolveSleep, ms));
14056
14098
  var parseRetryDelayMs = (message) => {
14057
14099
  const resetMatch = message.match(/limit resets at:\s*([^"}\n]+)/i);
@@ -14086,6 +14128,34 @@ var providerRetryDelayMs = (message, maxDelayMs) => {
14086
14128
  if (hintedDelay === null) return null;
14087
14129
  return Math.min(hintedDelay, maxDelayMs);
14088
14130
  };
14131
+ var adaptiveFailureKind = (message) => {
14132
+ if (/context(?: length| window)|maximum context|too many tokens|prompt too long|input too long|token limit|context_length_exceeded|\b413\b/i.test(
14133
+ message
14134
+ )) {
14135
+ return "context-limit";
14136
+ }
14137
+ if (/timeout|timed out|deadline exceeded|abort(?:ed|error)?|ETIMEDOUT/i.test(message)) {
14138
+ return "timeout";
14139
+ }
14140
+ 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(
14141
+ message
14142
+ )) {
14143
+ return "transient";
14144
+ }
14145
+ return null;
14146
+ };
14147
+ var compactClusterContext = (context, keepFraction) => {
14148
+ if (!context || context.supportFiles.length === 0) return void 0;
14149
+ const keepCount = Math.max(
14150
+ 0,
14151
+ Math.min(
14152
+ context.supportFiles.length - 1,
14153
+ Math.floor(context.supportFiles.length * keepFraction)
14154
+ )
14155
+ );
14156
+ if (keepCount >= context.supportFiles.length) return context;
14157
+ return { ...context, supportFiles: context.supportFiles.slice(0, keepCount) };
14158
+ };
14089
14159
  var findingDedupeKey2 = (finding) => finding.rootCauseKey ? ["root", finding.file, finding.rootCauseKey].join("\0") : [
14090
14160
  "line",
14091
14161
  finding.file,
@@ -14141,6 +14211,26 @@ var createAiExecutor = (options) => {
14141
14211
  Math.floor(options.providerRetry?.maxDelayMs ?? DEFAULT_PROVIDER_RETRY_MAX_DELAY_MS)
14142
14212
  );
14143
14213
  const providerRetrySleep = options.providerRetry?.sleep ?? sleep2;
14214
+ const adaptiveRetryMaxRetries = Math.max(
14215
+ 0,
14216
+ Math.floor(options.adaptiveRetry?.maxRetries ?? DEFAULT_ADAPTIVE_RETRY_MAX_RETRIES)
14217
+ );
14218
+ const adaptiveContextReductionFactor = Math.min(
14219
+ 0.95,
14220
+ Math.max(
14221
+ 0.25,
14222
+ options.adaptiveRetry?.contextReductionFactor ?? DEFAULT_ADAPTIVE_CONTEXT_REDUCTION_FACTOR
14223
+ )
14224
+ );
14225
+ const adaptiveTimeoutMultiplier = Math.min(
14226
+ 3,
14227
+ Math.max(1.1, options.adaptiveRetry?.timeoutMultiplier ?? DEFAULT_ADAPTIVE_TIMEOUT_MULTIPLIER)
14228
+ );
14229
+ const adaptiveRetryMaxDelayMs = Math.max(
14230
+ 0,
14231
+ Math.floor(options.adaptiveRetry?.maxDelayMs ?? DEFAULT_ADAPTIVE_MAX_DELAY_MS)
14232
+ );
14233
+ const adaptiveRetrySleep = options.adaptiveRetry?.sleep ?? sleep2;
14144
14234
  const extraText = extraInstructions?.trim() ?? "";
14145
14235
  const extraDiscriminator = extraText.length === 0 ? "" : `xi:${extraText.length}:${extraText.slice(0, 32)}`;
14146
14236
  return async function executeAiRule(rule, file, _parsed, clusterContext, moduleContext) {
@@ -14206,74 +14296,134 @@ var createAiExecutor = (options) => {
14206
14296
  })
14207
14297
  );
14208
14298
  }
14209
- const clusterFilesVar = scope === "per-cluster" && clusterContext ? clusterContext.supportFiles.map((m) => m.path).join("\n") : "";
14210
- const clusterSummaryVar = scope === "per-cluster" && clusterContext ? clusterContext.supportFiles.map((m) => `--- ${m.path} (layer=${m.layer}) ---
14299
+ const renderUserPrompt = (currentClusterContext2) => {
14300
+ const clusterFilesVar = scope === "per-cluster" && currentClusterContext2 ? currentClusterContext2.supportFiles.map((m) => m.path).join("\n") : "";
14301
+ const clusterSummaryVar = scope === "per-cluster" && currentClusterContext2 ? currentClusterContext2.supportFiles.map((m) => `--- ${m.path} (layer=${m.layer}) ---
14211
14302
  ${m.content}`).join("\n\n") : "";
14212
- const moduleFeaturesVar = scope === "per-module" && moduleContext ? moduleContext.features.map((f) => `- ${f.primaryPath} (findings=${f.findingCount})`).join("\n") : "";
14213
- const moduleFindingsVar = scope === "per-module" && moduleContext ? moduleContext.findings.map(
14214
- (f) => `- ${f.file}:${f.line} [${f.ruleId}] (${f.severity}) ${f.message}${f.suggestion ? ` \u2014 ${f.suggestion}` : ""}`
14215
- ).join("\n") : "";
14216
- const moduleSummaryVar = scope === "per-module" && moduleContext ? `Module ${moduleContext.moduleRootPath} \u2014 ${moduleContext.members.length} file(s):
14303
+ const moduleFeaturesVar = scope === "per-module" && moduleContext ? moduleContext.features.map((f) => `- ${f.primaryPath} (findings=${f.findingCount})`).join("\n") : "";
14304
+ const moduleFindingsVar = scope === "per-module" && moduleContext ? moduleContext.findings.map(
14305
+ (f) => `- ${f.file}:${f.line} [${f.ruleId}] (${f.severity}) ${f.message}${f.suggestion ? ` \u2014 ${f.suggestion}` : ""}`
14306
+ ).join("\n") : "";
14307
+ const moduleSummaryVar = scope === "per-module" && moduleContext ? `Module ${moduleContext.moduleRootPath} \u2014 ${moduleContext.members.length} file(s):
14217
14308
  ${moduleContext.members.map((p) => ` ${p}`).join("\n")}` : "";
14218
- const moduleTransactionBoundariesVar = scope === "per-module" && moduleContext?.transactionBoundaries ? moduleContext.transactionBoundaries.map(
14219
- (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}`
14220
- ).join("\n") : "";
14221
- const promptFilePath = scope === "per-module" && moduleContext ? moduleContext.moduleRootPath : file.path;
14222
- const promptCode = scope === "per-module" && moduleContext ? "" : file.content;
14223
- const baseRendered = renderPrompt(tmplResult.value, {
14224
- file: promptFilePath,
14225
- language: file.language,
14226
- code: promptCode,
14227
- cluster_files: clusterFilesVar,
14228
- cluster_summary: clusterSummaryVar,
14229
- module_features: moduleFeaturesVar,
14230
- module_findings: moduleFindingsVar,
14231
- module_summary: moduleSummaryVar,
14232
- module_transaction_boundaries: moduleTransactionBoundariesVar
14233
- });
14234
- const rendered = extraText.length === 0 ? baseRendered : `${baseRendered}
14309
+ const moduleTransactionBoundariesVar = scope === "per-module" && moduleContext?.transactionBoundaries ? moduleContext.transactionBoundaries.map(
14310
+ (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}`
14311
+ ).join("\n") : "";
14312
+ const promptFilePath = scope === "per-module" && moduleContext ? moduleContext.moduleRootPath : file.path;
14313
+ const promptCode = scope === "per-module" && moduleContext ? "" : file.content;
14314
+ const baseRendered = renderPrompt(tmplResult.value, {
14315
+ file: promptFilePath,
14316
+ language: file.language,
14317
+ code: promptCode,
14318
+ cluster_files: clusterFilesVar,
14319
+ cluster_summary: clusterSummaryVar,
14320
+ module_features: moduleFeaturesVar,
14321
+ module_findings: moduleFindingsVar,
14322
+ module_summary: moduleSummaryVar,
14323
+ module_transaction_boundaries: moduleTransactionBoundariesVar
14324
+ });
14325
+ return extraText.length === 0 ? baseRendered : `${baseRendered}
14235
14326
 
14236
14327
  --- Additional reviewer instructions ---
14237
14328
  ${extraText}
14238
14329
  `;
14239
- const promptTokens = estimateTokens(rendered);
14240
- if (promptTokens > tokenBudgetWarn) {
14330
+ };
14331
+ const initialRendered = renderUserPrompt(clusterContext);
14332
+ const initialPromptTokens = estimateTokens(initialRendered);
14333
+ if (initialPromptTokens > tokenBudgetWarn) {
14241
14334
  logger.warn(
14242
- { ruleId: rule.id, file: file.path, promptTokens, tokenBudgetWarn },
14243
- formatTokenWarning(rule.id, promptTokens, tokenBudgetWarn)
14335
+ {
14336
+ event: "ai_prompt_budget_warning",
14337
+ ruleId: rule.id,
14338
+ file: file.path,
14339
+ promptTokens: initialPromptTokens,
14340
+ tokenBudgetWarn
14341
+ },
14342
+ formatTokenWarning(rule.id, initialPromptTokens, tokenBudgetWarn)
14244
14343
  );
14245
14344
  }
14246
- const request = {
14247
- user: rendered,
14345
+ let currentClusterContext = clusterContext;
14346
+ let currentRendered = initialRendered;
14347
+ let currentTimeoutMs = timeoutMs;
14348
+ let currentMaxTokens = rule.maxTokens;
14349
+ const buildRequest = () => ({
14350
+ user: currentRendered,
14248
14351
  model,
14249
14352
  temperature,
14250
14353
  responseFormat: "json",
14251
- ...rule.maxTokens !== void 0 ? { maxTokens: rule.maxTokens } : {},
14252
- ...timeoutMs !== void 0 ? { timeoutMs } : {},
14354
+ ...currentMaxTokens !== void 0 ? { maxTokens: currentMaxTokens } : {},
14355
+ ...currentTimeoutMs !== void 0 ? { timeoutMs: currentTimeoutMs } : {},
14253
14356
  ...tier !== void 0 ? { tier } : {}
14357
+ });
14358
+ const completeWithProviderRetry = async (request) => {
14359
+ let result = await client.complete(request);
14360
+ for (let attempt = 0; !result.ok && attempt < providerRetryMaxRetries; attempt += 1) {
14361
+ const retryDelayMs = providerRetryDelayMs(result.error.message, providerRetryMaxDelayMs);
14362
+ if (retryDelayMs === null) break;
14363
+ logger.warn(
14364
+ {
14365
+ event: "ai_provider_retry",
14366
+ ruleId: rule.id,
14367
+ file: file.path,
14368
+ code: result.error.code,
14369
+ retryDelayMs,
14370
+ retryAttempt: attempt + 1,
14371
+ retryMaxRetries: providerRetryMaxRetries
14372
+ },
14373
+ `AI provider retry in ${retryDelayMs}ms`
14374
+ );
14375
+ await providerRetrySleep(retryDelayMs);
14376
+ result = await client.complete(request);
14377
+ }
14378
+ return result;
14254
14379
  };
14255
- let aiResult = await client.complete(request);
14256
- for (let attempt = 0; !aiResult.ok && attempt < providerRetryMaxRetries; attempt += 1) {
14257
- const retryDelayMs = providerRetryDelayMs(aiResult.error.message, providerRetryMaxDelayMs);
14258
- if (retryDelayMs === null) break;
14380
+ let aiResult = await completeWithProviderRetry(buildRequest());
14381
+ for (let attempt = 0; !aiResult.ok && attempt < adaptiveRetryMaxRetries; attempt += 1) {
14382
+ const failureKind = adaptiveFailureKind(aiResult.error.message);
14383
+ const nextContext = failureKind === "context-limit" ? compactClusterContext(currentClusterContext, adaptiveContextReductionFactor) : currentClusterContext;
14384
+ const nextTimeoutMs = failureKind === "timeout" ? Math.ceil((currentTimeoutMs ?? DEFAULT_PROVIDER_TIMEOUT_MS) * adaptiveTimeoutMultiplier) : currentTimeoutMs;
14385
+ const nextMaxTokens = failureKind === "context-limit" && currentMaxTokens !== void 0 ? Math.max(256, Math.floor(currentMaxTokens * adaptiveContextReductionFactor)) : currentMaxTokens;
14386
+ const contextChanged = nextContext !== currentClusterContext;
14387
+ const timeoutChanged = nextTimeoutMs !== currentTimeoutMs;
14388
+ const maxTokensChanged = nextMaxTokens !== currentMaxTokens;
14389
+ const canAdapt = failureKind === "transient" || failureKind !== null && (contextChanged || timeoutChanged || maxTokensChanged);
14390
+ if (!canAdapt) break;
14391
+ const backoffMs = failureKind === "transient" ? Math.min(adaptiveRetryMaxDelayMs, 250 * 2 ** attempt) : 0;
14392
+ if (backoffMs > 0) await adaptiveRetrySleep(backoffMs);
14393
+ currentClusterContext = nextContext;
14394
+ currentTimeoutMs = nextTimeoutMs;
14395
+ currentMaxTokens = nextMaxTokens;
14396
+ currentRendered = renderUserPrompt(currentClusterContext);
14259
14397
  logger.warn(
14260
14398
  {
14399
+ event: "ai_adaptive_retry",
14261
14400
  ruleId: rule.id,
14262
14401
  file: file.path,
14263
- code: aiResult.error.code,
14264
- retryDelayMs,
14265
- retryAttempt: attempt + 1,
14266
- retryMaxRetries: providerRetryMaxRetries
14402
+ failureKind,
14403
+ adaptiveAttempt: attempt + 1,
14404
+ adaptiveMaxRetries: adaptiveRetryMaxRetries,
14405
+ supportFiles: currentClusterContext?.supportFiles.length ?? 0,
14406
+ promptTokens: estimateTokens(currentRendered),
14407
+ timeoutMs: currentTimeoutMs,
14408
+ maxTokens: currentMaxTokens,
14409
+ backoffMs
14267
14410
  },
14268
- `AI provider transient failure; retrying in ${retryDelayMs}ms`
14411
+ `AI request adapted after ${failureKind}; retrying`
14269
14412
  );
14270
- await providerRetrySleep(retryDelayMs);
14271
- aiResult = await client.complete(request);
14413
+ aiResult = await completeWithProviderRetry(buildRequest());
14272
14414
  }
14273
14415
  if (!aiResult.ok) {
14274
14416
  onOutcome?.(rule.id, "skipped", "provider-error");
14275
14417
  logger.warn(
14276
- { ruleId: rule.id, file: file.path, code: aiResult.error.code },
14418
+ {
14419
+ event: "ai_rule_error",
14420
+ provider: client.name,
14421
+ model,
14422
+ ruleId: rule.id,
14423
+ file: file.path,
14424
+ code: aiResult.error.code,
14425
+ failureKind: adaptiveFailureKind(aiResult.error.message) ?? "provider"
14426
+ },
14277
14427
  `AI rule skipped: ${aiResult.error.message}`
14278
14428
  );
14279
14429
  return ok([]);
@@ -14281,8 +14431,8 @@ ${extraText}
14281
14431
  let parsedResp = parseAiResponse(aiResult.value.text);
14282
14432
  if (!parsedResp.ok) {
14283
14433
  const repairRequest = {
14284
- ...request,
14285
- user: `${rendered}
14434
+ ...buildRequest(),
14435
+ user: `${currentRendered}
14286
14436
 
14287
14437
  --- Response repair ---
14288
14438
  Your previous response was invalid: ${parsedResp.error.message}
@@ -14299,7 +14449,14 @@ ${aiResult.value.text.slice(0, 4e3)}`
14299
14449
  if (!parsedResp.ok) {
14300
14450
  onOutcome?.(rule.id, "skipped", "invalid-response");
14301
14451
  logger.warn(
14302
- { ruleId: rule.id, file: file.path },
14452
+ {
14453
+ event: "ai_response_error",
14454
+ provider: client.name,
14455
+ model,
14456
+ ruleId: rule.id,
14457
+ file: file.path,
14458
+ code: parsedResp.error.code
14459
+ },
14303
14460
  `AI rule produced invalid response: ${parsedResp.error.message}`
14304
14461
  );
14305
14462
  return ok([]);
@@ -15206,12 +15363,12 @@ var extractTransactionBoundaries = (files) => {
15206
15363
  facts.sort((a, b) => a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1);
15207
15364
  return facts;
15208
15365
  };
15209
- var renderPrDiffPrompt = (input3) => {
15366
+ var renderPrDiffPrompt = (input4) => {
15210
15367
  const parts = [
15211
15368
  "# Merge request",
15212
- `Title: ${input3.title}`,
15213
- input3.description ? `Description:
15214
- ${input3.description}` : "Description: <empty>",
15369
+ `Title: ${input4.title}`,
15370
+ input4.description ? `Description:
15371
+ ${input4.description}` : "Description: <empty>",
15215
15372
  "",
15216
15373
  "# Review rules",
15217
15374
  "- Report only issues introduced by this merge request.",
@@ -15220,20 +15377,20 @@ ${input3.description}` : "Description: <empty>",
15220
15377
  "- Return strict JSON with a top-level `violations` array.",
15221
15378
  "",
15222
15379
  "# Diff hunks",
15223
- input3.hunks.join("\n\n---\n\n")
15380
+ input4.hunks.join("\n\n---\n\n")
15224
15381
  ];
15225
- if (input3.staticFindings && input3.staticFindings.length > 0) {
15382
+ if (input4.staticFindings && input4.staticFindings.length > 0) {
15226
15383
  parts.push(
15227
15384
  "",
15228
15385
  "# Nearby static findings",
15229
- input3.staticFindings.map((f) => `- ${f.ruleId} ${f.file}:${f.line} ${f.message}`).join("\n")
15386
+ input4.staticFindings.map((f) => `- ${f.ruleId} ${f.file}:${f.line} ${f.message}`).join("\n")
15230
15387
  );
15231
15388
  }
15232
- if (input3.supportFiles.length > 0) {
15389
+ if (input4.supportFiles.length > 0) {
15233
15390
  parts.push(
15234
15391
  "",
15235
15392
  "# Support files",
15236
- input3.supportFiles.map((f) => `## ${f.path}
15393
+ input4.supportFiles.map((f) => `## ${f.path}
15237
15394
  \`\`\`
15238
15395
  ${f.content}
15239
15396
  \`\`\``).join("\n\n")
@@ -15270,10 +15427,10 @@ var prDiffResponseSchema = external_exports.object({
15270
15427
  )
15271
15428
  });
15272
15429
  var createPrDiffReviewer = (options) => ({
15273
- async review(input3) {
15430
+ async review(input4) {
15274
15431
  const response = await options.client.complete({
15275
15432
  system: "You are Code Sentinel PR diff reviewer. Output strict JSON only. Report only issues introduced by the diff.",
15276
- user: renderPrDiffPrompt(input3),
15433
+ user: renderPrDiffPrompt(input4),
15277
15434
  model: options.model ?? "",
15278
15435
  responseFormat: "json",
15279
15436
  temperature: options.temperature ?? 0.1,
@@ -15307,14 +15464,14 @@ var createPrDiffReviewer = (options) => ({
15307
15464
  );
15308
15465
  }
15309
15466
  });
15310
- var renderGroupedRulePrompt = (input3) => {
15467
+ var renderGroupedRulePrompt = (input4) => {
15311
15468
  const parts = [
15312
15469
  "# PR grouped rule review",
15313
- `Primary file: ${input3.primaryFile.path}`,
15314
- `Language: ${input3.primaryFile.language}`,
15470
+ `Primary file: ${input4.primaryFile.path}`,
15471
+ `Language: ${input4.primaryFile.language}`,
15315
15472
  "",
15316
15473
  "# Rules to evaluate",
15317
- input3.rules.map(
15474
+ input4.rules.map(
15318
15475
  (rule) => [
15319
15476
  `## ${rule.ruleId}`,
15320
15477
  `Title: ${rule.title}`,
@@ -15333,17 +15490,17 @@ ${rule.description}` : "Description: <empty>"
15333
15490
  "",
15334
15491
  "# Primary file",
15335
15492
  "```",
15336
- input3.primaryFile.content,
15493
+ input4.primaryFile.content,
15337
15494
  "```",
15338
15495
  "",
15339
15496
  "# Diff hunks",
15340
- input3.diffHunks.join("\n\n---\n\n")
15497
+ input4.diffHunks.join("\n\n---\n\n")
15341
15498
  ];
15342
- if (input3.supportFiles.length > 0) {
15499
+ if (input4.supportFiles.length > 0) {
15343
15500
  parts.push(
15344
15501
  "",
15345
15502
  "# Support files",
15346
- input3.supportFiles.map((file) => `## ${file.path}
15503
+ input4.supportFiles.map((file) => `## ${file.path}
15347
15504
  \`\`\`
15348
15505
  ${file.content}
15349
15506
  \`\`\``).join("\n\n")
@@ -15410,11 +15567,11 @@ var labelToConfidence = (label) => {
15410
15567
  }
15411
15568
  };
15412
15569
  var createGroupedRuleReviewer = (options) => ({
15413
- async review(input3) {
15414
- const allowedRuleIds = new Set(input3.rules.map((rule) => rule.ruleId));
15570
+ async review(input4) {
15571
+ const allowedRuleIds = new Set(input4.rules.map((rule) => rule.ruleId));
15415
15572
  const response = await options.client.complete({
15416
15573
  system: "You are Code Sentinel grouped PR rule reviewer. Output strict JSON only. Map every finding to one provided ruleId.",
15417
- user: renderGroupedRulePrompt(input3),
15574
+ user: renderGroupedRulePrompt(input4),
15418
15575
  model: options.model ?? "",
15419
15576
  responseFormat: "json",
15420
15577
  temperature: options.temperature ?? 0.1,
@@ -15445,7 +15602,7 @@ var createGroupedRuleReviewer = (options) => ({
15445
15602
  findings2.push({
15446
15603
  ruleId: ruleResult.ruleId,
15447
15604
  message: finding.title,
15448
- file: input3.primaryFile.path,
15605
+ file: input4.primaryFile.path,
15449
15606
  range: {
15450
15607
  line: finding.lineStart,
15451
15608
  column: 1,
@@ -15460,19 +15617,19 @@ var createGroupedRuleReviewer = (options) => ({
15460
15617
  return ok(findings2);
15461
15618
  }
15462
15619
  });
15463
- var renderPerRulePrompt = (input3) => {
15620
+ var renderPerRulePrompt = (input4) => {
15464
15621
  const parts = [
15465
15622
  "# PR targeted review",
15466
- `Primary file: ${input3.primaryFile.path}`,
15467
- `Language: ${input3.primaryFile.language}`,
15623
+ `Primary file: ${input4.primaryFile.path}`,
15624
+ `Language: ${input4.primaryFile.language}`,
15468
15625
  "",
15469
15626
  "# Rule to evaluate",
15470
- `Rule id: ${input3.rule.ruleId}`,
15471
- `Title: ${input3.rule.title}`,
15472
- `Category: ${input3.rule.category}`,
15473
- `Default severity: ${input3.rule.severity}`,
15474
- input3.rule.description ? `Description:
15475
- ${input3.rule.description}` : "Description: <empty>",
15627
+ `Rule id: ${input4.rule.ruleId}`,
15628
+ `Title: ${input4.rule.title}`,
15629
+ `Category: ${input4.rule.category}`,
15630
+ `Default severity: ${input4.rule.severity}`,
15631
+ input4.rule.description ? `Description:
15632
+ ${input4.rule.description}` : "Description: <empty>",
15476
15633
  "",
15477
15634
  "# Review constraints",
15478
15635
  "- Report only issues introduced by this merge request.",
@@ -15481,21 +15638,21 @@ ${input3.rule.description}` : "Description: <empty>",
15481
15638
  "- Return strict JSON with a top-level `violations` array.",
15482
15639
  "",
15483
15640
  "# Rule prompt",
15484
- input3.renderedRulePrompt,
15641
+ input4.renderedRulePrompt,
15485
15642
  "",
15486
15643
  "# Primary file",
15487
15644
  "```",
15488
- input3.primaryFile.content,
15645
+ input4.primaryFile.content,
15489
15646
  "```",
15490
15647
  "",
15491
15648
  "# Diff hunks",
15492
- input3.diffHunks.join("\n\n---\n\n")
15649
+ input4.diffHunks.join("\n\n---\n\n")
15493
15650
  ];
15494
- if (input3.supportFiles.length > 0) {
15651
+ if (input4.supportFiles.length > 0) {
15495
15652
  parts.push(
15496
15653
  "",
15497
15654
  "# Support files",
15498
- input3.supportFiles.map((file) => `## ${file.path}
15655
+ input4.supportFiles.map((file) => `## ${file.path}
15499
15656
  \`\`\`
15500
15657
  ${file.content}
15501
15658
  \`\`\``).join("\n\n")
@@ -15507,7 +15664,7 @@ ${file.content}
15507
15664
  JSON.stringify({
15508
15665
  violations: [
15509
15666
  {
15510
- file: input3.primaryFile.path,
15667
+ file: input4.primaryFile.path,
15511
15668
  line: 123,
15512
15669
  message: "Concrete issue introduced by the PR",
15513
15670
  suggestion: "Short fix suggestion",
@@ -15519,8 +15676,8 @@ ${file.content}
15519
15676
  return parts.join("\n");
15520
15677
  };
15521
15678
  var createPerRuleReviewer = (options) => ({
15522
- async review(input3) {
15523
- const template = await loadPromptTemplate(input3.promptPath);
15679
+ async review(input4) {
15680
+ const template = await loadPromptTemplate(input4.promptPath);
15524
15681
  if (!template.ok) {
15525
15682
  return err(
15526
15683
  new AIProviderError(`Failed to load PR targeted prompt: ${template.error.message}`, {
@@ -15529,16 +15686,16 @@ var createPerRuleReviewer = (options) => ({
15529
15686
  );
15530
15687
  }
15531
15688
  const renderedRulePrompt = renderPrompt(template.value, {
15532
- file: input3.primaryFile.path,
15533
- language: input3.primaryFile.language,
15534
- code: input3.primaryFile.content,
15535
- cluster_files: input3.supportFiles.map((file) => file.path).join("\n"),
15536
- cluster_summary: input3.supportFiles.map((file) => `--- ${file.path} ---
15689
+ file: input4.primaryFile.path,
15690
+ language: input4.primaryFile.language,
15691
+ code: input4.primaryFile.content,
15692
+ cluster_files: input4.supportFiles.map((file) => file.path).join("\n"),
15693
+ cluster_summary: input4.supportFiles.map((file) => `--- ${file.path} ---
15537
15694
  ${file.content}`).join("\n\n")
15538
15695
  });
15539
15696
  const response = await options.client.complete({
15540
15697
  system: "You are Code Sentinel PR targeted reviewer. Output strict JSON only. Report only issues introduced by the diff.",
15541
- user: renderPerRulePrompt({ ...input3, renderedRulePrompt }),
15698
+ user: renderPerRulePrompt({ ...input4, renderedRulePrompt }),
15542
15699
  model: options.model ?? "",
15543
15700
  responseFormat: "json",
15544
15701
  temperature: options.temperature ?? 0.1,
@@ -15553,9 +15710,9 @@ ${file.content}`).join("\n\n")
15553
15710
  }
15554
15711
  return ok(
15555
15712
  parsed.value.violations.map((violation) => ({
15556
- ruleId: input3.rule.ruleId,
15713
+ ruleId: input4.rule.ruleId,
15557
15714
  message: violation.message,
15558
- file: input3.primaryFile.path,
15715
+ file: input4.primaryFile.path,
15559
15716
  range: {
15560
15717
  line: violation.line,
15561
15718
  column: 1,
@@ -17628,19 +17785,19 @@ var SQLiteDeleteBase = class extends QueryPromise {
17628
17785
  };
17629
17786
 
17630
17787
  // ../../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
17631
- function toSnakeCase(input3) {
17632
- const words = input3.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
17788
+ function toSnakeCase(input4) {
17789
+ const words = input4.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
17633
17790
  return words.map((word) => word.toLowerCase()).join("_");
17634
17791
  }
17635
- function toCamelCase(input3) {
17636
- const words = input3.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
17792
+ function toCamelCase(input4) {
17793
+ const words = input4.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
17637
17794
  return words.reduce((acc, word, i) => {
17638
17795
  const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`;
17639
17796
  return acc + formattedWord;
17640
17797
  }, "");
17641
17798
  }
17642
- function noopCase(input3) {
17643
- return input3;
17799
+ function noopCase(input4) {
17800
+ return input4;
17644
17801
  }
17645
17802
  var CasingCache = class {
17646
17803
  static [entityKind] = "CasingCache";
@@ -22202,6 +22359,103 @@ var migration0025 = {
22202
22359
  "ALTER TABLE review_runs ADD COLUMN IF NOT EXISTS duration_ms BIGINT NULL"
22203
22360
  ]
22204
22361
  };
22362
+ var migration0026 = {
22363
+ version: 26,
22364
+ name: "cli-refresh-tokens",
22365
+ statements: [
22366
+ `ALTER TABLE cli_access_tokens
22367
+ ADD COLUMN IF NOT EXISTS session_id CHAR(32) NULL AFTER user_id`,
22368
+ `CREATE INDEX IF NOT EXISTS cli_access_tokens_session_idx
22369
+ ON cli_access_tokens (session_id, expires_at)`,
22370
+ `CREATE TABLE IF NOT EXISTS cli_refresh_tokens (
22371
+ token_hash CHAR(64) PRIMARY KEY,
22372
+ user_id VARCHAR(384) NOT NULL,
22373
+ session_id CHAR(32) NOT NULL,
22374
+ expires_at BIGINT NOT NULL,
22375
+ created_at BIGINT NOT NULL,
22376
+ last_used_at BIGINT NULL,
22377
+ revoked_at BIGINT NULL,
22378
+ replaced_by_hash CHAR(64) NULL,
22379
+ CONSTRAINT cli_refresh_tokens_user_fk
22380
+ FOREIGN KEY (user_id) REFERENCES dashboard_users(id) ON DELETE CASCADE,
22381
+ INDEX cli_refresh_tokens_session_idx (session_id, expires_at),
22382
+ INDEX cli_refresh_tokens_user_idx (user_id, expires_at DESC),
22383
+ INDEX cli_refresh_tokens_expiry_idx (expires_at)
22384
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`
22385
+ ]
22386
+ };
22387
+ var migration0027 = {
22388
+ version: 27,
22389
+ name: "run-ai-insights",
22390
+ statements: [
22391
+ `CREATE TABLE IF NOT EXISTS run_ai_insights (
22392
+ run_id VARCHAR(384) PRIMARY KEY,
22393
+ project_id VARCHAR(255) NOT NULL,
22394
+ provider VARCHAR(128) NOT NULL,
22395
+ model VARCHAR(255) NOT NULL,
22396
+ status VARCHAR(32) NOT NULL,
22397
+ summary_json LONGTEXT NULL,
22398
+ error_message TEXT NULL,
22399
+ generated_by VARCHAR(384) NULL,
22400
+ created_at BIGINT NOT NULL,
22401
+ updated_at BIGINT NOT NULL,
22402
+ CONSTRAINT run_ai_insights_run_fk
22403
+ FOREIGN KEY (run_id) REFERENCES review_runs(id) ON DELETE CASCADE,
22404
+ CONSTRAINT run_ai_insights_project_fk
22405
+ FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
22406
+ CONSTRAINT run_ai_insights_status_check
22407
+ CHECK (status IN ('running', 'completed', 'failed')),
22408
+ INDEX run_ai_insights_project_idx (project_id),
22409
+ INDEX run_ai_insights_status_idx (status, updated_at DESC),
22410
+ INDEX run_ai_insights_generated_by_idx (generated_by)
22411
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`
22412
+ ]
22413
+ };
22414
+ var migration0028 = {
22415
+ version: 28,
22416
+ name: "site-ai-config",
22417
+ statements: [
22418
+ `CREATE TABLE IF NOT EXISTS site_ai_configs (
22419
+ config_key VARCHAR(64) PRIMARY KEY,
22420
+ config_json LONGTEXT NOT NULL,
22421
+ updated_by VARCHAR(384) NULL,
22422
+ updated_at BIGINT NOT NULL,
22423
+ CONSTRAINT site_ai_configs_updated_by_fk
22424
+ FOREIGN KEY (updated_by) REFERENCES dashboard_users(id) ON DELETE SET NULL,
22425
+ INDEX site_ai_configs_updated_idx (updated_at DESC)
22426
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`
22427
+ ]
22428
+ };
22429
+ var migration0029 = {
22430
+ version: 29,
22431
+ name: "audit-events",
22432
+ statements: [
22433
+ `CREATE TABLE IF NOT EXISTS audit_events (
22434
+ id VARCHAR(384) PRIMARY KEY,
22435
+ event_type VARCHAR(96) NOT NULL,
22436
+ actor_user_id VARCHAR(384) NULL,
22437
+ target_user_id VARCHAR(384) NULL,
22438
+ project_id VARCHAR(255) NULL,
22439
+ resource_type VARCHAR(96) NULL,
22440
+ resource_id VARCHAR(384) NULL,
22441
+ before_json LONGTEXT NULL,
22442
+ after_json LONGTEXT NULL,
22443
+ ip_address VARCHAR(128) NULL,
22444
+ user_agent TEXT NULL,
22445
+ created_at BIGINT NOT NULL,
22446
+ CONSTRAINT audit_events_actor_fk
22447
+ FOREIGN KEY (actor_user_id) REFERENCES dashboard_users(id) ON DELETE SET NULL,
22448
+ CONSTRAINT audit_events_target_fk
22449
+ FOREIGN KEY (target_user_id) REFERENCES dashboard_users(id) ON DELETE SET NULL,
22450
+ CONSTRAINT audit_events_project_fk
22451
+ FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE SET NULL,
22452
+ INDEX audit_events_created_idx (created_at DESC),
22453
+ INDEX audit_events_type_idx (event_type, created_at DESC),
22454
+ INDEX audit_events_actor_idx (actor_user_id, created_at DESC),
22455
+ INDEX audit_events_project_idx (project_id, created_at DESC)
22456
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`
22457
+ ]
22458
+ };
22205
22459
  var MARIADB_MIGRATIONS = [
22206
22460
  migration0001,
22207
22461
  migration0002,
@@ -22227,7 +22481,11 @@ var MARIADB_MIGRATIONS = [
22227
22481
  migration0022,
22228
22482
  migration0023,
22229
22483
  migration0024,
22230
- migration0025
22484
+ migration0025,
22485
+ migration0026,
22486
+ migration0027,
22487
+ migration0028,
22488
+ migration0029
22231
22489
  ];
22232
22490
  MARIADB_MIGRATIONS[MARIADB_MIGRATIONS.length - 1]?.version ?? 0;
22233
22491
 
@@ -22346,18 +22604,6 @@ var buildOneProvider = (name, config, logger) => {
22346
22604
  defaultModel: config.ai.opencodeGo.model,
22347
22605
  defaultTimeoutMs: config.ai.timeoutMs
22348
22606
  });
22349
- case "freemodel":
22350
- if (!config.ai.freemodel.apiKey) {
22351
- logger.warn("freemodel provider requested but no apiKey \u2014 skipping");
22352
- return null;
22353
- }
22354
- return createAiSdkProvider({
22355
- providerType: "freemodel",
22356
- baseUrl: config.ai.freemodel.baseUrl,
22357
- apiKey: config.ai.freemodel.apiKey,
22358
- defaultModel: config.ai.freemodel.model,
22359
- defaultTimeoutMs: config.ai.timeoutMs
22360
- });
22361
22607
  case "openai-compatible": {
22362
22608
  const c = config.ai.openaiCompatible;
22363
22609
  if (!c.baseUrl || !c.model) {
@@ -22373,6 +22619,8 @@ var buildOneProvider = (name, config, logger) => {
22373
22619
  ...c.apiKey ? { apiKey: c.apiKey } : {}
22374
22620
  });
22375
22621
  }
22622
+ default:
22623
+ throw new Error(`Unsupported AI provider: ${String(name)}`);
22376
22624
  }
22377
22625
  };
22378
22626
  var resolveActiveModel = (config) => {
@@ -22387,12 +22635,12 @@ var resolveActiveModel = (config) => {
22387
22635
  return config.ai.viettelNetmind.model;
22388
22636
  case "opencode-go":
22389
22637
  return config.ai.opencodeGo.model;
22390
- case "freemodel":
22391
- return config.ai.freemodel.model;
22392
22638
  case "openai-compatible":
22393
22639
  return config.ai.openaiCompatible.model ?? "openai-compatible";
22394
22640
  case "none":
22395
22641
  return "";
22642
+ default:
22643
+ throw new Error(`Unsupported AI provider: ${String(config.ai.provider)}`);
22396
22644
  }
22397
22645
  };
22398
22646
  var buildAiClient = (config, logger) => {
@@ -22451,7 +22699,8 @@ var buildContainer = async (options) => {
22451
22699
  ...options.aiOverrides?.numMaxFindings !== void 0 ? { numMaxFindings: options.aiOverrides.numMaxFindings } : {},
22452
22700
  timeoutMs: config.ai.timeoutMs,
22453
22701
  temperature: config.ai.temperature,
22454
- tokenBudgetWarn: config.ai.tokenBudgetWarn
22702
+ tokenBudgetWarn: config.ai.tokenBudgetWarn,
22703
+ adaptiveRetry: config.ai.adaptiveRetry
22455
22704
  });
22456
22705
  return async (rule, file, parsed, clusterContext, moduleContext) => aiExec(rule, file, parsed, clusterContext, moduleContext);
22457
22706
  })() : void 0;
@@ -22532,7 +22781,34 @@ var prReviewLayerSchema = external_exports.enum([
22532
22781
  ]);
22533
22782
  var ruleIdPattern = /^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/;
22534
22783
  var ruleIdSchema2 = external_exports.string().regex(ruleIdPattern, "Rule id must match `<scope>/<kebab-id>` (e.g. general/no-console-log)");
22535
- var codeReviewConfigSchema = external_exports.object({
22784
+ var migrateLegacyFreemodel = (value) => {
22785
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
22786
+ const root = value;
22787
+ const ai = typeof root.ai === "object" && root.ai !== null && !Array.isArray(root.ai) ? { ...root.ai } : null;
22788
+ const provider = typeof ai?.provider === "string" ? ai.provider : typeof root.aiProvider === "string" ? root.aiProvider : null;
22789
+ if (provider !== "freemodel") return value;
22790
+ const legacy = typeof ai?.freemodel === "object" && ai.freemodel !== null && !Array.isArray(ai.freemodel) ? ai.freemodel : {};
22791
+ const custom2 = typeof ai?.openaiCompatible === "object" && ai.openaiCompatible !== null && !Array.isArray(ai.openaiCompatible) ? ai.openaiCompatible : {};
22792
+ const fallback = Array.isArray(ai?.fallback) ? ai.fallback.map((item) => item === "freemodel" ? "openai-compatible" : item) : ai?.fallback;
22793
+ const { freemodel: _legacyFreemodel, ...aiWithoutLegacyProvider } = ai ?? {};
22794
+ return {
22795
+ ...root,
22796
+ aiProvider: "openai-compatible",
22797
+ ai: {
22798
+ ...aiWithoutLegacyProvider,
22799
+ provider: "openai-compatible",
22800
+ ...fallback !== void 0 ? { fallback } : {},
22801
+ openaiCompatible: {
22802
+ ...legacy,
22803
+ ...custom2,
22804
+ baseUrl: custom2.baseUrl ?? legacy.baseUrl ?? "https://api.freemodel.dev",
22805
+ model: custom2.model ?? legacy.model ?? "gpt-5.5",
22806
+ name: custom2.name ?? "freemodel-legacy"
22807
+ }
22808
+ }
22809
+ };
22810
+ };
22811
+ var codeReviewConfigObjectSchema = external_exports.object({
22536
22812
  mode: external_exports.enum(["auto", "economy", "balanced", "performance"]).default("auto"),
22537
22813
  include: external_exports.array(external_exports.string()).default([
22538
22814
  "**/*.ts",
@@ -22723,7 +22999,6 @@ var codeReviewConfigSchema = external_exports.object({
22723
22999
  "groq",
22724
23000
  "viettel-netmind",
22725
23001
  "opencode-go",
22726
- "freemodel",
22727
23002
  "openai-compatible",
22728
23003
  "none"
22729
23004
  ]).default("ollama"),
@@ -22734,7 +23009,6 @@ var codeReviewConfigSchema = external_exports.object({
22734
23009
  "groq",
22735
23010
  "viettel-netmind",
22736
23011
  "opencode-go",
22737
- "freemodel",
22738
23012
  "openai-compatible"
22739
23013
  ])
22740
23014
  ).default([]),
@@ -22742,6 +23016,17 @@ var codeReviewConfigSchema = external_exports.object({
22742
23016
  timeoutMs: external_exports.number().int().positive().default(18e4),
22743
23017
  tokenBudgetWarn: external_exports.number().int().positive().default(3e4),
22744
23018
  clusterTokenBudget: external_exports.number().int().positive().default(3e4),
23019
+ adaptiveRetry: external_exports.object({
23020
+ maxRetries: external_exports.number().int().min(0).max(3).default(1),
23021
+ contextReductionFactor: external_exports.number().min(0.25).max(0.95).default(0.75),
23022
+ timeoutMultiplier: external_exports.number().min(1.1).max(3).default(1.5),
23023
+ maxDelayMs: external_exports.number().int().min(0).max(3e4).default(5e3)
23024
+ }).default({
23025
+ maxRetries: 1,
23026
+ contextReductionFactor: 0.75,
23027
+ timeoutMultiplier: 1.5,
23028
+ maxDelayMs: 5e3
23029
+ }),
22745
23030
  /**
22746
23031
  * AI-resilience re-run ([ADR-0029]). After the main pass, AI rules whose
22747
23032
  * invocations were skipped for a RETRYABLE reason (provider down / parse
@@ -22781,7 +23066,7 @@ var codeReviewConfigSchema = external_exports.object({
22781
23066
  * default until M3 passes the repository's finding-quality gate.
22782
23067
  */
22783
23068
  viettelNetmind: external_exports.object({
22784
- baseUrl: external_exports.string().url().default("https://netmind.viettel.vn/gateway/v1"),
23069
+ baseUrl: external_exports.string().url().default("https://example.invalid/netmind/v1"),
22785
23070
  apiKey: external_exports.string().optional(),
22786
23071
  // Model access is team-scoped; `/models` is the source of truth.
22787
23072
  // M2.7 is the measured fast option but under-detected per-module
@@ -22789,7 +23074,7 @@ var codeReviewConfigSchema = external_exports.object({
22789
23074
  // remains opt-in until the same gate has measured its recall.
22790
23075
  model: external_exports.string().default("zai-org/GLM-4.7-cc")
22791
23076
  }).default({
22792
- baseUrl: "https://netmind.viettel.vn/gateway/v1",
23077
+ baseUrl: "https://example.invalid/netmind/v1",
22793
23078
  model: "zai-org/GLM-4.7-cc"
22794
23079
  }),
22795
23080
  opencodeGo: external_exports.object({
@@ -22800,14 +23085,6 @@ var codeReviewConfigSchema = external_exports.object({
22800
23085
  baseUrl: "https://opencode.ai/zen/go/v1",
22801
23086
  model: "qwen3.6-plus"
22802
23087
  }),
22803
- freemodel: external_exports.object({
22804
- baseUrl: external_exports.string().url().default("https://api.freemodel.dev"),
22805
- apiKey: external_exports.string().optional(),
22806
- model: external_exports.string().default("gpt-5.5")
22807
- }).default({
22808
- baseUrl: "https://api.freemodel.dev",
22809
- model: "gpt-5.5"
22810
- }),
22811
23088
  /**
22812
23089
  * Generic OpenAI-compatible escape hatch (LM Studio, vLLM, custom
22813
23090
  * self-hosted gateways, OpenRouter, Together, Anyscale, ...).
@@ -22827,16 +23104,21 @@ var codeReviewConfigSchema = external_exports.object({
22827
23104
  timeoutMs: 18e4,
22828
23105
  tokenBudgetWarn: 3e4,
22829
23106
  clusterTokenBudget: 3e4,
23107
+ adaptiveRetry: {
23108
+ maxRetries: 1,
23109
+ contextReductionFactor: 0.75,
23110
+ timeoutMultiplier: 1.5,
23111
+ maxDelayMs: 5e3
23112
+ },
22830
23113
  skipRerun: { maxPasses: 1, delayMs: 2e3 },
22831
23114
  ollama: { baseUrl: "http://localhost:11434", model: "qwen2.5-coder:7b", temperature: 0.1 },
22832
23115
  gemini: { model: "gemini-2.0-flash" },
22833
23116
  groq: { model: "llama-3.3-70b-versatile" },
22834
23117
  viettelNetmind: {
22835
- baseUrl: "https://netmind.viettel.vn/gateway/v1",
23118
+ baseUrl: "https://example.invalid/netmind/v1",
22836
23119
  model: "zai-org/GLM-4.7-cc"
22837
23120
  },
22838
23121
  opencodeGo: { baseUrl: "https://opencode.ai/zen/go/v1", model: "qwen3.6-plus" },
22839
- freemodel: { baseUrl: "https://api.freemodel.dev", model: "gpt-5.5" },
22840
23122
  openaiCompatible: { name: "openai-compatible" }
22841
23123
  }),
22842
23124
  report: external_exports.object({
@@ -23138,7 +23420,7 @@ var codeReviewConfigSchema = external_exports.object({
23138
23420
  * `${ENV_VAR}` interpolation for the token so secrets stay out of the file.
23139
23421
  */
23140
23422
  dashboard: external_exports.object({
23141
- /** Base URL of the @code-sentinel/server instance, e.g. `https://codesentinel.vtscloud.vn`. */
23423
+ /** Base URL of the @code-sentinel/server instance, e.g. `https://example.invalid/code-sentinel-dashboard`. */
23142
23424
  serverUrl: external_exports.string().url().optional(),
23143
23425
  /** Project-scoped bearer token for `POST /api/runs`. */
23144
23426
  token: external_exports.string().optional(),
@@ -23146,6 +23428,10 @@ var codeReviewConfigSchema = external_exports.object({
23146
23428
  projectId: external_exports.string().min(1).optional()
23147
23429
  }).default({})
23148
23430
  });
23431
+ var codeReviewConfigSchema = external_exports.preprocess(
23432
+ migrateLegacyFreemodel,
23433
+ codeReviewConfigObjectSchema
23434
+ );
23149
23435
 
23150
23436
  // src/config/load.ts
23151
23437
  var MODULE_NAME = "codereview";
@@ -23478,24 +23764,31 @@ var pathMatchesAnyGlob = (path, patterns) => {
23478
23764
  };
23479
23765
 
23480
23766
  // src/config/dashboard-defaults.ts
23481
- var DEFAULT_DASHBOARD_SERVER_URL = "https://codesentinel.vtscloud.vn";
23767
+ var DEFAULT_DASHBOARD_SERVER_URL = "https://example.invalid/code-sentinel-dashboard";
23482
23768
  var getDefaultDashboardServerUrl = () => process.env.CODE_SENTINEL_DASHBOARD_URL?.trim() || DEFAULT_DASHBOARD_SERVER_URL;
23483
23769
 
23484
23770
  // src/commands/push.command.ts
23485
23771
  var pushRunToServer = async (args) => {
23486
23772
  const doFetch = args.fetchFn ?? fetch;
23487
23773
  const url = `${args.serverUrl.replace(/\/+$/, "")}/api/runs`;
23488
- let res;
23489
- try {
23490
- res = await doFetch(url, {
23774
+ const send = () => {
23775
+ const token = args.getToken?.() ?? args.token;
23776
+ return doFetch(url, {
23491
23777
  method: "POST",
23492
23778
  headers: {
23493
23779
  "content-type": "application/json",
23494
- ...args.token !== void 0 ? { authorization: `Bearer ${args.token}` } : {},
23780
+ ...token !== void 0 ? { authorization: `Bearer ${token}` } : {},
23495
23781
  ...args.dto.status === "completed" ? { "idempotency-key": args.idempotencyKey ?? args.dto.id } : {}
23496
23782
  },
23497
23783
  body: JSON.stringify(args.dto)
23498
23784
  });
23785
+ };
23786
+ let res;
23787
+ try {
23788
+ res = await send();
23789
+ if (res.status === 401 && args.onUnauthorized && await args.onUnauthorized()) {
23790
+ res = await send();
23791
+ }
23499
23792
  } catch (e) {
23500
23793
  return err(new Error(`network error posting to ${url}: ${e.message}`));
23501
23794
  }
@@ -23538,6 +23831,8 @@ var pushReviewRunToServer = async (args) => {
23538
23831
  dto: finalDto,
23539
23832
  serverUrl: args.serverUrl,
23540
23833
  ...args.token !== void 0 ? { token: args.token } : {},
23834
+ ...args.getToken !== void 0 ? { getToken: args.getToken } : {},
23835
+ ...args.onUnauthorized !== void 0 ? { onUnauthorized: args.onUnauthorized } : {},
23541
23836
  ...args.run.status === "completed" ? { idempotencyKey: args.run.id } : {},
23542
23837
  ...args.fetchFn !== void 0 ? { fetchFn: args.fetchFn } : {}
23543
23838
  });
@@ -23563,12 +23858,28 @@ var runPush = async (options = {}, deps = {}) => {
23563
23858
  return EXIT.USAGE;
23564
23859
  }
23565
23860
  let token = options.token ?? config.dashboard.token ?? process.env.CODE_SENTINEL_DASHBOARD_TOKEN;
23861
+ let refreshDashboardCredential;
23566
23862
  if (!token && link && serverUrl === link.serverUrl) {
23567
23863
  try {
23568
- const credential = await createPlatformCredentialStore().read(link.serverUrl);
23569
- if (credential && (!credential.expiresAt || Date.parse(credential.expiresAt) > Date.now())) {
23570
- token = credential.accessToken;
23571
- }
23864
+ const store = createPlatformCredentialStore();
23865
+ const credential = await getAuthenticatedCredential({
23866
+ server: link.serverUrl,
23867
+ store
23868
+ });
23869
+ token = credential.accessToken;
23870
+ refreshDashboardCredential = async () => {
23871
+ try {
23872
+ const refreshed = await getAuthenticatedCredential({
23873
+ server: link.serverUrl,
23874
+ store,
23875
+ forceRefresh: true
23876
+ });
23877
+ token = refreshed.accessToken;
23878
+ return true;
23879
+ } catch {
23880
+ return false;
23881
+ }
23882
+ };
23572
23883
  } catch (error) {
23573
23884
  console.error(
23574
23885
  red(
@@ -23626,6 +23937,7 @@ var runPush = async (options = {}, deps = {}) => {
23626
23937
  projectId,
23627
23938
  serverUrl,
23628
23939
  ...token !== void 0 ? { token } : {},
23940
+ ...refreshDashboardCredential ? { getToken: () => token, onUnauthorized: refreshDashboardCredential } : {},
23629
23941
  ...link?.codebaseId ? { repositoryId: link.codebaseId } : {},
23630
23942
  ...reviewRequestId ? { reviewRequestId } : {},
23631
23943
  ...deps.fetchFn !== void 0 ? { fetchFn: deps.fetchFn } : {}
@@ -24071,13 +24383,13 @@ var createInkProgressRenderer = (opts) => {
24071
24383
  };
24072
24384
 
24073
24385
  // src/ui/ink/should-use-ink.ts
24074
- var shouldUseInkUi = (input3) => {
24075
- if (input3.noUi) return false;
24076
- if (input3.silent) return false;
24077
- if (!input3.isTty) return false;
24078
- const ci = (input3.ci ?? "").trim().toLowerCase();
24386
+ var shouldUseInkUi = (input4) => {
24387
+ if (input4.noUi) return false;
24388
+ if (input4.silent) return false;
24389
+ if (!input4.isTty) return false;
24390
+ const ci = (input4.ci ?? "").trim().toLowerCase();
24079
24391
  if (ci === "true" || ci === "1") return false;
24080
- if (input3.outputToStdout) return false;
24392
+ if (input4.outputToStdout) return false;
24081
24393
  return true;
24082
24394
  };
24083
24395
 
@@ -24275,23 +24587,23 @@ var isReviewableDiffPacket = (packet, excludes = DEFAULT_EXCLUDES) => {
24275
24587
  };
24276
24588
 
24277
24589
  // src/pr/hunk-chunker.ts
24278
- var chunkDiffHunks = (input3) => {
24279
- if (input3.maxChunks <= 0 || input3.hunks.length === 0) return [];
24590
+ var chunkDiffHunks = (input4) => {
24591
+ if (input4.maxChunks <= 0 || input4.hunks.length === 0) return [];
24280
24592
  const chunks = [];
24281
24593
  let current = [];
24282
24594
  let currentTokens = 0;
24283
- for (const hunk of input3.hunks) {
24284
- const tokens = input3.estimateTokens(hunk);
24285
- if (current.length > 0 && currentTokens + tokens > input3.tokenBudget) {
24595
+ for (const hunk of input4.hunks) {
24596
+ const tokens = input4.estimateTokens(hunk);
24597
+ if (current.length > 0 && currentTokens + tokens > input4.tokenBudget) {
24286
24598
  chunks.push(current);
24287
24599
  current = [];
24288
24600
  currentTokens = 0;
24289
- if (chunks.length >= input3.maxChunks) break;
24601
+ if (chunks.length >= input4.maxChunks) break;
24290
24602
  }
24291
24603
  current.push(hunk);
24292
24604
  currentTokens += tokens;
24293
24605
  }
24294
- if (current.length > 0 && chunks.length < input3.maxChunks) {
24606
+ if (current.length > 0 && chunks.length < input4.maxChunks) {
24295
24607
  chunks.push(current);
24296
24608
  }
24297
24609
  return chunks.map((hunks) => ({ hunks }));
@@ -24422,17 +24734,17 @@ var selectRulesForGroup = (group, profile, maxRules) => group.rules.filter((rule
24422
24734
  var strategyIncludesDiffReview = (strategy) => strategy === "adaptive" || strategy === "diff-only";
24423
24735
  var strategyIncludesGroupedReview = (strategy) => strategy === "adaptive" || strategy === "grouped";
24424
24736
  var strategyIncludesPerRuleReview = (strategy) => strategy === "targeted";
24425
- var buildAiReviewPlan = (input3) => {
24426
- const { config } = input3;
24737
+ var buildAiReviewPlan = (input4) => {
24738
+ const { config } = input4;
24427
24739
  const diffCalls = config.diffReview.enabled && strategyIncludesDiffReview(config.aiStrategy) ? chunkDiffHunks({
24428
- hunks: input3.packets.map(renderPrAgentHunks),
24740
+ hunks: input4.packets.map(renderPrAgentHunks),
24429
24741
  tokenBudget: config.diffChunkTokenBudget,
24430
24742
  maxChunks: Math.min(config.diffReview.maxChunkCalls, config.maxAiCalls),
24431
- estimateTokens: input3.estimateTokens
24743
+ estimateTokens: input4.estimateTokens
24432
24744
  }) : [];
24433
- const profiles = profilePrFiles(input3.sourceFiles, input3.packets, input3.diffFindings, config);
24745
+ const profiles = profilePrFiles(input4.sourceFiles, input4.packets, input4.diffFindings, config);
24434
24746
  const primaryProfiles = selectPrimaryProfiles(profiles, config);
24435
- const groups = collectPrRuleGroups(input3.rules);
24747
+ const groups = collectPrRuleGroups(input4.rules);
24436
24748
  const groupedCalls = [];
24437
24749
  const specializedCalls = [];
24438
24750
  let remaining = Math.max(0, config.maxAiCalls - diffCalls.length);
@@ -24513,8 +24825,8 @@ var renderGitLabCodeQualityReport = (findings2) => findings2.map((finding) => ({
24513
24825
  }
24514
24826
  }
24515
24827
  }));
24516
- var writeGitLabCodeQualityReport = async (findings2, root, output) => {
24517
- const path = resolve(root, output);
24828
+ var writeGitLabCodeQualityReport = async (findings2, root, output2) => {
24829
+ const path = resolve(root, output2);
24518
24830
  await mkdir(dirname(path), { recursive: true });
24519
24831
  await writeFile(path, JSON.stringify(renderGitLabCodeQualityReport(findings2), null, 2), "utf8");
24520
24832
  return path;
@@ -24633,15 +24945,15 @@ var decodePath = (segments) => {
24633
24945
  }
24634
24946
  };
24635
24947
  var isValidProjectPath = (value) => decodePath(value.split("/").filter((segment) => segment.length > 0)) === value;
24636
- var parseGitLabMrUrl = (input3) => {
24948
+ var parseGitLabMrUrl = (input4) => {
24637
24949
  let url;
24638
24950
  try {
24639
- url = new URL(input3);
24951
+ url = new URL(input4);
24640
24952
  } catch (e) {
24641
24953
  return err(
24642
24954
  new IOError(`Invalid GitLab MR URL: ${e.message}`, {
24643
24955
  cause: e,
24644
- context: { input: input3 }
24956
+ context: { input: input4 }
24645
24957
  })
24646
24958
  );
24647
24959
  }
@@ -24652,31 +24964,31 @@ var parseGitLabMrUrl = (input3) => {
24652
24964
  if (dashIndex <= 0) {
24653
24965
  return err(
24654
24966
  new IOError("Invalid GitLab MR URL: expected /<group>/<project>/-/merge_requests/<iid>", {
24655
- context: { input: input3 }
24967
+ context: { input: input4 }
24656
24968
  })
24657
24969
  );
24658
24970
  }
24659
24971
  const iidRaw = segments[dashIndex + 2];
24660
24972
  if (!iidRaw || !/^[1-9]\d*$/.test(iidRaw)) {
24661
24973
  return err(
24662
- new IOError(`Invalid GitLab MR iid: ${iidRaw ?? "<missing>"}`, { context: { input: input3 } })
24974
+ new IOError(`Invalid GitLab MR iid: ${iidRaw ?? "<missing>"}`, { context: { input: input4 } })
24663
24975
  );
24664
24976
  }
24665
24977
  const iid = Number.parseInt(iidRaw ?? "", 10);
24666
24978
  if (!Number.isInteger(iid) || iid < 1) {
24667
24979
  return err(
24668
- new IOError(`Invalid GitLab MR iid: ${iidRaw ?? "<missing>"}`, { context: { input: input3 } })
24980
+ new IOError(`Invalid GitLab MR iid: ${iidRaw ?? "<missing>"}`, { context: { input: input4 } })
24669
24981
  );
24670
24982
  }
24671
24983
  const projectPath = decodePath(segments.slice(0, dashIndex));
24672
24984
  if (!projectPath) {
24673
- return err(new IOError("Invalid GitLab project path encoding", { context: { input: input3 } }));
24985
+ return err(new IOError("Invalid GitLab project path encoding", { context: { input: input4 } }));
24674
24986
  }
24675
24987
  return ok({
24676
24988
  baseUrl: cleanBaseUrl(url.origin),
24677
24989
  projectPath,
24678
24990
  iid,
24679
- webUrl: input3
24991
+ webUrl: input4
24680
24992
  });
24681
24993
  };
24682
24994
  var resolveGitLabAutoTarget = (env = process.env) => {
@@ -25640,23 +25952,23 @@ var runWithConcurrency2 = async (tasks, limit) => {
25640
25952
  await Promise.all(workers);
25641
25953
  return results;
25642
25954
  };
25643
- var runDiffAiReview = async (input3) => {
25955
+ var runDiffAiReview = async (input4) => {
25644
25956
  const found = [];
25645
25957
  let succeeded = 0;
25646
25958
  let skipped = 0;
25647
- for (const [index2, call] of input3.calls.entries()) {
25648
- input3.onProgress?.({
25959
+ for (const [index2, call] of input4.calls.entries()) {
25960
+ input4.onProgress?.({
25649
25961
  phase: "PR AI diff review",
25650
25962
  detail: `chunk ${index2 + 1}`,
25651
25963
  done: index2,
25652
- total: input3.calls.length
25964
+ total: input4.calls.length
25653
25965
  });
25654
- const result = await input3.reviewer.review({
25655
- title: input3.mr.title,
25656
- description: input3.mr.description,
25966
+ const result = await input4.reviewer.review({
25967
+ title: input4.mr.title,
25968
+ description: input4.mr.description,
25657
25969
  hunks: call.hunks,
25658
- supportFiles: input3.supportFiles,
25659
- staticFindings: input3.staticFindings.slice(0, MAX_STATIC_FINDINGS_IN_DIFF_PROMPT).map((finding) => ({
25970
+ supportFiles: input4.supportFiles,
25971
+ staticFindings: input4.staticFindings.slice(0, MAX_STATIC_FINDINGS_IN_DIFF_PROMPT).map((finding) => ({
25660
25972
  ruleId: finding.ruleId,
25661
25973
  file: finding.file,
25662
25974
  line: finding.range.line,
@@ -25665,28 +25977,28 @@ var runDiffAiReview = async (input3) => {
25665
25977
  });
25666
25978
  if (!result.ok) {
25667
25979
  skipped += 1;
25668
- input3.logger.warn({ err: result.error.message }, "PR AI diff review skipped for one chunk");
25669
- input3.onProgress?.({
25980
+ input4.logger.warn({ err: result.error.message }, "PR AI diff review skipped for one chunk");
25981
+ input4.onProgress?.({
25670
25982
  phase: "PR AI diff review",
25671
25983
  detail: `chunk ${index2 + 1}`,
25672
25984
  done: index2 + 1,
25673
- total: input3.calls.length
25985
+ total: input4.calls.length
25674
25986
  });
25675
25987
  continue;
25676
25988
  }
25677
25989
  succeeded += 1;
25678
- found.push(...result.value.map((raw) => toAiFinding(input3.runId, raw)));
25679
- input3.onProgress?.({
25990
+ found.push(...result.value.map((raw) => toAiFinding(input4.runId, raw)));
25991
+ input4.onProgress?.({
25680
25992
  phase: "PR AI diff review",
25681
25993
  detail: `chunk ${index2 + 1}`,
25682
25994
  done: index2 + 1,
25683
- total: input3.calls.length
25995
+ total: input4.calls.length
25684
25996
  });
25685
25997
  }
25686
25998
  return { findings: found, succeeded, skipped };
25687
25999
  };
25688
26000
  var diffHunksForFile = (packets, filePath) => packets.filter((packet) => packet.newPath === filePath).map(renderPrAgentHunks);
25689
- var runGroupedAiReview = async (input3) => {
26001
+ var runGroupedAiReview = async (input4) => {
25690
26002
  const found = [];
25691
26003
  const stats = {};
25692
26004
  const record = (ruleIds, outcome) => {
@@ -25698,22 +26010,22 @@ var runGroupedAiReview = async (input3) => {
25698
26010
  };
25699
26011
  }
25700
26012
  };
25701
- for (const [index2, call] of input3.calls.entries()) {
26013
+ for (const [index2, call] of input4.calls.entries()) {
25702
26014
  const ruleIds = call.rules.map((rule) => rule.id);
25703
- input3.onProgress?.({
26015
+ input4.onProgress?.({
25704
26016
  phase: "PR AI grouped review",
25705
26017
  detail: call.profile.file.path,
25706
26018
  done: index2,
25707
- total: input3.calls.length
26019
+ total: input4.calls.length
25708
26020
  });
25709
- const result = await input3.reviewer.review({
26021
+ const result = await input4.reviewer.review({
25710
26022
  primaryFile: {
25711
26023
  path: call.profile.file.path,
25712
26024
  language: call.profile.file.language,
25713
26025
  content: call.profile.file.content
25714
26026
  },
25715
- diffHunks: diffHunksForFile(input3.packets, call.profile.file.path),
25716
- supportFiles: input3.supportFiles,
26027
+ diffHunks: diffHunksForFile(input4.packets, call.profile.file.path),
26028
+ supportFiles: input4.supportFiles,
25717
26029
  rules: call.rules.map((rule) => ({
25718
26030
  ruleId: rule.id,
25719
26031
  title: rule.title,
@@ -25723,34 +26035,34 @@ var runGroupedAiReview = async (input3) => {
25723
26035
  });
25724
26036
  if (!result.ok) {
25725
26037
  record(ruleIds, "skipped");
25726
- input3.logger.warn(
26038
+ input4.logger.warn(
25727
26039
  { groupId: call.groupId, file: call.profile.file.path, err: result.error.message },
25728
26040
  "PR grouped AI review skipped for one call"
25729
26041
  );
25730
- input3.onProgress?.({
26042
+ input4.onProgress?.({
25731
26043
  phase: "PR AI grouped review",
25732
26044
  detail: call.profile.file.path,
25733
26045
  done: index2 + 1,
25734
- total: input3.calls.length
26046
+ total: input4.calls.length
25735
26047
  });
25736
26048
  continue;
25737
26049
  }
25738
26050
  record(ruleIds, "succeeded");
25739
26051
  found.push(
25740
26052
  ...result.value.filter(
25741
- (raw) => raw.file === call.profile.file.path && getDiffLinePosition(input3.lineMap, raw.file, raw.range.line) !== void 0
25742
- ).map((raw) => toGroupedFinding(input3.runId, raw, input3.ruleById))
26053
+ (raw) => raw.file === call.profile.file.path && getDiffLinePosition(input4.lineMap, raw.file, raw.range.line) !== void 0
26054
+ ).map((raw) => toGroupedFinding(input4.runId, raw, input4.ruleById))
25743
26055
  );
25744
- input3.onProgress?.({
26056
+ input4.onProgress?.({
25745
26057
  phase: "PR AI grouped review",
25746
26058
  detail: call.profile.file.path,
25747
26059
  done: index2 + 1,
25748
- total: input3.calls.length
26060
+ total: input4.calls.length
25749
26061
  });
25750
26062
  }
25751
26063
  return { findings: found, stats };
25752
26064
  };
25753
- var runPerRuleAiReview = async (input3) => {
26065
+ var runPerRuleAiReview = async (input4) => {
25754
26066
  const found = [];
25755
26067
  const stats = {};
25756
26068
  let completed = 0;
@@ -25761,21 +26073,21 @@ var runPerRuleAiReview = async (input3) => {
25761
26073
  skipped: current.skipped + (outcome === "skipped" ? 1 : 0)
25762
26074
  };
25763
26075
  };
25764
- input3.onProgress?.({
26076
+ input4.onProgress?.({
25765
26077
  phase: "PR AI targeted review",
25766
- detail: input3.calls.length === 0 ? "no calls" : input3.calls[0]?.profile.file.path ?? "",
26078
+ detail: input4.calls.length === 0 ? "no calls" : input4.calls[0]?.profile.file.path ?? "",
25767
26079
  done: 0,
25768
- total: input3.calls.length
26080
+ total: input4.calls.length
25769
26081
  });
25770
- const tasks = input3.calls.map((call) => async () => {
25771
- const result = await input3.reviewer.review({
26082
+ const tasks = input4.calls.map((call) => async () => {
26083
+ const result = await input4.reviewer.review({
25772
26084
  primaryFile: {
25773
26085
  path: call.profile.file.path,
25774
26086
  language: call.profile.file.language,
25775
26087
  content: call.profile.file.content
25776
26088
  },
25777
- diffHunks: diffHunksForFile(input3.packets, call.profile.file.path),
25778
- supportFiles: input3.supportFiles,
26089
+ diffHunks: diffHunksForFile(input4.packets, call.profile.file.path),
26090
+ supportFiles: input4.supportFiles,
25779
26091
  rule: {
25780
26092
  ruleId: call.rule.id,
25781
26093
  title: call.rule.title,
@@ -25786,15 +26098,15 @@ var runPerRuleAiReview = async (input3) => {
25786
26098
  promptPath: call.rule.prompt
25787
26099
  });
25788
26100
  completed += 1;
25789
- input3.onProgress?.({
26101
+ input4.onProgress?.({
25790
26102
  phase: "PR AI targeted review",
25791
26103
  detail: `${call.profile.file.path} \xB7 ${call.rule.id}`,
25792
26104
  done: completed,
25793
- total: input3.calls.length
26105
+ total: input4.calls.length
25794
26106
  });
25795
26107
  if (!result.ok) {
25796
26108
  record(call.rule.id, "skipped");
25797
- input3.logger.warn(
26109
+ input4.logger.warn(
25798
26110
  { ruleId: call.rule.id, file: call.profile.file.path, err: result.error.message },
25799
26111
  "PR targeted AI review skipped for one call"
25800
26112
  );
@@ -25802,10 +26114,10 @@ var runPerRuleAiReview = async (input3) => {
25802
26114
  }
25803
26115
  record(call.rule.id, "succeeded");
25804
26116
  return result.value.filter(
25805
- (raw) => raw.file === call.profile.file.path && getDiffLinePosition(input3.lineMap, raw.file, raw.range.line) !== void 0
25806
- ).map((raw) => toPerRuleFinding(input3.runId, raw, input3.ruleById));
26117
+ (raw) => raw.file === call.profile.file.path && getDiffLinePosition(input4.lineMap, raw.file, raw.range.line) !== void 0
26118
+ ).map((raw) => toPerRuleFinding(input4.runId, raw, input4.ruleById));
25807
26119
  });
25808
- const settled = await runWithConcurrency2(tasks, input3.concurrency);
26120
+ const settled = await runWithConcurrency2(tasks, input4.concurrency);
25809
26121
  for (const findings2 of settled) found.push(...findings2);
25810
26122
  return { findings: found, stats };
25811
26123
  };
@@ -26467,9 +26779,9 @@ var runPrReview = async (options) => {
26467
26779
  };
26468
26780
 
26469
26781
  // src/review-profile.ts
26470
- var resolveReviewProfile = (input3) => {
26471
- const name = input3.requested ?? input3.configured.name;
26472
- const configured = input3.configured;
26782
+ var resolveReviewProfile = (input4) => {
26783
+ const name = input4.requested ?? input4.configured.name;
26784
+ const configured = input4.configured;
26473
26785
  if (name === "fast" && configured.name === "fast" && configured.ai !== "disabled") {
26474
26786
  return {
26475
26787
  ok: false,
@@ -26477,7 +26789,7 @@ var resolveReviewProfile = (input3) => {
26477
26789
  };
26478
26790
  }
26479
26791
  if (name === "fast") {
26480
- const gitFilter = input3.explicitGitFilter ?? { mode: "staged" };
26792
+ const gitFilter = input4.explicitGitFilter ?? { mode: "staged" };
26481
26793
  const scope = gitFilter.mode === "staged" ? "staged" : gitFilter.mode === "changed" ? "changed" : "range";
26482
26794
  return {
26483
26795
  ok: true,
@@ -26489,29 +26801,29 @@ var resolveReviewProfile = (input3) => {
26489
26801
  ai: "disabled",
26490
26802
  maxBudgetMs: configured.name === "fast" ? configured.maxBudgetMs : 5e3,
26491
26803
  gateCoverageLabel: "deterministic checks on selected changes; AI intentionally not run",
26492
- aiSkipReason: input3.aiOff ? "explicit --ai-off" : "fast profile policy"
26804
+ aiSkipReason: input4.aiOff ? "explicit --ai-off" : "fast profile policy"
26493
26805
  },
26494
26806
  gitFilter,
26495
26807
  noGraphCache: false,
26496
26808
  aiOff: true
26497
26809
  };
26498
26810
  }
26499
- if (input3.explicitGitFilter) {
26811
+ if (input4.explicitGitFilter) {
26500
26812
  return {
26501
26813
  ok: true,
26502
26814
  profile: {
26503
26815
  name: "deep",
26504
- fileScope: input3.explicitGitFilter.mode === "staged" ? "staged" : "range",
26816
+ fileScope: input4.explicitGitFilter.mode === "staged" ? "staged" : "range",
26505
26817
  deterministicRules: "required",
26506
26818
  graph: "full",
26507
- ai: input3.aiOff ? "disabled" : configured.ai,
26819
+ ai: input4.aiOff ? "disabled" : configured.ai,
26508
26820
  ...configured.maxBudgetMs ? { maxBudgetMs: configured.maxBudgetMs } : {},
26509
26821
  gateCoverageLabel: "configured deterministic checks on selected scope",
26510
- ...input3.aiOff ? { aiSkipReason: "explicit --ai-off" } : {}
26822
+ ...input4.aiOff ? { aiSkipReason: "explicit --ai-off" } : {}
26511
26823
  },
26512
- gitFilter: input3.explicitGitFilter,
26824
+ gitFilter: input4.explicitGitFilter,
26513
26825
  noGraphCache: true,
26514
- aiOff: input3.aiOff
26826
+ aiOff: input4.aiOff
26515
26827
  };
26516
26828
  }
26517
26829
  return {
@@ -26521,13 +26833,13 @@ var resolveReviewProfile = (input3) => {
26521
26833
  fileScope: "repository",
26522
26834
  deterministicRules: "required",
26523
26835
  graph: "full",
26524
- ai: input3.aiOff ? "disabled" : configured.ai,
26836
+ ai: input4.aiOff ? "disabled" : configured.ai,
26525
26837
  ...configured.maxBudgetMs ? { maxBudgetMs: configured.maxBudgetMs } : {},
26526
26838
  gateCoverageLabel: "configured deterministic checks across the repository",
26527
- ...input3.aiOff ? { aiSkipReason: "explicit --ai-off" } : {}
26839
+ ...input4.aiOff ? { aiSkipReason: "explicit --ai-off" } : {}
26528
26840
  },
26529
26841
  noGraphCache: true,
26530
- aiOff: input3.aiOff
26842
+ aiOff: input4.aiOff
26531
26843
  };
26532
26844
  };
26533
26845
 
@@ -28352,10 +28664,10 @@ var repositoryConfigFromLocalConfig = (config) => ({
28352
28664
  review: config.review,
28353
28665
  prReview: config.prReview
28354
28666
  });
28355
- var getLocalEffectiveConfig = async (input3) => {
28356
- const cwd = resolve(input3.path ?? process.cwd());
28667
+ var getLocalEffectiveConfig = async (input4) => {
28668
+ const cwd = resolve(input4.path ?? process.cwd());
28357
28669
  const loaded = await loadConfig(
28358
- input3.configPath === void 0 ? { cwd } : { cwd, configPath: input3.configPath }
28670
+ input4.configPath === void 0 ? { cwd } : { cwd, configPath: input4.configPath }
28359
28671
  );
28360
28672
  if (!loaded.ok) return { error: loaded.error.message };
28361
28673
  const effectiveConfig = repositoryConfigFromLocalConfig(loaded.value.config);
@@ -28394,17 +28706,10 @@ var runConfigEffective = async (options = {}) => {
28394
28706
  return EXIT.USAGE;
28395
28707
  }
28396
28708
  try {
28397
- const credential = await createPlatformCredentialStore().read(link.serverUrl);
28398
- if (!credential || credential.expiresAt && Date.parse(credential.expiresAt) <= Date.now()) {
28399
- writeError(
28400
- `Not authenticated with ${link.serverUrl}. Run \`cs auth login --server ${link.serverUrl}\`.`
28401
- );
28402
- return EXIT.USAGE;
28403
- }
28404
- const response = await createRemoteConfigClient({
28405
- serverUrl: link.serverUrl,
28406
- token: credential.accessToken
28407
- }).resolveConfig({
28709
+ const response = await (await createAuthenticatedRemoteClient({
28710
+ server: link.serverUrl,
28711
+ store: createPlatformCredentialStore()
28712
+ })).resolveConfig({
28408
28713
  schemaVersion: 1,
28409
28714
  projectId: link.projectId,
28410
28715
  codebaseId: link.codebaseId,
@@ -29619,15 +29924,15 @@ var decodeSegment = (value) => {
29619
29924
  return null;
29620
29925
  }
29621
29926
  };
29622
- var parseGitHubPullUrl = (input3) => {
29927
+ var parseGitHubPullUrl = (input4) => {
29623
29928
  let url;
29624
29929
  try {
29625
- url = new URL(input3);
29930
+ url = new URL(input4);
29626
29931
  } catch (e) {
29627
29932
  return err(
29628
29933
  new IOError(`Invalid GitHub PR URL: ${e.message}`, {
29629
29934
  cause: e,
29630
- context: { input: input3 }
29935
+ context: { input: input4 }
29631
29936
  })
29632
29937
  );
29633
29938
  }
@@ -29635,7 +29940,7 @@ var parseGitHubPullUrl = (input3) => {
29635
29940
  if (segments.length < 4 || segments[2] !== "pull") {
29636
29941
  return err(
29637
29942
  new IOError("Invalid GitHub PR URL: expected /<owner>/<repo>/pull/<number>", {
29638
- context: { input: input3 }
29943
+ context: { input: input4 }
29639
29944
  })
29640
29945
  );
29641
29946
  }
@@ -29643,18 +29948,18 @@ var parseGitHubPullUrl = (input3) => {
29643
29948
  const repo = decodeSegment(segments[1] ?? "");
29644
29949
  const pullNumberRaw = segments[3];
29645
29950
  if (!owner || !repo) {
29646
- return err(new IOError("Invalid GitHub repository path encoding", { context: { input: input3 } }));
29951
+ return err(new IOError("Invalid GitHub repository path encoding", { context: { input: input4 } }));
29647
29952
  }
29648
29953
  if (!pullNumberRaw || !/^[1-9]\d*$/.test(pullNumberRaw)) {
29649
29954
  return err(
29650
29955
  new IOError(`Invalid GitHub PR number: ${pullNumberRaw ?? "<missing>"}`, {
29651
- context: { input: input3 }
29956
+ context: { input: input4 }
29652
29957
  })
29653
29958
  );
29654
29959
  }
29655
29960
  const pullNumber = Number.parseInt(pullNumberRaw, 10);
29656
29961
  if (!Number.isInteger(pullNumber) || pullNumber < 1) {
29657
- return err(new IOError(`Invalid GitHub PR number: ${pullNumberRaw}`, { context: { input: input3 } }));
29962
+ return err(new IOError(`Invalid GitHub PR number: ${pullNumberRaw}`, { context: { input: input4 } }));
29658
29963
  }
29659
29964
  const baseUrl = cleanBaseUrl2(url.origin);
29660
29965
  return ok({
@@ -29663,7 +29968,7 @@ var parseGitHubPullUrl = (input3) => {
29663
29968
  repo,
29664
29969
  pullNumber,
29665
29970
  cloneUrl: `${baseUrl}/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}.git`,
29666
- webUrl: input3
29971
+ webUrl: input4
29667
29972
  });
29668
29973
  };
29669
29974
 
@@ -30737,12 +31042,7 @@ var runProjectStatus = async (options = {}) => {
30737
31042
  var credentialStore2 = () => createPlatformCredentialStore();
30738
31043
  var authenticatedClient2 = async (server, store) => {
30739
31044
  const origin = new URL(server).origin;
30740
- const credential = await store.read(origin);
30741
- if (!credential) throw new Error("Not authenticated. Run `cs auth login --server <url>`.");
30742
- if (credential.expiresAt && Date.parse(credential.expiresAt) <= Date.now()) {
30743
- throw new Error("Credential expired. Run `cs auth login --server <url>`.");
30744
- }
30745
- return createRemoteConfigClient({ serverUrl: origin, token: credential.accessToken });
31045
+ return createAuthenticatedRemoteClient({ server: origin, store });
30746
31046
  };
30747
31047
  var runProjectList = async (options) => {
30748
31048
  const write = options.write ?? console.log;
@@ -30773,7 +31073,7 @@ var canonicalRepositoryUrl = (value) => {
30773
31073
  return null;
30774
31074
  }
30775
31075
  };
30776
- var workspaceFingerprint = (input3) => createHash("sha256").update(JSON.stringify(input3)).digest("hex");
31076
+ var workspaceFingerprint = (input4) => createHash("sha256").update(JSON.stringify(input4)).digest("hex");
30777
31077
  var suggestedIdentifier = (canonicalRemote) => {
30778
31078
  const lastPath = canonicalRemote.split("/").filter(Boolean).at(-1) ?? "project";
30779
31079
  return lastPath.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}", "gu"), "").replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 128) || "project";
@@ -30914,19 +31214,12 @@ var aiProviderConfigKey = (provider) => {
30914
31214
  case "ollama":
30915
31215
  case "gemini":
30916
31216
  case "groq":
30917
- case "freemodel":
30918
31217
  return provider;
30919
31218
  default:
30920
31219
  return null;
30921
31220
  }
30922
31221
  };
30923
- var LOCAL_API_KEY_PROVIDERS = /* @__PURE__ */ new Set([
30924
- "gemini",
30925
- "groq",
30926
- "viettel-netmind",
30927
- "opencode-go",
30928
- "freemodel"
30929
- ]);
31222
+ var LOCAL_API_KEY_PROVIDERS = /* @__PURE__ */ new Set(["gemini", "groq", "viettel-netmind", "opencode-go"]);
30930
31223
  var providerUsesLocalApiKey = (provider) => LOCAL_API_KEY_PROVIDERS.has(provider);
30931
31224
  var mergeIfMissing = (target, key, value) => {
30932
31225
  if (value !== void 0 && target[key] === void 0) target[key] = value;
@@ -30964,8 +31257,8 @@ var materializeDashboardRuntimeConfig = (config) => {
30964
31257
  mergeIfMissing(report2, "output", config.reportOutput);
30965
31258
  if (Object.keys(report2).length > 0) config.report = report2;
30966
31259
  };
30967
- var dashboardPolicyToLocalConfig = (input3) => {
30968
- const config = { ...unwrapProjectReviewConfig(input3.value) };
31260
+ var dashboardPolicyToLocalConfig = (input4) => {
31261
+ const config = { ...unwrapProjectReviewConfig(input4.value) };
30969
31262
  materializeDashboardRuntimeConfig(config);
30970
31263
  for (const key of [
30971
31264
  "schemaVersion",
@@ -30987,8 +31280,8 @@ var dashboardPolicyToLocalConfig = (input3) => {
30987
31280
  }
30988
31281
  return {
30989
31282
  dashboard: {
30990
- projectId: input3.projectId,
30991
- serverUrl: new URL(input3.server).origin
31283
+ projectId: input4.projectId,
31284
+ serverUrl: new URL(input4.server).origin
30992
31285
  },
30993
31286
  ...config
30994
31287
  };
@@ -31267,14 +31560,14 @@ var hasGitRepository = async (cwd) => {
31267
31560
  return false;
31268
31561
  }
31269
31562
  };
31270
- var getLocalReadiness = async (input3 = {}) => {
31271
- const root = resolve(input3.path ?? process.cwd());
31563
+ var getLocalReadiness = async (input4 = {}) => {
31564
+ const root = resolve(input4.path ?? process.cwd());
31272
31565
  const [project, isGitRepository, config] = await Promise.all([
31273
- input3.projectStatus ? input3.projectStatus() : getLocalProjectStatus(root),
31274
- input3.gitRepository ? input3.gitRepository() : hasGitRepository(root),
31566
+ input4.projectStatus ? input4.projectStatus() : getLocalProjectStatus(root),
31567
+ input4.gitRepository ? input4.gitRepository() : hasGitRepository(root),
31275
31568
  getLocalEffectiveConfig({
31276
31569
  path: root,
31277
- ...input3.configPath ? { configPath: input3.configPath } : {}
31570
+ ...input4.configPath ? { configPath: input4.configPath } : {}
31278
31571
  })
31279
31572
  ]);
31280
31573
  const checks = [
@@ -31483,12 +31776,10 @@ var runReport = async (options) => {
31483
31776
  };
31484
31777
  var remoteClient = async (server) => {
31485
31778
  const origin = new URL(server).origin;
31486
- const credential = await createPlatformCredentialStore().read(origin);
31487
- if (!credential) throw new Error("Not authenticated. Run `cs auth login`.");
31488
- if (credential.expiresAt && Date.parse(credential.expiresAt) <= Date.now()) {
31489
- throw new Error("Credential expired. Run `cs auth login`.");
31490
- }
31491
- return createRemoteConfigClient({ serverUrl: origin, token: credential.accessToken });
31779
+ return createAuthenticatedRemoteClient({
31780
+ server: origin,
31781
+ store: createPlatformCredentialStore()
31782
+ });
31492
31783
  };
31493
31784
  var linkedContext = async (path) => {
31494
31785
  const link = await new FileWorkspaceLinkStore(resolve(path ?? process.cwd())).read();
@@ -31550,9 +31841,9 @@ var runResultsExport = async (options) => {
31550
31841
  const client = options.client ?? await remoteClient(server);
31551
31842
  const exported = await client.exportRun(options.runId, options.format);
31552
31843
  if (options.output) {
31553
- const output = resolve(options.path ?? process.cwd(), options.output);
31554
- await writeFile(output, exported.content, "utf8");
31555
- write(`Exported Dashboard run ${options.runId} to ${output}.`);
31844
+ const output2 = resolve(options.path ?? process.cwd(), options.output);
31845
+ await writeFile(output2, exported.content, "utf8");
31846
+ write(`Exported Dashboard run ${options.runId} to ${output2}.`);
31556
31847
  } else {
31557
31848
  process.stdout.write(exported.content);
31558
31849
  }
@@ -31933,12 +32224,12 @@ var createRunnerLogPoster = (serverUrl, job) => {
31933
32224
  };
31934
32225
  return { log: log3, flush };
31935
32226
  };
31936
- var forwardChildOutput = (stream, output, logPoster, logStream) => {
32227
+ var forwardChildOutput = (stream, output2, logPoster, logStream) => {
31937
32228
  if (!stream) return;
31938
32229
  let buffered = "";
31939
32230
  stream.on("data", (chunk) => {
31940
32231
  const text2 = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
31941
- output.write(text2);
32232
+ output2.write(text2);
31942
32233
  buffered += text2;
31943
32234
  const lines = buffered.split(/\r?\n/);
31944
32235
  buffered = lines.pop() ?? "";
@@ -32128,7 +32419,7 @@ var RUNNER_PROCESS_ENV_ALLOWLIST = [
32128
32419
  "NO_COLOR",
32129
32420
  "CODE_SENTINEL_NETMIND_MIN_REQUEST_INTERVAL_MS"
32130
32421
  ];
32131
- var createRunnerChildEnv = (parentEnv, input3) => {
32422
+ var createRunnerChildEnv = (parentEnv, input4) => {
32132
32423
  const env = {};
32133
32424
  for (const key of RUNNER_PROCESS_ENV_ALLOWLIST) {
32134
32425
  if (parentEnv[key] !== void 0) env[key] = parentEnv[key];
@@ -32137,15 +32428,15 @@ var createRunnerChildEnv = (parentEnv, input3) => {
32137
32428
  ...env,
32138
32429
  CI: parentEnv.CI ?? "true",
32139
32430
  CODE_SENTINEL_CONFIG_FILE: "",
32140
- CODE_SENTINEL_SOURCE_WORKDIR: input3.workspace,
32141
- CODE_SENTINEL_DASHBOARD_URL: input3.serverUrl,
32142
- CODE_SENTINEL_DASHBOARD_TOKEN: input3.jobToken,
32143
- CODE_SENTINEL_PROJECT_ID: input3.projectId,
32144
- CODE_SENTINEL_REVIEW_REQUEST_ID: input3.requestId,
32145
- CODE_SENTINEL_RUNTIME_DIR: input3.runtimeDir,
32146
- CODE_SENTINEL_RUNTIME_STATE_FILE: join(input3.runtimeDir, "runtime.env"),
32147
- ...input3.runtimeAiConfigB64 ? { CODE_SENTINEL_RUNTIME_AI_CONFIG_B64: input3.runtimeAiConfigB64 } : {},
32148
- ...input3.cacheDbPath ? { CODE_SENTINEL_STORAGE_DB_PATH: input3.cacheDbPath } : {}
32431
+ CODE_SENTINEL_SOURCE_WORKDIR: input4.workspace,
32432
+ CODE_SENTINEL_DASHBOARD_URL: input4.serverUrl,
32433
+ CODE_SENTINEL_DASHBOARD_TOKEN: input4.jobToken,
32434
+ CODE_SENTINEL_PROJECT_ID: input4.projectId,
32435
+ CODE_SENTINEL_REVIEW_REQUEST_ID: input4.requestId,
32436
+ CODE_SENTINEL_RUNTIME_DIR: input4.runtimeDir,
32437
+ CODE_SENTINEL_RUNTIME_STATE_FILE: join(input4.runtimeDir, "runtime.env"),
32438
+ ...input4.runtimeAiConfigB64 ? { CODE_SENTINEL_RUNTIME_AI_CONFIG_B64: input4.runtimeAiConfigB64 } : {},
32439
+ ...input4.cacheDbPath ? { CODE_SENTINEL_STORAGE_DB_PATH: input4.cacheDbPath } : {}
32149
32440
  };
32150
32441
  };
32151
32442
  var runJob = async (serverUrl, job, options) => {
@@ -32258,25 +32549,6 @@ var runServerRunner = async (options = {}) => {
32258
32549
  await Promise.allSettled(active);
32259
32550
  return EXIT.SUCCESS;
32260
32551
  };
32261
- var loadDotenv = (options = {}) => {
32262
- if (options.skipFsLoad) return { loaded: [] };
32263
- const cwd = options.cwd ?? process.cwd();
32264
- const candidates = [resolve(cwd, ".env"), resolve(cwd, ".env.local")];
32265
- const loaded = [];
32266
- const merged = {};
32267
- for (const path of candidates) {
32268
- if (!existsSync(path)) continue;
32269
- const text2 = readFileSync(path, "utf8");
32270
- Object.assign(merged, parse(text2));
32271
- loaded.push(path);
32272
- }
32273
- for (const [key, value] of Object.entries(merged)) {
32274
- if (process.env[key] === void 0) {
32275
- process.env[key] = value;
32276
- }
32277
- }
32278
- return { loaded };
32279
- };
32280
32552
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
32281
32553
  var FETCH_TIMEOUT_MS = 1200;
32282
32554
  var truthy = (value) => value === "1" || value === "true" || value === "yes" || value === "on";
@@ -32326,6 +32598,14 @@ var fetchLatestVersion = async (packageName) => {
32326
32598
  clearTimeout(timeout);
32327
32599
  }
32328
32600
  };
32601
+ var checkLatestVersion = async (input4) => {
32602
+ const latest = await fetchLatestVersion(input4.packageName);
32603
+ return {
32604
+ current: input4.currentVersion,
32605
+ latest,
32606
+ updateAvailable: latest ? isNewerVersion(latest, input4.currentVersion) : false
32607
+ };
32608
+ };
32329
32609
  var printUpdateMessage = (packageName, current, latest) => {
32330
32610
  process.stderr.write(
32331
32611
  [
@@ -32368,6 +32648,98 @@ var maybeNotifyUpdate = async (options) => {
32368
32648
  printUpdateMessage(options.packageName, options.currentVersion, latest);
32369
32649
  }
32370
32650
  };
32651
+
32652
+ // src/commands/update.command.ts
32653
+ var updateCommand = (packageName, tag) => {
32654
+ const packageSpec = `${packageName}@${tag}`;
32655
+ const npmExecPath = process.env.npm_execpath;
32656
+ if (npmExecPath) return [process.execPath, [npmExecPath, "install", "-g", packageSpec]];
32657
+ return ["npm", ["install", "-g", packageSpec]];
32658
+ };
32659
+ var runProcess = (command, args) => new Promise((resolveRun) => {
32660
+ const child = spawn(command, args, { stdio: "inherit" });
32661
+ child.on("error", () => resolveRun(EXIT.RUNTIME));
32662
+ child.on("close", (code2) => resolveRun(code2 ?? EXIT.RUNTIME));
32663
+ });
32664
+ var askYes = async (question) => {
32665
+ const rl = createInterface({ input: stdin, output: stdout });
32666
+ try {
32667
+ const answer = (await rl.question(`${question} [y/N]: `)).trim().toLowerCase();
32668
+ return answer === "y" || answer === "yes";
32669
+ } finally {
32670
+ rl.close();
32671
+ }
32672
+ };
32673
+ var runUpdate = async (options) => {
32674
+ const tag = options.tag ?? "latest";
32675
+ if (options.privatePackage || !options.packageName || options.packageName === "@code-sentinel/cli") {
32676
+ if (options.json) {
32677
+ console.log(
32678
+ JSON.stringify({
32679
+ ok: false,
32680
+ error: "update_not_available",
32681
+ packageName: options.packageName
32682
+ })
32683
+ );
32684
+ } else {
32685
+ console.error(
32686
+ "This build is not an installable npm CLI package. Update from the release source you used."
32687
+ );
32688
+ }
32689
+ return EXIT.USAGE;
32690
+ }
32691
+ const latest = await checkLatestVersion({
32692
+ packageName: options.packageName,
32693
+ currentVersion: options.currentVersion
32694
+ });
32695
+ if (options.json) {
32696
+ console.log(
32697
+ JSON.stringify({
32698
+ packageName: options.packageName,
32699
+ current: latest.current,
32700
+ latest: latest.latest,
32701
+ updateAvailable: latest.updateAvailable
32702
+ })
32703
+ );
32704
+ } else if (!latest.latest) {
32705
+ console.log(`Could not check npm for ${options.packageName}.`);
32706
+ } else if (latest.updateAvailable) {
32707
+ console.log(`${options.packageName} ${latest.current} -> ${latest.latest} is available.`);
32708
+ } else {
32709
+ console.log(`${options.packageName} is up to date (${latest.current}).`);
32710
+ }
32711
+ if (options.check) return latest.latest ? EXIT.SUCCESS : EXIT.RUNTIME;
32712
+ if (latest.latest && !isNewerVersion(latest.latest, options.currentVersion)) return EXIT.SUCCESS;
32713
+ if (!options.yes) {
32714
+ if (!process.stdin.isTTY) {
32715
+ console.error("Use --yes to run npm install from a non-interactive shell.");
32716
+ return EXIT.USAGE;
32717
+ }
32718
+ const confirmed = await askYes(`Run npm install -g ${options.packageName}@${tag}?`);
32719
+ if (!confirmed) return EXIT.SUCCESS;
32720
+ }
32721
+ const [command, args] = updateCommand(options.packageName, tag);
32722
+ return runProcess(command, args);
32723
+ };
32724
+ var loadDotenv = (options = {}) => {
32725
+ if (options.skipFsLoad) return { loaded: [] };
32726
+ const cwd = options.cwd ?? process.cwd();
32727
+ const candidates = [resolve(cwd, ".env"), resolve(cwd, ".env.local")];
32728
+ const loaded = [];
32729
+ const merged = {};
32730
+ for (const path of candidates) {
32731
+ if (!existsSync(path)) continue;
32732
+ const text2 = readFileSync(path, "utf8");
32733
+ Object.assign(merged, parse(text2));
32734
+ loaded.push(path);
32735
+ }
32736
+ for (const [key, value] of Object.entries(merged)) {
32737
+ if (process.env[key] === void 0) {
32738
+ process.env[key] = value;
32739
+ }
32740
+ }
32741
+ return { loaded };
32742
+ };
32371
32743
  var DEFAULT_HOST = "0.0.0.0";
32372
32744
  var DEFAULT_PORT = 8787;
32373
32745
  var DEFAULT_PATH = "/webhooks/gitlab";
@@ -32388,7 +32760,7 @@ var outputForJob = (reviewRoot, outputRoot, job) => {
32388
32760
  return resolve(reviewRoot, outputRoot, `${eventPart}-${mrPart}`, "code-sentinel.md");
32389
32761
  };
32390
32762
  var toReviewOptions = (job, options) => {
32391
- const output = outputForJob(options.reviewRoot, options.outputRoot ?? DEFAULT_OUTPUT_ROOT, job);
32763
+ const output2 = outputForJob(options.reviewRoot, options.outputRoot ?? DEFAULT_OUTPUT_ROOT, job);
32392
32764
  return {
32393
32765
  invocationRoot: options.reviewRoot,
32394
32766
  pr: job.mrUrl,
@@ -32398,7 +32770,7 @@ var toReviewOptions = (job, options) => {
32398
32770
  silent: true,
32399
32771
  noUi: true,
32400
32772
  reportFormat: options.reportFormat ?? "both",
32401
- output,
32773
+ output: output2,
32402
32774
  ...options.minSeverity ? { minSeverity: options.minSeverity } : {},
32403
32775
  ...options.minConfidence !== void 0 ? { minConfidence: options.minConfidence } : {}
32404
32776
  };
@@ -32831,7 +33203,6 @@ var runWizard = async (deps = {}) => {
32831
33203
  aiProvider = await p.select({
32832
33204
  message: "AI provider:",
32833
33205
  choices: [
32834
- { name: "FreeModel (cloud, gpt-5.5)", value: "freemodel" },
32835
33206
  { name: "Ollama (local)", value: "ollama" },
32836
33207
  { name: "Gemini", value: "gemini" },
32837
33208
  { name: "Groq", value: "groq" },
@@ -32839,7 +33210,7 @@ var runWizard = async (deps = {}) => {
32839
33210
  { name: "OpenCode Go", value: "opencode-go" },
32840
33211
  { name: "OpenAI-compatible custom URL", value: "openai-compatible" }
32841
33212
  ],
32842
- default: "freemodel"
33213
+ default: "ollama"
32843
33214
  });
32844
33215
  const defaults2 = providerDefaults[aiProvider];
32845
33216
  if (defaults2.needsBaseUrl) {
@@ -32922,7 +33293,7 @@ var runWizard = async (deps = {}) => {
32922
33293
  };
32923
33294
  var wizardAnswersToReviewOptions = (answers) => {
32924
33295
  const path = normalizeWizardPath(answers.path);
32925
- const output = normalizeWizardPath(answers.reportOutput);
33296
+ const output2 = normalizeWizardPath(answers.reportOutput);
32926
33297
  const base = {
32927
33298
  path,
32928
33299
  aiOff: !answers.aiOn,
@@ -32930,7 +33301,7 @@ var wizardAnswersToReviewOptions = (answers) => {
32930
33301
  ...answers.aiTimeoutSeconds !== void 0 ? { aiTimeoutMs: answers.aiTimeoutSeconds * 1e3 } : {},
32931
33302
  reportFormat: answers.reportFormat,
32932
33303
  scope: answers.scope,
32933
- ...output.length > 0 ? { output } : {},
33304
+ ...output2.length > 0 ? { output: output2 } : {},
32934
33305
  ...answers.reviewTarget === "gitlab-pr" && answers.pr ? {
32935
33306
  pr: normalizeWizardPath(answers.pr),
32936
33307
  ...answers.post === true ? { post: true } : {},
@@ -32942,7 +33313,7 @@ var wizardAnswersToReviewOptions = (answers) => {
32942
33313
  return answers.reportStyle === "compact" ? { ...base, compact: true } : { ...base, full: true };
32943
33314
  };
32944
33315
  var wizardAnswersToInitConfig = (answers) => {
32945
- const provider = answers.aiOn ? answers.aiProvider ?? "freemodel" : "none";
33316
+ const provider = answers.aiOn ? answers.aiProvider ?? "ollama" : "none";
32946
33317
  const ai = {
32947
33318
  provider,
32948
33319
  fallback: parseFallbackProviders(answers.aiFallback),
@@ -33040,13 +33411,6 @@ var providerDefaults = {
33040
33411
  needsApiKey: false,
33041
33412
  needsBaseUrl: true
33042
33413
  },
33043
- freemodel: {
33044
- model: "gpt-5.5",
33045
- baseUrl: "https://api.freemodel.dev",
33046
- apiKeyEnv: "FREEMODEL_API_KEY",
33047
- needsApiKey: true,
33048
- needsBaseUrl: true
33049
- },
33050
33414
  gemini: {
33051
33415
  model: "gemini-2.0-flash",
33052
33416
  baseUrl: "",
@@ -33063,7 +33427,7 @@ var providerDefaults = {
33063
33427
  },
33064
33428
  "viettel-netmind": {
33065
33429
  model: "zai-org/GLM-4.7-cc",
33066
- baseUrl: "https://netmind.viettel.vn/gateway/v1",
33430
+ baseUrl: "https://example.invalid/netmind/v1",
33067
33431
  apiKeyEnv: "LLM_API_KEY",
33068
33432
  needsApiKey: true,
33069
33433
  needsBaseUrl: true
@@ -33078,8 +33442,8 @@ var providerDefaults = {
33078
33442
  "openai-compatible": {
33079
33443
  model: "mistral-7b-instruct",
33080
33444
  baseUrl: "http://localhost:8080/v1",
33081
- apiKeyEnv: "",
33082
- needsApiKey: false,
33445
+ apiKeyEnv: "CUSTOM_AI_API_KEY",
33446
+ needsApiKey: true,
33083
33447
  needsBaseUrl: true
33084
33448
  }
33085
33449
  };
@@ -33142,6 +33506,17 @@ var buildProgram = () => {
33142
33506
  `Code Sentinel ${BUILD_METADATA.version} (${BUILD_METADATA.gitSha}, ${BUILD_METADATA.buildTimestamp}; config ${BUILD_METADATA.configSchemaRange})`
33143
33507
  );
33144
33508
  });
33509
+ 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) => {
33510
+ process.exitCode = await runUpdate({
33511
+ packageName: pkg.name ?? "code-sentinel",
33512
+ currentVersion: VERSION,
33513
+ privatePackage: pkg.private === true,
33514
+ check: opts.check === true,
33515
+ yes: opts.yes === true,
33516
+ tag: opts.tag,
33517
+ json: opts.json === true
33518
+ });
33519
+ });
33145
33520
  const auth = program.command("auth").description("Authenticate this CLI with Code Sentinel");
33146
33521
  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) => {
33147
33522
  process.exitCode = await runAuthLogin({