@mcoda/mswarm 0.1.135-codali.42 → 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 (92) hide show
  1. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts +5 -0
  2. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts.map +1 -1
  3. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.js +63 -0
  4. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.js +2 -2
  5. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.js +2 -2
  6. package/dist/vendor/codali/permissions/PermissionGate.js +1 -1
  7. package/dist/vendor/codali/providers/ClaudeCliProvider.d.ts.map +1 -1
  8. package/dist/vendor/codali/providers/ClaudeCliProvider.js +1 -0
  9. package/dist/vendor/codali/providers/CodexCliProvider.d.ts.map +1 -1
  10. package/dist/vendor/codali/providers/CodexCliProvider.js +1 -0
  11. package/dist/vendor/codali/providers/ModelServiceError.d.ts +14 -0
  12. package/dist/vendor/codali/providers/ModelServiceError.d.ts.map +1 -1
  13. package/dist/vendor/codali/providers/ModelServiceError.js +15 -2
  14. package/dist/vendor/codali/providers/OllamaRemoteProvider.d.ts.map +1 -1
  15. package/dist/vendor/codali/providers/OllamaRemoteProvider.js +1 -0
  16. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  17. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +4 -0
  18. package/dist/vendor/codali/providers/ProviderTypes.d.ts +4 -0
  19. package/dist/vendor/codali/providers/ProviderTypes.d.ts.map +1 -1
  20. package/dist/vendor/codali/runtime/AnswerEdits.d.ts +39 -0
  21. package/dist/vendor/codali/runtime/AnswerEdits.d.ts.map +1 -0
  22. package/dist/vendor/codali/runtime/AnswerEdits.js +134 -0
  23. package/dist/vendor/codali/runtime/AnswerVerification.d.ts.map +1 -1
  24. package/dist/vendor/codali/runtime/AnswerVerification.js +4 -2
  25. package/dist/vendor/codali/runtime/AuditGuards.d.ts +41 -0
  26. package/dist/vendor/codali/runtime/AuditGuards.d.ts.map +1 -0
  27. package/dist/vendor/codali/runtime/AuditGuards.js +81 -0
  28. package/dist/vendor/codali/runtime/CompletionReport.d.ts +4 -2
  29. package/dist/vendor/codali/runtime/CompletionReport.d.ts.map +1 -1
  30. package/dist/vendor/codali/runtime/CompletionReport.js +8 -3
  31. package/dist/vendor/codali/runtime/DeliveryDocs.d.ts +21 -0
  32. package/dist/vendor/codali/runtime/DeliveryDocs.d.ts.map +1 -0
  33. package/dist/vendor/codali/runtime/DeliveryDocs.js +148 -0
  34. package/dist/vendor/codali/runtime/FigureCheck.d.ts +61 -2
  35. package/dist/vendor/codali/runtime/FigureCheck.d.ts.map +1 -1
  36. package/dist/vendor/codali/runtime/FigureCheck.js +210 -14
  37. package/dist/vendor/codali/runtime/GatewayRequest.d.ts +13 -0
  38. package/dist/vendor/codali/runtime/GatewayRequest.d.ts.map +1 -1
  39. package/dist/vendor/codali/runtime/GatewayRequest.js +54 -1
  40. package/dist/vendor/codali/runtime/InspectionConvergence.d.ts +4 -0
  41. package/dist/vendor/codali/runtime/InspectionConvergence.d.ts.map +1 -1
  42. package/dist/vendor/codali/runtime/InspectionConvergence.js +24 -1
  43. package/dist/vendor/codali/runtime/NumericProvenance.d.ts +102 -0
  44. package/dist/vendor/codali/runtime/NumericProvenance.d.ts.map +1 -0
  45. package/dist/vendor/codali/runtime/NumericProvenance.js +411 -0
  46. package/dist/vendor/codali/runtime/OutageWait.d.ts +13 -0
  47. package/dist/vendor/codali/runtime/OutageWait.d.ts.map +1 -1
  48. package/dist/vendor/codali/runtime/OutageWait.js +13 -0
  49. package/dist/vendor/codali/runtime/ResearchEvidence.d.ts.map +1 -1
  50. package/dist/vendor/codali/runtime/ResearchEvidence.js +79 -3
  51. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts +22 -0
  52. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts.map +1 -1
  53. package/dist/vendor/codali/runtime/ReviewCoordinator.js +201 -24
  54. package/dist/vendor/codali/runtime/SessionController.d.ts +31 -22
  55. package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
  56. package/dist/vendor/codali/runtime/SessionController.js +592 -176
  57. package/dist/vendor/codali/runtime/StructuralEvidence.d.ts +10 -0
  58. package/dist/vendor/codali/runtime/StructuralEvidence.d.ts.map +1 -1
  59. package/dist/vendor/codali/runtime/StructuralEvidence.js +10 -0
  60. package/dist/vendor/codali/runtime/TaskReview.d.ts +10 -0
  61. package/dist/vendor/codali/runtime/TaskReview.d.ts.map +1 -1
  62. package/dist/vendor/codali/runtime/TaskReview.js +14 -1
  63. package/dist/vendor/codali/tools/ToolRegistry.d.ts.map +1 -1
  64. package/dist/vendor/codali/tools/ToolRegistry.js +11 -2
  65. package/dist/vendor/codali/tools/browser/BrowserWorker.js +142 -2
  66. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts +1 -1
  67. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -1
  68. package/dist/vendor/codali/tools/calculation/CalculatorTool.js +209 -41
  69. package/dist/vendor/codali/tools/deterministic/DeterministicTools.js +1 -1
  70. package/dist/vendor/codali/tools/deterministic/node-worker.cjs +10 -10
  71. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts +2 -0
  72. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts.map +1 -1
  73. package/dist/vendor/codali/tools/shell/AsyncProcess.js +32 -5
  74. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +29 -1
  75. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  76. package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +169 -7
  77. package/dist/vendor/codali/tools/shell/ShellTool.js +1 -1
  78. package/dist/vendor/codali/tools/verification/CodeRunTool.d.ts +19 -0
  79. package/dist/vendor/codali/tools/verification/CodeRunTool.d.ts.map +1 -0
  80. package/dist/vendor/codali/tools/verification/CodeRunTool.js +104 -0
  81. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -1
  82. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.js +21 -10
  83. package/dist/vendor/codali/tools/verification/VitestTool.d.ts +27 -0
  84. package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -1
  85. package/dist/vendor/codali/tools/verification/VitestTool.js +160 -16
  86. package/dist/vendor/config/deterministic/node-worker.mjs +15 -2
  87. package/dist/vendor/config/skills/code-implementation/SKILL.md +1 -1
  88. package/dist/vendor/config/skills/planning/SKILL.md +1 -1
  89. package/dist/vendor/config/skills/ui-ux-design/SKILL.md +1 -1
  90. package/dist/vendor/config/skills/webapp-testing/SKILL.md +2 -11
  91. package/dist/vendor/config/skills/webapp-testing/journey-driver.mjs +104 -3
  92. package/package.json +3 -3
