@mcoda/codali 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 (137) hide show
  1. package/CHANGELOG.md +140 -0
  2. package/README.md +8 -0
  3. package/config/deterministic/node-worker.mjs +15 -2
  4. package/config/skills/code-implementation/SKILL.md +1 -1
  5. package/config/skills/planning/SKILL.md +1 -1
  6. package/config/skills/testing-and-verification/SKILL.md +5 -5
  7. package/config/skills/ui-ux-design/SKILL.md +1 -1
  8. package/config/skills/webapp-testing/SKILL.md +4 -0
  9. package/config/skills/webapp-testing/journey-driver.mjs +186 -0
  10. package/dist/cli/TerminalCommand.js +2 -2
  11. package/dist/cli/tui/TerminalPresentation.js +1 -1
  12. package/dist/config/OrchestrationConfig.d.ts +1 -0
  13. package/dist/config/OrchestrationConfig.d.ts.map +1 -1
  14. package/dist/config/OrchestrationConfig.js +3 -1
  15. package/dist/docdex/DocdexClient.d.ts +11 -0
  16. package/dist/docdex/DocdexClient.d.ts.map +1 -1
  17. package/dist/docdex/DocdexClient.js +55 -1
  18. package/dist/eval/fixtures/ContractReviewProvider.d.ts +5 -0
  19. package/dist/eval/fixtures/ContractReviewProvider.d.ts.map +1 -1
  20. package/dist/eval/fixtures/ContractReviewProvider.js +63 -0
  21. package/dist/eval/fixtures/MixedMediaRecoveryJourney.js +2 -2
  22. package/dist/eval/fixtures/TerminalRecoveryJourney.js +2 -2
  23. package/dist/permissions/PermissionGate.d.ts +7 -0
  24. package/dist/permissions/PermissionGate.d.ts.map +1 -1
  25. package/dist/permissions/PermissionGate.js +27 -1
  26. package/dist/providers/ClaudeCliProvider.d.ts.map +1 -1
  27. package/dist/providers/ClaudeCliProvider.js +1 -0
  28. package/dist/providers/CodexCliProvider.d.ts.map +1 -1
  29. package/dist/providers/CodexCliProvider.js +1 -0
  30. package/dist/providers/ConfiguredProvider.d.ts +2 -0
  31. package/dist/providers/ConfiguredProvider.d.ts.map +1 -1
  32. package/dist/providers/ConfiguredProvider.js +29 -0
  33. package/dist/providers/ModelServiceError.d.ts +16 -2
  34. package/dist/providers/ModelServiceError.d.ts.map +1 -1
  35. package/dist/providers/ModelServiceError.js +18 -1
  36. package/dist/providers/OllamaRemoteProvider.d.ts.map +1 -1
  37. package/dist/providers/OllamaRemoteProvider.js +1 -0
  38. package/dist/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  39. package/dist/providers/OpenAiCompatibleProvider.js +4 -0
  40. package/dist/providers/ProviderTypes.d.ts +4 -0
  41. package/dist/providers/ProviderTypes.d.ts.map +1 -1
  42. package/dist/runtime/AnswerEdits.d.ts +39 -0
  43. package/dist/runtime/AnswerEdits.d.ts.map +1 -0
  44. package/dist/runtime/AnswerEdits.js +134 -0
  45. package/dist/runtime/AnswerVerification.d.ts.map +1 -1
  46. package/dist/runtime/AnswerVerification.js +4 -2
  47. package/dist/runtime/AuditGuards.d.ts +41 -0
  48. package/dist/runtime/AuditGuards.d.ts.map +1 -0
  49. package/dist/runtime/AuditGuards.js +81 -0
  50. package/dist/runtime/CompletionReport.d.ts +4 -2
  51. package/dist/runtime/CompletionReport.d.ts.map +1 -1
  52. package/dist/runtime/CompletionReport.js +8 -3
  53. package/dist/runtime/ContextCompression.d.ts +5 -0
  54. package/dist/runtime/ContextCompression.d.ts.map +1 -1
  55. package/dist/runtime/ContextCompression.js +16 -4
  56. package/dist/runtime/DeliveryDocs.d.ts +21 -0
  57. package/dist/runtime/DeliveryDocs.d.ts.map +1 -0
  58. package/dist/runtime/DeliveryDocs.js +148 -0
  59. package/dist/runtime/FigureCheck.d.ts +61 -2
  60. package/dist/runtime/FigureCheck.d.ts.map +1 -1
  61. package/dist/runtime/FigureCheck.js +210 -14
  62. package/dist/runtime/GatewayRequest.d.ts +13 -0
  63. package/dist/runtime/GatewayRequest.d.ts.map +1 -1
  64. package/dist/runtime/GatewayRequest.js +54 -1
  65. package/dist/runtime/InspectionConvergence.d.ts +4 -0
  66. package/dist/runtime/InspectionConvergence.d.ts.map +1 -1
  67. package/dist/runtime/InspectionConvergence.js +24 -1
  68. package/dist/runtime/InteractionContract.d.ts +15 -0
  69. package/dist/runtime/InteractionContract.d.ts.map +1 -1
  70. package/dist/runtime/InteractionContract.js +33 -0
  71. package/dist/runtime/InteractionRouter.d.ts +3 -3
  72. package/dist/runtime/InteractionRouter.d.ts.map +1 -1
  73. package/dist/runtime/InteractionRouter.js +1 -1
  74. package/dist/runtime/NumericProvenance.d.ts +102 -0
  75. package/dist/runtime/NumericProvenance.d.ts.map +1 -0
  76. package/dist/runtime/NumericProvenance.js +411 -0
  77. package/dist/runtime/OutageWait.d.ts +46 -5
  78. package/dist/runtime/OutageWait.d.ts.map +1 -1
  79. package/dist/runtime/OutageWait.js +81 -8
  80. package/dist/runtime/ResearchEvidence.d.ts +14 -0
  81. package/dist/runtime/ResearchEvidence.d.ts.map +1 -1
  82. package/dist/runtime/ResearchEvidence.js +139 -3
  83. package/dist/runtime/ReviewCoordinator.d.ts +22 -0
  84. package/dist/runtime/ReviewCoordinator.d.ts.map +1 -1
  85. package/dist/runtime/ReviewCoordinator.js +203 -25
  86. package/dist/runtime/ReviewSource.d.ts +5 -0
  87. package/dist/runtime/ReviewSource.d.ts.map +1 -1
  88. package/dist/runtime/ReviewSource.js +6 -1
  89. package/dist/runtime/SessionController.d.ts +85 -10
  90. package/dist/runtime/SessionController.d.ts.map +1 -1
  91. package/dist/runtime/SessionController.js +996 -176
  92. package/dist/runtime/StructuralEvidence.d.ts +10 -0
  93. package/dist/runtime/StructuralEvidence.d.ts.map +1 -1
  94. package/dist/runtime/StructuralEvidence.js +10 -0
  95. package/dist/runtime/TaskReview.d.ts +10 -0
  96. package/dist/runtime/TaskReview.d.ts.map +1 -1
  97. package/dist/runtime/TaskReview.js +31 -3
  98. package/dist/runtime/VerificationCommand.d.ts +8 -0
  99. package/dist/runtime/VerificationCommand.d.ts.map +1 -1
  100. package/dist/runtime/VerificationCommand.js +114 -0
  101. package/dist/runtime/WorkingStyle.d.ts +20 -0
  102. package/dist/runtime/WorkingStyle.d.ts.map +1 -0
  103. package/dist/runtime/WorkingStyle.js +71 -0
  104. package/dist/tools/ToolRegistry.d.ts.map +1 -1
  105. package/dist/tools/ToolRegistry.js +30 -4
  106. package/dist/tools/ToolTypes.d.ts +3 -0
  107. package/dist/tools/ToolTypes.d.ts.map +1 -1
  108. package/dist/tools/browser/BrowserTool.d.ts +23 -1
  109. package/dist/tools/browser/BrowserTool.d.ts.map +1 -1
  110. package/dist/tools/browser/BrowserTool.js +83 -4
  111. package/dist/tools/browser/BrowserWorker.js +142 -2
  112. package/dist/tools/browser/HttpFallback.d.ts +39 -0
  113. package/dist/tools/browser/HttpFallback.d.ts.map +1 -0
  114. package/dist/tools/browser/HttpFallback.js +240 -0
  115. package/dist/tools/calculation/CalculatorTool.d.ts +16 -1
  116. package/dist/tools/calculation/CalculatorTool.d.ts.map +1 -1
  117. package/dist/tools/calculation/CalculatorTool.js +321 -26
  118. package/dist/tools/deterministic/DeterministicTools.js +1 -1
  119. package/dist/tools/deterministic/node-worker.cjs +10 -10
  120. package/dist/tools/shell/AsyncProcess.d.ts +2 -0
  121. package/dist/tools/shell/AsyncProcess.d.ts.map +1 -1
  122. package/dist/tools/shell/AsyncProcess.js +38 -5
  123. package/dist/tools/shell/IsolatedExecutor.d.ts +29 -1
  124. package/dist/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  125. package/dist/tools/shell/IsolatedExecutor.js +179 -9
  126. package/dist/tools/shell/ShellTool.d.ts +2 -0
  127. package/dist/tools/shell/ShellTool.d.ts.map +1 -1
  128. package/dist/tools/shell/ShellTool.js +33 -3
  129. package/dist/tools/verification/CodeRunTool.d.ts +19 -0
  130. package/dist/tools/verification/CodeRunTool.d.ts.map +1 -0
  131. package/dist/tools/verification/CodeRunTool.js +104 -0
  132. package/dist/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -1
  133. package/dist/tools/verification/JavaScriptVerificationTool.js +21 -10
  134. package/dist/tools/verification/VitestTool.d.ts +27 -0
  135. package/dist/tools/verification/VitestTool.d.ts.map +1 -1
  136. package/dist/tools/verification/VitestTool.js +232 -18
  137. package/package.json +3 -3
