@mcoda/mswarm 0.1.135-codali.41 → 0.1.135-codali.47

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 (135) hide show
  1. package/dist/vendor/codali/cli/TerminalCommand.js +2 -2
  2. package/dist/vendor/codali/cli/tui/TerminalPresentation.js +1 -1
  3. package/dist/vendor/codali/config/OrchestrationConfig.d.ts +1 -0
  4. package/dist/vendor/codali/config/OrchestrationConfig.d.ts.map +1 -1
  5. package/dist/vendor/codali/config/OrchestrationConfig.js +3 -1
  6. package/dist/vendor/codali/docdex/DocdexClient.d.ts +11 -0
  7. package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -1
  8. package/dist/vendor/codali/docdex/DocdexClient.js +55 -1
  9. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts +5 -0
  10. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts.map +1 -1
  11. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.js +63 -0
  12. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.js +2 -2
  13. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.js +2 -2
  14. package/dist/vendor/codali/permissions/PermissionGate.d.ts +7 -0
  15. package/dist/vendor/codali/permissions/PermissionGate.d.ts.map +1 -1
  16. package/dist/vendor/codali/permissions/PermissionGate.js +27 -1
  17. package/dist/vendor/codali/providers/ClaudeCliProvider.d.ts.map +1 -1
  18. package/dist/vendor/codali/providers/ClaudeCliProvider.js +1 -0
  19. package/dist/vendor/codali/providers/CodexCliProvider.d.ts.map +1 -1
  20. package/dist/vendor/codali/providers/CodexCliProvider.js +1 -0
  21. package/dist/vendor/codali/providers/ConfiguredProvider.d.ts +2 -0
  22. package/dist/vendor/codali/providers/ConfiguredProvider.d.ts.map +1 -1
  23. package/dist/vendor/codali/providers/ConfiguredProvider.js +29 -0
  24. package/dist/vendor/codali/providers/ModelServiceError.d.ts +16 -2
  25. package/dist/vendor/codali/providers/ModelServiceError.d.ts.map +1 -1
  26. package/dist/vendor/codali/providers/ModelServiceError.js +18 -1
  27. package/dist/vendor/codali/providers/OllamaRemoteProvider.d.ts.map +1 -1
  28. package/dist/vendor/codali/providers/OllamaRemoteProvider.js +1 -0
  29. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  30. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +4 -0
  31. package/dist/vendor/codali/providers/ProviderTypes.d.ts +4 -0
  32. package/dist/vendor/codali/providers/ProviderTypes.d.ts.map +1 -1
  33. package/dist/vendor/codali/runtime/AnswerEdits.d.ts +39 -0
  34. package/dist/vendor/codali/runtime/AnswerEdits.d.ts.map +1 -0
  35. package/dist/vendor/codali/runtime/AnswerEdits.js +134 -0
  36. package/dist/vendor/codali/runtime/AnswerVerification.d.ts.map +1 -1
  37. package/dist/vendor/codali/runtime/AnswerVerification.js +4 -2
  38. package/dist/vendor/codali/runtime/AuditGuards.d.ts +41 -0
  39. package/dist/vendor/codali/runtime/AuditGuards.d.ts.map +1 -0
  40. package/dist/vendor/codali/runtime/AuditGuards.js +81 -0
  41. package/dist/vendor/codali/runtime/CompletionReport.d.ts +4 -2
  42. package/dist/vendor/codali/runtime/CompletionReport.d.ts.map +1 -1
  43. package/dist/vendor/codali/runtime/CompletionReport.js +8 -3
  44. package/dist/vendor/codali/runtime/ContextCompression.d.ts +5 -0
  45. package/dist/vendor/codali/runtime/ContextCompression.d.ts.map +1 -1
  46. package/dist/vendor/codali/runtime/ContextCompression.js +16 -4
  47. package/dist/vendor/codali/runtime/DeliveryDocs.d.ts +21 -0
  48. package/dist/vendor/codali/runtime/DeliveryDocs.d.ts.map +1 -0
  49. package/dist/vendor/codali/runtime/DeliveryDocs.js +148 -0
  50. package/dist/vendor/codali/runtime/FigureCheck.d.ts +61 -2
  51. package/dist/vendor/codali/runtime/FigureCheck.d.ts.map +1 -1
  52. package/dist/vendor/codali/runtime/FigureCheck.js +210 -14
  53. package/dist/vendor/codali/runtime/GatewayRequest.d.ts +13 -0
  54. package/dist/vendor/codali/runtime/GatewayRequest.d.ts.map +1 -1
  55. package/dist/vendor/codali/runtime/GatewayRequest.js +54 -1
  56. package/dist/vendor/codali/runtime/InspectionConvergence.d.ts +4 -0
  57. package/dist/vendor/codali/runtime/InspectionConvergence.d.ts.map +1 -1
  58. package/dist/vendor/codali/runtime/InspectionConvergence.js +24 -1
  59. package/dist/vendor/codali/runtime/InteractionContract.d.ts +15 -0
  60. package/dist/vendor/codali/runtime/InteractionContract.d.ts.map +1 -1
  61. package/dist/vendor/codali/runtime/InteractionContract.js +33 -0
  62. package/dist/vendor/codali/runtime/InteractionRouter.d.ts +3 -3
  63. package/dist/vendor/codali/runtime/InteractionRouter.d.ts.map +1 -1
  64. package/dist/vendor/codali/runtime/InteractionRouter.js +1 -1
  65. package/dist/vendor/codali/runtime/NumericProvenance.d.ts +102 -0
  66. package/dist/vendor/codali/runtime/NumericProvenance.d.ts.map +1 -0
  67. package/dist/vendor/codali/runtime/NumericProvenance.js +411 -0
  68. package/dist/vendor/codali/runtime/OutageWait.d.ts +46 -5
  69. package/dist/vendor/codali/runtime/OutageWait.d.ts.map +1 -1
  70. package/dist/vendor/codali/runtime/OutageWait.js +81 -8
  71. package/dist/vendor/codali/runtime/ResearchEvidence.d.ts +14 -0
  72. package/dist/vendor/codali/runtime/ResearchEvidence.d.ts.map +1 -1
  73. package/dist/vendor/codali/runtime/ResearchEvidence.js +139 -3
  74. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts +22 -0
  75. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts.map +1 -1
  76. package/dist/vendor/codali/runtime/ReviewCoordinator.js +203 -25
  77. package/dist/vendor/codali/runtime/ReviewSource.d.ts +5 -0
  78. package/dist/vendor/codali/runtime/ReviewSource.d.ts.map +1 -1
  79. package/dist/vendor/codali/runtime/ReviewSource.js +6 -1
  80. package/dist/vendor/codali/runtime/SessionController.d.ts +85 -10
  81. package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
  82. package/dist/vendor/codali/runtime/SessionController.js +996 -176
  83. package/dist/vendor/codali/runtime/StructuralEvidence.d.ts +10 -0
  84. package/dist/vendor/codali/runtime/StructuralEvidence.d.ts.map +1 -1
  85. package/dist/vendor/codali/runtime/StructuralEvidence.js +10 -0
  86. package/dist/vendor/codali/runtime/TaskReview.d.ts +10 -0
  87. package/dist/vendor/codali/runtime/TaskReview.d.ts.map +1 -1
  88. package/dist/vendor/codali/runtime/TaskReview.js +31 -3
  89. package/dist/vendor/codali/runtime/VerificationCommand.d.ts +8 -0
  90. package/dist/vendor/codali/runtime/VerificationCommand.d.ts.map +1 -1
  91. package/dist/vendor/codali/runtime/VerificationCommand.js +114 -0
  92. package/dist/vendor/codali/runtime/WorkingStyle.d.ts +20 -0
  93. package/dist/vendor/codali/runtime/WorkingStyle.d.ts.map +1 -0
  94. package/dist/vendor/codali/runtime/WorkingStyle.js +71 -0
  95. package/dist/vendor/codali/tools/ToolRegistry.d.ts.map +1 -1
  96. package/dist/vendor/codali/tools/ToolRegistry.js +30 -4
  97. package/dist/vendor/codali/tools/ToolTypes.d.ts +3 -0
  98. package/dist/vendor/codali/tools/ToolTypes.d.ts.map +1 -1
  99. package/dist/vendor/codali/tools/browser/BrowserTool.d.ts +23 -1
  100. package/dist/vendor/codali/tools/browser/BrowserTool.d.ts.map +1 -1
  101. package/dist/vendor/codali/tools/browser/BrowserTool.js +83 -4
  102. package/dist/vendor/codali/tools/browser/BrowserWorker.js +142 -2
  103. package/dist/vendor/codali/tools/browser/HttpFallback.d.ts +39 -0
  104. package/dist/vendor/codali/tools/browser/HttpFallback.d.ts.map +1 -0
  105. package/dist/vendor/codali/tools/browser/HttpFallback.js +240 -0
  106. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts +16 -1
  107. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -1
  108. package/dist/vendor/codali/tools/calculation/CalculatorTool.js +321 -26
  109. package/dist/vendor/codali/tools/deterministic/DeterministicTools.js +1 -1
  110. package/dist/vendor/codali/tools/deterministic/node-worker.cjs +10 -10
  111. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts +2 -0
  112. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts.map +1 -1
  113. package/dist/vendor/codali/tools/shell/AsyncProcess.js +38 -5
  114. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +29 -1
  115. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  116. package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +179 -9
  117. package/dist/vendor/codali/tools/shell/ShellTool.d.ts +2 -0
  118. package/dist/vendor/codali/tools/shell/ShellTool.d.ts.map +1 -1
  119. package/dist/vendor/codali/tools/shell/ShellTool.js +33 -3
  120. package/dist/vendor/codali/tools/verification/CodeRunTool.d.ts +19 -0
  121. package/dist/vendor/codali/tools/verification/CodeRunTool.d.ts.map +1 -0
  122. package/dist/vendor/codali/tools/verification/CodeRunTool.js +104 -0
  123. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -1
  124. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.js +21 -10
  125. package/dist/vendor/codali/tools/verification/VitestTool.d.ts +27 -0
  126. package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -1
  127. package/dist/vendor/codali/tools/verification/VitestTool.js +232 -18
  128. package/dist/vendor/config/deterministic/node-worker.mjs +15 -2
  129. package/dist/vendor/config/skills/code-implementation/SKILL.md +1 -1
  130. package/dist/vendor/config/skills/planning/SKILL.md +1 -1
  131. package/dist/vendor/config/skills/testing-and-verification/SKILL.md +5 -5
  132. package/dist/vendor/config/skills/ui-ux-design/SKILL.md +1 -1
  133. package/dist/vendor/config/skills/webapp-testing/SKILL.md +4 -0
  134. package/dist/vendor/config/skills/webapp-testing/journey-driver.mjs +186 -0
  135. package/package.json +3 -3