@@ -12,21 +12,22 @@ const finite = (value) => {
12
12
  }
13
13
  return value;
14
14
  };
15
+ const MAX_SCRIPT_CHARS = 32000;
15
16
  /** A numeric grammar, not JavaScript: every character is consumed, and nothing is evaluated as code. */
16
17
  const tokenize = (expression) => {
17
- if (typeof expression !== "string" || !expression.trim() || expression.length > 4096)
18
- throw new Error("Expected an expression of 1 to 4096 characters");
19
- 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;
20
21
  const tokens = [];
21
22
  let offset = 0;
22
23
  while (offset < expression.length) {
23
24
  pattern.lastIndex = offset;
24
25
  const match = pattern.exec(expression);
25
26
  if (!match)
26
- 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])}`);
27
28
  offset = pattern.lastIndex;
28
- // Literal aliases enter the same bounded grammar; no object lookup or code execution.
29
- 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];
30
31
  if (token.trim())
31
32
  tokens.push(token);
32
33
  if (tokens.length > 1024)
@@ -34,6 +35,70 @@ const tokenize = (expression) => {
34
35
  }
35
36
  return tokens;
36
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
+ };
37
102
  const countArgs = (n, k) => {
38
103
  if (!Number.isInteger(n) || !Number.isInteger(k) || n < 0 || k < 0)
39
104
  throw new Error("Counting functions take non-negative integers");
@@ -84,7 +149,12 @@ const functions = new Map([
84
149
  ["pow", { min: 2, max: 2, run: Math.pow }],
85
150
  ["floor", { min: 1, max: 1, run: Math.floor }],
86
151
  ["ceil", { min: 1, max: 1, run: Math.ceil }],
87
- ["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) }],
88
158
  ["min", { min: 1, max: 128, run: Math.min }],
89
159
  ["max", { min: 1, max: 128, run: Math.max }],
90
160
  ["sum", { min: 1, max: 128, run: (...args) => args.reduce((total, value) => finite(total + value), 0) }],
@@ -134,8 +204,12 @@ const evaluateTokens = (tokens, variables) => {
134
204
  // e is an eccentricity and P a pressure as often as they are e and nPr.
135
205
  else if (token && variables?.has(token) && tokens[position] !== "(")
136
206
  value = variables.get(token);
137
- else if (token === "pi" || token === "PI")
207
+ // pi() as Python and spreadsheet users write it.
208
+ else if (token === "pi" || token === "PI") {
138
209
  value = Math.PI;
210
+ if (tokens[position] === "(" && tokens[position + 1] === ")")
211
+ position += 2;
212
+ }
139
213
  else if (token === "e" || token === "E")
140
214
  value = Math.E;
141
215
  else {
@@ -196,15 +270,67 @@ const evaluateTokens = (tokens, variables) => {
196
270
  // JSON has a single zero representation; keep the exported numeric API consistent.
197
271
  return result === 0 ? 0 : result;
198
272
  };
199
- const MAX_STATEMENTS = 64;
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
+ };
200
326
  /** A calculation script: statements separated by ";" or line breaks, each either
201
327
  * `name = formula` or a bare formula. Names are numbers held in a Map and can be
202
328
  * used by later statements. Still the numeric grammar above: no code runs.
203
329
  * The models write multi-step arithmetic this way; refusing it cost a round
204
330
  * trip on about one calculator call in three. */
205
331
  export const evaluateCalculationScript = (script, options = {}) => {
206
- if (typeof script !== "string" || !script.trim() || script.length > 4096)
207
- throw new Error("Expected an expression of 1 to 4096 characters");
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`);
208
334
  // A line break separates statements only outside parentheses, so a formula may wrap.