@@ -1,33 +1,104 @@
1
1
  import { ToolExecutionError } from "../ToolTypes.js";
2
+ /** Set while a caller accepts integers beyond 2^53 as rounded doubles (capacity
3
+ * arithmetic such as bytes per year); without it they are refused as inexact. */
4
+ let inexactInteger;
2
5
  const finite = (value) => {
3
6
  if (!Number.isFinite(value))
4
7
  throw new Error("Calculation is undefined or exceeds finite numeric range");
5
- if (Number.isInteger(value) && !Number.isSafeInteger(value))
6
- throw new Error("Integer exceeds exact supported range");
8
+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
9
+ if (!inexactInteger)
10
+ throw new Error("Integer exceeds exact supported range");
11
+ inexactInteger();
12
+ }
7
13
  return value;
8
14
  };
15
+ const MAX_SCRIPT_CHARS = 32000;
9
16
  /** A numeric grammar, not JavaScript: every character is consumed, and nothing is evaluated as code. */
10
17
  const tokenize = (expression) => {
11
- if (typeof expression !== "string" || !expression.trim() || expression.length > 4096)
12
- throw new Error("Expected an expression of 1 to 4096 characters");
13
- const pattern = /\s+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|Math\.[A-Za-z_][A-Za-z_0-9]*|[A-Za-z_][A-Za-z_0-9]*|\*\*|[+*/%^(),-]/y;
18
+ if (typeof expression !== "string" || !expression.trim() || expression.length > MAX_SCRIPT_CHARS)
19
+ throw new Error(`Expected an expression of 1 to ${MAX_SCRIPT_CHARS} characters`);
20
+ const pattern = /\s+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|(?:Math|math)\.[A-Za-z_][A-Za-z_0-9]*|[A-Za-z_][A-Za-z_0-9]*|\*\*|[+*/%^(),=;[\]-]/y;
14
21
  const tokens = [];
15
22
  let offset = 0;
16
23
  while (offset < expression.length) {
17
24
  pattern.lastIndex = offset;
18
25
  const match = pattern.exec(expression);
19
26
  if (!match)
20
- throw new Error(`Unsupported character at position ${offset + 1}`);
27
+ throw new Error(`Unsupported character ${JSON.stringify(expression[offset])} at position ${offset + 1} of ${quoted(expression)}${unsupportedHint(expression[offset])}`);
21
28
  offset = pattern.lastIndex;
22
- // Literal aliases enter the same bounded grammar; no object lookup or code execution.
23
- const token = match[0].startsWith("Math.") ? match[0].slice(5) : match[0];
29
+ // Literal aliases (JavaScript Math.x, Python math.x) enter the same bounded grammar; no object lookup or code execution.
30
+ const token = /^(?:Math|math)\./.test(match[0]) ? match[0].slice(5) : match[0];
24
31
  if (token.trim())
25
- tokens.push(token === "PI" ? "pi" : token === "E" ? "e" : token);
32
+ tokens.push(token);
26
33
  if (tokens.length > 1024)
27
34
  throw new Error("Expression exceeds 1024 tokens");
28
35
  }
29
36
  return tokens;
30
37
  };