@@ -0,0 +1,411 @@
1
+ /** Which numbers in an answer rest on results that were actually executed.
2
+ *
3
+ * Cycle 7 lost three numeric answers (0, 60 and 80 points) whose values were in
4
+ * no tool result at all, or came from a later, simplified rerun that disagreed
5
+ * with an earlier full one; and an equation review with no tools changed a value
6
+ * that executed code had printed. Both the delivery check and the review guard
7
+ * decide here by evidence: a value is backed when an executed result shows it at
8
+ * the precision the answer states it, allowing the usual derivations (rounding,
9
+ * percent and common unit factors, sign). Matching is deliberately lenient: a
10
+ * missed match costs one reconcile turn, a false match only keeps old behaviour. */
11
+ const NUMBER_SOURCE = String.raw `-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?`;
12
+ const NUMBER = new RegExp(NUMBER_SOURCE, "g");
13
+ const FRACTION = /(-?\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)/g;
14
+ const MAX_TEXT = 20000;
15
+ export const normalizedKey = (key) => key.toLowerCase().replace(/[^a-z0-9]/g, "");
16
+ /** Decimal places a token states; "2.8910" states four, "2" none. */
17
+ const decimals = (token) => {
18
+ const [mantissa, exponent] = token.toLowerCase().replace(/^-/, "").split("e");
19
+ return Math.max(0, (mantissa.split(".")[1] ?? "").length - Number(exponent ?? 0));
20
+ };
21
+ const tolerance = (token, value) => 0.5 * 10 ** -decimals(token) * (1 + 1e-9) + 1e-12 * Math.max(1, Math.abs(value));
22
+ /** Factors that turn one correct figure into another correct one: percent, milli/kilo, minutes/hours/days. */
23
+ const DERIVATIONS = [1, 100, 0.01, 1000, 0.001, 60, 1 / 60, 3600, 1 / 3600, 24, 1 / 24];
24
+ /** A whole-number token, or a strict check, matches only the value itself: with
25
+ * unit factors almost any small integer matches something by chance (25 by 0.25,
26
+ * 6 by 0.1 minutes), and a chance match must never count as support. */
27
+ const matches = (token, value, candidate, strict = false, unit) => {
28
+ const allowed = tolerance(token, value);
29
+ // A whole number with its unit stated ("25%", "120 minutes") is a conversion, not a chance match.
30
+ const factors = strict || decimals(token) === 0 && !unit ? [1] : DERIVATIONS;
31
+ return factors.some(factor => Math.abs(Math.abs(candidate * factor) - Math.abs(value)) <= allowed);
32
+ };
33
+ const numbersCache = new WeakMap();
34
+ /** Receipt envelope fields: timings, hashes, versions and settings, never computed values. */
35
+ const ENVELOPE_FIELDS = new Set(["elapsedms", "inputsha256", "workersha256", "sourcesha256", "sha256", "version", "library", "precision", "rounding", "arithmetic",
36
+ "semantics", "scope", "isolation", "warning", "exitcode", "timedout", "index", "passed", "ran", "runonly", "runonlycases", "truncated", "language"]);
37
+ const textNumbers = (text) => {
38
+ const numbers = (text.match(NUMBER) ?? []).map(Number).filter(Number.isFinite);
39
+ for (const [, a, b] of text.matchAll(FRACTION)) {
40
+ const value = Number(a) / Number(b);
41
+ if (Number.isFinite(value))
42
+ numbers.push(value);
43
+ }
44
+ return numbers;
45
+ };
46
+ /** The numbers a result reports, fractions (65/4) evaluated as well. A JSON
47
+ * receipt contributes its values, not its envelope (elapsed time, hashes,
48
+ * library versions); printed output contributes every number it shows. */
49
+ export const resultNumbers = (result) => {
50
+ const cached = numbersCache.get(result);
51
+ if (cached)
52
+ return cached;
53
+ const text = result.text.slice(0, MAX_TEXT);
54
+ let numbers;
55
+ try {
56
+ const parsed = JSON.parse(text);
57
+ numbers = [];
58
+ const walk = (value, key, depth) => {
59
+ if (depth > 16 || key && ENVELOPE_FIELDS.has(normalizedKey(key)))
60
+ return;
61
+ if (typeof value === "number") {
62
+ if (Number.isFinite(value))
63
+ numbers.push(value);
64
+ }
65
+ else if (typeof value === "string") {
66
+ const trimmed = value.trim();
67
+ if (/^[[{]/.test(trimmed)) {
68
+ try {
69
+ walk(JSON.parse(trimmed), key, depth + 1);
70
+ return;
71
+ }
72
+ catch { /* Not JSON. */ }
73
+ }
74
+ if (new RegExp(`^(?:${NUMBER_SOURCE}|${FRACTION.source})$`).test(trimmed))
75
+ numbers.push(...textNumbers(trimmed));
76
+ }
77
+ else if (Array.isArray(value))
78
+ value.forEach(item => walk(item, key, depth + 1));
79
+ else if (value && typeof value === "object")
80
+ for (const [k, v] of Object.entries(value))
81
+ walk(v, k, depth + 1);
82
+ };
83
+ walk(parsed, undefined, 0);
84
+ }
85
+ catch {
86
+ numbers = textNumbers(text);
87
+ }
88
+ numbersCache.set(result, numbers);
89
+ return numbers;
90
+ };
91
+ /** Named values a result reports, last value per name: JSON fields at any depth
92
+ * (JSON inside strings too) and `name: value` / `name = value` lines of printed output. */
93
+ export const keyedValues = (text) => {
94
+ const found = new Map();
95
+ const walk = (value, key, depth) => {
96
+ if (depth > 12)
97
+ return;
98
+ if (typeof value === "number" && key)
99
+ found.set(normalizedKey(key), value);
100
+ else if (typeof value === "string") {
101
+ const trimmed = value.trim();
102
+ if (/^[[{]/.test(trimmed)) {
103
+ try {
104
+ walk(JSON.parse(trimmed), key, depth + 1);
105
+ return;
106
+ }
107
+ catch { /* Not JSON: read as printed text. */ }
108
+ }
109
+ if (key && new RegExp(`^${NUMBER_SOURCE}$`).test(trimmed))
110
+ found.set(normalizedKey(key), Number(trimmed));
111
+ else if (depth > 0)
112
+ for (const [k, v] of printedPairs(value))
113
+ found.set(k, v);
114
+ }
115
+ else if (Array.isArray(value))
116
+ value.forEach(item => walk(item, key, depth + 1));
117
+ else if (value && typeof value === "object")
118
+ for (const [k, v] of Object.entries(value))
119
+ walk(v, /^\d+$/.test(k) && key ? `${key}${k}` : k, depth + 1);
120
+ };
121
+ const slice = text.slice(0, MAX_TEXT);
122
+ try {
123
+ walk(JSON.parse(slice), undefined, 0);
124
+ }
125
+ catch {
126
+ for (const [k, v] of printedPairs(slice))
127
+ found.set(k, v);
128
+ }
129
+ return found;
130
+ };
131
+ const printedPairs = (text) => [...text.matchAll(new RegExp(String.raw `([A-Za-z_][A-Za-z0-9_ ]{0,48}?)\s*[:=]\s*(${NUMBER_SOURCE})(?![\d.])`, "g"))]
132
+ .map(([, key, value]) => [normalizedKey(key), Number(value)]).filter(([key, value]) => key && Number.isFinite(value));
133
+ /** The answer's JSON document, if it is one (bare or in a single json fence). */
134
+ const jsonDocument = (reply) => {
135
+ const trimmed = reply.trim();
136
+ const fenced = trimmed.match(/^```(?:json)?\s*\n([\s\S]*?)\n?```$/i)?.[1] ?? trimmed;
137
+ return /^[[{]/.test(fenced.trim()) ? fenced.trim() : undefined;
138
+ };
139
+ const UNIT_SOURCE = String.raw `%|percent|per cent|ms|milliseconds?|msec|s|secs?|seconds?|min|mins|minutes?|h|hrs?|hours?|d|days?`;
140
+ const UNIT_NAMES = [[/^(?:%|percent|per cent)$/i, "%"], [/^(?:ms|msec|milliseconds?)$/i, "ms"], [/^(?:s|secs?|seconds?)$/i, "s"],
141
+ [/^(?:min|mins|minutes?)$/i, "min"], [/^(?:h|hrs?|hours?)$/i, "h"], [/^(?:d|days?)$/i, "d"]];
142
+ const textUnit = (text) => { const word = text.trim(); return UNIT_NAMES.find(([pattern]) => pattern.test(word))?.[1]; };
143
+ /** A unit named by a JSON field ("utilisationPercent", "waitMinutes", "latency_ms"). */
144
+ const keyUnit = (key) => !key ? undefined
145
+ : /(?:percent|pct)$/i.test(key) ? "%" : /(?:ms|millis|milliseconds)$/i.test(key) ? "ms" : /(?:minutes|mins)$/i.test(key) ? "min"
146
+ : /(?:hours|hrs)$/i.test(key) ? "h" : /(?:seconds|secs)$/i.test(key) ? "s" : /days$/i.test(key) ? "d" : undefined;
147
+ const TOKEN_MARK = "\u0000num:";
148
+ /** Parse JSON keeping each number's own text, so "2.8910" keeps its four places. */
149
+ const parseKeepingTokens = (document) => {
150
+ const marked = document.replace(new RegExp(String.raw `([:\[,]\s*)(${NUMBER_SOURCE})(?=\s*[,}\]])`, "g"), (_, lead, token) => `${lead}"\\u0000num:${token}"`);
151
+ try {
152
+ return JSON.parse(marked);
153
+ }
154
+ catch {
155
+ return JSON.parse(document);
156
+ }
157
+ };
158
+ /** Numeric values in an answer. For JSON answers every numeric leaf with its path;
159
+ * for text answers the numbers that are not restated inputs, with a label when
160
+ * one precedes them ("mean wait: 4.2"). */
161
+ export const answerValues = (reply, prompt = "") => {
162
+ const document = jsonDocument(reply);
163
+ if (document) {
164
+ try {
165
+ const values = [];
166
+ const walk = (value, path, key) => {
167
+ const unit = keyUnit(key);
168
+ if (typeof value === "number")
169
+ values.push({ path, key, token: String(value), value, unit });
170
+ else if (typeof value === "string" && value.startsWith(TOKEN_MARK)) {
171
+ const token = value.slice(TOKEN_MARK.length);
172
+ values.push({ path, key, token, value: Number(token), unit });
173
+ }
174
+ else if (typeof value === "string" && new RegExp(`^${NUMBER_SOURCE}\\s*(?:${UNIT_SOURCE})?$`, "i").test(value.trim())) {
175
+ const token = value.trim().match(NUMBER)[0];
176
+ values.push({ path, key, token, value: Number(token), unit: unit ?? textUnit(value.trim().slice(token.length)) });
177
+ }
178
+ else if (Array.isArray(value))
179
+ value.forEach((item, index) => walk(item, `${path}[${index}]`, key));
180
+ else if (value && typeof value === "object")
181
+ for (const [k, v] of Object.entries(value))
182
+ walk(v, path ? `${path}.${k}` : k, k);
183
+ };
184
+ walk(parseKeepingTokens(document), "", undefined);
185
+ return { json: true, values };
186
+ }
187
+ catch { /* Not valid JSON: read it as text. */ }
188
+ }
189
+ const inputs = new Set((prompt.match(NUMBER) ?? []).map(Number));
190
+ const values = [];
191
+ const text = withoutNonQuantities(reply.replace(/```[\s\S]*?```/g, " "));
192
+ const pattern = new RegExp(String.raw `(?:([A-Za-z][A-Za-z_ ()/-]{0,40}?)\s*(?:[:=]|\bis\b|\bequals\b|≈)\s*\**\s*)?(?<![\w.])(${NUMBER_SOURCE})(?![\w.]*\d)(\s*(?:${UNIT_SOURCE})(?![A-Za-z]))?`, "gi");
193
+ for (const match of text.matchAll(pattern)) {
194
+ const token = match[2], value = Number(token);
195
+ if (!Number.isFinite(value) || inputs.has(value))
196
+ continue;
197
+ values.push({ path: `#${values.length}`, key: match[1]?.trim() || undefined, token, value, unit: match[3] ? textUnit(match[3]) : undefined });
198
+ }
199
+ return { json: false, values };
200
+ };
201
+ /** The executed result (latest first) or prompt input that shows a value at its stated precision. */
202
+ export const backingOf = (item, results, prompt = "", strict = false) => {
203
+ if (decimals(item.token) === 0 && [0, 1].includes(Math.abs(item.value)))
204
+ return { kind: "input" };
205
+ for (const result of [...results].sort((a, b) => b.seq - a.seq)) {
206
+ if (resultNumbers(result).some(candidate => matches(item.token, item.value, candidate, strict, item.unit)))
207
+ return { kind: result.kind, seq: result.seq, tool: result.tool };
208
+ }
209
+ // A restated input backs a value only at the precision the request gave it:
210
+ // "2" in the request does not support a computed "2.000000".
211
+ for (const token of prompt.match(NUMBER) ?? []) {
212
+ if (decimals(item.token) <= decimals(token) && Math.abs(Number(token) - item.value) <= tolerance(item.token, item.value))
213
+ return { kind: "input" };
214
+ }
215
+ return undefined;
216
+ };
217
+ /** Answer fields whose name an executed result also reports, where executed runs
218
+ * disagree with each other or the latest one disagrees with the answer. */
219
+ // Envelope fields of tool receipts, not names of computed quantities.
220
+ const GENERIC_KEYS = new Set(["result", "results", "value", "values", "answer", "output", "actual", "expected", "index", "elapsedms", "precision", "places", "version", "exitcode", "status"]);
221
+ export const receiptConflicts = (values, results) => {
222
+ const ordered = [...results].sort((a, b) => a.seq - b.seq).map(result => ({ result, keyed: keyedValues(result.text) }));
223
+ const conflicts = [];
224
+ for (const item of values) {
225
+ if (!item.key)
226
+ continue;
227
+ const key = normalizedKey(item.key);
228
+ if (key.length < 3 || GENERIC_KEYS.has(key))
229
+ continue;
230
+ const runs = ordered.filter(entry => entry.keyed.has(key)).map(entry => ({ seq: entry.result.seq, tool: entry.result.tool, value: entry.keyed.get(key) }));
231
+ if (!runs.length)
232
+ continue;
233
+ const latest = runs.at(-1);
234
+ const latestDisagrees = !matches(item.token, item.value, latest.value);
235
+ const runsDisagree = runs.some(run => !matches(item.token, latest.value, run.value));
236
+ if (latestDisagrees && backingOf(item, results.filter(result => result.seq > latest.seq)) === undefined || runsDisagree) {
237
+ conflicts.push({ key: item.key, drafted: item.token, runs: runs.slice(-4), latestDisagrees });
238
+ }
239
+ }
240
+ return conflicts;
241
+ };
242
+ /** Delivery check: answer values with no executed result behind them, and named
243
+ * values on which executed runs disagree. */
244
+ export const numericProvenance = (reply, prompt, results) => {
245
+ const { json, values } = answerValues(reply, prompt);
246
+ const unbacked = values.filter(item => !backingOf(item, results, prompt));
247
+ return { json, values, unbacked, conflicts: receiptConflicts(values, results) };
248
+ };
249
+ /** Whether every value of an answer was printed or returned by executed code. */
250
+ export const backedByExecutedCode = (reply, prompt, results) => {
251
+ const code = results.filter(result => result.kind === "code");
252
+ const { values } = answerValues(reply, prompt);
253
+ if (!values.length || !code.length)
254
+ return false;
255
+ return values.every(item => backingOf(item, code, prompt, true) !== undefined);
256
+ };
257
+ /** Whether a review kept a drafted value: judged at the draft's own precision. A
258
+ * review that states fewer places (2.3480 -> 2) changed the value, not kept it. */
259
+ const sameValue = (drafted, revised) => drafted.value === revised.value
260
+ || decimals(revised.token) >= decimals(drafted.token) && Math.abs(drafted.value - revised.value) <= tolerance(drafted.token, drafted.value);
261
+ /** A review value supports itself only by a direct match at no less precision than the draft. */
262
+ const reviewBacking = (drafted, revised, results, prompt) => decimals(revised.token) >= decimals(drafted.token) ? backingOf(revised, results, prompt, true) : undefined;
263
+ /** A review that adds places to a drafted value ("2.004" -> "2.0041") claims the
264
+ * extra digits. When an executed result backs the drafted value but contradicts
265
+ * those digits (2.0040083 -> 2.0040), the receipt's value at the review's
266
+ * precision replaces both; undefined when there is nothing to contradict. */
267
+ const receiptAtReviewPrecision = (drafted, revised, results) => {
268
+ const places = decimals(revised.token);
269
+ if (places <= decimals(drafted.token) || places > 20 || backingOf(revised, results, "", true))
270
+ return undefined;
271
+ let nearest;
272
+ for (const result of results)
273
+ for (const candidate of resultNumbers(result)) {
274
+ if (matches(drafted.token, drafted.value, candidate, true) && (nearest === undefined || Math.abs(candidate - drafted.value) < Math.abs(nearest - drafted.value)))
275
+ nearest = candidate;
276
+ }
277
+ return nearest === undefined ? undefined : nearest.toFixed(places);
278
+ };
279
+ /** Decide a tool-less review's edits field by field, by which side executed
280
+ * results support. A changed value is accepted when the review's value is itself
281
+ * backed, or when neither value has executed support (catching a figure that
282
+ * models the wrong quantity is the review's job). A value printed by executed
283
+ * code is never replaced by an unexecuted one. A value from a calculation receipt
284
+ * that the review contests is a dispute: the expression ran, but the review says
285
+ * it is the wrong expression, and only another executed method can settle that.
286
+ * Until one does, the executed value stays. A number is never replaced by null. */
287
+ export const decideReview = (draft, revised, prompt, results) => {
288
+ const before = answerValues(draft, prompt), after = answerValues(revised, prompt);
289
+ const protectedFields = [], disputes = [];
290
+ let acceptedChanges = 0, refined = 0;
291
+ if (before.json && after.json) {
292
+ const revisedByPath = new Map(after.values.map(item => [item.path, item]));
293
+ const restore = new Map();
294
+ const document = jsonDocument(revised);
295
+ let parsedRevised;
296
+ try {
297
+ parsedRevised = parseKeepingTokens(document);
298
+ }
299
+ catch {
300
+ parsedRevised = undefined;
301
+ }
302
+ for (const item of before.values) {
303
+ const next = revisedByPath.get(item.path);
304
+ if (next && sameValue(item, next)) {
305
+ const corrected = receiptAtReviewPrecision(item, next, results);
306
+ if (corrected !== undefined) {
307
+ protectedFields.push({ field: item.path, drafted: item.token, revised: next.token, backing: backingOf(item, results, prompt, true) });
308
+ restore.set(item.path, corrected);
309
+ refined++;
310
+ }
311
+ else if (next.token !== item.token)
312
+ refined++;
313
+ continue;
314
+ }
315
+ const nextBacking = next ? reviewBacking(item, next, results, prompt) : undefined;
316
+ if (next && nextBacking) {
317
+ acceptedChanges++;
318
+ continue;
319
+ }
320
+ const backing = backingOf(item, results, prompt);
321
+ if (next && !backing) {
322
+ acceptedChanges++;
323
+ continue;
324
+ }
325
+ const dispute = { field: item.path, drafted: item.token, revised: next?.token ?? null, backing };
326
+ if (backing?.kind === "code")
327
+ protectedFields.push(dispute);
328
+ else
329
+ disputes.push(dispute);
330
+ restore.set(item.path, item.token);
331
+ }
332
+ if (!restore.size)
333
+ return { verdict: "accept", answer: revised, protectedFields, disputes, acceptedChanges };
334
+ if (!acceptedChanges && !refined || parsedRevised === undefined)
335
+ return { verdict: "keep", answer: draft, protectedFields, disputes, acceptedChanges };
336
+ // Restore drafted tokens in the review's document, path by path.
337
+ const setPath = (root, path, token) => {
338
+ const parts = [...path.matchAll(/([^.[\]]+)|\[(\d+)\]/g)].map(match => match[1] ?? Number(match[2]));
339
+ let node = root;
340
+ for (const part of parts.slice(0, -1)) {
341
+ node = node?.[part];
342
+ if (!node || typeof node !== "object")
343
+ return false;
344
+ }
345
+ const last = parts.at(-1);
346
+ if (last === undefined || !node || typeof node !== "object")
347
+ return false;
348
+ node[last] = `${TOKEN_MARK}${token}`;
349
+ return true;
350
+ };
351
+ for (const [path, token] of restore)
352
+ if (!setPath(parsedRevised, path, token))
353
+ return { verdict: "keep", answer: draft, protectedFields, disputes, acceptedChanges };
354
+ const pretty = /\n/.test(document) ? 2 : undefined;
355
+ const rendered = JSON.stringify(parsedRevised, (_, value) => value, pretty).replace(new RegExp(`"${TOKEN_MARK.replace("\u0000", "\\\\u0000")}(${NUMBER_SOURCE})"`, "g"), "$1");
356
+ const answer = revised.trim() === document ? rendered : revised.replace(document, rendered);
357
+ return { verdict: "merge", answer, protectedFields, disputes, acceptedChanges };
358
+ }
359
+ // Prose: values cannot be paired by field. A drafted value the review dropped
360
+ // is contested unless one of the review's new values is itself backed.
361
+ const introduced = after.values.filter(next => !before.values.some(item => sameValue(item, next)));
362
+ const introducedBacked = introduced.some(next => backingOf(next, results, prompt, true));
363
+ for (const item of before.values) {
364
+ const kept = after.values.find(next => sameValue(item, next));
365
+ // Extra places the receipts contradict are not a kept value (prose cannot be merged: keep the draft).
366
+ if (kept && receiptAtReviewPrecision(item, kept, results) !== undefined) {
367
+ protectedFields.push({ field: item.key ?? item.path, drafted: item.token, revised: kept.token, backing: backingOf(item, results, prompt, true) });
368
+ continue;
369
+ }
370
+ if (kept)
371
+ continue;
372
+ const backing = backingOf(item, results, prompt);
373
+ if (!backing || introducedBacked) {
374
+ acceptedChanges++;
375
+ continue;
376
+ }
377
+ const dispute = { field: item.key ?? item.path, drafted: item.token, revised: introduced.map(next => next.token).join(", ") || null, backing };
378
+ if (backing.kind === "code")
379
+ protectedFields.push(dispute);
380
+ else
381
+ disputes.push(dispute);
382
+ }
383
+ const contested = protectedFields.length + disputes.length;
384
+ return { verdict: contested ? "keep" : "accept", answer: contested ? draft : revised, protectedFields, disputes, acceptedChanges };
385
+ };
386
+ const COMPUTE_WORDS = /\b(?:simulat|enumerat|comput|calculat|estimat|tally|probabilit|throughput|utili[sz]|round(?:ed)? to|decimal places?|significant (?:figures|digits))\w*|\bsolve for\b|\bhow (?:many|much)\b/i;
387
+ /** Words that ask for a number only when a numeric object follows: "the expected
388
+ * number of", "count the misses", "mean waiting time", not "what do you mean". */
389
+ const OBJECT_WORDS = /\b(?:mean|expect\w*|determin\w*|count\w*|averag\w*|varian\w*|evaluat\w*)\s+(?:(?:the|a|an|of|each|all|total)\s+){0,3}(?:\w+\s+){0,2}?(?:numbers?|values?|totals?|sums?|rates?|times?|costs?|lengths?|sizes?|counts?|probabilit\w*|waits?|waiting|delays?|amounts?|percentages?|fractions?|ratios?|hits?|misses|events?|steps?|orderings?)\b/i;
390
+ const NO_TOOLS = /\b(?:without (?:using )?(?:any )?(?:tools?|a calculator|code)|(?:do not|don't|never) (?:use|run|call) (?:any )?(?:tools?|code|a calculator)|no tools|by hand|mentally|in your head|from memory)\b/i;
391
+ /** A request whose answer is a computed quantity over several stated inputs (an
392
+ * event trace to simulate, orderings to count, a recurrence): one model call
393
+ * cannot work it out reliably in its head. In cycle 7 a 22-event banker's
394
+ * algorithm trace was answered in 24 seconds with counts that could not add up. */
395
+ export const requestNeedsComputation = (prompt) => (COMPUTE_WORDS.test(prompt) || OBJECT_WORDS.test(prompt)) && !NO_TOOLS.test(prompt) && (withoutNonQuantities(prompt).match(NUMBER) ?? []).length >= 4;
396
+ const VERSIONED = String.raw `(?:TLS|SSL|SSH|HTTP|IPv|TCP|QUIC|OAuth|USB|PCIe|DDR|Wi-?Fi|Bluetooth|Python|Node(?:\.js)?|Java|Go|Rust|Ruby|PHP|Perl|Ubuntu|Debian|RHEL|CentOS|Fedora|Alpine|Windows|macOS|iOS|Android|Postgres(?:QL)?|MySQL|MariaDB|SQLite|Redis|Kafka|Kubernetes|Docker|Chrome|Firefox|Safari|Edge|React|Angular|Vue|Django|Rails|Spring|Spark|Hadoop|Elasticsearch|MongoDB|Cassandra|Nginx|Apache|OpenSSL|Linux|v)`;
397
+ const WHOLE_VERSIONED = String.raw `(?:HTTP|IPv|USB|DDR|PCIe|Java|Windows|iOS|Android|Python)`;
398
+ const MONTH = String.raw `(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)[a-z]*\.?`;
399
+ const NON_QUANTITIES = [
400
+ /\b\d{4}-\d{1,2}-\d{1,2}(?:[T ]\d{1,2}:\d{2}(?::\d{2})?)?\b/g, /\b\d{1,2}[/.]\d{1,2}[/.]\d{2,4}\b/g, /\b\d{1,2}:\d{2}(?::\d{2})?\b/g,
401
+ new RegExp(String.raw `\b${MONTH}\s+\d{1,2}(?:st|nd|rd|th)?(?:,?\s+\d{4})?\b`, "g"), new RegExp(String.raw `\b\d{1,2}(?:st|nd|rd|th)?\s+${MONTH}(?:\s+\d{4})?\b`, "g"),
402
+ /\b(?:in|since|by|until|from|before|after|during)\s+(?:19|20)\d{2}\b/gi, /\b\d+(?:st|nd|rd|th)\b/gi,
403
+ /\bv(?:ersion\s*)?\d+(?:\.\d+)*\b/gi, /\b\d+\.\d+\.\d+(?:\.\d+)*\b/g,
404
+ // Named products with version-shaped numbers: TLS 1.2 or 1.3, Python 3.12, Ubuntu 24.04. Only a
405
+ // name, never any capitalised word: "MTBF 2000", "SLA 99.9" and "CPU 4, 8 and 16" are quantities.
406
+ new RegExp(String.raw `\b${VERSIONED}(?:\/|-|\s)?\d+\.\d+(?:\.\d+)*(?:\s*(?:,|or|and|vs\.?|versus|to|\/)\s*\d+\.\d+(?:\.\d+)*)*`, "g"),
407
+ // Products whose versions are whole numbers: HTTP/2 vs 3, IPv6, Java 21, Windows 11.
408
+ new RegExp(String.raw `\b${WHOLE_VERSIONED}(?:\/|-|\s)?\d+(?:\.\d+)*(?:\s*(?:,|or|and|vs\.?|versus|to|\/)\s*\d+(?:\.\d+)*)*`, "g"),
409
+ ];
410
+ /** Text with dates, times of day, ordinals and version numbers blanked out: they are labels, not quantities. */
411
+ export const withoutNonQuantities = (text) => NON_QUANTITIES.reduce((rest, pattern) => rest.replace(pattern, match => " ".repeat(match.length)), text);
@@ -3,12 +3,53 @@ export declare const PREFLIGHT_RECOVERY_WAITS_MS: number[];
3
3
  /** The outage waits that fit the host's total (CODALI_MODEL_OUTAGE_WAIT_MS, in
4
4
  * milliseconds); all of them when it is unset. */
5
5
  export declare const outageWaitsMs: (budget?: string | undefined) => number[];
6
- /** The longest a turn waits out one model-service outage. The ladder alone
7
- * (about four minutes) lost a three-hour build to a nine-minute relay outage. */
6
+ /** The longest one model-service outage is waited out when the turn itself has
7
+ * no time limit (an interactive session, an open-ended build). Outages happen
8
+ * in real use: a node restarts, a host runs out of memory, a gateway queue
9
+ * backs up. The 30 minutes allowed before (and half the turn's remaining
10
+ * time) ended long builds on outages they could have outlasted. Six hours by
11
+ * default; CODALI_MODEL_OUTAGE_WAIT_MS raises or lowers it. */
8
12
  export declare const MODEL_OUTAGE_WAIT_MS: number;
13
+ /** Time kept back before a turn's limit, so the turn can still hand over what
14
+ * it has (a draft, a status report) when the service is still down then. */
15
+ export declare const OUTAGE_DELIVERY_RESERVE_MS = 90000;
9
16
  /** The wait before outage retry `attempt` (0-based): the ladder, then a minute
10
- * per retry, while the total stays within the host's budget
11
- * (CODALI_MODEL_OUTAGE_WAIT_MS), MODEL_OUTAGE_WAIT_MS and half the time the
12
- * turn has left. Undefined once the outage has used that allowance. */
17
+ * per retry. The total stays within the host's budget (CODALI_MODEL_OUTAGE_WAIT_MS,
18
+ * default MODEL_OUTAGE_WAIT_MS) and within the turn's remaining time less
19
+ * OUTAGE_DELIVERY_RESERVE_MS. Undefined once the outage has used that allowance. */
13
20
  export declare const outageWaitMs: (attempt: number, remainingMs?: number, budget?: string | undefined) => number | undefined;
21
+ /** Compute the next delay from actual elapsed outage time. A server-directed
22
+ * delay must fit in full, including the time reserved for the final response. */
23
+ export declare const outageRetryDelayMs: (attempt: number, remainingMs: number, elapsedMs: number, retryAfterSeconds: number, injected: boolean, budget?: string | undefined) => number | undefined;
24
+ /** Whether an error says the model service could not be reached at all (as
25
+ * opposed to a refusal it gave). A dropped stream ("terminated"), a failed
26
+ * connection ("fetch failed") and their low-level codes all count; so does a
27
+ * timed-out catalog request, which only means the gateway did not answer. */
28
+ export declare const transportOutage: (error: unknown) => boolean;
29
+ /** How long one model request may stay unanswered before it is abandoned and
30
+ * retried. A request whose connection was lost, or that a scheduler dropped,
31
+ * never returns: a 12-hour build sat on one such review call for 158 minutes
32
+ * and ended unfinished although its work was done.
33
+ *
34
+ * The base allowance is the larger of ten minutes and four times the slowest
35
+ * request this turn has completed, but no more than the request could need at
36
+ * its ceiling on a slow server: two minutes to be scheduled, the prompt read at
37
+ * 1,000 tokens a second and the full output at 25. It doubles with every stall
38
+ * of the same request, without an upper bound short of an hour, so a model
39
+ * slower than those rates is waited for longer each time instead of being cut
40
+ * off at the same point for ever. */
41
+ export declare const modelStallAllowanceMs: (inputTokens: number, maxOutputTokens: number, longestModelMs: number, stalledAttempts?: number) => number;
42
+ /** How long a request that is streaming its generation may go without
43
+ * producing anything more before it counts as stalled. Wall-clock time alone
44
+ * cannot tell a live long generation from a lost request, so the full
45
+ * allowance above stays in force until the first generated chunk. Once output
46
+ * arrives the timer is reset by every chunk, and only a stream that stops for
47
+ * this long is abandoned: two minutes, or three times the slowest answered
48
+ * request when longer, never more than the full allowance. A lost request
49
+ * that was streaming is then given up in minutes instead of after the full
50
+ * allowance (ten minutes or more), while a live generation is never cut
51
+ * however long it runs. */
52
+ export declare const modelStreamGapAllowanceMs: (fullAllowanceMs: number, longestModelMs: number) => number;
53
+ /** The shortest silence after which a streaming request counts as stalled. */
54
+ export declare const STREAM_STALL_GAP_MS = 120000;
14
55
  //# sourceMappingURL=OutageWait.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"OutageWait.d.ts","sourceRoot":"","sources":["../../src/runtime/OutageWait.ts"],"names":[],"mappings":"AACA,0GAA0G;AAC1G,eAAO,MAAM,2BAA2B,UAA4D,CAAC;AACrG;kDACkD;AAClD,eAAO,MAAM,aAAa,GAAI,SAAQ,MAAM,GAAG,SAAmD,KAAG,MAAM,EAK1G,CAAC;AACF;iFACiF;AACjF,eAAO,MAAM,oBAAoB,QAAc,CAAC;AAChD;;;uEAGuE;AACvE,eAAO,MAAM,YAAY,GAAI,SAAS,MAAM,EAAE,oBAAsB,EAAE,SAAQ,MAAM,GAAG,SAAmD,KAAG,MAAM,GAAG,SAWrJ,CAAC"}
1
+ {"version":3,"file":"OutageWait.d.ts","sourceRoot":"","sources":["../../src/runtime/OutageWait.ts"],"names":[],"mappings":"AACA,0GAA0G;AAC1G,eAAO,MAAM,2BAA2B,UAA4D,CAAC;AACrG;kDACkD;AAClD,eAAO,MAAM,aAAa,GAAI,SAAQ,MAAM,GAAG,SAAmD,KAAG,MAAM,EAK1G,CAAC;AACF;;;;;+DAK+D;AAC/D,eAAO,MAAM,oBAAoB,QAAgB,CAAC;AAClD;4EAC4E;AAC5E,eAAO,MAAM,0BAA0B,QAAS,CAAC;AACjD;;;oFAGoF;AACpF,eAAO,MAAM,YAAY,GAAI,SAAS,MAAM,EAAE,oBAAsB,EAAE,SAAQ,MAAM,GAAG,SAAmD,KAAG,MAAM,GAAG,SAWrJ,CAAC;AAEF;iFACiF;AACjF,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,EAAE,aAAa,MAAM,EAAE,WAAW,MAAM,EAAE,mBAAmB,MAAM,EAAE,UAAU,OAAO,EAAE,2BAAgD,KAAG,MAAM,GAAG,SAYrM,CAAC;AAKF;;;6EAG6E;AAC7E,eAAO,MAAM,eAAe,GAAI,OAAO,OAAO,KAAG,OAShD,CAAC;AAEF;;;;;;;;;;;qCAWqC;AACrC,eAAO,MAAM,qBAAqB,GAAI,aAAa,MAAM,EAAE,iBAAiB,MAAM,EAAE,gBAAgB,MAAM,EAAE,wBAAmB,KAAG,MAIjI,CAAC;AAEF;;;;;;;;;2BAS2B;AAC3B,eAAO,MAAM,yBAAyB,GAAI,iBAAiB,MAAM,EAAE,gBAAgB,MAAM,KAAG,MACd,CAAC;AAC/E,8EAA8E;AAC9E,eAAO,MAAM,mBAAmB,SAAU,CAAC"}
@@ -10,16 +10,23 @@ export const outageWaitsMs = (budget = process.env.CODALI_MODEL_OUTAGE_WAIT_MS)
10
10
  let waited = 0;
11
11
  return PREFLIGHT_RECOVERY_WAITS_MS.filter(wait => (waited += wait) <= total);
12
12
  };
13
- /** The longest a turn waits out one model-service outage. The ladder alone
14
- * (about four minutes) lost a three-hour build to a nine-minute relay outage. */
15
- export const MODEL_OUTAGE_WAIT_MS = 30 * 60000;
13
+ /** The longest one model-service outage is waited out when the turn itself has
14
+ * no time limit (an interactive session, an open-ended build). Outages happen
15
+ * in real use: a node restarts, a host runs out of memory, a gateway queue
16
+ * backs up. The 30 minutes allowed before (and half the turn's remaining
17
+ * time) ended long builds on outages they could have outlasted. Six hours by
18
+ * default; CODALI_MODEL_OUTAGE_WAIT_MS raises or lowers it. */
19
+ export const MODEL_OUTAGE_WAIT_MS = 6 * 3600000;
20
+ /** Time kept back before a turn's limit, so the turn can still hand over what
21
+ * it has (a draft, a status report) when the service is still down then. */
22
+ export const OUTAGE_DELIVERY_RESERVE_MS = 90000;
16
23
  /** The wait before outage retry `attempt` (0-based): the ladder, then a minute
17
- * per retry, while the total stays within the host's budget
18
- * (CODALI_MODEL_OUTAGE_WAIT_MS), MODEL_OUTAGE_WAIT_MS and half the time the
19
- * turn has left. Undefined once the outage has used that allowance. */
24
+ * per retry. The total stays within the host's budget (CODALI_MODEL_OUTAGE_WAIT_MS,
25
+ * default MODEL_OUTAGE_WAIT_MS) and within the turn's remaining time less
26
+ * OUTAGE_DELIVERY_RESERVE_MS. Undefined once the outage has used that allowance. */
20
27
  export const outageWaitMs = (attempt, remainingMs = Infinity, budget = process.env.CODALI_MODEL_OUTAGE_WAIT_MS) => {
21
- const parsed = budget === undefined || budget.trim() === "" ? Infinity : Number(budget);
22
- const cap = Math.min(parsed >= 0 ? parsed : Infinity, MODEL_OUTAGE_WAIT_MS, remainingMs * 0.5);
28
+ const parsed = budget === undefined || budget.trim() === "" ? MODEL_OUTAGE_WAIT_MS : Number(budget);
29
+ const cap = Math.min(parsed >= 0 ? parsed : MODEL_OUTAGE_WAIT_MS, remainingMs - OUTAGE_DELIVERY_RESERVE_MS);
23
30
  let waited = 0;
24
31
  for (let index = 0; index <= attempt; index++) {
25
32
  const wait = PREFLIGHT_RECOVERY_WAITS_MS[index] ?? 60000;
@@ -31,3 +38,69 @@ export const outageWaitMs = (attempt, remainingMs = Infinity, budget = process.e
31
38
  }
32
39
  return undefined;
33
40
  };
41
+ /** Compute the next delay from actual elapsed outage time. A server-directed
42
+ * delay must fit in full, including the time reserved for the final response. */
43
+ export const outageRetryDelayMs = (attempt, remainingMs, elapsedMs, retryAfterSeconds, injected, budget = process.env.CODALI_MODEL_OUTAGE_WAIT_MS) => {
44
+ const parsed = budget?.trim() ? Number(budget) : MODEL_OUTAGE_WAIT_MS;
45
+ const allowance = Number.isFinite(parsed) && parsed >= 0 ? parsed : MODEL_OUTAGE_WAIT_MS;
46
+ const step = injected ? [500, 2000][attempt] : PREFLIGHT_RECOVERY_WAITS_MS[attempt] ?? 60000;
47
+ if (step === undefined)
48
+ return undefined;
49
+ const wait = Math.max(step, retryAfterSeconds * 1000);
50
+ // Interactive turns default to 90 seconds. Preserve a quick retry on those
51
+ // turns while leaving the full delivery reserve on long-running requests.
52
+ const reserveMs = Math.min(OUTAGE_DELIVERY_RESERVE_MS, remainingMs / 2);
53
+ const available = Math.min(allowance - elapsedMs, remainingMs - reserveMs);
54
+ if (injected && retryAfterSeconds > 2)
55
+ return undefined;
56
+ return wait <= available ? wait : undefined;
57
+ };
58
+ const NETWORK_CODES = new Set(["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "ENETDOWN", "ECONNABORTED",
59
+ "UND_ERR_SOCKET", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "UND_ERR_CLOSED"]);
60
+ /** Whether an error says the model service could not be reached at all (as
61
+ * opposed to a refusal it gave). A dropped stream ("terminated"), a failed
62
+ * connection ("fetch failed") and their low-level codes all count; so does a
63
+ * timed-out catalog request, which only means the gateway did not answer. */
64
+ export const transportOutage = (error) => {
65
+ let current = error;
66
+ for (let depth = 0; current && typeof current === "object" && depth < 4; current = current.cause, depth++) {
67
+ const code = current.code;
68
+ if (typeof code === "string" && NETWORK_CODES.has(code))
69
+ return true;
70
+ if (current instanceof TypeError && /^(?:fetch failed|terminated|network error)$/i.test(String(current.message)))
71
+ return true;
72
+ if (current instanceof Error && current.message === "Service request timed out")
73
+ return true;
74
+ }
75
+ return false;
76
+ };
77
+ /** How long one model request may stay unanswered before it is abandoned and
78
+ * retried. A request whose connection was lost, or that a scheduler dropped,
79
+ * never returns: a 12-hour build sat on one such review call for 158 minutes
80
+ * and ended unfinished although its work was done.
81
+ *
82
+ * The base allowance is the larger of ten minutes and four times the slowest
83
+ * request this turn has completed, but no more than the request could need at
84
+ * its ceiling on a slow server: two minutes to be scheduled, the prompt read at
85
+ * 1,000 tokens a second and the full output at 25. It doubles with every stall
86
+ * of the same request, without an upper bound short of an hour, so a model
87
+ * slower than those rates is waited for longer each time instead of being cut
88
+ * off at the same point for ever. */
89
+ export const modelStallAllowanceMs = (inputTokens, maxOutputTokens, longestModelMs, stalledAttempts = 0) => {
90
+ const ceiling = 120000 + Math.max(0, inputTokens) + Math.max(0, maxOutputTokens) * 40;
91
+ const base = Math.max(60000, Math.min(Math.max(600000, longestModelMs * 4), ceiling));
92
+ return Math.min(base * 2 ** Math.min(Math.max(0, stalledAttempts), 6), Math.max(base, 3600000));
93
+ };
94
+ /** How long a request that is streaming its generation may go without
95
+ * producing anything more before it counts as stalled. Wall-clock time alone
96
+ * cannot tell a live long generation from a lost request, so the full
97
+ * allowance above stays in force until the first generated chunk. Once output
98
+ * arrives the timer is reset by every chunk, and only a stream that stops for
99
+ * this long is abandoned: two minutes, or three times the slowest answered
100
+ * request when longer, never more than the full allowance. A lost request
101
+ * that was streaming is then given up in minutes instead of after the full
102
+ * allowance (ten minutes or more), while a live generation is never cut
103
+ * however long it runs. */
104
+ export const modelStreamGapAllowanceMs = (fullAllowanceMs, longestModelMs) => Math.min(fullAllowanceMs, Math.max(STREAM_STALL_GAP_MS, longestModelMs * 3));
105
+ /** The shortest silence after which a streaming request counts as stalled. */
106
+ export const STREAM_STALL_GAP_MS = 120000;
@@ -22,4 +22,18 @@ export declare function draftAnchors(draft: string): string[];
22
22
  * the audit saw 9 of 67 passages, missed the one with "Civil penalty: 30,000
23
23
  * penalty units", and relabelled that verbatim quote as unverified. */
24
24
  export declare function selectResearchEvidence(packets: ResearchPacket[], request: string, draft: string, maxChars?: number): ResearchPacket[];
25
+ /** What an investigation found, as a report, for when its answer could not be
26
+ * written: the model service was down or the final request would have run past
27
+ * the time limit. In cycle 6 a 41-minute investigation delivered nothing
28
+ * because that request hit three gateway timeouts in its last three minutes.
29
+ * Built without a model, so it is ready at once. It says plainly that it is
30
+ * evidence and not an answer, and quotes at most 25 words from any one source:
31
+ * the sentence that shares most with the request, figures and dates first. */
32
+ export declare function evidenceReport(packets: ResearchPacket[], request: string, reason: string, maxSources?: number): string | undefined;
33
+ /** The points a research draft itself leaves open: the sentences or list items
34
+ * in which it says something was not found, not verified or only alleged.
35
+ * A draft that says so with time left has not finished its research; in cycle
36
+ * 6 one called a core fact "alleged" and stopped with a quarter of its time
37
+ * unused. Decided from the draft's own words, not from the question. */
38
+ export declare function openResearchPoints(draft: string, limit?: number): string[];
25
39
  //# sourceMappingURL=ResearchEvidence.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ResearchEvidence.d.ts","sourceRoot":"","sources":["../../src/runtime/ResearchEvidence.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,cAAc;IAAG,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC9I,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAAE;AAE1F;8EAC8E;AAC9E,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAmBvG;AAID;qEACqE;AACrE,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAUpD;AAED;;;;uEAIuE;AACvE,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,cAAc,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,SAAQ,GAAG,cAAc,EAAE,CAqCpI"}
1
+ {"version":3,"file":"ResearchEvidence.d.ts","sourceRoot":"","sources":["../../src/runtime/ResearchEvidence.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,cAAc;IAAG,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC9I,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAAE;AAE1F;8EAC8E;AAC9E,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAmBvG;AASD;qEACqE;AACrE,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAUpD;AAED;;;;uEAIuE;AACvE,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,cAAc,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,SAAQ,GAAG,cAAc,EAAE,CAqEpI;AAED;;;;;;8EAM8E;AAC9E,wBAAgB,cAAc,CAAC,OAAO,EAAE,cAAc,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,SAAK,GAAG,MAAM,GAAG,SAAS,CAuB9H;AAgBD;;;;wEAIwE;AACxE,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,SAAI,GAAG,MAAM,EAAE,CAwBrE"}