209
335
  const statements = [];
210
336
  let depth = 0, piece = "";
@@ -229,36 +355,51 @@ export const evaluateCalculationScript = (script, options = {}) => {
229
355
  if (!statements.length)
230
356
  throw new Error("Expected an expression of 1 to 4096 characters");
231
357
  if (statements.length > MAX_STATEMENTS)
232
- throw new Error(`A calculation holds at most ${MAX_STATEMENTS} 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`);
233
359
  const variables = new Map(options.variables ?? []);
234
360
  const values = new Map();
235
361
  let result = NaN;
236
362
  const previous = inexactInteger;
237
363
  inexactInteger = options.onInexactInteger;
238
364
  try {
239
- for (const statement of statements) {
240
- const tokens = tokenize(statement);
241
- if (tokens[1] === "=") {
242
- const name = tokens[0];
243
- if (!variableName(name))
244
- throw new Error(`${name} cannot be assigned: a name starts with a letter and holds letters, digits or _`);
245
- if (tokens.indexOf("=", 2) !== -1)
246
- throw new Error("One assignment per statement");
247
- result = evaluateTokens(tokens.slice(2), variables);
248
- variables.set(name, result);
249
- values.set(name, result);
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
+ }
250
392
  }
251
- else {
252
- if (tokens.includes("="))
253
- throw new Error("Assignments take the form name = formula");
254
- result = evaluateTokens(tokens, variables);
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);
255
396
  }
256
397
  }