38
+ /** Statement text for an error message. */
39
+ const quoted = (statement) => JSON.stringify(statement.length > 80 ? `${statement.slice(0, 77)}...` : statement);
40
+ /** How to say the same thing in this grammar. */
41
+ const unsupportedHint = (char) => char === "{" ? ": use the expressions argument for named formulas"
42
+ : `"'`.includes(char) ? ": formulas hold numbers and names only, no strings"
43
+ : ["<", ">", "!", "&", "|", "?"].includes(char) ? ": comparisons and conditions need code; run it with run_code" : "";
44
+ /** Error function, |error| < 1e-15: a Taylor series near zero, a continued fraction in the tails. */
45
+ const erf = (x) => {
46
+ if (Number.isNaN(x))
47
+ return x;
48
+ const z = Math.abs(x);
49
+ if (z > 6)
50
+ return Math.sign(x);
51
+ if (z < 2.5) {
52
+ let term = z, sum = z;
53
+ for (let n = 1; n < 200; n++) {
54
+ term *= -z * z / n;
55
+ const next = term / (2 * n + 1);
56
+ sum += next;
57
+ if (Math.abs(next) < 1e-17 * Math.abs(sum))
58
+ break;
59
+ }
60
+ return Math.sign(x) * 2 / Math.sqrt(Math.PI) * sum;
61
+ }
62
+ return Math.sign(x) * (1 - erfcTail(z));
63
+ };
64
+ /** erfc for z >= 2.5 by Lentz's continued fraction, accurate where 1 - erf loses digits. */
65
+ const erfcTail = (z) => {
66
+ const tiny = 1e-300;
67
+ let f = z, c = z, d = 0;
68
+ for (let n = 1; n < 500; n++) {
69
+ const a = n / 2;
70
+ d = z + a * d;
71
+ d = Math.abs(d) < tiny ? tiny : d;
72
+ d = 1 / d;
73
+ c = z + a / c;
74
+ c = Math.abs(c) < tiny ? tiny : c;
75
+ const delta = c * d;
76
+ f *= delta;
77
+ if (Math.abs(delta - 1) < 1e-16)
78
+ break;
79
+ }
80
+ return Math.exp(-z * z) / Math.sqrt(Math.PI) / f;
81
+ };
82
+ const erfc = (x) => x >= 2.5 ? erfcTail(x) : 1 - erf(x);
83
+ /** Python's round: the nearest value with n decimal places, ties to even, decided
84
+ * on the exact binary value (round(2.675, 2) is 2.67 because 2.675 is stored a
85
+ * hair below the tie; round(2.5) is 2). The same answer run_code's Python gives. */
86
+ const roundTo = (value, places = 0) => {
87
+ if (!Number.isInteger(places) || places < -15 || places > 15)
88
+ throw new Error("round(x, n) takes a whole number of places from -15 to 15");
89
+ if (places < 0)
90
+ return roundTo(value / 10 ** -places, 0) * 10 ** -places;
91
+ const magnitude = Math.abs(value);
92
+ if (magnitude >= 1e21)
93
+ return value;
94
+ // toFixed rounds the exact binary value and takes the larger candidate on a tie.
95
+ const up = magnitude.toFixed(places), exact = magnitude.toFixed(100);
96
+ const point = exact.indexOf("."), tail = exact.slice(point + 1 + places);
97
+ let result = Number(up);
98
+ if (/^50*$/.test(tail) && Number(up.replace(".", "").at(-1)) % 2 === 1)
99
+ result = Number((result - 10 ** -places).toFixed(places));
100
+ return Math.sign(value) * result === 0 ? 0 : Math.sign(value) * result;
101
+ };
31
102
  const countArgs = (n, k) => {
32
103
  if (!Number.isInteger(n) || !Number.isInteger(k) || n < 0 || k < 0)
33
104
  throw new Error("Counting functions take non-negative integers");
@@ -61,10 +132,29 @@ const functions = new Map([
61
132
  ["sin", { min: 1, max: 1, run: Math.sin }],
62
133
  ["cos", { min: 1, max: 1, run: Math.cos }],
63
134
  ["tan", { min: 1, max: 1, run: Math.tan }],
135
+ // Orbit, heading and angle questions were answered from memory after asin,
136
+ // acos, atan and atan2 were each refused.
137
+ ["asin", { min: 1, max: 1, run: Math.asin }],
138
+ ["acos", { min: 1, max: 1, run: Math.acos }],
139
+ ["atan", { min: 1, max: 1, run: Math.atan }],
140
+ ["atan2", { min: 2, max: 2, run: Math.atan2 }],
141
+ ["sinh", { min: 1, max: 1, run: Math.sinh }],
142
+ ["cosh", { min: 1, max: 1, run: Math.cosh }],
143
+ ["tanh", { min: 1, max: 1, run: Math.tanh }],
144
+ ["log2", { min: 1, max: 1, run: Math.log2 }],
145
+ ["cbrt", { min: 1, max: 1, run: Math.cbrt }],
146
+ ["hypot", { min: 1, max: 128, run: Math.hypot }],
147
+ ["trunc", { min: 1, max: 1, run: Math.trunc }],
148
+ ["sign", { min: 1, max: 1, run: Math.sign }],
64
149
  ["pow", { min: 2, max: 2, run: Math.pow }],
65
150
  ["floor", { min: 1, max: 1, run: Math.floor }],
66
151
  ["ceil", { min: 1, max: 1, run: Math.ceil }],
67
- ["round", { min: 1, max: 1, run: Math.round }],
152
+ ["round", { min: 1, max: 2, run: roundTo }],
153
+ // Normal-distribution work (option pricing, z-scores) was done from memory after erf was refused.
154
+ ["erf", { min: 1, max: 1, run: erf }],
155
+ ["erfc", { min: 1, max: 1, run: erfc }],
156
+ ["normcdf", { min: 1, max: 1, run: (x) => 0.5 * erfc(-x / Math.SQRT2) }],
157
+ ["normpdf", { min: 1, max: 1, run: (x) => Math.exp(-x * x / 2) / Math.sqrt(2 * Math.PI) }],
68
158
  ["min", { min: 1, max: 128, run: Math.min }],
69
159
  ["max", { min: 1, max: 128, run: Math.max }],
70
160
  ["sum", { min: 1, max: 128, run: (...args) => args.reduce((total, value) => finite(total + value), 0) }],
@@ -74,9 +164,22 @@ const functions = new Map([
74
164
  ...["perm", "nPr", "P"].map(name => [name, { min: 2, max: 2, run: permutations }]),
75
165
  ["factorial", { min: 1, max: 1, run: (n) => permutations(n, n) }],
76
166
  ]);
167
+ const variableName = (name) => !!name && /^[A-Za-z][A-Za-z_0-9]{0,63}$/.test(name);
77
168
  /** Bounded Pratt parser; exponentiation is right associative and binds more tightly than unary minus. */
78
- export const evaluateCalculation = (expression) => {
169
+ export const evaluateCalculation = (expression, options = {}) => {
79
170
  const tokens = tokenize(expression);
171
+ if (tokens.includes("=") || tokens.includes(";"))
172
+ throw new Error("One formula only; assignments and several statements belong in a calculation script");
173
+ const previous = inexactInteger;
174
+ inexactInteger = options.onInexactInteger;
175
+ try {
176
+ return evaluateTokens(tokens, options.variables);
177
+ }
178
+ finally {
179
+ inexactInteger = previous;
180
+ }
181
+ };
182
+ const evaluateTokens = (tokens, variables) => {
80
183
  let position = 0;
81
184
  const expect = (token) => {
82
185
  if (tokens[position++] !== token)
@@ -97,14 +200,23 @@ export const evaluateCalculation = (expression) => {
97
200
  }
98
201
  else if (token && /^(?:\d|\.)/.test(token))
99
202
  value = finite(Number(token));
100
- else if (token === "pi")
203
+ // An assigned name wins over a constant or function of the same spelling:
204
+ // e is an eccentricity and P a pressure as often as they are e and nPr.
205
+ else if (token && variables?.has(token) && tokens[position] !== "(")
206
+ value = variables.get(token);
207
+ // pi() as Python and spreadsheet users write it.
208
+ else if (token === "pi" || token === "PI") {
101
209
  value = Math.PI;
102
- else if (token === "e")
210
+ if (tokens[position] === "(" && tokens[position + 1] === ")")
211
+ position += 2;
212
+ }
213
+ else if (token === "e" || token === "E")
103
214
  value = Math.E;
104
215
  else {
105
216
  const fn = functions.get(token);
106
217
  if (!fn)
107
- throw new Error(`Expected a number or supported function, received ${token ?? "end of expression"}`);
218
+ throw new Error(variableName(token) ? `Unknown name ${token}: assign it first (${token} = ...) or use a supported function`
219
+ : `Expected a number or supported function, received ${token ?? "end of expression"}`);
108
220
  expect("(");
109
221
  const args = [];
110
222
  if (tokens[position] !== ")") {
@@ -158,11 +270,150 @@ export const evaluateCalculation = (expression) => {
158
270
  // JSON has a single zero representation; keep the exported numeric API consistent.
159
271
  return result === 0 ? 0 : result;
160
272
  };
273
+ /** A fixed-point iteration or a 12-step recurrence written out takes a few hundred statements. */
274
+ const MAX_STATEMENTS = 1000;
275
+ const MAX_LABELS = 256;
276
+ const SEPARATOR_HINT = "write numbers without thousands separators (1000, not 1,000), or list several results in brackets, such as [a, b]";
277
+ /** A statement that lists values must be bracketed: [a, b, c]. A comma anywhere
278
+ * else at the top level is refused, never read as a list: "1,000 * 3" is a
279
+ * thousands separator, and reading it as [1, 0] would be a wrong success. */
280
+ const listItems = (tokens) => {
281
+ const split = (inner) => {
282
+ const items = [];
283
+ let depth = 0, current = [];
284
+ for (const token of inner) {
285
+ if (token === "(" || token === "[")
286
+ depth++;
287
+ else if (token === ")" || token === "]")
288
+ depth--;
289
+ if (token === "," && depth === 0) {
290
+ items.push(current);
291
+ current = [];
292
+ }
293
+ else
294
+ current.push(token);
295
+ }
296
+ items.push(current);
297
+ return items;
298
+ };
299
+ let enclosing = tokens[0] === "[" && tokens.at(-1) === "]";
300
+ if (enclosing) {
301
+ let depth = 0;
302
+ for (let index = 0; index < tokens.length; index++) {
303
+ if (tokens[index] === "(" || tokens[index] === "[")
304
+ depth++;
305
+ else if (tokens[index] === ")" || tokens[index] === "]")
306
+ depth--;
307
+ if (depth === 0 && index < tokens.length - 1) {
308
+ enclosing = false;
309
+ break;
310
+ }
311
+ }
312
+ }
313
+ if (!enclosing) {
314
+ // (a, b) or a, b: a comma outside any function call.
315
+ const top = split(tokens);
316
+ const grouped = tokens[0] === "(" && tokens.at(-1) === ")" && split(tokens.slice(1, -1)).length > 1;
317
+ if (top.length > 1 || grouped)
318
+ throw new Error(`A comma outside a function call is not a list: ${SEPARATOR_HINT}`);
319
+ return undefined;
320
+ }
321
+ const items = split(tokens.slice(1, -1));
322
+ if (items.some(item => !item.length || item.includes("[") || item.includes("]")))
323
+ throw new Error("A result list holds formulas separated by commas, such as [a, b, a*b]; lists cannot be nested or empty");
324
+ return items;
325
+ };
326
+ /** A calculation script: statements separated by ";" or line breaks, each either
327
+ * `name = formula` or a bare formula. Names are numbers held in a Map and can be
328
+ * used by later statements. Still the numeric grammar above: no code runs.
329
+ * The models write multi-step arithmetic this way; refusing it cost a round
330
+ * trip on about one calculator call in three. */
331
+ export const evaluateCalculationScript = (script, options = {}) => {
332
+ if (typeof script !== "string" || !script.trim() || script.length > MAX_SCRIPT_CHARS)
333
+ throw new Error(`Expected an expression of 1 to ${MAX_SCRIPT_CHARS} characters`);
334
+ // A line break separates statements only outside parentheses, so a formula may wrap.
335
+ const statements = [];
336
+ let depth = 0, piece = "";
337
+ for (const char of script) {
338
+ if (char === "(")
339
+ depth++;
340
+ else if (char === ")")
341
+ depth = Math.max(0, depth - 1);
342
+ if (char === ";" || char === "\n" && depth === 0) {
343
+ statements.push(piece);
344
+ piece = "";
345
+ }
346
+ else
347
+ piece += char === "\n" ? " " : char;
348
+ }
349
+ statements.push(piece);
350
+ for (let index = statements.length - 1; index >= 0; index--) {
351
+ statements[index] = statements[index].trim();
352
+ if (!statements[index])
353
+ statements.splice(index, 1);
354
+ }
355
+ if (!statements.length)
356
+ throw new Error("Expected an expression of 1 to 4096 characters");
357
+ if (statements.length > MAX_STATEMENTS)
358
+ throw new Error(`A calculation holds at most ${MAX_STATEMENTS} statements; for longer iterations write a loop and run it with run_code`);
359
+ const variables = new Map(options.variables ?? []);
360
+ const values = new Map();
361
+ let result = NaN;
362
+ const previous = inexactInteger;
363
+ inexactInteger = options.onInexactInteger;
364
+ try {
365
+ for (const [index, statement] of statements.entries()) {
366
+ try {
367
+ // In a result list, [12,500] is far more often twelve thousand five hundred
368
+ // than two values. Tokens carry no spacing, so read the source: [100, 200] is a list.
369
+ const separator = /^\[/.test(statement) ? statement.match(/\d,\d{3}(?!\d)/) : null;
370
+ if (separator)
371
+ throw new Error(`Ambiguous list item ${separator[0]}: ${SEPARATOR_HINT}, with a space after each comma`);
372
+ const tokens = tokenize(statement);
373
+ if (tokens[1] === "=") {
374
+ const name = tokens[0];
375
+ if (!variableName(name))
376
+ throw new Error(`${name} cannot be assigned: a name starts with a letter and holds letters, digits or _`);
377
+ if (tokens.indexOf("=", 2) !== -1)
378
+ throw new Error("One assignment per statement");
379
+ if (tokens.includes("[") || listItems(tokens.slice(2)))
380
+ throw new Error("A name holds one number; list several results in the last statement instead, such as [a, b, c]");
381
+ const value = evaluateTokens(tokens.slice(2), variables);
382
+ variables.set(name, value);
383
+ values.set(name, value);
384
+ result = value;
385
+ }
386
+ else {
387
+ if (tokens.includes("="))
388
+ throw new Error("Assignments take the form name = formula");
389
+ const items = listItems(tokens);
390
+ result = items ? items.map(item => { const value = evaluateTokens(item, variables); return value === 0 ? 0 : value; }) : evaluateTokens(tokens, variables);
391
+ }
392
+ }
393
+ catch (error) {
394
+ const message = error instanceof Error ? error.message : String(error);
395
+ throw new Error(statements.length > 1 ? `Statement ${index + 1} of ${statements.length} (${quoted(statement)}): ${message}` : message);
396
+ }
397
+ }
398
+ }
399
+ finally {
400
+ inexactInteger = previous;
401
+ }
402
+ return { result: typeof result === "number" && result === 0 ? 0 : result, values: Object.fromEntries(values) };
403
+ };
404
+ const ARITHMETIC = "IEEE-754 double; not exact decimal arithmetic";
405
+ /** Names that are constants until a calculation assigns them. */
406
+ const CONSTANT_NAMES = new Set(["e", "E", "pi", "PI"]);
407
+ const shadowNote = (names) => {
408
+ const shadowed = names.filter(name => CONSTANT_NAMES.has(name));
409
+ return shadowed.length ? `${shadowed.join(", ")} ${shadowed.length > 1 ? "were" : "was"} given a value here, so later formulas use that value, not the constant (${shadowed.map(name => name.toLowerCase() === "e" ? "Euler's number: use exp(x)" : "pi: use acos(-1)").join("; ")}).` : undefined;
410
+ };
411
+ const INEXACT = "An integer above 2^53 was rounded to about 16 significant digits; use decimal_calculate where every digit matters";
161
412
  export const createCalculatorTool = () => ({
162
413
  name: "calculate", capability: "calculation", readOnly: true,
163
- description: "Calculate {expression:'formula'} OR {expressions:{label:'formula'}} (up to16). Supports exp,ln/log(natural),log10,pow,sin/cos/tan(radians),abs,sqrt,floor,ceil,round,min,max,sum,comb/C(n,k),perm/P(n,k),factorial; + - * / %, ^ **, pi,e. Math.function aliases accepted only for this allowlist. No variables, assignments or code. IEEE-754 approximate; exact decimals use decimal_calculate. Tool success checks arithmetic, not whether your formula models the request.",
164
- inputSchema: { type: "object", properties: { expression: { type: "string", description: "One numeric formula, e.g. exp(-2)*3. Supply this OR expressions.", minLength: 1, maxLength: 4096 },
165
- expressions: { type: "object", description: "Map labels to complete formula STRINGS, e.g. {total:'2*3+4',check:'10'}. Each formula is independent; labels are not variables. Supply this OR expression.", minProperties: 1, maxProperties: 16, propertyNames: { pattern: "^[A-Za-z][A-Za-z0-9_]{0,63}$" }, additionalProperties: true },
414
+ description: `Calculate {expression:'formula'} OR {expressions:{label:'formula'}} (up to ${MAX_LABELS}). An expression may hold up to ${MAX_STATEMENTS} statements separated by ; or line breaks, with names: 'r1 = 6778; v = sqrt(398600/r1); [v, v*2]'; a final [a, b] returns each value; write numbers without thousands separators. In expressions, labels may use each other in any order. Supports exp,ln/log(natural),log2,log10,pow,sqrt,cbrt,hypot,sin/cos/tan,asin/acos/atan/atan2,sinh/cosh/tanh (radians),abs,floor,ceil,round(x) and round(x,n) (Python: ties to even),trunc,sign,min,max,sum,erf,erfc,normcdf,normpdf,comb/C(n,k),perm/P(n,k),factorial; + - * / %, ^ **, pi (or pi()), e. Math.x and math.x aliases accepted for this allowlist. Numbers only: loops, conditions, strings and imports need run_code. IEEE-754 approximate; exact decimals use decimal_calculate. Tool success checks arithmetic, not whether your formula models the request.`,
415
+ inputSchema: { type: "object", properties: { expression: { type: "string", description: "A numeric formula, e.g. exp(-2)*3, or statements separated by ; such as 'a = 2*3; b = a+4; [a, b, b/2]'. Supply this OR expressions.", minLength: 1, maxLength: MAX_SCRIPT_CHARS },
416
+ expressions: { type: "object", description: "Map labels to complete formula STRINGS, e.g. {total:'base*3+4',base:'2'}. A formula may use any other label as a number. Supply this OR expression.", minProperties: 1, maxProperties: MAX_LABELS, propertyNames: { pattern: "^[A-Za-z][A-Za-z0-9_]{0,63}$" }, additionalProperties: true },
166
417
  }, oneOf: [{ required: ["expression"] }, { required: ["expressions"] }], additionalProperties: false },
167
418
  handler: async (args, context) => {
168
419
  context.signal?.throwIfAborted();
@@ -170,22 +421,66 @@ export const createCalculatorTool = () => ({
170
421
  const input = args;
171
422
  if (!input || typeof input !== "object" || Array.isArray(input) || input.expression === undefined && input.expressions === undefined)
172
423
  throw new Error('Use {"expression":"2+3"} or {"expressions":{"total":"2+3"}}; formulas must be strings');
424
+ let inexact = false;
425
+ const options = { onInexactInteger: () => { inexact = true; } };
426
+ let assigned = [];
427
+ const note = () => { const warnings = [inexact ? INEXACT : undefined, shadowNote(assigned)].filter(Boolean); return warnings.length ? { arithmetic: ARITHMETIC, warning: warnings.join(" ") } : { arithmetic: ARITHMETIC }; };
173
428
  if (input.expressions !== undefined) {
174
- if (input.expression !== undefined || !input.expressions || Array.isArray(input.expressions) || Object.keys(input.expressions).length < 1 || Object.keys(input.expressions).length > 16)
175
- throw new Error("Supply expression or up to16 named expressions, not both");
176
- const results = Object.fromEntries(Object.entries(input.expressions).map(([label, expression]) => {
429
+ if (input.expression !== undefined)
430
+ throw new Error("Supply expression or expressions, not both");
431
+ if (!input.expressions || typeof input.expressions !== "object" || Array.isArray(input.expressions) || Object.keys(input.expressions).length < 1 || Object.keys(input.expressions).length > MAX_LABELS)
432
+ throw new Error(`Supply 1 to ${MAX_LABELS} named expressions`);
433
+ const entries = Object.entries(input.expressions);
434
+ for (const [label, expression] of entries) {
177
435
  if (!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(label))
178
436
  throw new Error("Invalid calculation label");
179
- return [label, evaluateCalculation(expression)];
180
- }));
181
- return { output: JSON.stringify({ results, arithmetic: "IEEE-754 double; not exact decimal arithmetic" }) };
437
+ if (typeof expression !== "string")
438
+ throw new Error(`Formula ${label} must be a string such as "2*3+4"`);
439
+ }
440
+ // Labels resolve in dependency order, so a formula may use a label written
441
+ // after it ("Unknown name H17" cost three raw-arm calls in cycle 7); the
442
+ // results keep the order they were given in.
443
+ const variables = new Map();
444
+ let pending = entries;
445
+ while (pending.length) {
446
+ const waiting = [];
447
+ for (const [label, expression] of pending) {
448
+ // A label still waiting on another label (P before P is computed would read as perm P(n,k)).
449
+ const names = expression.replace(/\b(?:Math|math)\.[A-Za-z_]\w*/g, "").match(/[A-Za-z_][A-Za-z_0-9]*/g) ?? [];
450
+ if (names.some(name => name !== label && !variables.has(name) && pending.some(([other]) => other === name))) {
451
+ waiting.push([label, expression]);
452
+ continue;
453
+ }
454
+ try {
455
+ variables.set(label, evaluateCalculation(expression, { ...options, variables }));
456
+ }
457
+ catch (error) {
458
+ const message = error instanceof Error ? error.message : String(error);
459
+ const unknown = message.match(/^Unknown name ([A-Za-z_][A-Za-z_0-9]*)/)?.[1];
460
+ if (unknown && unknown !== label && pending.some(([other]) => other === unknown)) {
461
+ waiting.push([label, expression]);
462
+ continue;
463
+ }
464
+ throw new Error(`Formula ${label} (${quoted(String(expression))}): ${message}`);
465
+ }
466
+ }
467
+ if (waiting.length === pending.length)
468
+ throw new Error(`Formulas ${waiting.map(([label]) => label).join(", ")} depend on each other in a cycle; give one of them a number`);
469
+ pending = waiting;
470
+ }
471
+ const results = Object.fromEntries(entries.map(([label]) => [label, variables.get(label)]));
472
+ assigned = Object.keys(results);
473
+ return { output: JSON.stringify({ results, ...note() }) };
182
474
  }
183
- const result = evaluateCalculation(input.expression);
184
- return { output: JSON.stringify({ result, arithmetic: "IEEE-754 double; not exact decimal arithmetic" }) };
475
+ if (typeof input.expression !== "string")
476
+ throw new Error('Use {"expression":"2+3"}; the formula must be a string');
477
+ const { result, values } = evaluateCalculationScript(input.expression, options);
478
+ assigned = Object.keys(values);
479
+ return { output: JSON.stringify(Object.keys(values).length ? { result, values, ...note() } : { result, ...note() }) };
185
480
  }
186
481
  catch (error) {
187
482
  const message = error instanceof Error ? error.message : String(error);
188
- throw new ToolExecutionError("tool_invalid_args", `${message}. Correct the arguments before retrying; use tools_describe for the schema. No assignments or arbitrary code; supported functions include exp(x), ln(x), log10(x), pow(x,y).`, { retryable: false });
483
+ throw new ToolExecutionError("tool_invalid_args", `${message}. Correct the arguments before retrying; use tools_describe for the schema. Write numbers, names (a = 2*3; a+1), the listed functions and, last, a result list such as [a, b]. Loops, conditions, strings and imports need code: run it with run_code (python or javascript) and print the values.`, { retryable: false });
189
484
  }
190
485
  },
191
486
  });
@@ -28,7 +28,7 @@ const schemas = {
28
28
  }, ["operation"]), 16) }, ["rows", "steps"]),
29
29
  };
30
30
  const descriptions = {
31
- decimal_calculate: "Decimal.js arithmetic on decimal STRING operands, default 50 significant digits, half-even rounding. Exact decimal representation with reported precision; use for money and decimal calculations.",
31
+ decimal_calculate: "Decimal.js arithmetic on decimal STRING operands (\"12.50\") or fraction strings (\"20/11\"), default 50 significant digits, half-even rounding. Exact decimal representation with reported precision; use for money and decimal calculations.",
32
32
  numerical_calculate: "math.js numerical vectors/matrices: determinant, inverse, multiply, transpose, linear solve, statistics, dot/cross. args is the function argument list; IEEE-754 approximations, not exact symbolic math.",
33
33
  validate_json: "Ajv validates data against JSON Schema draft-07, without mutation/coercion, remote refs or format checks. Returns valid/errors. Offline and bounded.",
34
34
  symbolic_math: "SymPy exact symbolic algebra/calculus. Declare symbols; expression uses + - * / ** and sin/cos/tan/exp/log/sqrt/Abs, pi/E. solve treats expression as zero; variable required for solve/differentiate/integrate.",