257
398
  }
258
399
  finally {
259
400
  inexactInteger = previous;
260
401
  }
261
- return { result: result === 0 ? 0 : result, values: Object.fromEntries(values) };
402
+ return { result: typeof result === "number" && result === 0 ? 0 : result, values: Object.fromEntries(values) };
262
403
  };
263
404
  const ARITHMETIC = "IEEE-754 double; not exact decimal arithmetic";
264
405
  /** Names that are constants until a calculation assigns them. */
@@ -270,9 +411,9 @@ const shadowNote = (names) => {
270
411
  const INEXACT = "An integer above 2^53 was rounded to about 16 significant digits; use decimal_calculate where every digit matters";
271
412
  export const createCalculatorTool = () => ({
272
413
  name: "calculate", capability: "calculation", readOnly: true,
273
- description: "Calculate {expression:'formula'} OR {expressions:{label:'formula'}} (up to 64). An expression may hold several statements separated by ; with names: 'r1 = 6778; v = sqrt(398600/r1); v*2'. In expressions, a later formula may use an earlier label as a number. 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,trunc,sign,min,max,sum,comb/C(n,k),perm/P(n,k),factorial; + - * / %, ^ **, pi,e. Math.function aliases accepted only for this allowlist. Numbers only: no strings, lists, loops, imports or code. IEEE-754 approximate; exact decimals use decimal_calculate. Tool success checks arithmetic, not whether your formula models the request.",
274
- 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; b/2'. Supply this OR expressions.", minLength: 1, maxLength: 4096 },
275
- expressions: { type: "object", description: "Map labels to complete formula STRINGS, e.g. {total:'2*3+4',check:'10'}. A formula may use the label of an earlier formula as a number. Supply this OR expression.", minProperties: 1, maxProperties: 64, 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 },
276
417
  }, oneOf: [{ required: ["expression"] }, { required: ["expressions"] }], additionalProperties: false },
277
418
  handler: async (args, context) => {
278
419
  context.signal?.throwIfAborted();
@@ -287,20 +428,47 @@ export const createCalculatorTool = () => ({
287
428
  if (input.expressions !== undefined) {
288
429
  if (input.expression !== undefined)
289
430
  throw new Error("Supply expression or expressions, not both");
290
- if (!input.expressions || typeof input.expressions !== "object" || Array.isArray(input.expressions) || Object.keys(input.expressions).length < 1 || Object.keys(input.expressions).length > MAX_STATEMENTS)
291
- throw new Error(`Supply 1 to ${MAX_STATEMENTS} named expressions`);
292
- const variables = new Map();
293
- const results = {};
294
- for (const [label, expression] of Object.entries(input.expressions)) {
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) {
295
435
  if (!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(label))
296
436
  throw new Error("Invalid calculation label");
297
437
  if (typeof expression !== "string")
298
438
  throw new Error(`Formula ${label} must be a string such as "2*3+4"`);
299
- const value = evaluateCalculation(expression, { ...options, variables });
300
- results[label] = value;
301
- if (variableName(label))
302
- variables.set(label, value);
303
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)]));
304
472
  assigned = Object.keys(results);
305
473
  return { output: JSON.stringify({ results, ...note() }) };
306
474
  }
@@ -312,7 +480,7 @@ export const createCalculatorTool = () => ({
312
480
  }
313
481
  catch (error) {
314
482
  const message = error instanceof Error ? error.message : String(error);
315
- throw new ToolExecutionError("tool_invalid_args", `${message}. Correct the arguments before retrying; use tools_describe for the schema. Numbers, names (a = 2*3; a+1) and the listed functions only; strings, lists, loops and imports need a code tool such as verify_javascript.`, { 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 });
316
484
  }
317
485
  },
318
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.",