@hotpathrun/cli 0.3.1 → 0.4.0

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.
package/dist/hotpath.mjs CHANGED
@@ -934,18 +934,18 @@ var require_suggestSimilar = __commonJS({
934
934
  }
935
935
  return d2[a2.length][b3.length];
936
936
  }
937
- function suggestSimilar(word, candidates2) {
938
- if (!candidates2 || candidates2.length === 0) return "";
939
- candidates2 = Array.from(new Set(candidates2));
937
+ function suggestSimilar(word, candidates3) {
938
+ if (!candidates3 || candidates3.length === 0) return "";
939
+ candidates3 = Array.from(new Set(candidates3));
940
940
  const searchingOptions = word.startsWith("--");
941
941
  if (searchingOptions) {
942
942
  word = word.slice(2);
943
- candidates2 = candidates2.map((candidate) => candidate.slice(2));
943
+ candidates3 = candidates3.map((candidate) => candidate.slice(2));
944
944
  }
945
945
  let similar = [];
946
946
  let bestDistance = maxDistance;
947
947
  const minSimilarity = 0.4;
948
- candidates2.forEach((candidate) => {
948
+ candidates3.forEach((candidate) => {
949
949
  if (candidate.length <= 1) return;
950
950
  const distance = editDistance(word, candidate);
951
951
  const length = Math.max(word.length, candidate.length);
@@ -3101,13 +3101,13 @@ var init_util = __esm({
3101
3101
  });
3102
3102
  };
3103
3103
  util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => {
3104
- const keys = [];
3104
+ const keys2 = [];
3105
3105
  for (const key in object3) {
3106
3106
  if (Object.prototype.hasOwnProperty.call(object3, key)) {
3107
- keys.push(key);
3107
+ keys2.push(key);
3108
3108
  }
3109
3109
  }
3110
- return keys;
3110
+ return keys2;
3111
3111
  };
3112
3112
  util3.find = (arr, checker) => {
3113
3113
  for (const item of arr) {
@@ -5451,8 +5451,8 @@ var init_types = __esm({
5451
5451
  if (this._cached !== null)
5452
5452
  return this._cached;
5453
5453
  const shape = this._def.shape();
5454
- const keys = util.objectKeys(shape);
5455
- this._cached = { shape, keys };
5454
+ const keys2 = util.objectKeys(shape);
5455
+ this._cached = { shape, keys: keys2 };
5456
5456
  return this._cached;
5457
5457
  }
5458
5458
  _parse(input) {
@@ -6284,8 +6284,8 @@ var init_types = __esm({
6284
6284
  maxSize: { value: maxSize, message: errorUtil.toString(message) }
6285
6285
  });
6286
6286
  }
6287
- size(size, message) {
6288
- return this.min(size, message).max(size, message);
6287
+ size(size2, message) {
6288
+ return this.min(size2, message).max(size2, message);
6289
6289
  }
6290
6290
  nonempty(message) {
6291
6291
  return this.min(1, message);
@@ -7291,13 +7291,13 @@ function selectedItems(selection, ctx) {
7291
7291
  }
7292
7292
  return list.filter((_3, i2) => keep[i2]);
7293
7293
  }
7294
- function listsIn(node, at2, out) {
7294
+ function listsIn(node, at3, out) {
7295
7295
  if (Array.isArray(node)) {
7296
- if (node.length > 0 && node.every(isItem)) out.set(at2, node);
7296
+ if (node.length > 0 && node.every(isItem)) out.set(at3, node);
7297
7297
  return;
7298
7298
  }
7299
7299
  if (isItem(node)) {
7300
- for (const [k3, v3] of Object.entries(node)) listsIn(v3, `${at2}.${k3}`, out);
7300
+ for (const [k3, v3] of Object.entries(node)) listsIn(v3, `${at3}.${k3}`, out);
7301
7301
  }
7302
7302
  }
7303
7303
  function learnRules(list, selected, ctx) {
@@ -7515,6 +7515,9 @@ function statesTime(text, time3) {
7515
7515
  return false;
7516
7516
  }
7517
7517
  function computeFigures(calc, ctx) {
7518
+ if (calc.group || calc.per || calc.where || calc.match || calc.op === "top" || calc.list.includes(".*.")) {
7519
+ return computeExtended(calc, ctx);
7520
+ }
7518
7521
  const items = calc.selection ? selectedItems(calc.selection, ctx) : (() => {
7519
7522
  const list = lookupReference(calc.list, ctx);
7520
7523
  return Array.isArray(list) && list.every(isItem2) ? list : null;
@@ -7600,7 +7603,153 @@ function missingRates(calc, ctx) {
7600
7603
  }
7601
7604
  return [...missing];
7602
7605
  }
7603
- var rateSourceSchema, conversionSchema, timeShiftSchema, calculationSchema, isItem2, round2, formatFigure, OFFSET, TIMESTAMP, hhmm, NUMBER_TOKEN, MONTH, DATE_AND_TIME;
7606
+ function listAt(ref, ctx) {
7607
+ const star = ref.indexOf(".*.");
7608
+ if (star < 0) {
7609
+ const node = lookupReference(ref, ctx);
7610
+ return Array.isArray(node) ? node : null;
7611
+ }
7612
+ const outer = lookupReference(ref.slice(0, star), ctx);
7613
+ if (!Array.isArray(outer)) return null;
7614
+ const rest = ref.slice(star + 3).split(".");
7615
+ const out = [];
7616
+ for (const o2 of outer) {
7617
+ let v3 = o2;
7618
+ for (const k3 of rest) v3 = isItem2(v3) ? v3[k3] : void 0;
7619
+ if (!Array.isArray(v3)) return null;
7620
+ out.push(...v3);
7621
+ }
7622
+ return out;
7623
+ }
7624
+ function passes(item, where, ctx) {
7625
+ if (!where) return true;
7626
+ if (!isItem2(item)) return false;
7627
+ const v3 = item[where.field];
7628
+ if (where.equals !== void 0) return v3 === where.equals;
7629
+ if (where.not !== void 0) return v3 !== where.not;
7630
+ const ref = where.before ?? where.after;
7631
+ if (ref !== void 0) {
7632
+ const other = ctx ? lookupReference(ref, ctx) : void 0;
7633
+ if (typeof v3 !== "string" || typeof other !== "string") return false;
7634
+ if (!ISO.test(v3) || !ISO.test(other)) return false;
7635
+ const [a2, b3] = [v3.slice(0, 10), other.slice(0, 10)];
7636
+ return where.before !== void 0 ? a2 < b3 : a2 > b3;
7637
+ }
7638
+ return true;
7639
+ }
7640
+ function messageAfter(line, word) {
7641
+ if (!wordIn(line, word)) return null;
7642
+ const at3 = line.search(new RegExp(`(?<![A-Za-z])${word}(?![A-Za-z])`));
7643
+ const rest = line.slice(at3 + word.length);
7644
+ const colon = rest.indexOf(": ");
7645
+ const msg = (colon >= 0 ? rest.slice(colon + 2) : rest).trim();
7646
+ return msg.length > 0 ? msg : null;
7647
+ }
7648
+ function topLabel(calc) {
7649
+ if (calc.op !== "top") return "";
7650
+ return calc.match ? ` most frequent ${calc.match} message` : ` top ${calc.by}`;
7651
+ }
7652
+ function figureOver(calc, items, ctx) {
7653
+ const kept = items.filter((it2) => passes(it2, calc.where, ctx));
7654
+ if (calc.op === "count") {
7655
+ if (calc.match) {
7656
+ if (!kept.every((l2) => typeof l2 === "string")) return null;
7657
+ return {
7658
+ value: kept.filter((l2) => wordIn(l2, calc.match)).length
7659
+ };
7660
+ }
7661
+ return { value: kept.length };
7662
+ }
7663
+ if (calc.op === "top" && calc.match) {
7664
+ if (!kept.every((l2) => typeof l2 === "string")) return null;
7665
+ const counts = /* @__PURE__ */ new Map();
7666
+ for (const l2 of kept) {
7667
+ const m3 = messageAfter(l2, calc.match);
7668
+ if (m3) counts.set(m3, (counts.get(m3) ?? 0) + 1);
7669
+ }
7670
+ const best = [...counts].sort((a2, b3) => b3[1] - a2[1])[0];
7671
+ return best ? { name: best[0], value: best[1] } : NO_LINES;
7672
+ }
7673
+ if (!calc.field || !kept.every(isItem2)) return null;
7674
+ const values = [];
7675
+ for (const it2 of kept) {
7676
+ const v3 = it2[calc.field];
7677
+ if (typeof v3 !== "number" || !Number.isFinite(v3)) return null;
7678
+ values.push(v3);
7679
+ }
7680
+ if (calc.op === "sum")
7681
+ return { value: round2(values.reduce((a2, b3) => a2 + b3, 0)) };
7682
+ if (calc.op === "avg")
7683
+ return {
7684
+ value: values.length ? round2(values.reduce((a2, b3) => a2 + b3, 0) / values.length) : 0
7685
+ };
7686
+ if (calc.op === "top") {
7687
+ if (!calc.by) return null;
7688
+ const sums = /* @__PURE__ */ new Map();
7689
+ kept.forEach((it2, i2) => {
7690
+ const k3 = it2[calc.by];
7691
+ if (typeof k3 === "string") sums.set(k3, (sums.get(k3) ?? 0) + values[i2]);
7692
+ });
7693
+ const best = [...sums].sort((a2, b3) => b3[1] - a2[1])[0];
7694
+ return best ? { name: best[0], value: round2(best[1]) } : null;
7695
+ }
7696
+ return null;
7697
+ }
7698
+ function computeExtended(calc, ctx) {
7699
+ const fmt = (x3) => calc.decimals ? round2(x3).toFixed(calc.decimals) : formatFigure(x3);
7700
+ const describe2 = (got2) => calc.op === "top" ? `${got2.name} (${fmt(got2.value)})` : fmt(got2.value);
7701
+ if (calc.group) {
7702
+ const groups = calc.group.refs ? calc.group.refs.map((r2) => lookupReference(r2, ctx)) : listAt(calc.list, ctx);
7703
+ if (groups === null) return null;
7704
+ const out = [];
7705
+ for (const g3 of groups) {
7706
+ if (!isItem2(g3)) return null;
7707
+ const name = g3[calc.group.name];
7708
+ const items2 = g3[calc.group.path];
7709
+ if (typeof name !== "string" || !Array.isArray(items2)) return null;
7710
+ const got2 = figureOver(calc, items2, ctx);
7711
+ if (got2 === null) return null;
7712
+ out.push({
7713
+ text: `${name}${topLabel(calc)}: ${describe2(got2)}`,
7714
+ value: got2.value,
7715
+ ...got2.name !== void 0 ? { name: got2.name } : {}
7716
+ });
7717
+ }
7718
+ return out;
7719
+ }
7720
+ const items = listAt(calc.list, ctx);
7721
+ if (items === null) return null;
7722
+ if (calc.per) {
7723
+ const kept = items.filter((it2) => passes(it2, calc.where, ctx));
7724
+ const groups = /* @__PURE__ */ new Map();
7725
+ for (const it2 of kept) {
7726
+ const name = isItem2(it2) ? it2[calc.per] : void 0;
7727
+ if (typeof name !== "string") return null;
7728
+ groups.set(name, [...groups.get(name) ?? [], it2]);
7729
+ }
7730
+ const out = [];
7731
+ for (const [name, group] of groups) {
7732
+ const got2 = figureOver({ ...calc, where: void 0 }, group, ctx);
7733
+ if (got2 === null) return null;
7734
+ out.push({
7735
+ text: `${name}${topLabel(calc)}: ${describe2(got2)}`,
7736
+ value: got2.value,
7737
+ ...got2.name !== void 0 ? { name: got2.name } : {}
7738
+ });
7739
+ }
7740
+ return out;
7741
+ }
7742
+ const got = figureOver(calc, items, ctx);
7743
+ if (got === null) return null;
7744
+ return [
7745
+ {
7746
+ text: calc.line.replace("<calculated>", describe2(got)),
7747
+ value: got.value,
7748
+ ...got.name !== void 0 ? { name: got.name } : {}
7749
+ }
7750
+ ];
7751
+ }
7752
+ var rateSourceSchema, conversionSchema, timeShiftSchema, calcFilterSchema, calculationSchema, isItem2, round2, formatFigure, OFFSET, TIMESTAMP, hhmm, NUMBER_TOKEN, MONTH, DATE_AND_TIME, ISO, wordIn, NO_LINES;
7604
7753
  var init_calc = __esm({
7605
7754
  "../shared/src/calc.ts"() {
7606
7755
  "use strict";
@@ -7623,10 +7772,22 @@ var init_calc = __esm({
7623
7772
  external_exports.object({ zoneRef: external_exports.string() }),
7624
7773
  external_exports.object({ utc: external_exports.literal(true) })
7625
7774
  ]);
7775
+ calcFilterSchema = external_exports.object({
7776
+ field: external_exports.string(),
7777
+ equals: external_exports.string().optional(),
7778
+ not: external_exports.string().optional(),
7779
+ /** the item's date is earlier than the one at this reference (overdue: before inputs.date) */
7780
+ before: external_exports.string().optional(),
7781
+ after: external_exports.string().optional()
7782
+ });
7626
7783
  calculationSchema = external_exports.object({
7627
7784
  /** the recorded line with the figure as <calculated> */
7628
7785
  line: external_exports.string(),
7629
- op: external_exports.enum(["count", "sum", "avg", "each", "time"]),
7786
+ /**
7787
+ * `top`: the item value (`by`) whose summed `field` is largest, and that sum;
7788
+ * with `match` over text lines, the most frequent message after the word, and how often
7789
+ */
7790
+ op: external_exports.enum(["count", "sum", "avg", "each", "time", "top"]),
7630
7791
  /** the items: a whole list, or the selected ones */
7631
7792
  list: external_exports.string(),
7632
7793
  selection: selectionSchema.optional(),
@@ -7643,7 +7804,27 @@ var init_calc = __esm({
7643
7804
  */
7644
7805
  units: external_exports.object({ field: external_exports.string(), seen: external_exports.array(external_exports.string()) }).optional(),
7645
7806
  /** the figure in the recorded text, for the stale check (`time`: how many items it timed) */
7646
- recorded: external_exports.number()
7807
+ recorded: external_exports.number(),
7808
+ where: calcFilterSchema.optional(),
7809
+ /** `count` over a list of text lines: the lines holding this word (ERROR) */
7810
+ match: external_exports.string().optional(),
7811
+ /** `top`: the item field the sums are grouped by (customer) */
7812
+ by: external_exports.string().optional(),
7813
+ /**
7814
+ * One figure per item of `list` (a loop's results, one per region): over that
7815
+ * item's `path` list, named by its `name` field. `list` may also end in
7816
+ * `.*.<path>` elsewhere: every item's list, put together (a total).
7817
+ */
7818
+ group: external_exports.object({
7819
+ name: external_exports.string(),
7820
+ path: external_exports.string(),
7821
+ /** the groups are these steps' results (one call per service), not a loop's */
7822
+ refs: external_exports.array(external_exports.string()).min(2).optional()
7823
+ }).optional(),
7824
+ /** one figure per value of this item field (per vendor), over the items `where` keeps */
7825
+ per: external_exports.string().optional(),
7826
+ /** decimals the recorded figure was written with (money: 2), so today's is written alike */
7827
+ decimals: external_exports.number().int().min(1).max(6).optional()
7647
7828
  });
7648
7829
  isItem2 = (v3) => v3 !== null && typeof v3 === "object" && !Array.isArray(v3);
7649
7830
  round2 = (x3) => Math.round(x3 * 100) / 100;
@@ -7663,6 +7844,132 @@ var init_calc = __esm({
7663
7844
  ].join("|"),
7664
7845
  "gi"
7665
7846
  );
7847
+ ISO = /^\d{4}-\d{2}-\d{2}/;
7848
+ wordIn = (line, word) => /^[A-Z]+$/.test(word) && new RegExp(`(?<![A-Za-z])${word}(?![A-Za-z])`).test(line);
7849
+ NO_LINES = { name: "none", value: 0 };
7850
+ }
7851
+ });
7852
+
7853
+ // ../shared/src/bands.ts
7854
+ function inBand(band, v3) {
7855
+ return (band.gte === void 0 || v3 >= band.gte) && (band.lte === void 0 || v3 <= band.lte) && (band.lt === void 0 || v3 < band.lt);
7856
+ }
7857
+ function numberAt(node, path36) {
7858
+ let v3 = node;
7859
+ for (const k3 of path36)
7860
+ v3 = v3 !== null && typeof v3 === "object" ? v3[k3] : void 0;
7861
+ return typeof v3 === "number" && Number.isFinite(v3) ? v3 : null;
7862
+ }
7863
+ function bandDecision(rule, item, details) {
7864
+ const v3 = numberAt(rule.from === "item" ? item : details, rule.path);
7865
+ if (v3 === null) return null;
7866
+ const band = rule.bands.find((b3) => inBand(b3, v3));
7867
+ return band ? { action: rule.action, [rule.field]: band.value } : null;
7868
+ }
7869
+ function bandsText(rule) {
7870
+ const one = (b3) => {
7871
+ const lo = b3.gte !== void 0 ? `${b3.gte}` : void 0;
7872
+ const hi = b3.lt !== void 0 ? `below ${b3.lt}` : b3.lte !== void 0 ? `up to ${b3.lte}` : void 0;
7873
+ const range = lo && hi ? `${lo}, ${hi}` : lo ? `${lo} or more` : hi;
7874
+ return `${range}: ${b3.value}`;
7875
+ };
7876
+ return `${rule.path.join(".")}: ${rule.bands.map(one).join("; ")}`;
7877
+ }
7878
+ function inOpenGap(rule, item, details) {
7879
+ const v3 = numberAt(rule.from === "item" ? item : details, rule.path);
7880
+ if (v3 === null || rule.bands.some((b3) => inBand(b3, v3))) return null;
7881
+ const below = rule.bands.some(
7882
+ (b3) => b3.lte !== void 0 && b3.lte < v3 || b3.lt !== void 0 && b3.lt <= v3
7883
+ );
7884
+ const above = rule.bands.some((b3) => b3.gte !== void 0 && b3.gte > v3);
7885
+ return below && above ? v3 : null;
7886
+ }
7887
+ var init_bands = __esm({
7888
+ "../shared/src/bands.ts"() {
7889
+ "use strict";
7890
+ }
7891
+ });
7892
+
7893
+ // ../shared/src/table.ts
7894
+ function at(node, path36) {
7895
+ let v3 = node;
7896
+ for (const k3 of path36)
7897
+ v3 = v3 !== null && typeof v3 === "object" ? v3[k3] : void 0;
7898
+ return v3;
7899
+ }
7900
+ function tableDecision(node, item, details) {
7901
+ if ("leaf" in node) {
7902
+ const out = {
7903
+ action: node.leaf.action
7904
+ };
7905
+ for (const [field2, v3] of Object.entries(node.leaf.values)) {
7906
+ const got = "const" in v3 ? v3.const : at(v3.from === "item" ? item : details, v3.path);
7907
+ if (got === void 0 || got === null)
7908
+ return { unknown: `no ${"path" in v3 ? v3.path.join(".") : field2}` };
7909
+ out[field2] = got;
7910
+ }
7911
+ return { decision: out };
7912
+ }
7913
+ const value = at(node.from === "item" ? item : details, node.path);
7914
+ const name = node.path.join(".");
7915
+ if ("cases" in node) {
7916
+ const next = typeof value === "string" || typeof value === "number" ? node.cases[String(value)] : void 0;
7917
+ return next ? tableDecision(next, item, details) : { unknown: `${name} ${JSON.stringify(value)}` };
7918
+ }
7919
+ if (typeof value !== "number" || !Number.isFinite(value))
7920
+ return { unknown: `${name} ${JSON.stringify(value)}` };
7921
+ const band = node.bands.find((b3) => inBand(b3, value));
7922
+ if (band) return tableDecision(band.node, item, details);
7923
+ const below = node.bands.some(
7924
+ (b3) => b3.lte !== void 0 && b3.lte < value || b3.lt !== void 0 && b3.lt <= value
7925
+ );
7926
+ const above = node.bands.some((b3) => b3.gte !== void 0 && b3.gte > value);
7927
+ return below && above ? { gap: `${name} ${value}` } : { unknown: `${name} ${value}` };
7928
+ }
7929
+ function tableSize(node) {
7930
+ if ("leaf" in node) return 1;
7931
+ if ("cases" in node)
7932
+ return Object.values(node.cases).reduce((n3, c2) => n3 + tableSize(c2), 0);
7933
+ return node.bands.reduce((n3, b3) => n3 + tableSize(b3.node), 0);
7934
+ }
7935
+ var valueSchema, bandSchema, tableNodeSchema;
7936
+ var init_table = __esm({
7937
+ "../shared/src/table.ts"() {
7938
+ "use strict";
7939
+ init_zod();
7940
+ init_bands();
7941
+ valueSchema = external_exports.union([
7942
+ external_exports.object({ const: external_exports.union([external_exports.string(), external_exports.number()]) }),
7943
+ external_exports.object({
7944
+ from: external_exports.enum(["item", "details"]),
7945
+ path: external_exports.array(external_exports.string()).min(1)
7946
+ })
7947
+ ]);
7948
+ bandSchema = external_exports.object({
7949
+ gte: external_exports.number().optional(),
7950
+ lte: external_exports.number().optional(),
7951
+ lt: external_exports.number().optional()
7952
+ });
7953
+ tableNodeSchema = external_exports.lazy(
7954
+ () => external_exports.union([
7955
+ external_exports.object({
7956
+ leaf: external_exports.object({
7957
+ action: external_exports.string(),
7958
+ values: external_exports.record(external_exports.string(), valueSchema)
7959
+ })
7960
+ }),
7961
+ external_exports.object({
7962
+ from: external_exports.enum(["item", "details"]),
7963
+ path: external_exports.array(external_exports.string()).min(1),
7964
+ cases: external_exports.record(external_exports.string(), tableNodeSchema)
7965
+ }),
7966
+ external_exports.object({
7967
+ from: external_exports.enum(["item", "details"]),
7968
+ path: external_exports.array(external_exports.string()).min(1),
7969
+ bands: external_exports.array(bandSchema.extend({ node: tableNodeSchema })).min(2)
7970
+ })
7971
+ ])
7972
+ );
7666
7973
  }
7667
7974
  });
7668
7975
 
@@ -7708,13 +8015,14 @@ var init_task_name = __esm({
7708
8015
  });
7709
8016
 
7710
8017
  // ../shared/src/schemas.ts
7711
- var taskName, traceToolInfoSchema, traceMetaSchema, traceToolCallSchema, traceEndSchema, traceLineSchema, groundingEntrySchema, stepGuardSchema, conditionSchema, toolStepSchema, llmStepSchema, foreachStepSchema, DEFAULT_MAX_ITEMS, caseStepSchema, branchStepSchema, workflowStepSchema, workflowInputSchema, droppedCallSchema, workflowSchema;
8018
+ var taskName, traceToolInfoSchema, traceMetaSchema, traceToolCallSchema, traceEndSchema, traceLineSchema, groundingEntrySchema, stepGuardSchema, ruleConditions, ruleConditionSchema, conditionSchema, toolStepSchema, llmStepSchema, itemDecisionSchema, foreachStepSchema, DEFAULT_MAX_ITEMS, caseStepSchema, branchStepSchema, workflowStepSchema, workflowInputSchema, droppedCallSchema, workflowSchema;
7712
8019
  var init_schemas = __esm({
7713
8020
  "../shared/src/schemas.ts"() {
7714
8021
  "use strict";
7715
8022
  init_zod();
7716
8023
  init_calc();
7717
8024
  init_selection();
8025
+ init_table();
7718
8026
  init_task_name();
7719
8027
  taskName = external_exports.string().superRefine((value, ctx) => {
7720
8028
  const problem = taskNameProblem(value);
@@ -7798,7 +8106,7 @@ var init_schemas = __esm({
7798
8106
  */
7799
8107
  exampleFacts: external_exports.array(external_exports.union([external_exports.string(), external_exports.number()])).optional()
7800
8108
  });
7801
- conditionSchema = external_exports.discriminatedUnion("kind", [
8109
+ ruleConditions = [
7802
8110
  external_exports.object({ kind: external_exports.literal("nonEmpty"), ref: external_exports.string() }),
7803
8111
  external_exports.object({ kind: external_exports.literal("empty"), ref: external_exports.string() }),
7804
8112
  external_exports.object({
@@ -7811,6 +8119,25 @@ var init_schemas = __esm({
7811
8119
  ref: external_exports.string(),
7812
8120
  value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null()])
7813
8121
  }),
8122
+ /** the number at `ref` is greater than `value` (page if the error rate is above 2) */
8123
+ external_exports.object({ kind: external_exports.literal("above"), ref: external_exports.string(), value: external_exports.number() }),
8124
+ /** the number at `ref` is less than `value` (reorder if stock is below 10) */
8125
+ external_exports.object({ kind: external_exports.literal("below"), ref: external_exports.string(), value: external_exports.number() }),
8126
+ /** the date at `ref` is earlier than the one at `other` (due before today's date input) */
8127
+ external_exports.object({ kind: external_exports.literal("before"), ref: external_exports.string(), other: external_exports.string() }),
8128
+ /** the date at `ref` is later than the one at `other` */
8129
+ external_exports.object({ kind: external_exports.literal("after"), ref: external_exports.string(), other: external_exports.string() })
8130
+ ];
8131
+ ruleConditionSchema = external_exports.discriminatedUnion("kind", [
8132
+ ...ruleConditions
8133
+ ]);
8134
+ conditionSchema = external_exports.discriminatedUnion("kind", [
8135
+ ...ruleConditions,
8136
+ /** every one of these rules holds (overdue and over 10,000) */
8137
+ external_exports.object({
8138
+ kind: external_exports.literal("all"),
8139
+ of: external_exports.array(ruleConditionSchema).min(2)
8140
+ }),
7814
8141
  external_exports.object({
7815
8142
  kind: external_exports.literal("ask"),
7816
8143
  /** what would run, in words ("send_message (to=\"me\")") */
@@ -7870,6 +8197,17 @@ var init_schemas = __esm({
7870
8197
  * output must state them (see calc.ts).
7871
8198
  */
7872
8199
  calculations: external_exports.array(calculationSchema).optional(),
8200
+ /**
8201
+ * Lists left out of the prompt (each replaced by a note): code computes
8202
+ * every figure the recorded text took from them, so the model is not sent
8203
+ * the items (a day of log lines). Learned from the recording (see trim.ts).
8204
+ */
8205
+ trim: external_exports.array(external_exports.string()).optional(),
8206
+ /**
8207
+ * Length of the data part of the prompt on the recorded run (after `trim`).
8208
+ * A run sending far more is warned about: it costs that much more.
8209
+ */
8210
+ inputChars: external_exports.number().int().nonnegative().optional(),
7873
8211
  /**
7874
8212
  * The example with its list rows taken out (`skeleton`, one marker line per
7875
8213
  * list) and how one row is written (`rows`). At run time code writes the
@@ -7888,6 +8226,59 @@ var init_schemas = __esm({
7888
8226
  guard: stepGuardSchema,
7889
8227
  when: conditionSchema.optional()
7890
8228
  });
8229
+ itemDecisionSchema = external_exports.object({
8230
+ model: external_exports.string(),
8231
+ /** the run's data as templates, like an llm step's prompt */
8232
+ prompt: external_exports.string(),
8233
+ /** the path in an item that names it (["id"]) */
8234
+ key: external_exports.array(external_exports.string()),
8235
+ /**
8236
+ * An earlier loop over the same list that looked each item up (its company,
8237
+ * its stock): shown next to the item, so the model never pairs lists itself.
8238
+ * With `distinct`, that loop ran once per distinct value at this path.
8239
+ */
8240
+ details: external_exports.object({ step: external_exports.string(), distinct: external_exports.array(external_exports.string()).optional() }).optional(),
8241
+ actions: external_exports.array(
8242
+ external_exports.object({
8243
+ tool: external_exports.string(),
8244
+ /** values the decision must give for this action, by type */
8245
+ fields: external_exports.record(external_exports.string(), external_exports.enum(["string", "number"]))
8246
+ })
8247
+ ).min(1),
8248
+ /**
8249
+ * The recorded choices follow one number of the item or its details in bands
8250
+ * (a tier from the company's employee count): code decides every item whose
8251
+ * number falls in a band, the model only the rest (see bands.ts).
8252
+ */
8253
+ bands: external_exports.object({
8254
+ from: external_exports.enum(["item", "details"]),
8255
+ path: external_exports.array(external_exports.string()).min(1),
8256
+ action: external_exports.string(),
8257
+ field: external_exports.string(),
8258
+ bands: external_exports.array(
8259
+ external_exports.object({
8260
+ value: external_exports.string(),
8261
+ gte: external_exports.number().optional(),
8262
+ lte: external_exports.number().optional(),
8263
+ lt: external_exports.number().optional()
8264
+ })
8265
+ ).min(2)
8266
+ }).optional(),
8267
+ /**
8268
+ * The recorded choices follow a small rulebook over the item or its details
8269
+ * (category, then priority or an amount threshold): code decides by it (see table.ts).
8270
+ */
8271
+ table: tableNodeSchema.optional(),
8272
+ /** the recorded items with what was done to them (action "none": nothing) */
8273
+ examples: external_exports.array(
8274
+ external_exports.object({
8275
+ item: external_exports.unknown(),
8276
+ /** the item's own looked-up data (its company, its ticket), when there was a lookup per item */
8277
+ details: external_exports.unknown().optional(),
8278
+ choice: external_exports.record(external_exports.string(), external_exports.unknown())
8279
+ })
8280
+ )
8281
+ });
7891
8282
  foreachStepSchema = external_exports.object({
7892
8283
  id: external_exports.string(),
7893
8284
  type: external_exports.literal("foreach"),
@@ -7895,7 +8286,13 @@ var init_schemas = __esm({
7895
8286
  as: external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).refine((v3) => v3 !== "inputs" && v3 !== "steps", "reserved name"),
7896
8287
  body: external_exports.array(toolStepSchema).min(1),
7897
8288
  maxItems: external_exports.number().int().positive(),
7898
- when: conditionSchema.optional()
8289
+ when: conditionSchema.optional(),
8290
+ decide: itemDecisionSchema.optional(),
8291
+ /**
8292
+ * Run the body once per distinct value at this path in the item (the agent
8293
+ * checked stock once per product, not once per order); repeats are skipped.
8294
+ */
8295
+ distinct: external_exports.array(external_exports.string()).min(1).optional()
7899
8296
  });
7900
8297
  DEFAULT_MAX_ITEMS = 50;
7901
8298
  caseStepSchema = external_exports.discriminatedUnion("type", [
@@ -7954,8 +8351,25 @@ var init_schemas = __esm({
7954
8351
  * fallback applies them again.
7955
8352
  */
7956
8353
  require: external_exports.array(external_exports.string()).optional(),
8354
+ /**
8355
+ * Actions on items of a list picked by position (item 0, item 1…) that could
8356
+ * not be compiled into a loop. A new day's list has other items in other
8357
+ * places, so these are never replayed: the agent runs instead.
8358
+ */
8359
+ positional: external_exports.array(external_exports.object({ list: external_exports.string(), steps: external_exports.array(external_exports.string()).min(2) })).optional(),
7957
8360
  /** failed/retried calls from the trace that did not become steps */
7958
8361
  droppedCalls: external_exports.array(droppedCallSchema).optional(),
8362
+ /**
8363
+ * Has the user confirmed what the recording did (hotpath compile prompt,
8364
+ * --yes or hotpath confirm)? Absent means a workflow compiled before this
8365
+ * check existed: treated as confirmed so current users are not broken.
8366
+ */
8367
+ confirmed: external_exports.boolean().optional(),
8368
+ /**
8369
+ * The owner said this task only reads (`compile --read-only`): a recording with
8370
+ * no action is then the job, not an agent that stopped early. Kept by recompiles.
8371
+ */
8372
+ readOnly: external_exports.boolean().optional(),
7959
8373
  /** what the recorded agent run took: the reference for "saved" estimates */
7960
8374
  baseline: external_exports.object({
7961
8375
  durationMs: external_exports.number().nonnegative(),
@@ -8783,9 +9197,9 @@ var init_baggage_impl = __esm({
8783
9197
  newBaggage._entries.delete(key);
8784
9198
  return newBaggage;
8785
9199
  }
8786
- removeEntries(...keys) {
9200
+ removeEntries(...keys2) {
8787
9201
  const newBaggage = new BaggageImpl2(this._entries);
8788
- for (const key of keys) newBaggage._entries.delete(key);
9202
+ for (const key of keys2) newBaggage._entries.delete(key);
8789
9203
  return newBaggage;
8790
9204
  }
8791
9205
  clear() {
@@ -10083,12 +10497,12 @@ var init_headers = __esm({
10083
10497
  clearSentinel = /* @__PURE__ */ Symbol("clear");
10084
10498
  APPEND_HEADERS = /* @__PURE__ */ new Set(["x-stainless-helper"]);
10085
10499
  appendHeaderValue = (existing, addition) => {
10086
- const tokens = existing ? existing.split(",").map((t2) => t2.trim()).filter(Boolean) : [];
10500
+ const tokens2 = existing ? existing.split(",").map((t2) => t2.trim()).filter(Boolean) : [];
10087
10501
  for (const tok of addition.split(",").map((t2) => t2.trim())) {
10088
- if (tok && !tokens.includes(tok))
10089
- tokens.push(tok);
10502
+ if (tok && !tokens2.includes(tok))
10503
+ tokens2.push(tok);
10090
10504
  }
10091
- return tokens.join(", ");
10505
+ return tokens2.join(", ");
10092
10506
  };
10093
10507
  buildHeaders = (newHeaders) => {
10094
10508
  const targetHeaders = new Headers();
@@ -10595,8 +11009,8 @@ function inner_stringify(object3, prefix, generateArrayPrefix, commaRoundTrip, a
10595
11009
  } else if (isArray(filter)) {
10596
11010
  obj_keys = filter;
10597
11011
  } else {
10598
- const keys = Object.keys(obj);
10599
- obj_keys = sort ? keys.sort(sort) : keys;
11012
+ const keys2 = Object.keys(obj);
11013
+ obj_keys = sort ? keys2.sort(sort) : keys2;
10600
11014
  }
10601
11015
  const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix);
10602
11016
  const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix;
@@ -10715,7 +11129,7 @@ function stringify(object3, opts = {}) {
10715
11129
  filter = options.filter;
10716
11130
  obj_keys = filter;
10717
11131
  }
10718
- const keys = [];
11132
+ const keys2 = [];
10719
11133
  if (typeof obj !== "object" || obj === null) {
10720
11134
  return "";
10721
11135
  }
@@ -10733,7 +11147,7 @@ function stringify(object3, opts = {}) {
10733
11147
  if (options.skipNulls && obj[key] === null) {
10734
11148
  continue;
10735
11149
  }
10736
- push_to_array(keys, inner_stringify(
11150
+ push_to_array(keys2, inner_stringify(
10737
11151
  obj[key],
10738
11152
  key,
10739
11153
  // @ts-expect-error
@@ -10755,7 +11169,7 @@ function stringify(object3, opts = {}) {
10755
11169
  sideChannel
10756
11170
  ));
10757
11171
  }
10758
- const joined = keys.join(options.delimiter);
11172
+ const joined = keys2.join(options.delimiter);
10759
11173
  let prefix = options.addQueryPrefix === true ? "?" : "";
10760
11174
  if (options.charsetSentinel) {
10761
11175
  if (options.charset === "iso-8859-1") {
@@ -11192,7 +11606,7 @@ function setMessageContentAttributes(call, body, output, limit3) {
11192
11606
  return;
11193
11607
  }
11194
11608
  }
11195
- const size = setContentAttributes(span, {
11609
+ const size2 = setContentAttributes(span, {
11196
11610
  // An empty list sets no attribute.
11197
11611
  [ATTR_GEN_AI_REQUEST_STOP_SEQUENCES]: body.stop_sequences?.length ? [...body.stop_sequences] : void 0,
11198
11612
  [ATTR_GEN_AI_SYSTEM_INSTRUCTIONS]: body.system === void 0 ? void 0 : contentParts(body.system),
@@ -11200,7 +11614,7 @@ function setMessageContentAttributes(call, body, output, limit3) {
11200
11614
  [ATTR_GEN_AI_OUTPUT_MESSAGES]: output === void 0 ? void 0 : [{ role: "assistant", parts: contentParts(output) }]
11201
11615
  }, limit3);
11202
11616
  if (output === void 0) {
11203
- call.requestContentSize = size;
11617
+ call.requestContentSize = size2;
11204
11618
  }
11205
11619
  }
11206
11620
  function contentParts(content) {
@@ -11319,7 +11733,7 @@ function setContentAttributes(span, attributes, limit3) {
11319
11733
  const sizeOfMessages = () => Object.keys(messages).reduce((sum, key) => sum + sizeOf(values[key] ?? ""), 0);
11320
11734
  const stopSequencesSize = stopSequences?.reduce((sum, each) => sum + sizeOf(each), 0) ?? 0;
11321
11735
  const keepsStopSequences = stopSequences !== void 0 && stopSequencesSize <= limit3;
11322
- let size = keepsStopSequences ? stopSequencesSize : 0;
11736
+ let size2 = keepsStopSequences ? stopSequencesSize : 0;
11323
11737
  let truncated = stopSequences !== void 0 && !keepsStopSequences;
11324
11738
  for (const key of Object.keys(others)) {
11325
11739
  const jsonSize = sizeOf(values[key] ?? "");
@@ -11327,21 +11741,21 @@ function setContentAttributes(span, attributes, limit3) {
11327
11741
  delete values[key];
11328
11742
  truncated = true;
11329
11743
  } else {
11330
- size += jsonSize;
11744
+ size2 += jsonSize;
11331
11745
  }
11332
11746
  }
11333
11747
  let messagesSize = sizeOfMessages();
11334
- if (size + messagesSize > limit3) {
11335
- const { truncated: lostParts, ...fitted } = withoutFirstParts(messages, size + messagesSize - limit3);
11748
+ if (size2 + messagesSize > limit3) {
11749
+ const { truncated: lostParts, ...fitted } = withoutFirstParts(messages, size2 + messagesSize - limit3);
11336
11750
  truncated || (truncated = lostParts);
11337
11751
  serialize(fitted, values);
11338
11752
  messagesSize = sizeOfMessages();
11339
11753
  }
11340
- size += messagesSize;
11754
+ size2 += messagesSize;
11341
11755
  if (blocks !== void 0) {
11342
- const kept = truncateToolResultContent(blocks, limit3 - size, sizeOf);
11756
+ const kept = truncateToolResultContent(blocks, limit3 - size2, sizeOf);
11343
11757
  values[ATTR_ANTHROPIC_TOOL_RESULT_CONTENT] = kept.json;
11344
- size += kept.size;
11758
+ size2 += kept.size;
11345
11759
  truncated || (truncated = kept.truncated);
11346
11760
  }
11347
11761
  if (truncated) {
@@ -11353,7 +11767,7 @@ function setContentAttributes(span, attributes, limit3) {
11353
11767
  for (const [key, value] of Object.entries(values)) {
11354
11768
  span.setAttribute(key, value);
11355
11769
  }
11356
- return size;
11770
+ return size2;
11357
11771
  }
11358
11772
  function serialize(attributes, values) {
11359
11773
  let length = 0;
@@ -11377,17 +11791,17 @@ function withoutFirstParts(attributes, excess) {
11377
11791
  let removed = 0;
11378
11792
  while (excess > 0 && removed < parts.length) {
11379
11793
  const part = parts[removed];
11380
- const size = utf8Length(JSON.stringify(part));
11794
+ const size2 = utf8Length(JSON.stringify(part));
11381
11795
  const content = part["content"];
11382
11796
  if (left === 1 && part.type === "text" && typeof content === "string") {
11383
- const kept = startThatFits(part, content, size - excess);
11797
+ const kept = startThatFits(part, content, size2 - excess);
11384
11798
  if (kept !== content) {
11385
11799
  parts[removed] = { ...part, content: kept };
11386
11800
  truncated = true;
11387
11801
  }
11388
11802
  break;
11389
11803
  }
11390
- excess -= size + (removed + 1 < parts.length ? 1 : 0);
11804
+ excess -= size2 + (removed + 1 < parts.length ? 1 : 0);
11391
11805
  removed++;
11392
11806
  left--;
11393
11807
  truncated = true;
@@ -11407,13 +11821,13 @@ function startThatFits(part, content, limit3) {
11407
11821
  const escaped = JSON.stringify(head);
11408
11822
  let length = 0;
11409
11823
  let escapedLength = 0;
11410
- let size = 0;
11824
+ let size2 = 0;
11411
11825
  while (length < head.length) {
11412
11826
  const point = escaped.codePointAt(1 + escapedLength);
11413
11827
  const units = point > 65535 ? 2 : 1;
11414
11828
  const escapedUnits = point !== 92 ? units : escaped[2 + escapedLength] === "u" ? 6 : 2;
11415
- size += point < 128 ? escapedUnits : point < 2048 ? 2 : point < 65536 ? 3 : 4;
11416
- if (size > room) {
11829
+ size2 += point < 128 ? escapedUnits : point < 2048 ? 2 : point < 65536 ? 3 : 4;
11830
+ if (size2 > room) {
11417
11831
  break;
11418
11832
  }
11419
11833
  escapedLength += escapedUnits;
@@ -11423,33 +11837,33 @@ function startThatFits(part, content, limit3) {
11423
11837
  }
11424
11838
  function truncateToolResultContent(blocks, limit3, sizeOf) {
11425
11839
  const kept = [];
11426
- let size = 2;
11840
+ let size2 = 2;
11427
11841
  for (const block of blocks) {
11428
- const next = size + (kept.length === 0 ? 0 : 1) + sizeOf(block);
11842
+ const next = size2 + (kept.length === 0 ? 0 : 1) + sizeOf(block);
11429
11843
  if (next > limit3) {
11430
11844
  break;
11431
11845
  }
11432
11846
  kept.push(block);
11433
- size = next;
11847
+ size2 = next;
11434
11848
  }
11435
- return { json: "[" + kept.join(",") + "]", size, truncated: kept.length < blocks.length };
11849
+ return { json: "[" + kept.join(",") + "]", size: size2, truncated: kept.length < blocks.length };
11436
11850
  }
11437
11851
  function utf8Length(text) {
11438
- let size = 0;
11852
+ let size2 = 0;
11439
11853
  for (let index = 0; index < text.length; index++) {
11440
11854
  const unit = text.charCodeAt(index);
11441
11855
  if (unit < 128) {
11442
- size += 1;
11856
+ size2 += 1;
11443
11857
  } else if (unit < 2048) {
11444
- size += 2;
11858
+ size2 += 2;
11445
11859
  } else if (unit >= 55296 && unit < 56320 && (text.charCodeAt(index + 1) & 64512) === 56320) {
11446
- size += 4;
11860
+ size2 += 4;
11447
11861
  index++;
11448
11862
  } else {
11449
- size += 3;
11863
+ size2 += 3;
11450
11864
  }
11451
11865
  }
11452
- return size;
11866
+ return size2;
11453
11867
  }
11454
11868
  var init_content = __esm({
11455
11869
  "../../node_modules/.pnpm/@anthropic-ai+sdk@1.4.0_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/internal/tracing/content.mjs"() {
@@ -11468,10 +11882,10 @@ function setResponseAttributes(span, message, usage, complete) {
11468
11882
  if (usage.cache_read_input_tokens != null) {
11469
11883
  span.setAttribute(ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, usage.cache_read_input_tokens);
11470
11884
  }
11471
- const written = usage.cache_creation;
11472
- if (written != null) {
11473
- span.setAttribute(ATTR_ANTHROPIC_USAGE_CACHE_CREATION_EPHEMERAL_5M_INPUT_TOKENS, written.ephemeral_5m_input_tokens);
11474
- span.setAttribute(ATTR_ANTHROPIC_USAGE_CACHE_CREATION_EPHEMERAL_1H_INPUT_TOKENS, written.ephemeral_1h_input_tokens);
11885
+ const written2 = usage.cache_creation;
11886
+ if (written2 != null) {
11887
+ span.setAttribute(ATTR_ANTHROPIC_USAGE_CACHE_CREATION_EPHEMERAL_5M_INPUT_TOKENS, written2.ephemeral_5m_input_tokens);
11888
+ span.setAttribute(ATTR_ANTHROPIC_USAGE_CACHE_CREATION_EPHEMERAL_1H_INPUT_TOKENS, written2.ephemeral_1h_input_tokens);
11475
11889
  }
11476
11890
  if (usage.service_tier != null) {
11477
11891
  span.setAttribute(ATTR_ANTHROPIC_RESPONSE_SERVICE_TIER, usage.service_tier);
@@ -13342,7 +13756,7 @@ var init_parser2 = __esm({
13342
13756
  "../../node_modules/.pnpm/@anthropic-ai+sdk@1.4.0_zod@3.25.76/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs"() {
13343
13757
  tokenize = (input) => {
13344
13758
  let current = 0;
13345
- let tokens = [];
13759
+ let tokens2 = [];
13346
13760
  while (current < input.length) {
13347
13761
  let char = input[current];
13348
13762
  if (char === "\\") {
@@ -13350,7 +13764,7 @@ var init_parser2 = __esm({
13350
13764
  continue;
13351
13765
  }
13352
13766
  if (char === "{") {
13353
- tokens.push({
13767
+ tokens2.push({
13354
13768
  type: "brace",
13355
13769
  value: "{"
13356
13770
  });
@@ -13358,7 +13772,7 @@ var init_parser2 = __esm({
13358
13772
  continue;
13359
13773
  }
13360
13774
  if (char === "}") {
13361
- tokens.push({
13775
+ tokens2.push({
13362
13776
  type: "brace",
13363
13777
  value: "}"
13364
13778
  });
@@ -13366,7 +13780,7 @@ var init_parser2 = __esm({
13366
13780
  continue;
13367
13781
  }
13368
13782
  if (char === "[") {
13369
- tokens.push({
13783
+ tokens2.push({
13370
13784
  type: "paren",
13371
13785
  value: "["
13372
13786
  });
@@ -13374,7 +13788,7 @@ var init_parser2 = __esm({
13374
13788
  continue;
13375
13789
  }
13376
13790
  if (char === "]") {
13377
- tokens.push({
13791
+ tokens2.push({
13378
13792
  type: "paren",
13379
13793
  value: "]"
13380
13794
  });
@@ -13382,7 +13796,7 @@ var init_parser2 = __esm({
13382
13796
  continue;
13383
13797
  }
13384
13798
  if (char === ":") {
13385
- tokens.push({
13799
+ tokens2.push({
13386
13800
  type: "separator",
13387
13801
  value: ":"
13388
13802
  });
@@ -13390,7 +13804,7 @@ var init_parser2 = __esm({
13390
13804
  continue;
13391
13805
  }
13392
13806
  if (char === ",") {
13393
- tokens.push({
13807
+ tokens2.push({
13394
13808
  type: "delimiter",
13395
13809
  value: ","
13396
13810
  });
@@ -13420,7 +13834,7 @@ var init_parser2 = __esm({
13420
13834
  if (danglingQuote) {
13421
13835
  current = input.length;
13422
13836
  } else {
13423
- tokens.push({
13837
+ tokens2.push({
13424
13838
  type: "string",
13425
13839
  value: input.slice(start, end)
13426
13840
  });
@@ -13446,7 +13860,7 @@ var init_parser2 = __esm({
13446
13860
  value += char;
13447
13861
  char = input[++current];
13448
13862
  }
13449
- tokens.push({
13863
+ tokens2.push({
13450
13864
  type: "number",
13451
13865
  value,
13452
13866
  unterminated: current === input.length
@@ -13464,7 +13878,7 @@ var init_parser2 = __esm({
13464
13878
  char = input[++current];
13465
13879
  }
13466
13880
  if (value == "true" || value == "false" || value === "null") {
13467
- tokens.push({
13881
+ tokens2.push({
13468
13882
  type: "name",
13469
13883
  value
13470
13884
  });
@@ -13476,11 +13890,11 @@ var init_parser2 = __esm({
13476
13890
  }
13477
13891
  current++;
13478
13892
  }
13479
- return tokens;
13893
+ return tokens2;
13480
13894
  };
13481
- strip = (tokens) => {
13895
+ strip = (tokens2) => {
13482
13896
  let open = [];
13483
- for (const token of tokens) {
13897
+ for (const token of tokens2) {
13484
13898
  if (token.type === "brace" || token.type === "paren") {
13485
13899
  if (token.value === "{" || token.value === "[") {
13486
13900
  open.push(token.value);
@@ -13490,10 +13904,10 @@ var init_parser2 = __esm({
13490
13904
  }
13491
13905
  }
13492
13906
  let innermostOpenBracket = open[open.length - 1];
13493
- let length = tokens.length;
13907
+ let length = tokens2.length;
13494
13908
  let JSON_NUMBER = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?$/;
13495
13909
  while (length > 0) {
13496
- let lastToken = tokens[length - 1];
13910
+ let lastToken = tokens2[length - 1];
13497
13911
  switch (lastToken.type) {
13498
13912
  case "separator":
13499
13913
  length--;
@@ -13505,7 +13919,7 @@ var init_parser2 = __esm({
13505
13919
  }
13506
13920
  break;
13507
13921
  case "string":
13508
- let tokenBeforeTheLastToken = tokens[length - 2];
13922
+ let tokenBeforeTheLastToken = tokens2[length - 2];
13509
13923
  if (innermostOpenBracket === "{" && (tokenBeforeTheLastToken?.type === "delimiter" || tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{")) {
13510
13924
  length--;
13511
13925
  continue;
@@ -13517,11 +13931,11 @@ var init_parser2 = __esm({
13517
13931
  }
13518
13932
  break;
13519
13933
  }
13520
- return tokens.slice(0, length);
13934
+ return tokens2.slice(0, length);
13521
13935
  };
13522
- unstrip = (tokens) => {
13936
+ unstrip = (tokens2) => {
13523
13937
  let tail = [];
13524
- tokens.map((token) => {
13938
+ tokens2.map((token) => {
13525
13939
  if (token.type === "brace") {
13526
13940
  if (token.value === "{") {
13527
13941
  tail.push("}");
@@ -13540,23 +13954,23 @@ var init_parser2 = __esm({
13540
13954
  if (tail.length > 0) {
13541
13955
  tail.reverse().map((item) => {
13542
13956
  if (item === "}") {
13543
- tokens.push({
13957
+ tokens2.push({
13544
13958
  type: "brace",
13545
13959
  value: "}"
13546
13960
  });
13547
13961
  } else if (item === "]") {
13548
- tokens.push({
13962
+ tokens2.push({
13549
13963
  type: "paren",
13550
13964
  value: "]"
13551
13965
  });
13552
13966
  }
13553
13967
  });
13554
13968
  }
13555
- return tokens;
13969
+ return tokens2;
13556
13970
  };
13557
- generate = (tokens) => {
13971
+ generate = (tokens2) => {
13558
13972
  let output = "";
13559
- tokens.map((token) => {
13973
+ tokens2.map((token) => {
13560
13974
  switch (token.type) {
13561
13975
  case "string":
13562
13976
  output += '"' + token.value + '"';
@@ -16305,8 +16719,8 @@ var require_dist = __commonJS({
16305
16719
  endpointVerificationResponse(challenge) {
16306
16720
  const encoder = new TextEncoder();
16307
16721
  const verificationKey = sha256.hmac(this.key, encoder.encode("wev-v1"));
16308
- const signature = base642.encode(sha256.hmac(verificationKey, encoder.encode(challenge)));
16309
- return `v1,${signature}`;
16722
+ const signature2 = base642.encode(sha256.hmac(verificationKey, encoder.encode(challenge)));
16723
+ return `v1,${signature2}`;
16310
16724
  }
16311
16725
  verifyEndpointVerificationResponse(challenge, header2) {
16312
16726
  if (!header2) {
@@ -30762,8 +31176,8 @@ function startsWith(messages, prefix) {
30762
31176
  }
30763
31177
  function sameMessage(a2, b3) {
30764
31178
  const [left, right] = [toMessageParam(a2), toMessageParam(b3)];
30765
- const keys = Object.keys({ ...left, ...right });
30766
- return keys.every((key) => left[key] === right[key] || JSON.stringify(left[key]) === JSON.stringify(right[key]));
31179
+ const keys2 = Object.keys({ ...left, ...right });
31180
+ return keys2.every((key) => left[key] === right[key] || JSON.stringify(left[key]) === JSON.stringify(right[key]));
30767
31181
  }
30768
31182
  function toMessageParam(message) {
30769
31183
  return "id" in message ? { role: message.role, content: message.content } : message;
@@ -37102,12 +37516,12 @@ var require_main = __commonJS({
37102
37516
  err.code = "MISSING_DATA";
37103
37517
  throw err;
37104
37518
  }
37105
- const keys = _dotenvKey(options).split(",");
37106
- const length = keys.length;
37519
+ const keys2 = _dotenvKey(options).split(",");
37520
+ const length = keys2.length;
37107
37521
  let decrypted;
37108
37522
  for (let i2 = 0; i2 < length; i2++) {
37109
37523
  try {
37110
- const key = keys[i2].trim();
37524
+ const key = keys2[i2].trim();
37111
37525
  const attrs = _instructions(result, key);
37112
37526
  decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
37113
37527
  break;
@@ -37518,8 +37932,8 @@ function inner_stringify2(object3, prefix, generateArrayPrefix, commaRoundTrip,
37518
37932
  } else if (is_array2(filter)) {
37519
37933
  obj_keys = filter;
37520
37934
  } else {
37521
- const keys = Object.keys(obj);
37522
- obj_keys = sort ? keys.sort(sort) : keys;
37935
+ const keys2 = Object.keys(obj);
37936
+ obj_keys = sort ? keys2.sort(sort) : keys2;
37523
37937
  }
37524
37938
  const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix);
37525
37939
  const adjusted_prefix = commaRoundTrip && is_array2(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix;
@@ -37638,7 +38052,7 @@ function stringify2(object3, opts = {}) {
37638
38052
  filter = options.filter;
37639
38053
  obj_keys = filter;
37640
38054
  }
37641
- const keys = [];
38055
+ const keys2 = [];
37642
38056
  if (typeof obj !== "object" || obj === null) {
37643
38057
  return "";
37644
38058
  }
@@ -37656,7 +38070,7 @@ function stringify2(object3, opts = {}) {
37656
38070
  if (options.skipNulls && obj[key] === null) {
37657
38071
  continue;
37658
38072
  }
37659
- push_to_array2(keys, inner_stringify2(
38073
+ push_to_array2(keys2, inner_stringify2(
37660
38074
  obj[key],
37661
38075
  key,
37662
38076
  // @ts-expect-error
@@ -37678,7 +38092,7 @@ function stringify2(object3, opts = {}) {
37678
38092
  sideChannel
37679
38093
  ));
37680
38094
  }
37681
- const joined = keys.join(options.delimiter);
38095
+ const joined = keys2.join(options.delimiter);
37682
38096
  let prefix = options.addQueryPrefix === true ? "?" : "";
37683
38097
  if (options.charsetSentinel) {
37684
38098
  if (options.charset === "iso-8859-1") {
@@ -37955,9 +38369,9 @@ var require_utils = __commonJS({
37955
38369
  "../../node_modules/.pnpm/whatwg-url@5.0.0/node_modules/whatwg-url/lib/utils.js"(exports, module) {
37956
38370
  "use strict";
37957
38371
  module.exports.mixin = function mixin(target, source) {
37958
- const keys = Object.getOwnPropertyNames(source);
37959
- for (let i2 = 0; i2 < keys.length; ++i2) {
37960
- Object.defineProperty(target, keys[i2], Object.getOwnPropertyDescriptor(source, keys[i2]));
38372
+ const keys2 = Object.getOwnPropertyNames(source);
38373
+ for (let i2 = 0; i2 < keys2.length; ++i2) {
38374
+ Object.defineProperty(target, keys2[i2], Object.getOwnPropertyDescriptor(source, keys2[i2]));
37961
38375
  }
37962
38376
  };
37963
38377
  module.exports.wrapperSymbol = /* @__PURE__ */ Symbol("wrapper");
@@ -38158,7 +38572,7 @@ var require_url_state_machine = __commonJS({
38158
38572
  function countSymbols(str3) {
38159
38573
  return punycode.ucs2.decode(str3).length;
38160
38574
  }
38161
- function at2(input, idx) {
38575
+ function at3(input, idx) {
38162
38576
  const c2 = input[idx];
38163
38577
  return isNaN(c2) ? void 0 : String.fromCodePoint(c2);
38164
38578
  }
@@ -38350,7 +38764,7 @@ var require_url_state_machine = __commonJS({
38350
38764
  let value = 0;
38351
38765
  let length = 0;
38352
38766
  while (length < 4 && isASCIIHex(input[pointer])) {
38353
- value = value * 16 + parseInt(at2(input, pointer), 16);
38767
+ value = value * 16 + parseInt(at3(input, pointer), 16);
38354
38768
  ++pointer;
38355
38769
  ++length;
38356
38770
  }
@@ -38376,7 +38790,7 @@ var require_url_state_machine = __commonJS({
38376
38790
  return failure;
38377
38791
  }
38378
38792
  while (isASCIIDigit(input[pointer])) {
38379
- const number4 = parseInt(at2(input, pointer));
38793
+ const number4 = parseInt(at3(input, pointer));
38380
38794
  if (ipv4Piece === null) {
38381
38795
  ipv4Piece = number4;
38382
38796
  } else if (ipv4Piece === 0) {
@@ -39589,7 +40003,7 @@ var require_lib2 = __commonJS({
39589
40003
  const blobParts = arguments[0];
39590
40004
  const options = arguments[1];
39591
40005
  const buffers = [];
39592
- let size = 0;
40006
+ let size2 = 0;
39593
40007
  if (blobParts) {
39594
40008
  const a2 = blobParts;
39595
40009
  const length = Number(a2.length);
@@ -39607,7 +40021,7 @@ var require_lib2 = __commonJS({
39607
40021
  } else {
39608
40022
  buffer = Buffer.from(typeof element === "string" ? element : String(element));
39609
40023
  }
39610
- size += buffer.length;
40024
+ size2 += buffer.length;
39611
40025
  buffers.push(buffer);
39612
40026
  }
39613
40027
  }
@@ -39643,23 +40057,23 @@ var require_lib2 = __commonJS({
39643
40057
  return "[object Blob]";
39644
40058
  }
39645
40059
  slice() {
39646
- const size = this.size;
40060
+ const size2 = this.size;
39647
40061
  const start = arguments[0];
39648
40062
  const end = arguments[1];
39649
40063
  let relativeStart, relativeEnd;
39650
40064
  if (start === void 0) {
39651
40065
  relativeStart = 0;
39652
40066
  } else if (start < 0) {
39653
- relativeStart = Math.max(size + start, 0);
40067
+ relativeStart = Math.max(size2 + start, 0);
39654
40068
  } else {
39655
- relativeStart = Math.min(start, size);
40069
+ relativeStart = Math.min(start, size2);
39656
40070
  }
39657
40071
  if (end === void 0) {
39658
- relativeEnd = size;
40072
+ relativeEnd = size2;
39659
40073
  } else if (end < 0) {
39660
- relativeEnd = Math.max(size + end, 0);
40074
+ relativeEnd = Math.max(size2 + end, 0);
39661
40075
  } else {
39662
- relativeEnd = Math.min(end, size);
40076
+ relativeEnd = Math.min(end, size2);
39663
40077
  }
39664
40078
  const span = Math.max(relativeEnd - relativeStart, 0);
39665
40079
  const buffer = this[BUFFER];
@@ -39702,7 +40116,7 @@ var require_lib2 = __commonJS({
39702
40116
  function Body(body) {
39703
40117
  var _this = this;
39704
40118
  var _ref = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, _ref$size = _ref.size;
39705
- let size = _ref$size === void 0 ? 0 : _ref$size;
40119
+ let size2 = _ref$size === void 0 ? 0 : _ref$size;
39706
40120
  var _ref$timeout = _ref.timeout;
39707
40121
  let timeout = _ref$timeout === void 0 ? 0 : _ref$timeout;
39708
40122
  if (body == null) {
@@ -39724,7 +40138,7 @@ var require_lib2 = __commonJS({
39724
40138
  disturbed: false,
39725
40139
  error: null
39726
40140
  };
39727
- this.size = size;
40141
+ this.size = size2;
39728
40142
  this.timeout = timeout;
39729
40143
  if (body instanceof Stream3) {
39730
40144
  body.on("error", function(err) {
@@ -40236,8 +40650,8 @@ var require_lib2 = __commonJS({
40236
40650
  });
40237
40651
  function getHeaders(headers) {
40238
40652
  let kind2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "key+value";
40239
- const keys = Object.keys(headers[MAP]).sort();
40240
- return keys.map(kind2 === "key" ? function(k3) {
40653
+ const keys2 = Object.keys(headers[MAP]).sort();
40654
+ return keys2.map(kind2 === "key" ? function(k3) {
40241
40655
  return k3.toLowerCase();
40242
40656
  } : kind2 === "value" ? function(k3) {
40243
40657
  return headers[MAP][k3].join(", ");
@@ -41255,7 +41669,7 @@ function nt(e2, t2) {
41255
41669
  Rt(e3);
41256
41670
  })(r2) : Et(r2)), e2._backpressure = t2;
41257
41671
  }
41258
- function at(e2) {
41672
+ function at2(e2) {
41259
41673
  return !!r(e2) && (!!Object.prototype.hasOwnProperty.call(e2, "_ownerWritableStream") && e2 instanceof WritableStreamDefaultWriter);
41260
41674
  }
41261
41675
  function it(e2, t2) {
@@ -42189,10 +42603,10 @@ var init_ponyfill = __esm({
42189
42603
  var r2;
42190
42604
  }
42191
42605
  get closed() {
42192
- return at(this) ? this._closedPromise : d(mt("closed"));
42606
+ return at2(this) ? this._closedPromise : d(mt("closed"));
42193
42607
  }
42194
42608
  get desiredSize() {
42195
- if (!at(this)) throw mt("desiredSize");
42609
+ if (!at2(this)) throw mt("desiredSize");
42196
42610
  if (void 0 === this._ownerWritableStream) throw yt("desiredSize");
42197
42611
  return (function(e2) {
42198
42612
  const t2 = e2._ownerWritableStream, r2 = t2._state;
@@ -42202,20 +42616,20 @@ var init_ponyfill = __esm({
42202
42616
  })(this);
42203
42617
  }
42204
42618
  get ready() {
42205
- return at(this) ? this._readyPromise : d(mt("ready"));
42619
+ return at2(this) ? this._readyPromise : d(mt("ready"));
42206
42620
  }
42207
42621
  abort(e2) {
42208
- return at(this) ? void 0 === this._ownerWritableStream ? d(yt("abort")) : (function(e3, t2) {
42622
+ return at2(this) ? void 0 === this._ownerWritableStream ? d(yt("abort")) : (function(e3, t2) {
42209
42623
  return Je(e3._ownerWritableStream, t2);
42210
42624
  })(this, e2) : d(mt("abort"));
42211
42625
  }
42212
42626
  close() {
42213
- if (!at(this)) return d(mt("close"));
42627
+ if (!at2(this)) return d(mt("close"));
42214
42628
  const e2 = this._ownerWritableStream;
42215
42629
  return void 0 === e2 ? d(yt("close")) : rt(e2) ? d(new TypeError("Cannot close an already-closing stream")) : Ke(this._ownerWritableStream);
42216
42630
  }
42217
42631
  releaseLock() {
42218
- if (!at(this)) throw mt("releaseLock");
42632
+ if (!at2(this)) throw mt("releaseLock");
42219
42633
  void 0 !== this._ownerWritableStream && (function(e2) {
42220
42634
  const t2 = e2._ownerWritableStream, r2 = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");
42221
42635
  it(e2, r2), (function(e3, t3) {
@@ -42226,7 +42640,7 @@ var init_ponyfill = __esm({
42226
42640
  })(this);
42227
42641
  }
42228
42642
  write(e2) {
42229
- return at(this) ? void 0 === this._ownerWritableStream ? d(yt("write to")) : (function(e3, t2) {
42643
+ return at2(this) ? void 0 === this._ownerWritableStream ? d(yt("write to")) : (function(e3, t2) {
42230
42644
  const r2 = e3._ownerWritableStream, o2 = r2._writableStreamController, n3 = (function(e4, t3) {
42231
42645
  try {
42232
42646
  return e4._strategySizeAlgorithm(t3);
@@ -42629,8 +43043,8 @@ async function* clonePart(part) {
42629
43043
  const end = part.byteOffset + part.byteLength;
42630
43044
  let position = part.byteOffset;
42631
43045
  while (position !== end) {
42632
- const size = Math.min(end - position, CHUNK_SIZE);
42633
- const chunk = part.buffer.slice(position, position + size);
43046
+ const size2 = Math.min(end - position, CHUNK_SIZE);
43047
+ const chunk = part.buffer.slice(position, position + size2);
42634
43048
  position += chunk.byteLength;
42635
43049
  yield new Uint8Array(chunk);
42636
43050
  }
@@ -43610,9 +44024,9 @@ var require_event_target_shim = __commonJS({
43610
44024
  timeStamp: event.timeStamp || Date.now()
43611
44025
  });
43612
44026
  Object.defineProperty(this, "isTrusted", { value: false, enumerable: true });
43613
- const keys = Object.keys(event);
43614
- for (let i2 = 0; i2 < keys.length; ++i2) {
43615
- const key = keys[i2];
44027
+ const keys2 = Object.keys(event);
44028
+ for (let i2 = 0; i2 < keys2.length; ++i2) {
44029
+ const key = keys2[i2];
43616
44030
  if (!(key in this)) {
43617
44031
  Object.defineProperty(this, key, defineRedirectDescriptor(key));
43618
44032
  }
@@ -43831,8 +44245,8 @@ var require_event_target_shim = __commonJS({
43831
44245
  };
43832
44246
  }
43833
44247
  function defineWrapper(BaseEvent, proto) {
43834
- const keys = Object.keys(proto);
43835
- if (keys.length === 0) {
44248
+ const keys2 = Object.keys(proto);
44249
+ if (keys2.length === 0) {
43836
44250
  return BaseEvent;
43837
44251
  }
43838
44252
  function CustomEvent(eventTarget, event) {
@@ -43841,8 +44255,8 @@ var require_event_target_shim = __commonJS({
43841
44255
  CustomEvent.prototype = Object.create(BaseEvent.prototype, {
43842
44256
  constructor: { value: CustomEvent, configurable: true, writable: true }
43843
44257
  });
43844
- for (let i2 = 0; i2 < keys.length; ++i2) {
43845
- const key = keys[i2];
44258
+ for (let i2 = 0; i2 < keys2.length; ++i2) {
44259
+ const key = keys2[i2];
43846
44260
  if (!(key in BaseEvent.prototype)) {
43847
44261
  const descriptor = Object.getOwnPropertyDescriptor(proto, key);
43848
44262
  const isFunc = typeof descriptor.value === "function";
@@ -44233,9 +44647,9 @@ var require_abort_controller = __commonJS({
44233
44647
 
44234
44648
  // ../../node_modules/.pnpm/form-data-encoder@1.7.2/node_modules/form-data-encoder/lib/esm/util/createBoundary.js
44235
44649
  function createBoundary() {
44236
- let size = 16;
44650
+ let size2 = 16;
44237
44651
  let res = "";
44238
- while (size--) {
44652
+ while (size2--) {
44239
44653
  res += alphabet[Math.random() * alphabet.length << 0];
44240
44654
  }
44241
44655
  return res;
@@ -44522,14 +44936,14 @@ __export(fileFromPath_exports, {
44522
44936
  });
44523
44937
  import { statSync, createReadStream as createReadStream2, promises as fs5 } from "fs";
44524
44938
  import { basename } from "path";
44525
- function createFileFromPath(path36, { mtimeMs, size }, filenameOrOptions, options = {}) {
44939
+ function createFileFromPath(path36, { mtimeMs, size: size2 }, filenameOrOptions, options = {}) {
44526
44940
  let filename;
44527
44941
  if (isPlainObject_default2(filenameOrOptions)) {
44528
44942
  [options, filename] = [filenameOrOptions, void 0];
44529
44943
  } else {
44530
44944
  filename = filenameOrOptions;
44531
44945
  }
44532
- const file2 = new FileFromPath({ path: path36, size, lastModified: mtimeMs });
44946
+ const file2 = new FileFromPath({ path: path36, size: size2, lastModified: mtimeMs });
44533
44947
  if (!filename) {
44534
44948
  filename = file2.name;
44535
44949
  }
@@ -51722,8 +52136,8 @@ function renderRow(template, item) {
51722
52136
  function fillRows(text, rows, ctx) {
51723
52137
  const lines = text.split("\n");
51724
52138
  for (const group of rows) {
51725
- const at2 = lines.map((line, i2) => line.trim() === group.marker ? i2 : -1).filter((i2) => i2 >= 0);
51726
- if (at2.length !== 1) return null;
52139
+ const at3 = lines.map((line, i2) => line.trim() === group.marker ? i2 : -1).filter((i2) => i2 >= 0);
52140
+ if (at3.length !== 1) return null;
51727
52141
  const list = lookupReference(group.over, ctx);
51728
52142
  if (!Array.isArray(list)) return null;
51729
52143
  const rendered = [];
@@ -51732,7 +52146,7 @@ function fillRows(text, rows, ctx) {
51732
52146
  if (row === null) return null;
51733
52147
  rendered.push(row);
51734
52148
  }
51735
- lines.splice(at2[0], 1, ...rendered);
52149
+ lines.splice(at3[0], 1, ...rendered);
51736
52150
  }
51737
52151
  return lines.some((l2) => /\[\[rows:\d+\]\]/.test(l2)) ? null : lines.join("\n");
51738
52152
  }
@@ -51769,6 +52183,16 @@ function whenText(when) {
51769
52183
  return `${when.ref} is ${JSON.stringify(when.value)}`;
51770
52184
  case "notEquals":
51771
52185
  return `${when.ref} is not ${JSON.stringify(when.value)}`;
52186
+ case "above":
52187
+ return `${when.ref} is above ${when.value}`;
52188
+ case "below":
52189
+ return `${when.ref} is below ${when.value}`;
52190
+ case "before":
52191
+ return `${when.ref} is before ${when.other}`;
52192
+ case "after":
52193
+ return `${when.ref} is after ${when.other}`;
52194
+ case "all":
52195
+ return when.of.map(whenText).join(" and ");
51772
52196
  case "ask":
51773
52197
  return "the replay model says yes (no rule told the recordings apart)";
51774
52198
  }
@@ -51806,6 +52230,24 @@ function mergePages(acc, page, next) {
51806
52230
  function isRecord(v3) {
51807
52231
  return v3 !== null && typeof v3 === "object" && !Array.isArray(v3);
51808
52232
  }
52233
+ function atPath(value, path36) {
52234
+ let v3 = value;
52235
+ for (const p3 of path36) {
52236
+ v3 = v3 !== null && typeof v3 === "object" ? v3[p3] : void 0;
52237
+ }
52238
+ return v3;
52239
+ }
52240
+ function detailsPerItem(items, results, distinct) {
52241
+ if (!Array.isArray(results)) return items.map(() => void 0);
52242
+ if (!distinct)
52243
+ return results.length === items.length ? results : items.map(() => void 0);
52244
+ const firsts = [];
52245
+ return items.map((item) => {
52246
+ const value = JSON.stringify(atPath(item, distinct));
52247
+ if (!firsts.includes(value)) firsts.push(value);
52248
+ return results[firsts.indexOf(value)];
52249
+ });
52250
+ }
51809
52251
  var DEFAULT_MAX_PAGES;
51810
52252
  var init_items = __esm({
51811
52253
  "../shared/src/items.ts"() {
@@ -51814,6 +52256,39 @@ var init_items = __esm({
51814
52256
  }
51815
52257
  });
51816
52258
 
52259
+ // ../shared/src/trim.ts
52260
+ function trimData(ctx, paths) {
52261
+ const steps = structuredClone(ctx.steps);
52262
+ for (const p3 of paths) {
52263
+ const parts = p3.split(".");
52264
+ if (parts[0] !== "steps" || !replaceAt(steps, parts.slice(1))) return null;
52265
+ }
52266
+ return { ...ctx, steps };
52267
+ }
52268
+ function replaceAt(node, parts) {
52269
+ const [key, ...rest] = parts;
52270
+ if (key === void 0) return false;
52271
+ if (key === "*") {
52272
+ return Array.isArray(node) && node.every((n3) => replaceAt(n3, rest));
52273
+ }
52274
+ if (node === null || typeof node !== "object") return false;
52275
+ const obj = node;
52276
+ if (rest.length === 0) {
52277
+ const list = obj[key];
52278
+ if (!Array.isArray(list)) return false;
52279
+ obj[key] = trimmedNote(list.length);
52280
+ return true;
52281
+ }
52282
+ return replaceAt(obj[key], rest);
52283
+ }
52284
+ var trimmedNote;
52285
+ var init_trim = __esm({
52286
+ "../shared/src/trim.ts"() {
52287
+ "use strict";
52288
+ trimmedNote = (n3) => `(${n3} items not shown: code computed the figures below from all of them)`;
52289
+ }
52290
+ });
52291
+
51817
52292
  // ../shared/src/index.ts
51818
52293
  var init_src = __esm({
51819
52294
  "../shared/src/index.ts"() {
@@ -51835,6 +52310,9 @@ var init_src = __esm({
51835
52310
  init_items();
51836
52311
  init_selection();
51837
52312
  init_calc();
52313
+ init_trim();
52314
+ init_bands();
52315
+ init_table();
51838
52316
  }
51839
52317
  });
51840
52318
 
@@ -51883,7 +52361,130 @@ function learnRule(yes, no) {
51883
52361
  }
51884
52362
  return null;
51885
52363
  }
51886
- function learnItemRule(yes, no) {
52364
+ function byRoundness(numbers) {
52365
+ const zeros = (n3) => {
52366
+ if (!Number.isInteger(n3)) return -1;
52367
+ let z2 = 0;
52368
+ for (let x3 = Math.abs(n3); x3 !== 0 && x3 % 10 === 0; x3 /= 10) z2++;
52369
+ return z2;
52370
+ };
52371
+ return [...numbers].sort((a2, b3) => zeros(b3) - zeros(a2));
52372
+ }
52373
+ function learnNumberRule(yes, no, written2, dataValues) {
52374
+ if (yes.length === 0 || no.length === 0) return null;
52375
+ const thresholds = byRoundness(
52376
+ [...new Set(written2)].filter((n3) => !dataValues.has(n3))
52377
+ );
52378
+ const refs = [...yes[0].keys()].filter(
52379
+ (r2) => [...yes, ...no].every((f3) => {
52380
+ const v3 = f3.get(r2);
52381
+ return v3 !== void 0 && "scalar" in v3 && typeof v3.scalar === "number";
52382
+ })
52383
+ );
52384
+ const num2 = (f3, r2) => f3.get(r2).scalar;
52385
+ const many = yes.length >= 3 && no.length >= 3;
52386
+ for (const ref of refs) {
52387
+ const ys = yes.map((f3) => num2(f3, ref));
52388
+ const ns = no.map((f3) => num2(f3, ref));
52389
+ const [minY, maxY, minN, maxN] = [
52390
+ Math.min(...ys),
52391
+ Math.max(...ys),
52392
+ Math.min(...ns),
52393
+ Math.max(...ns)
52394
+ ];
52395
+ if (minY > maxN) {
52396
+ const n3 = thresholds.find((t2) => t2 >= maxN && t2 < minY);
52397
+ if (n3 !== void 0) return { kind: "above", ref, value: n3 };
52398
+ if (many)
52399
+ return {
52400
+ kind: "above",
52401
+ ref,
52402
+ value: Math.round((maxN + minY) / 2 * 100) / 100
52403
+ };
52404
+ }
52405
+ if (maxY < minN) {
52406
+ const n3 = thresholds.find((t2) => t2 > maxY && t2 <= minN);
52407
+ if (n3 !== void 0) return { kind: "below", ref, value: n3 };
52408
+ if (many)
52409
+ return {
52410
+ kind: "below",
52411
+ ref,
52412
+ value: Math.round((maxY + minN) / 2 * 100) / 100
52413
+ };
52414
+ }
52415
+ }
52416
+ return null;
52417
+ }
52418
+ function learnItemThresholdRule(yes, no, written2, dataValues, inputs) {
52419
+ if (yes.length === 0 || no.length === 0) return null;
52420
+ const all = [...yes, ...no];
52421
+ const scalar2 = (m3, ref) => {
52422
+ const f3 = m3.get(ref);
52423
+ return f3 && "scalar" in f3 ? f3.scalar : void 0;
52424
+ };
52425
+ const refs = [...yes[0].keys()].filter(
52426
+ (r2) => all.every((m3) => scalar2(m3, r2) !== void 0)
52427
+ );
52428
+ const thresholds = byRoundness(
52429
+ [...new Set(written2)].filter(
52430
+ (n3) => !dataValues.has(n3) && Number.isFinite(n3)
52431
+ )
52432
+ );
52433
+ const dates = Object.entries(inputs).filter(
52434
+ (e2) => typeof e2[1] === "string" && ISO_DATE.test(e2[1])
52435
+ );
52436
+ const atoms = [];
52437
+ for (const ref of refs) {
52438
+ if (all.every((m3) => typeof scalar2(m3, ref) === "number")) {
52439
+ for (const value of thresholds) {
52440
+ atoms.push({ kind: "above", ref, value });
52441
+ atoms.push({ kind: "below", ref, value });
52442
+ }
52443
+ }
52444
+ }
52445
+ for (const ref of refs) {
52446
+ const isDate = (v3) => typeof v3 === "string" && ISO_DATE.test(v3);
52447
+ if (all.every((m3) => isDate(scalar2(m3, ref)))) {
52448
+ for (const [name] of dates) {
52449
+ atoms.push({ kind: "before", ref, other: `inputs.${name}` });
52450
+ atoms.push({ kind: "after", ref, other: `inputs.${name}` });
52451
+ }
52452
+ }
52453
+ }
52454
+ const holds = (a2, m3) => {
52455
+ const v3 = scalar2(m3, a2.ref);
52456
+ if (a2.kind === "above") return typeof v3 === "number" && v3 > a2.value;
52457
+ if (a2.kind === "below") return typeof v3 === "number" && v3 < a2.value;
52458
+ const other = inputs[a2.other.slice("inputs.".length)];
52459
+ if (typeof v3 !== "string" || typeof other !== "string") return false;
52460
+ const [x3, y2] = [v3.slice(0, 10), other.slice(0, 10)];
52461
+ return a2.kind === "before" ? x3 < y2 : x3 > y2;
52462
+ };
52463
+ const separates = (test) => yes.every(test) && no.every((m3) => !test(m3));
52464
+ for (const a2 of atoms) {
52465
+ if (!separates((m3) => holds(a2, m3))) continue;
52466
+ if (a2.kind === "above" || a2.kind === "below") {
52467
+ const date4 = atoms.find(
52468
+ (d2) => (d2.kind === "before" || d2.kind === "after") && yes.every((m3) => holds(d2, m3)) && no.some((m3) => !holds(d2, m3))
52469
+ );
52470
+ if (date4) return { kind: "all", of: [a2, date4] };
52471
+ }
52472
+ return a2;
52473
+ }
52474
+ const onYes = atoms.filter((a2) => yes.every((m3) => holds(a2, m3)));
52475
+ for (let i2 = 0; i2 < onYes.length; i2++) {
52476
+ for (let j2 = i2 + 1; j2 < onYes.length; j2++) {
52477
+ const [a2, b3] = [onYes[i2], onYes[j2]];
52478
+ if (a2.ref === b3.ref) continue;
52479
+ if (separates((m3) => holds(a2, m3) && holds(b3, m3)))
52480
+ return { kind: "all", of: [a2, b3] };
52481
+ }
52482
+ }
52483
+ return null;
52484
+ }
52485
+ function learnItemRule(allYes, allNo) {
52486
+ const yes = allYes.map(withoutIdentifiers);
52487
+ const no = allNo.map(withoutIdentifiers);
51887
52488
  const rule = learnRule(yes, no);
51888
52489
  if (rule || yes.length === 0 || no.length === 0) return rule;
51889
52490
  const refs = [...yes[0].keys()].filter(
@@ -51899,6 +52500,9 @@ function learnItemRule(yes, no) {
51899
52500
  }
51900
52501
  return null;
51901
52502
  }
52503
+ function withoutIdentifiers(f3) {
52504
+ return new Map([...f3].filter(([ref]) => !IDENTIFIER_FIELD.test(ref)));
52505
+ }
51902
52506
  function learnPathRule(yes, no) {
51903
52507
  const rule = learnRule(yes, no);
51904
52508
  if (rule) return rule;
@@ -51936,10 +52540,12 @@ function learnInputRule(yes, no) {
51936
52540
  }
51937
52541
  return null;
51938
52542
  }
51939
- var CATEGORY_FIELD, filled, givenInputs;
52543
+ var ISO_DATE, IDENTIFIER_FIELD, CATEGORY_FIELD, filled, givenInputs;
51940
52544
  var init_rules3 = __esm({
51941
52545
  "../compiler/src/rules.ts"() {
51942
52546
  "use strict";
52547
+ ISO_DATE = /^\d{4}-\d{2}-\d{2}/;
52548
+ IDENTIFIER_FIELD = /(?:^|[._])(?:id|uuid|guid|key|ref)$/i;
51943
52549
  CATEGORY_FIELD = /\.(priority|category|type|kind|status|severity|level|class|tier|state|urgency|intent|label|action|decision|route|queue)$/i;
51944
52550
  filled = (v3) => v3 !== void 0 && v3 !== null && v3 !== "" && !(Array.isArray(v3) && v3.length === 0);
51945
52551
  givenInputs = (inputs, names2) => names2.filter((n3) => filled(inputs[n3]));
@@ -51953,12 +52559,13 @@ function collapsePages(calls, isReadOnly) {
51953
52559
  const taken = /* @__PURE__ */ new Set();
51954
52560
  for (let i2 = 0; i2 < calls.length; i2++) {
51955
52561
  if (taken.has(i2)) continue;
51956
- const chain = pageChain(calls, i2, isReadOnly, taken);
52562
+ const chain = pageChain(calls, i2, isReadOnly, taken) ?? cursorChain(calls, i2, isReadOnly, taken);
51957
52563
  if (!chain) {
51958
52564
  out.push(calls[i2]);
51959
52565
  continue;
51960
52566
  }
51961
52567
  for (const k3 of chain.indices) taken.add(k3);
52568
+ for (const k3 of pastTheEnd(calls, chain, isReadOnly, taken)) taken.add(k3);
51962
52569
  const merged = chain.indices.slice(1).reduce(
51963
52570
  (acc, k3) => mergePages(acc, calls[k3].result, chain.next),
51964
52571
  calls[i2].result
@@ -51969,6 +52576,71 @@ function collapsePages(calls, isReadOnly) {
51969
52576
  }
51970
52577
  return { calls: out, paginate };
51971
52578
  }
52579
+ function pastTheEnd(calls, chain, isReadOnly, taken) {
52580
+ const last = calls[chain.indices[chain.indices.length - 1]];
52581
+ const lastPage = last.args[chain.arg];
52582
+ if (typeof lastPage !== "number") return [];
52583
+ const rest = (c2) => Object.fromEntries(Object.entries(c2.args).filter(([k3]) => k3 !== chain.arg));
52584
+ const out = [];
52585
+ for (let k3 = chain.indices[chain.indices.length - 1] + 1; k3 < calls.length; k3++) {
52586
+ const c2 = calls[k3];
52587
+ if (!isReadOnly(c2.tool)) break;
52588
+ if (taken.has(k3) || c2.tool !== last.tool) continue;
52589
+ const page = c2.args[chain.arg];
52590
+ if (typeof page !== "number" || page <= lastPage) continue;
52591
+ if (!same2(rest(c2), rest(last)) || !isObject2(c2.result)) continue;
52592
+ const r2 = c2.result;
52593
+ const empty = Object.values(r2).every(
52594
+ (v3) => !Array.isArray(v3) || v3.length === 0
52595
+ );
52596
+ const hasList = Object.values(r2).some(Array.isArray);
52597
+ if (hasList && empty && (r2[chain.next] ?? null) === null) out.push(k3);
52598
+ }
52599
+ return out;
52600
+ }
52601
+ function cursorChain(calls, start, isReadOnly, taken) {
52602
+ const first = calls[start];
52603
+ if (!isReadOnly(first.tool) || !isObject2(first.result)) return null;
52604
+ for (const [next, token] of Object.entries(first.result)) {
52605
+ if (typeof token !== "string" || token === "") continue;
52606
+ let arg = null;
52607
+ const indices = [start];
52608
+ for (; ; ) {
52609
+ const prev = calls[indices[indices.length - 1]];
52610
+ const want = isObject2(prev.result) ? prev.result[next] : void 0;
52611
+ if (typeof want !== "string" || want === "") break;
52612
+ let found = -1;
52613
+ for (let k3 = indices[indices.length - 1] + 1; k3 < calls.length; k3++) {
52614
+ const cand = calls[k3];
52615
+ if (!isReadOnly(cand.tool)) break;
52616
+ if (taken.has(k3) || cand.tool !== first.tool || !isObject2(cand.result))
52617
+ continue;
52618
+ const carrying = Object.keys(cand.args).filter(
52619
+ (a3) => cand.args[a3] === want && (arg === null || a3 === arg)
52620
+ );
52621
+ if (carrying.length !== 1) continue;
52622
+ const a2 = carrying[0];
52623
+ const rest = /* @__PURE__ */ new Set([
52624
+ ...Object.keys(first.args),
52625
+ ...Object.keys(cand.args)
52626
+ ]);
52627
+ rest.delete(a2);
52628
+ if (![...rest].every((key) => same2(first.args[key], cand.args[key])))
52629
+ continue;
52630
+ arg = a2;
52631
+ found = k3;
52632
+ break;
52633
+ }
52634
+ if (found < 0) break;
52635
+ indices.push(found);
52636
+ }
52637
+ const last = calls[indices[indices.length - 1]];
52638
+ if (arg !== null && indices.length >= 2 && isObject2(last.result) && (last.result[next] ?? null) === null) {
52639
+ return { indices, arg, next };
52640
+ }
52641
+ }
52642
+ return null;
52643
+ }
51972
52644
  function isNextPage(prev, cand, arg, next) {
51973
52645
  const page = prev.args[arg];
51974
52646
  if (cand.tool !== prev.tool || typeof page !== "number") return false;
@@ -51993,10 +52665,10 @@ function pageChain(calls, start, isReadOnly, taken) {
51993
52665
  if (next === void 0) continue;
51994
52666
  const indices = [start];
51995
52667
  for (; ; ) {
51996
- const at2 = indices[indices.length - 1];
51997
- const prev = calls[at2];
52668
+ const at3 = indices[indices.length - 1];
52669
+ const prev = calls[at3];
51998
52670
  let found = -1;
51999
- for (let k3 = at2 + 1; k3 < calls.length; k3++) {
52671
+ for (let k3 = at3 + 1; k3 < calls.length; k3++) {
52000
52672
  if (!isReadOnly(calls[k3].tool)) break;
52001
52673
  if (!taken.has(k3) && isNextPage(prev, calls[k3], arg, next)) {
52002
52674
  found = k3;
@@ -52038,8 +52710,8 @@ function splitIndex(ref) {
52038
52710
  return null;
52039
52711
  }
52040
52712
  function wildcardPrefix(ref) {
52041
- const at2 = ref.lastIndexOf(".*");
52042
- return at2 < 0 ? null : ref.slice(0, at2);
52713
+ const at3 = ref.lastIndexOf(".*");
52714
+ return at3 < 0 ? null : ref.slice(0, at3);
52043
52715
  }
52044
52716
  function outerCovered(prefix, covered) {
52045
52717
  const parts = prefix.split(".");
@@ -52286,8 +52958,29 @@ function compileTraceDetailed(trace2, compiledFrom, hints = {}) {
52286
52958
  }
52287
52959
  return value;
52288
52960
  };
52961
+ const facts = {
52962
+ written: kept.flatMap(
52963
+ (c2) => Object.values(c2.args).filter((v3) => typeof v3 === "string").flatMap((v3) => numbersInText(v3))
52964
+ ),
52965
+ dataValues: /* @__PURE__ */ new Set(),
52966
+ inputs: trace2.meta.inputs
52967
+ };
52968
+ const collectNumbers = (v3) => {
52969
+ if (typeof v3 === "number") facts.dataValues.add(v3);
52970
+ else if (Array.isArray(v3)) v3.forEach(collectNumbers);
52971
+ else if (v3 !== null && typeof v3 === "object")
52972
+ Object.values(v3).forEach(collectNumbers);
52973
+ };
52974
+ for (const c2 of kept) collectNumbers(c2.result);
52289
52975
  for (let index = 0; index < kept.length; ) {
52290
- const loop = detectLoop(kept, index, earlier, hints);
52976
+ const loop = detectLoop(
52977
+ kept,
52978
+ index,
52979
+ earlier,
52980
+ hints,
52981
+ !isSideEffect(kept[index].tool),
52982
+ facts
52983
+ );
52291
52984
  if (loop) {
52292
52985
  const loopId = newId();
52293
52986
  const calls = kept.slice(index, index + loop.count);
@@ -52326,7 +53019,8 @@ function compileTraceDetailed(trace2, compiledFrom, hints = {}) {
52326
53019
  ...loop.when ? { when: loop.when } : {}
52327
53020
  }
52328
53021
  ],
52329
- maxItems: DEFAULT_MAX_ITEMS
53022
+ maxItems: DEFAULT_MAX_ITEMS,
53023
+ ...loop.distinct ? { distinct: loop.distinct } : {}
52330
53024
  });
52331
53025
  earlier.push({ id: loopId, field: "results", result: results });
52332
53026
  if (!sideEffect2) {
@@ -52340,6 +53034,28 @@ function compileTraceDetailed(trace2, compiledFrom, hints = {}) {
52340
53034
  index += loop.count;
52341
53035
  continue;
52342
53036
  }
53037
+ const decision = detectDecisionLoop(kept, index, earlier, isSideEffect);
53038
+ if (decision) {
53039
+ const loopId = newId();
53040
+ const built = buildDecisionLoop(decision, loopId, {
53041
+ task: trace2.meta.task,
53042
+ request: requestInputs(trace2.meta.inputs),
53043
+ readOnlyResults,
53044
+ steps,
53045
+ earlier,
53046
+ templateValue
53047
+ });
53048
+ steps.push(built.step);
53049
+ earlier.push({ id: loopId, field: "results", result: built.results });
53050
+ readOnlyResults.push({
53051
+ id: loopId,
53052
+ field: "results",
53053
+ tool: `decisions per ${built.as}`,
53054
+ result: built.results
53055
+ });
53056
+ index += decision.count;
53057
+ continue;
53058
+ }
52343
53059
  const call = kept[index++];
52344
53060
  const sideEffect = isSideEffect(call.tool);
52345
53061
  const args = {};
@@ -52418,6 +53134,7 @@ function compileTraceDetailed(trace2, compiledFrom, hints = {}) {
52418
53134
  addSamples(hints, tool, sampleItems(list, src.as, /* @__PURE__ */ new Set()));
52419
53135
  }
52420
53136
  }
53137
+ const positional = positionalActions(steps);
52421
53138
  const workflow = {
52422
53139
  version: 1,
52423
53140
  task: trace2.meta.task,
@@ -52432,7 +53149,8 @@ function compileTraceDetailed(trace2, compiledFrom, hints = {}) {
52432
53149
  ])
52433
53150
  ),
52434
53151
  steps,
52435
- ...dropped.length > 0 ? { droppedCalls: dropped } : {}
53152
+ ...dropped.length > 0 ? { droppedCalls: dropped } : {},
53153
+ ...positional.length > 0 ? { positional } : {}
52436
53154
  };
52437
53155
  return { workflow, recorded: earlier };
52438
53156
  }
@@ -52482,29 +53200,31 @@ function loopVariable(path36) {
52482
53200
  const singular = last.endsWith("ies") ? `${last.slice(0, -3)}y` : last.endsWith("s") ? last.slice(0, -1) : "";
52483
53201
  return /^[A-Za-z_][A-Za-z0-9_]*$/.test(singular) && !["inputs", "steps", ""].includes(singular) ? singular : "item";
52484
53202
  }
52485
- function detectLoop(calls, index, earlier, hints) {
53203
+ function detectLoop(calls, index, earlier, hints, readOnly = false, facts) {
52486
53204
  const tool = calls[index].tool;
52487
53205
  const known = hints.loopTools?.has(tool) === true;
52488
53206
  let runEnd = index;
52489
53207
  while (runEnd < calls.length && calls[runEnd].tool === tool) runEnd++;
52490
53208
  const runLength = runEnd - index;
52491
- if (runLength < (known ? 1 : 2)) return null;
53209
+ if (runLength < (known ? 1 : 2)) {
53210
+ return runLength === 1 && !readOnly && facts ? detectSingleItemLoop(calls[index], earlier, facts) : null;
53211
+ }
52492
53212
  for (const source of earlier) {
52493
53213
  if (source.field !== "result") continue;
52494
53214
  for (const list of arraysIn(source.result, [], known ? 1 : 2)) {
52495
53215
  const n3 = list.items.length;
52496
53216
  if (n3 > runLength) continue;
52497
53217
  const window2 = calls.slice(index, index + n3);
52498
- const keys = Object.keys(window2[0].args).sort().join("\0");
52499
- if (window2.some((c2) => Object.keys(c2.args).sort().join("\0") !== keys)) {
53218
+ const keys2 = Object.keys(window2[0].args).sort().join("\0");
53219
+ if (window2.some((c2) => Object.keys(c2.args).sort().join("\0") !== keys2)) {
52500
53220
  continue;
52501
53221
  }
52502
53222
  const varying = varyingArgs(window2, known ? list.items : null);
52503
53223
  if (varying.length === 0) continue;
52504
53224
  const itemArgs = /* @__PURE__ */ new Map();
52505
53225
  for (const key of varying) {
52506
- const candidates2 = pathsOf(list.items[0], window2[0].args[key]);
52507
- const path36 = candidates2.find(
53226
+ const candidates3 = pathsOf(list.items[0], window2[0].args[key]);
53227
+ const path36 = candidates3.find(
52508
53228
  (p3) => window2.every(
52509
53229
  (c2, i2) => deepEqual(c2.args[key], walk4(list.items[i2], p3))
52510
53230
  )
@@ -52526,13 +53246,96 @@ function detectLoop(calls, index, earlier, hints) {
52526
53246
  };
52527
53247
  }
52528
53248
  }
52529
- return detectItemSubsetLoop(calls, index, runLength, earlier, hints);
53249
+ return detectDistinctLoop(calls, index, runLength, earlier, readOnly) ?? detectItemSubsetLoop(calls, index, runLength, earlier, hints) ?? // a tool another pass already looped is "known" and skips the early exit
53250
+ (runLength === 1 && !readOnly && facts ? detectSingleItemLoop(calls[index], earlier, facts) : null);
53251
+ }
53252
+ function detectSingleItemLoop(call, earlier, facts) {
53253
+ const unique = (items, path36, value) => items.filter((it2) => deepEqual(walk4(it2, path36), value)).length === 1;
53254
+ for (const source of earlier) {
53255
+ if (source.field !== "result") continue;
53256
+ for (const list of arraysIn(source.result, [], 2)) {
53257
+ const items = list.items;
53258
+ for (const [key, value] of Object.entries(call.args)) {
53259
+ if (typeof value !== "string" && typeof value !== "number") continue;
53260
+ const ix = items.findIndex((it2) => pathsOf(it2, value).length > 0);
53261
+ if (ix < 0) continue;
53262
+ const path36 = pathsOf(items[ix], value).find(
53263
+ (p3) => unique(items, p3, value)
53264
+ );
53265
+ if (!path36) continue;
53266
+ const itemArgs = /* @__PURE__ */ new Map([[key, path36]]);
53267
+ for (const [other, v3] of Object.entries(call.args)) {
53268
+ if (other === key) continue;
53269
+ const p3 = pathsOf(items[ix], v3)[0];
53270
+ if (p3) itemArgs.set(other, p3);
53271
+ }
53272
+ const as = loopVariable(list.path);
53273
+ const { yes, no } = sampleItems(items, as, /* @__PURE__ */ new Set([ix]));
53274
+ const when = learnItemThresholdRule(
53275
+ yes,
53276
+ no,
53277
+ facts.written,
53278
+ facts.dataValues,
53279
+ facts.inputs
53280
+ );
53281
+ if (!when) continue;
53282
+ return {
53283
+ count: 1,
53284
+ source: { id: source.id, path: list.path },
53285
+ as,
53286
+ itemArgs,
53287
+ when
53288
+ };
53289
+ }
53290
+ }
53291
+ }
53292
+ return null;
53293
+ }
53294
+ function detectDistinctLoop(calls, index, runLength, earlier, readOnly) {
53295
+ if (runLength < 2) return null;
53296
+ const window2 = calls.slice(index, index + runLength);
53297
+ const keys2 = Object.keys(window2[0].args).sort().join("\0");
53298
+ if (window2.some((c2) => Object.keys(c2.args).sort().join("\0") !== keys2))
53299
+ return null;
53300
+ const varying = varyingArgs(window2, null);
53301
+ if (varying.length !== 1) return null;
53302
+ const key = varying[0];
53303
+ for (const source of earlier) {
53304
+ if (source.field !== "result") continue;
53305
+ for (const list of arraysIn(source.result, [], 2)) {
53306
+ const candidates3 = /* @__PURE__ */ new Set();
53307
+ for (const item of list.items) {
53308
+ for (const p3 of pathsOf(item, window2[0].args[key])) {
53309
+ if (p3.length > 0) candidates3.add(JSON.stringify(p3));
53310
+ }
53311
+ }
53312
+ for (const raw of candidates3) {
53313
+ const path36 = JSON.parse(raw);
53314
+ const firsts = [];
53315
+ for (const item of list.items) {
53316
+ const v3 = walk4(item, path36);
53317
+ if (!firsts.some((f3) => deepEqual(f3, v3))) firsts.push(v3);
53318
+ }
53319
+ const ordered = firsts.length < list.items.length && firsts.length === window2.length && window2.every((c2, i2) => deepEqual(c2.args[key], firsts[i2]));
53320
+ const sameValues = readOnly && window2.every((c2) => firsts.some((f3) => deepEqual(f3, c2.args[key]))) && firsts.every((f3) => window2.some((c2) => deepEqual(c2.args[key], f3)));
53321
+ if (!ordered && !sameValues) continue;
53322
+ return {
53323
+ count: runLength,
53324
+ source: { id: source.id, path: list.path },
53325
+ as: loopVariable(list.path),
53326
+ itemArgs: /* @__PURE__ */ new Map([[key, path36]]),
53327
+ distinct: path36
53328
+ };
53329
+ }
53330
+ }
53331
+ }
53332
+ return null;
52530
53333
  }
52531
53334
  function detectItemSubsetLoop(calls, index, runLength, earlier, hints) {
52532
53335
  const known = hints.loopTools?.has(calls[index].tool) === true;
52533
53336
  const window2 = calls.slice(index, index + runLength);
52534
- const keys = Object.keys(window2[0].args).sort().join("\0");
52535
- if (window2.some((c2) => Object.keys(c2.args).sort().join("\0") !== keys)) {
53337
+ const keys2 = Object.keys(window2[0].args).sort().join("\0");
53338
+ if (window2.some((c2) => Object.keys(c2.args).sort().join("\0") !== keys2)) {
52536
53339
  return null;
52537
53340
  }
52538
53341
  const sourceLists = (source) => source.field === "result" ? arraysIn(source.result, [], known ? 1 : 2) : [];
@@ -52556,13 +53359,13 @@ function detectItemSubsetLoop(calls, index, runLength, earlier, hints) {
52556
53359
  for (const raw of paths) {
52557
53360
  const path36 = JSON.parse(raw);
52558
53361
  const chosen = [];
52559
- let at2 = 0;
53362
+ let at3 = 0;
52560
53363
  for (const c2 of window2) {
52561
- while (at2 < items.length && !deepEqual(walk4(items[at2], path36), c2.args[first])) {
52562
- at2++;
53364
+ while (at3 < items.length && !deepEqual(walk4(items[at3], path36), c2.args[first])) {
53365
+ at3++;
52563
53366
  }
52564
- if (at2 === items.length) break;
52565
- chosen.push(at2++);
53367
+ if (at3 === items.length) break;
53368
+ chosen.push(at3++);
52566
53369
  }
52567
53370
  if (chosen.length !== window2.length) continue;
52568
53371
  const itemArgs = /* @__PURE__ */ new Map([[first, path36]]);
@@ -52603,15 +53406,15 @@ function inferCommonSchema(values) {
52603
53406
  (v3) => v3 !== null && typeof v3 === "object" && !Array.isArray(v3)
52604
53407
  )) {
52605
53408
  const objects = values;
52606
- const keys = Object.keys(objects[0]).filter(
53409
+ const keys2 = Object.keys(objects[0]).filter(
52607
53410
  (k3) => objects.every((o2) => Object.hasOwn(o2, k3))
52608
53411
  );
52609
53412
  return {
52610
53413
  type: "object",
52611
53414
  properties: Object.fromEntries(
52612
- keys.map((k3) => [k3, inferCommonSchema(objects.map((o2) => o2[k3]))])
53415
+ keys2.map((k3) => [k3, inferCommonSchema(objects.map((o2) => o2[k3]))])
52613
53416
  ),
52614
- required: keys
53417
+ required: keys2
52615
53418
  };
52616
53419
  }
52617
53420
  const types = new Set(values.map((v3) => v3 === null ? "null" : typeof v3));
@@ -52646,22 +53449,22 @@ function withoutCovered(entries, example) {
52646
53449
  const text = normalizeText(example);
52647
53450
  const occurrences = (s3) => {
52648
53451
  const out = [];
52649
- for (let at2 = text.indexOf(s3); at2 >= 0; at2 = text.indexOf(s3, at2 + 1)) {
52650
- out.push(at2);
53452
+ for (let at3 = text.indexOf(s3); at3 >= 0; at3 = text.indexOf(s3, at3 + 1)) {
53453
+ out.push(at3);
52651
53454
  }
52652
53455
  return out;
52653
53456
  };
52654
53457
  const strings = entries.filter((e2) => typeof e2.value === "string").map((e2) => normalizeText(String(e2.value)));
52655
53458
  const spans = strings.flatMap(
52656
- (s3) => occurrences(s3).map((at2) => ({ s: s3, at: at2, end: at2 + s3.length }))
53459
+ (s3) => occurrences(s3).map((at3) => ({ s: s3, at: at3, end: at3 + s3.length }))
52657
53460
  );
52658
53461
  return entries.filter((e2) => {
52659
53462
  if (typeof e2.value !== "string") return true;
52660
53463
  const v3 = normalizeText(e2.value);
52661
53464
  const own = occurrences(v3);
52662
53465
  return own.length === 0 || !own.every(
52663
- (at2) => spans.some(
52664
- (sp) => sp.s.length > v3.length && sp.at <= at2 && at2 + v3.length <= sp.end
53466
+ (at3) => spans.some(
53467
+ (sp) => sp.s.length > v3.length && sp.at <= at3 && at3 + v3.length <= sp.end
52665
53468
  )
52666
53469
  );
52667
53470
  });
@@ -52739,15 +53542,15 @@ function generalizeListFields(entries, results) {
52739
53542
  }
52740
53543
  }
52741
53544
  const shape = (key) => key.replace(/^steps\.[^.]+\.(results?)\./, "steps.<step>.$1.");
52742
- const shapes = /* @__PURE__ */ new Map();
53545
+ const shapes2 = /* @__PURE__ */ new Map();
52743
53546
  for (const [key, group] of groups) {
52744
- const s3 = shapes.get(shape(key)) ?? { mentioned: 0, items: 0, keys: [] };
53547
+ const s3 = shapes2.get(shape(key)) ?? { mentioned: 0, items: 0, keys: [] };
52745
53548
  s3.mentioned += group.indices.size;
52746
53549
  s3.items += listLength(key.split("\0")[0]);
52747
53550
  s3.keys.push(key);
52748
- shapes.set(shape(key), s3);
53551
+ shapes2.set(shape(key), s3);
52749
53552
  }
52750
- for (const s3 of shapes.values()) {
53553
+ for (const s3 of shapes2.values()) {
52751
53554
  if (s3.keys.length >= 2 && s3.items >= 2 && s3.mentioned >= Math.max(2, Math.ceil(s3.items / 2))) {
52752
53555
  for (const key of s3.keys) general.set(key, groups.get(key).value);
52753
53556
  }
@@ -52879,7 +53682,226 @@ function inferSchema(value) {
52879
53682
  function deepEqual(a2, b3) {
52880
53683
  return JSON.stringify(a2) === JSON.stringify(b3);
52881
53684
  }
52882
- var LLM_TEXT_MIN_CHARS, textArgKey, GROUNDING_MIN_STRING, QUOTE_MIN_CHARS;
53685
+ function detectDecisionLoop(calls, index, earlier, isSideEffect) {
53686
+ const first = calls[index];
53687
+ if (!isSideEffect(first.tool)) return null;
53688
+ for (const source of earlier) {
53689
+ if (source.field !== "result") continue;
53690
+ for (const list of arraysIn(source.result, [], 2)) {
53691
+ for (const [argName, value] of Object.entries(first.args)) {
53692
+ if (typeof value !== "string" && typeof value !== "number") continue;
53693
+ for (const [start, item] of list.items.entries()) {
53694
+ for (const keyPath of pathsOf(item, value)) {
53695
+ if (keyPath.length === 0) continue;
53696
+ const keys2 = list.items.map(
53697
+ (it2) => JSON.stringify(walk4(it2, keyPath))
53698
+ );
53699
+ if (new Set(keys2).size !== keys2.length) continue;
53700
+ const run = extendDecisionRun(
53701
+ calls,
53702
+ index,
53703
+ list.items,
53704
+ keyPath,
53705
+ start,
53706
+ argName,
53707
+ isSideEffect
53708
+ );
53709
+ if (run.acted.size >= 2) {
53710
+ return {
53711
+ ...run,
53712
+ source: { id: source.id, path: list.path },
53713
+ items: list.items,
53714
+ keyPath
53715
+ };
53716
+ }
53717
+ }
53718
+ }
53719
+ }
53720
+ }
53721
+ }
53722
+ return null;
53723
+ }
53724
+ function extendDecisionRun(calls, index, items, keyPath, start, firstArg, isSideEffect) {
53725
+ const acted = /* @__PURE__ */ new Map([[start, calls[index]]]);
53726
+ const keyArg = /* @__PURE__ */ new Map([[calls[index].tool, firstArg]]);
53727
+ let last = start;
53728
+ let j2 = index + 1;
53729
+ for (; j2 < calls.length && isSideEffect(calls[j2].tool); j2++) {
53730
+ const c2 = calls[j2];
53731
+ const names2 = keyArg.has(c2.tool) ? [keyArg.get(c2.tool)] : Object.keys(c2.args);
53732
+ let found = null;
53733
+ for (const arg of names2) {
53734
+ for (let m3 = last + 1; m3 < items.length && !found; m3++) {
53735
+ if (deepEqual(walk4(items[m3], keyPath), c2.args[arg]))
53736
+ found = { arg, at: m3 };
53737
+ }
53738
+ if (found) break;
53739
+ }
53740
+ if (!found) break;
53741
+ acted.set(found.at, c2);
53742
+ keyArg.set(c2.tool, found.arg);
53743
+ last = found.at;
53744
+ }
53745
+ return { count: j2 - index, acted, keyArg };
53746
+ }
53747
+ function buildDecisionLoop(match, loopId, ctx) {
53748
+ const overPath = match.source.path.length > 0 ? `.${match.source.path.join(".")}` : "";
53749
+ const over = `{{steps.${match.source.id}.result${overPath}}}`;
53750
+ const named = loopVariable(match.source.path);
53751
+ const as = named === CHOICE ? "item" : named;
53752
+ const lookup2 = itemDetails(over, match.items, ctx);
53753
+ const detailsOf = lookup2.of;
53754
+ const byTool = /* @__PURE__ */ new Map();
53755
+ for (const [at3, c2] of [...match.acted].sort(([a2], [b3]) => a2 - b3)) {
53756
+ byTool.set(c2.tool, [...byTool.get(c2.tool) ?? [], [at3, c2]]);
53757
+ }
53758
+ const body = [];
53759
+ const actions = [];
53760
+ const chosen = /* @__PURE__ */ new Map();
53761
+ for (const [tool, done] of byTool) {
53762
+ const keyArg = match.keyArg.get(tool);
53763
+ const args = {
53764
+ [keyArg]: `{{${[as, ...match.keyPath].join(".")}}}`
53765
+ };
53766
+ const fields = {};
53767
+ for (const name of Object.keys(done[0][1].args)) {
53768
+ if (name === keyArg) continue;
53769
+ const values = done.map(([, c2]) => c2.args[name]);
53770
+ const inItem = pathsOf(match.items[done[0][0]], values[0]).find(
53771
+ (p3) => p3.length > 0 && done.every(
53772
+ ([at3, c2]) => deepEqual(walk4(match.items[at3], p3), c2.args[name])
53773
+ )
53774
+ );
53775
+ if (inItem) {
53776
+ args[name] = `{{${[as, ...inItem].join(".")}}}`;
53777
+ continue;
53778
+ }
53779
+ const same3 = values.every((v3) => deepEqual(v3, values[0]));
53780
+ const fromData = ctx.templateValue(values[0]) !== values[0] || done.some(([at3]) => pathsOf(detailsOf(at3), values[0]).length > 0);
53781
+ const primitive = values.every(
53782
+ (v3) => typeof v3 === "string" || typeof v3 === "number"
53783
+ );
53784
+ if (same3 && !fromData || !primitive) {
53785
+ args[name] = values[0];
53786
+ continue;
53787
+ }
53788
+ fields[name] = values.every((v3) => typeof v3 === "number") ? "number" : "string";
53789
+ args[name] = `{{${CHOICE}.${name}}}`;
53790
+ for (const [at3, c2] of done)
53791
+ chosen.set(at3, { ...chosen.get(at3) ?? {}, [name]: c2.args[name] });
53792
+ }
53793
+ actions.push({ tool, fields });
53794
+ body.push({
53795
+ id: `${loopId}.${body.length + 1}`,
53796
+ type: "tool",
53797
+ tool,
53798
+ args,
53799
+ sideEffect: true,
53800
+ guard: { schema: inferCommonSchema(done.map(([, c2]) => c2.result)) },
53801
+ when: { kind: "equals", ref: `${CHOICE}.action`, value: tool }
53802
+ });
53803
+ }
53804
+ const decide = {
53805
+ model: "cheap",
53806
+ prompt: decisionContextPrompt(ctx),
53807
+ key: match.keyPath,
53808
+ ...lookup2.spec ? { details: lookup2.spec } : {},
53809
+ actions,
53810
+ examples: decisionExamples(match, detailsOf, chosen)
53811
+ };
53812
+ return {
53813
+ step: {
53814
+ id: loopId,
53815
+ type: "foreach",
53816
+ over,
53817
+ as,
53818
+ decide,
53819
+ body,
53820
+ maxItems: DEFAULT_MAX_ITEMS
53821
+ },
53822
+ results: match.items.map((item, at3) => {
53823
+ const c2 = match.acted.get(at3);
53824
+ return {
53825
+ [match.keyPath.join(".")]: walk4(item, match.keyPath),
53826
+ action: c2 ? c2.tool : "none",
53827
+ ...chosen.get(at3) ?? {}
53828
+ };
53829
+ }),
53830
+ as
53831
+ };
53832
+ }
53833
+ function itemDetails(over, items, ctx) {
53834
+ const lookup2 = ctx.steps.find(
53835
+ (s3) => s3.type === "foreach" && s3.over === over && !s3.decide
53836
+ );
53837
+ if (!lookup2) return { of: () => void 0 };
53838
+ const results = ctx.earlier.find(
53839
+ (e2) => e2.id === lookup2.id && e2.field === "results"
53840
+ )?.result;
53841
+ const paired = detailsPerItem(items, results, lookup2.distinct);
53842
+ return {
53843
+ of: (at3) => paired[at3],
53844
+ spec: {
53845
+ step: lookup2.id,
53846
+ ...lookup2.distinct ? { distinct: lookup2.distinct } : {}
53847
+ }
53848
+ };
53849
+ }
53850
+ function decisionExamples(match, detailsOf, chosen) {
53851
+ const order = [...match.acted.keys(), ...match.items.keys()].filter(
53852
+ (at3, i2, all) => all.indexOf(at3) === i2
53853
+ );
53854
+ return order.slice(0, MAX_DECISION_EXAMPLES).sort((a2, b3) => a2 - b3).map((at3) => {
53855
+ const details = detailsOf(at3);
53856
+ const c2 = match.acted.get(at3);
53857
+ return {
53858
+ item: compactValue(match.items[at3]),
53859
+ ...details !== void 0 ? { details: compactValue(details) } : {},
53860
+ choice: c2 ? { action: c2.tool, ...chosen.get(at3) ?? {} } : { action: "none" }
53861
+ };
53862
+ });
53863
+ }
53864
+ function compactValue(value) {
53865
+ if (typeof value === "string")
53866
+ return value.length > 300 ? `${value.slice(0, 300)}\u2026` : value;
53867
+ if (Array.isArray(value)) return value.slice(0, 20).map(compactValue);
53868
+ if (value !== null && typeof value === "object") {
53869
+ return Object.fromEntries(
53870
+ Object.entries(value).map(([k3, v3]) => [k3, compactValue(v3)])
53871
+ );
53872
+ }
53873
+ return value;
53874
+ }
53875
+ function decisionContextPrompt(ctx) {
53876
+ const parts = [
53877
+ `You are replaying the task "${ctx.task}": deciding what to do with each item of a list.`
53878
+ ];
53879
+ for (const name of ctx.request)
53880
+ parts.push(`the request (inputs.${name}):
53881
+ {{inputs.${name}}}`);
53882
+ for (const { id, tool, field: field2 } of ctx.readOnlyResults) {
53883
+ const label = field2 === "results" ? "results (one per item)" : "result";
53884
+ parts.push(`${id} ${tool} ${label}:
53885
+ {{steps.${id}.${field2}}}`);
53886
+ }
53887
+ return parts.join("\n\n");
53888
+ }
53889
+ function positionalActions(steps) {
53890
+ const byList = /* @__PURE__ */ new Map();
53891
+ const ref = /\{\{(steps\.[\w-]+\.results?(?:\.[\w-]+)*?)\.(\d+)(?:\.[^}]*)?\}\}/g;
53892
+ for (const step of steps) {
53893
+ if (step.type !== "tool" || !step.sideEffect) continue;
53894
+ for (const m3 of JSON.stringify(step.args).matchAll(ref)) {
53895
+ const list = m3[1];
53896
+ const entry = byList.get(list) ?? { steps: [], at: /* @__PURE__ */ new Set() };
53897
+ if (!entry.steps.includes(step.id)) entry.steps.push(step.id);
53898
+ entry.at.add(m3[2]);
53899
+ byList.set(list, entry);
53900
+ }
53901
+ }
53902
+ return [...byList].filter(([, e2]) => e2.at.size >= 2 && e2.steps.length >= 2).map(([list, e2]) => ({ list, steps: e2.steps }));
53903
+ }
53904
+ var LLM_TEXT_MIN_CHARS, textArgKey, GROUNDING_MIN_STRING, QUOTE_MIN_CHARS, CHOICE, MAX_DECISION_EXAMPLES;
52883
53905
  var init_compiler = __esm({
52884
53906
  "../compiler/src/compiler.ts"() {
52885
53907
  "use strict";
@@ -52892,6 +53914,8 @@ var init_compiler = __esm({
52892
53914
  textArgKey = (tool, arg) => `${tool}\0${arg}`;
52893
53915
  GROUNDING_MIN_STRING = 4;
52894
53916
  QUOTE_MIN_CHARS = 12;
53917
+ CHOICE = "choice";
53918
+ MAX_DECISION_EXAMPLES = 20;
52895
53919
  }
52896
53920
  });
52897
53921
 
@@ -52963,39 +53987,662 @@ var init_derived = __esm({
52963
53987
  }
52964
53988
  });
52965
53989
 
53990
+ // ../compiler/src/group-calculations.ts
53991
+ function shapes(results) {
53992
+ const first = results[0];
53993
+ const names2 = Object.keys(first).filter(
53994
+ (k3) => results.every((r2) => typeof r2[k3] === "string") && new Set(results.map((r2) => r2[k3])).size === results.length
53995
+ );
53996
+ const paths = Object.keys(first).filter(
53997
+ (k3) => results.every((r2) => Array.isArray(r2[k3]))
53998
+ );
53999
+ return names2.flatMap((name) => paths.map((path36) => ({ name, path: path36 })));
54000
+ }
54001
+ function groupSources(ctx) {
54002
+ const out = [];
54003
+ for (const [id, entry] of Object.entries(ctx.steps)) {
54004
+ const results = entry?.results;
54005
+ if (!Array.isArray(results) || results.length < 2) continue;
54006
+ if (!results.every(isItem3)) continue;
54007
+ for (const { name, path: path36 } of shapes(results))
54008
+ out.push({ list: `steps.${id}.results`, name, path: path36, groups: results });
54009
+ }
54010
+ const byShape = /* @__PURE__ */ new Map();
54011
+ for (const [id, entry] of Object.entries(ctx.steps)) {
54012
+ const result = entry?.result;
54013
+ if (!isItem3(result)) continue;
54014
+ const key = Object.keys(result).sort().join(",");
54015
+ byShape.set(key, [
54016
+ ...byShape.get(key) ?? [],
54017
+ { ref: `steps.${id}.result`, result }
54018
+ ]);
54019
+ }
54020
+ for (const same3 of byShape.values()) {
54021
+ if (same3.length < 2) continue;
54022
+ const results = same3.map((s3) => s3.result);
54023
+ const refs = same3.map((s3) => s3.ref);
54024
+ for (const { name, path: path36 } of shapes(results))
54025
+ out.push({ list: refs[0], name, path: path36, groups: results, refs });
54026
+ }
54027
+ return out;
54028
+ }
54029
+ function dateRefs(ctx) {
54030
+ return Object.entries(ctx.inputs).filter(([, v3]) => typeof v3 === "string" && ISO_DATE2.test(v3)).map(([k3]) => `inputs.${k3}`);
54031
+ }
54032
+ function candidates2(items, withCounts, dates = []) {
54033
+ if (items.length === 0) return [];
54034
+ if (items.every((x3) => typeof x3 === "string")) {
54035
+ const words = /* @__PURE__ */ new Set();
54036
+ for (const line of items)
54037
+ for (const w3 of line.match(/\b[A-Z]{3,}\b/g) ?? []) words.add(w3);
54038
+ return words.size > 12 ? [] : [...words].flatMap((match) => [
54039
+ { op: "count", match },
54040
+ { op: "top", match }
54041
+ ]);
54042
+ }
54043
+ if (!items.every(isItem3)) return [];
54044
+ const rows = items;
54045
+ const keys2 = Object.keys(rows[0]);
54046
+ const numeric = keys2.filter(
54047
+ (k3) => rows.every((r2) => typeof r2[k3] === "number")
54048
+ );
54049
+ const strings = keys2.filter(
54050
+ (k3) => rows.every((r2) => typeof r2[k3] === "string")
54051
+ );
54052
+ const distinct = (k3) => [...new Set(rows.map((r2) => r2[k3]))];
54053
+ const filters = strings.filter((k3) => {
54054
+ const n3 = distinct(k3).length;
54055
+ return n3 >= 2 && n3 <= 5 && n3 < rows.length;
54056
+ }).flatMap((k3) => [
54057
+ ...distinct(k3).map((v3) => ({ field: k3, equals: v3 })),
54058
+ ...distinct(k3).map((v3) => ({ field: k3, not: v3 }))
54059
+ ]);
54060
+ const bys = strings.filter((k3) => {
54061
+ const n3 = distinct(k3).length;
54062
+ return n3 >= 2 && n3 < rows.length;
54063
+ });
54064
+ for (const k3 of strings) {
54065
+ if (!rows.every((r2) => ISO_DATE2.test(r2[k3]))) continue;
54066
+ for (const ref of dates)
54067
+ filters.push({ field: k3, before: ref }, { field: k3, after: ref });
54068
+ }
54069
+ const wheres = [void 0, ...filters];
54070
+ const out = [];
54071
+ for (const where of wheres) {
54072
+ if (withCounts) out.push({ op: "count", ...where ? { where } : {} });
54073
+ for (const field2 of numeric)
54074
+ for (const op of ["sum", "avg"])
54075
+ out.push({ op, field: field2, ...where ? { where } : {} });
54076
+ }
54077
+ for (const where of wheres)
54078
+ for (const by of bys)
54079
+ for (const field2 of numeric)
54080
+ out.push({ op: "top", by, field: field2, ...where ? { where } : {} });
54081
+ return out;
54082
+ }
54083
+ function written(line, figure) {
54084
+ const trimmed = line.trim();
54085
+ for (const m3 of trimmed.matchAll(
54086
+ /(?<![\w.-])-?\d[\d,]*(?:\.\d+)?(?![\w-])/g
54087
+ )) {
54088
+ if (!close(Number(m3[0].replace(/,/g, "")), figure)) continue;
54089
+ const decimals = /\.(\d+)$/.exec(m3[0])?.[1]?.length;
54090
+ return {
54091
+ line: trimmed.slice(0, m3.index) + CALCULATED + trimmed.slice(m3.index + m3[0].length),
54092
+ ...decimals ? { decimals } : {}
54093
+ };
54094
+ }
54095
+ return null;
54096
+ }
54097
+ function learnGroupCalculations(example, ctx, plainLists = []) {
54098
+ const bySentence = learnWithRows(example, ctx, plainLists, SENTENCE);
54099
+ const byClause = learnWithRows(example, ctx, plainLists, CLAUSE);
54100
+ const same3 = (c2) => JSON.stringify([
54101
+ c2.op,
54102
+ c2.list,
54103
+ c2.group,
54104
+ c2.per,
54105
+ c2.where,
54106
+ c2.field,
54107
+ c2.by,
54108
+ c2.match
54109
+ ]);
54110
+ const have = new Set(bySentence.calcs.map(same3));
54111
+ return {
54112
+ calcs: [
54113
+ ...bySentence.calcs,
54114
+ ...byClause.calcs.filter((c2) => !have.has(same3(c2)))
54115
+ ],
54116
+ covered: /* @__PURE__ */ new Set([...bySentence.covered, ...byClause.covered])
54117
+ };
54118
+ }
54119
+ function learnWithRows(example, ctx, plainLists, split) {
54120
+ const lines = example.split("\n").flatMap(
54121
+ (text, line) => text.split(split).map((part) => ({ text: part, line }))
54122
+ );
54123
+ const at2line = (i2) => lines[i2].line;
54124
+ const calcs = [];
54125
+ const covered = /* @__PURE__ */ new Set();
54126
+ const dates = dateRefs(ctx);
54127
+ const rowOf = (name) => lines.findIndex((l2) => namedIn(l2.text, name) && /\d/.test(l2.text));
54128
+ const rowText = (i2, at3) => {
54129
+ const parts = [lines[i2].text];
54130
+ for (let k3 = i2 + 1; k3 < lines.length; k3++) {
54131
+ if (lines[k3].line !== lines[i2].line || at3.includes(k3)) break;
54132
+ parts.push(lines[k3].text);
54133
+ }
54134
+ return parts.join(" ");
54135
+ };
54136
+ const fitsRows = (got, at3, op, whole = false) => got.every((x3, i2) => {
54137
+ const line = whole ? rowText(at3[i2], at3) : lines[at3[i2]].text;
54138
+ return statesFigure(line, x3.value) && (op !== "top" || namedIn(line, x3.name));
54139
+ }) && // a count of 0 or 1 everywhere, or the same figure in every group, says nothing
54140
+ new Set(got.map((x3) => x3.value)).size > 1 && !got.every((x3) => Math.abs(x3.value) < 2);
54141
+ for (const source of groupSources(ctx)) {
54142
+ const at3 = source.groups.map((g3) => rowOf(g3[source.name]));
54143
+ if (at3.some((i2) => i2 < 0) || new Set(at3).size !== at3.length) continue;
54144
+ const all = source.groups.flatMap((g3) => g3[source.path]);
54145
+ const seen = /* @__PURE__ */ new Set();
54146
+ for (const cand of candidates2(all, true, dates)) {
54147
+ const got = source.groups.map(
54148
+ (g3) => figureOver(cand, g3[source.path], ctx)
54149
+ );
54150
+ if (got.some((x3) => x3 === null)) continue;
54151
+ const values = got.map((x3) => x3.value);
54152
+ const sig = `${cand.op}:${signature(values)}`;
54153
+ if (seen.has(sig)) continue;
54154
+ const whole = cand.op === "top";
54155
+ if (!fitsRows(got, at3, cand.op, whole))
54156
+ continue;
54157
+ seen.add(sig);
54158
+ const w3 = written(
54159
+ whole ? rowText(at3[0], at3) : lines[at3[0]].text,
54160
+ values[0]
54161
+ );
54162
+ if (!w3) continue;
54163
+ calcs.push({
54164
+ ...cand,
54165
+ ...w3,
54166
+ list: source.list,
54167
+ group: {
54168
+ name: source.name,
54169
+ path: source.path,
54170
+ ...source.refs ? { refs: source.refs } : {}
54171
+ },
54172
+ recorded: values[0]
54173
+ });
54174
+ values.forEach((v3, i2) => covered.add(`${at2line(at3[i2])}:${round2(v3)}`));
54175
+ }
54176
+ }
54177
+ for (const ref of plainLists) {
54178
+ const items = listAt(ref, ctx);
54179
+ if (!items || items.length < 3 || !items.every(isItem3)) continue;
54180
+ const rows = items;
54181
+ const fields = Object.keys(rows[0]).filter((k3) => {
54182
+ if (!rows.every((r2) => typeof r2[k3] === "string")) return false;
54183
+ const n3 = new Set(rows.map((r2) => r2[k3])).size;
54184
+ return n3 >= 2 && n3 <= 30 && n3 < rows.length;
54185
+ });
54186
+ for (const per of fields) {
54187
+ const seen = /* @__PURE__ */ new Set();
54188
+ for (const cand of candidates2(rows, true, dates)) {
54189
+ if (cand.op === "top") continue;
54190
+ const kept = rows.filter((r2) => passes(r2, cand.where, ctx));
54191
+ const groups = /* @__PURE__ */ new Map();
54192
+ for (const r2 of kept) {
54193
+ const name = r2[per];
54194
+ groups.set(name, [...groups.get(name) ?? [], r2]);
54195
+ }
54196
+ if (groups.size < 2) continue;
54197
+ const names2 = [...groups.keys()];
54198
+ const at3 = names2.map(rowOf);
54199
+ if (at3.some((i2) => i2 < 0) || new Set(at3).size !== at3.length) continue;
54200
+ const got = names2.map(
54201
+ (n3) => figureOver({ ...cand, where: void 0 }, groups.get(n3), ctx)
54202
+ );
54203
+ if (got.some((x3) => x3 === null)) continue;
54204
+ const values = got.map((x3) => x3.value);
54205
+ const sig = `${cand.op}:${signature(values)}`;
54206
+ if (seen.has(sig)) continue;
54207
+ if (!fitsRows(got, at3, cand.op)) continue;
54208
+ const left = new Set(rows.map((r2) => r2[per]));
54209
+ for (const n3 of names2) left.delete(n3);
54210
+ if ([...left].some((n3) => rowOf(n3) >= 0)) continue;
54211
+ seen.add(sig);
54212
+ const w3 = written(lines[at3[0]].text, values[0]);
54213
+ if (!w3) continue;
54214
+ calcs.push({ ...cand, ...w3, list: ref, per, recorded: values[0] });
54215
+ values.forEach(
54216
+ (v3, i2) => covered.add(`${at2line(at3[i2])}:${round2(v3)}`)
54217
+ );
54218
+ }
54219
+ }
54220
+ }
54221
+ return { calcs, covered };
54222
+ }
54223
+ function explainAcross(line, figure, ctx, plainLists) {
54224
+ const refs = [
54225
+ // (sibling steps have no one list to put together: their totals stay with the model)
54226
+ ...groupSources(ctx).filter((s3) => !s3.refs).map((s3) => ({
54227
+ ref: `${s3.list}.*.${s3.path}`,
54228
+ counts: true
54229
+ })),
54230
+ // one list: only filtered amounts (a filtered count matches small numbers by chance)
54231
+ ...plainLists.map((ref) => ({ ref, counts: false }))
54232
+ ];
54233
+ const done = /* @__PURE__ */ new Set();
54234
+ for (const { ref, counts } of refs) {
54235
+ if (done.has(ref)) continue;
54236
+ done.add(ref);
54237
+ const items = listAt(ref, ctx);
54238
+ if (!items) continue;
54239
+ for (const cand of candidates2(items, counts, dateRefs(ctx))) {
54240
+ if (!counts && !cand.where && cand.op !== "top") continue;
54241
+ const got = figureOver(cand, items, ctx);
54242
+ if (!got || !close(got.value, figure)) continue;
54243
+ if (cand.op === "top" && !namedIn(line, got.name)) continue;
54244
+ const w3 = written(line, figure);
54245
+ if (!w3) return null;
54246
+ return { ...cand, ...w3, list: ref, recorded: figure };
54247
+ }
54248
+ }
54249
+ return null;
54250
+ }
54251
+ var isItem3, close, namedIn, ISO_DATE2, signature, SENTENCE, CLAUSE;
54252
+ var init_group_calculations = __esm({
54253
+ "../compiler/src/group-calculations.ts"() {
54254
+ "use strict";
54255
+ init_src();
54256
+ init_derived();
54257
+ isItem3 = (v3) => v3 !== null && typeof v3 === "object" && !Array.isArray(v3);
54258
+ close = (a2, b3) => Math.abs(round2(a2) - round2(b3)) < 5e-3;
54259
+ namedIn = (line, name) => new RegExp(
54260
+ `(?<![A-Za-z0-9])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![A-Za-z0-9])`
54261
+ ).test(line);
54262
+ ISO_DATE2 = /^\d{4}-\d{2}-\d{2}/;
54263
+ signature = (values) => values.map((v3) => round2(v3)).join(",");
54264
+ SENTENCE = /(?<=[.;])\s+(?=\S)/;
54265
+ CLAUSE = /(?<=[.;,])\s+(?=\S)/;
54266
+ }
54267
+ });
54268
+
54269
+ // ../compiler/src/decision-table.ts
54270
+ function keys(exs, from, kind2) {
54271
+ const first = sourceOf(exs[0], from);
54272
+ if (!isItem4(first)) return [];
54273
+ return Object.keys(first).filter(
54274
+ (k3) => exs.every((e2) => {
54275
+ const s3 = sourceOf(e2, from);
54276
+ return isItem4(s3) && typeof s3[k3] === kind2;
54277
+ })
54278
+ );
54279
+ }
54280
+ function leafOf(exs, decide) {
54281
+ const action = exs[0].choice.action;
54282
+ if (typeof action !== "string") return null;
54283
+ if (!exs.every((e2) => e2.choice.action === action)) return null;
54284
+ const spec = decide.actions.find((a2) => a2.tool === action);
54285
+ const values = {};
54286
+ for (const [field2, type] of Object.entries(spec?.fields ?? {})) {
54287
+ const vals = exs.map((e2) => e2.choice[field2]);
54288
+ if (vals.some((v3) => typeof v3 !== type)) return null;
54289
+ const same3 = vals.every((v3) => v3 === vals[0]);
54290
+ const copied = ["details", "item"].flatMap(
54291
+ (from) => keys(exs, from, type).filter(
54292
+ (k3) => exs.every((e2) => sourceOf(e2, from)[k3] === e2.choice[field2])
54293
+ ).map((k3) => ({ from, path: [k3] }))
54294
+ );
54295
+ if (type === "number") {
54296
+ if (copied.length > 0) values[field2] = copied[0];
54297
+ else if (same3 && exs.length >= 2)
54298
+ values[field2] = { const: vals[0] };
54299
+ else return null;
54300
+ } else if (same3) values[field2] = { const: vals[0] };
54301
+ else if (copied.length > 0) values[field2] = copied[0];
54302
+ else return null;
54303
+ }
54304
+ return { leaf: { action, values } };
54305
+ }
54306
+ function numberSplit(exs, decide, from, key, written2) {
54307
+ const num2 = (e2) => sourceOf(e2, from)[key];
54308
+ const sorted = [...exs].sort((a2, b3) => num2(a2) - num2(b3));
54309
+ const runs = [];
54310
+ for (const e2 of sorted) {
54311
+ const last = runs[runs.length - 1];
54312
+ if (last && leafOf([...last, e2], decide)) last.push(e2);
54313
+ else if (last && num2(last[last.length - 1]) === num2(e2)) return null;
54314
+ else runs.push([e2]);
54315
+ }
54316
+ if (runs.length < 2) return null;
54317
+ const leaves3 = runs.map((r2) => leafOf(r2, decide));
54318
+ if (leaves3.some((l2) => l2 === null)) return null;
54319
+ let closed = 0;
54320
+ const cuts = runs.slice(1).map((hi, i2) => {
54321
+ const lo = Math.max(...runs[i2].map(num2));
54322
+ const up = Math.min(...hi.map(num2));
54323
+ const adjacent = Number.isInteger(lo) && Number.isInteger(up) && up - lo === 1;
54324
+ const cut = adjacent ? up : byRoundness(written2.filter((w3) => w3 > lo && w3 <= up))[0];
54325
+ if (cut !== void 0) closed++;
54326
+ return { lo, up, cut };
54327
+ });
54328
+ if (closed === 0 && runs.some((r2) => r2.length < 3)) return null;
54329
+ return {
54330
+ from,
54331
+ path: [key],
54332
+ bands: runs.map((_3, i2) => {
54333
+ const below = cuts[i2 - 1];
54334
+ const above = cuts[i2];
54335
+ return {
54336
+ ...below ? { gte: below.cut ?? below.up } : {},
54337
+ ...above ? above.cut !== void 0 ? { lt: above.cut } : { lte: above.lo } : {},
54338
+ node: leaves3[i2]
54339
+ };
54340
+ })
54341
+ };
54342
+ }
54343
+ function learn(exs, decide, written2, depth) {
54344
+ const leaf = leafOf(exs, decide);
54345
+ if (leaf) return leaf;
54346
+ if (depth >= MAX_DEPTH || exs.length < 2) return null;
54347
+ const found = [];
54348
+ for (const from of ["details", "item"]) {
54349
+ for (const key of keys(exs, from, "string")) {
54350
+ if (!CATEGORY_LIKE.test(key)) continue;
54351
+ const groups = /* @__PURE__ */ new Map();
54352
+ for (const e2 of exs) {
54353
+ const v3 = sourceOf(e2, from)[key];
54354
+ groups.set(v3, [...groups.get(v3) ?? [], e2]);
54355
+ }
54356
+ if (groups.size < 2 || groups.size > 12) continue;
54357
+ const cases = {};
54358
+ let ok = true;
54359
+ for (const [v3, g3] of groups) {
54360
+ const child2 = learn(g3, decide, written2, depth + 1);
54361
+ if (!child2) {
54362
+ ok = false;
54363
+ break;
54364
+ }
54365
+ cases[v3] = child2;
54366
+ }
54367
+ if (ok) found.push({ from, path: [key], cases });
54368
+ }
54369
+ for (const key of keys(exs, from, "number")) {
54370
+ const split = numberSplit(exs, decide, from, key, written2);
54371
+ if (split) found.push(split);
54372
+ }
54373
+ }
54374
+ if (found.length === 0) return null;
54375
+ return found.sort((a2, b3) => size(a2) - size(b3))[0];
54376
+ }
54377
+ function learnTable(decide, written2) {
54378
+ if (decide.examples.length < 4) return null;
54379
+ const table2 = learn(decide.examples, decide, written2, 0);
54380
+ return table2 && !("leaf" in table2) ? table2 : null;
54381
+ }
54382
+ var isItem4, CATEGORY_LIKE, MAX_DEPTH, sourceOf, size;
54383
+ var init_decision_table = __esm({
54384
+ "../compiler/src/decision-table.ts"() {
54385
+ "use strict";
54386
+ init_rules3();
54387
+ isItem4 = (v3) => v3 !== null && typeof v3 === "object" && !Array.isArray(v3);
54388
+ CATEGORY_LIKE = /(^|_)(category|priority|status|kind|type|tier|level|severity|stage|plan|label|channel|reason|segment|state)($|_)/i;
54389
+ MAX_DEPTH = 3;
54390
+ sourceOf = (e2, from) => from === "item" ? e2.item : e2.details;
54391
+ size = (n3) => "leaf" in n3 ? 1 : "cases" in n3 ? Object.values(n3.cases).reduce((a2, c2) => a2 + size(c2), 0) : n3.bands.reduce((a2, b3) => a2 + size(b3.node), 0);
54392
+ }
54393
+ });
54394
+
54395
+ // ../compiler/src/decision-bands.ts
54396
+ function learnBands(decide, written2) {
54397
+ const ex = decide.examples;
54398
+ if (ex.length < 4) return null;
54399
+ const action = ex[0].choice.action;
54400
+ if (typeof action !== "string" || action === "none") return null;
54401
+ if (!ex.every((e2) => e2.choice.action === action)) return null;
54402
+ const fields = Object.keys(ex[0].choice).filter((k3) => k3 !== "action");
54403
+ if (fields.length !== 1) return null;
54404
+ const field2 = fields[0];
54405
+ const values = ex.map((e2) => e2.choice[field2]);
54406
+ if (!values.every((v3) => typeof v3 === "string")) return null;
54407
+ if (Object.keys(ex[0].choice).length !== 2) return null;
54408
+ const distinct = [...new Set(values)];
54409
+ if (distinct.length < 2) return null;
54410
+ const sources = [
54411
+ ...numericKeys(ex.map((e2) => e2.details)).map((key) => ({
54412
+ from: "details",
54413
+ key
54414
+ })),
54415
+ ...numericKeys(ex.map((e2) => e2.item)).map((key) => ({
54416
+ from: "item",
54417
+ key
54418
+ }))
54419
+ ];
54420
+ const found = [];
54421
+ for (const { from, key } of sources) {
54422
+ const num2 = (e2) => e2[from === "item" ? "item" : "details"][key];
54423
+ const ranges = distinct.map((value) => {
54424
+ const ns = ex.filter((e2) => e2.choice[field2] === value).map(num2);
54425
+ return {
54426
+ value,
54427
+ min: Math.min(...ns),
54428
+ max: Math.max(...ns),
54429
+ n: ns.length
54430
+ };
54431
+ }).sort((a2, b3) => a2.min - b3.min);
54432
+ if (ranges.some((r2, i2) => i2 > 0 && ranges[i2 - 1].max >= r2.min)) continue;
54433
+ let closed = 0;
54434
+ const cuts = ranges.slice(1).map((hi, i2) => {
54435
+ const lo = ranges[i2];
54436
+ const adjacent = Number.isInteger(lo.max) && Number.isInteger(hi.min) && hi.min - lo.max === 1;
54437
+ const cut = adjacent ? hi.min : byRoundness(written2.filter((w3) => w3 > lo.max && w3 <= hi.min))[0];
54438
+ if (cut !== void 0) closed++;
54439
+ return { lo: lo.max, hi: hi.min, cut };
54440
+ });
54441
+ if (closed === 0 && ranges.some((r2) => r2.n < 3)) continue;
54442
+ const bands = ranges.map((r2, i2) => {
54443
+ const below = cuts[i2 - 1];
54444
+ const above = cuts[i2];
54445
+ return {
54446
+ value: r2.value,
54447
+ ...below ? { gte: below.cut ?? below.hi } : {},
54448
+ ...above ? above.cut !== void 0 ? { lt: above.cut } : { lte: above.lo } : {}
54449
+ };
54450
+ });
54451
+ found.push({ rule: { from, path: [key], action, field: field2, bands }, closed });
54452
+ }
54453
+ if (found.length === 0) return null;
54454
+ const best = Math.max(...found.map((f3) => f3.closed));
54455
+ const top = found.filter((f3) => f3.closed === best);
54456
+ return top.length === 1 ? top[0].rule : null;
54457
+ }
54458
+ function writtenThresholds(text) {
54459
+ const out = [];
54460
+ for (const m3 of text.matchAll(THRESHOLD)) {
54461
+ for (const g3 of m3.slice(1)) {
54462
+ if (g3 === void 0) continue;
54463
+ const [n3] = numbersInText(g3);
54464
+ if (n3 !== void 0) out.push(n3);
54465
+ }
54466
+ }
54467
+ return out;
54468
+ }
54469
+ function markDecisionBands(workflow) {
54470
+ if (process.env.HOTPATH_BANDS === "0") return workflow;
54471
+ const written2 = workflow.steps.flatMap(
54472
+ (s3) => s3.type === "llm" ? writtenThresholds(s3.example) : []
54473
+ );
54474
+ const limits = /* @__PURE__ */ new Set();
54475
+ const bandKeys = [];
54476
+ const steps = workflow.steps.map((s3) => {
54477
+ if (s3.type !== "foreach" || !s3.decide) return s3;
54478
+ const bands = learnBands(s3.decide, written2);
54479
+ if (!bands) {
54480
+ const table2 = learnTable(s3.decide, written2);
54481
+ return table2 ? { ...s3, decide: { ...s3.decide, table: table2 } } : s3;
54482
+ }
54483
+ bandKeys.push(bands.path.join("."));
54484
+ for (const b3 of bands.bands)
54485
+ for (const n3 of [b3.gte, b3.lte, b3.lt]) if (n3 !== void 0) limits.add(n3);
54486
+ return { ...s3, decide: { ...s3.decide, bands } };
54487
+ });
54488
+ if (limits.size === 0) return { ...workflow, steps };
54489
+ const isWrittenLimit = (fact) => {
54490
+ const n3 = typeof fact === "number" ? fact : /^\s*\d[\d,]*(?:\.\d+)?\s*$/.test(fact) ? Number(fact.replace(/,/g, "")) : NaN;
54491
+ return limits.has(n3) || written2.includes(n3);
54492
+ };
54493
+ const keys2 = new Set(bandKeys);
54494
+ const citesByLimit = (g3) => g3.positions !== void 0 && isWrittenLimit(g3.value) && g3.paths.every((p3) => [...keys2].some((k3) => p3.endsWith(`.*.${k3}`)));
54495
+ return {
54496
+ ...workflow,
54497
+ steps: steps.map(
54498
+ (s3) => s3.type === "llm" ? {
54499
+ ...s3,
54500
+ guard: {
54501
+ ...s3.guard,
54502
+ ...s3.guard.exampleFacts ? {
54503
+ exampleFacts: s3.guard.exampleFacts.filter(
54504
+ (f3) => !isWrittenLimit(f3)
54505
+ )
54506
+ } : {},
54507
+ ...s3.guard.grounding ? {
54508
+ grounding: s3.guard.grounding.filter(
54509
+ (g3) => !citesByLimit(g3)
54510
+ )
54511
+ } : {}
54512
+ }
54513
+ } : s3
54514
+ )
54515
+ };
54516
+ }
54517
+ var isItem5, numericKeys, NUM2, THRESHOLD;
54518
+ var init_decision_bands = __esm({
54519
+ "../compiler/src/decision-bands.ts"() {
54520
+ "use strict";
54521
+ init_src();
54522
+ init_decision_table();
54523
+ init_rules3();
54524
+ isItem5 = (v3) => v3 !== null && typeof v3 === "object" && !Array.isArray(v3);
54525
+ numericKeys = (nodes) => {
54526
+ if (nodes.length === 0 || !nodes.every(isItem5)) return [];
54527
+ return Object.keys(nodes[0]).filter(
54528
+ (k3) => nodes.every(
54529
+ (n3) => typeof n3[k3] === "number" && Number.isFinite(n3[k3])
54530
+ )
54531
+ );
54532
+ };
54533
+ NUM2 = String.raw`\d[\d,]*(?:\.\d+)?`;
54534
+ THRESHOLD = new RegExp(
54535
+ String.raw`(?:[≥≤<>]=?\s*|\b(?:below|under|over|above|at least|at most|fewer than|less than|more than)\s+)(${NUM2})` + String.raw`|(${NUM2})\s*(?:[–—-]|to)\s*(${NUM2})` + String.raw`|(${NUM2})\s*(?:\+|or more|or fewer|or less|and above|and up|and below)`,
54536
+ "gi"
54537
+ );
54538
+ }
54539
+ });
54540
+
54541
+ // ../compiler/src/trim.ts
54542
+ function listsRead(calc) {
54543
+ if (calc.selection) return [];
54544
+ if (calc.group) {
54545
+ return calc.group.refs ? calc.group.refs.map((r2) => `${r2}.${calc.group.path}`) : [`${calc.list}.*.${calc.group.path}`];
54546
+ }
54547
+ return [calc.list];
54548
+ }
54549
+ function learnTrim(o2) {
54550
+ if (process.env.HOTPATH_TRIM === "0") return [];
54551
+ const grounded = (o2.grounding ?? []).flatMap((g3) => g3.paths);
54552
+ const paths = [...new Set(o2.calcs.flatMap(listsRead))].filter((p3) => {
54553
+ const items = listAt(p3, o2.ctx);
54554
+ if (!items || items.length < MIN_ITEMS) return false;
54555
+ const inside2 = pathPattern(p3);
54556
+ return !grounded.some((g3) => inside2.test(g3));
54557
+ });
54558
+ if (paths.length === 0) return [];
54559
+ const trimmed = trimData(o2.ctx, paths);
54560
+ if (!trimmed) return [];
54561
+ const figures = [];
54562
+ for (const c2 of o2.calcs) {
54563
+ const got = computeFigures(c2, o2.ctx);
54564
+ if (got === null) {
54565
+ if (listsRead(c2).some((l2) => paths.includes(l2))) return [];
54566
+ continue;
54567
+ }
54568
+ figures.push(...got);
54569
+ }
54570
+ const sent = renderTemplate(o2.prompt, trimmed);
54571
+ const known = [
54572
+ sent,
54573
+ ...figures.map((f3) => f3.text),
54574
+ ...o2.calcs.flatMap((c2) => [
54575
+ c2.match ?? "",
54576
+ c2.where?.equals ?? "",
54577
+ c2.where?.not ?? ""
54578
+ ])
54579
+ ].join("\n");
54580
+ const removed = paths.map((p3) => JSON.stringify(listAt(p3, o2.ctx) ?? [])).join("\n");
54581
+ const knownNumbers = /* @__PURE__ */ new Set([
54582
+ ...numbersInText(known).map(round2),
54583
+ ...figures.map((f3) => round2(f3.value))
54584
+ ]);
54585
+ if (numbersInText(o2.example).some((n3) => !knownNumbers.has(round2(n3))))
54586
+ return [];
54587
+ const knownWords = tokens(known);
54588
+ const removedWords = tokens(removed);
54589
+ for (const w3 of tokens(o2.example)) {
54590
+ if (removedWords.has(w3) && !knownWords.has(w3)) return [];
54591
+ }
54592
+ return paths;
54593
+ }
54594
+ var MIN_ITEMS, pathPattern, tokens;
54595
+ var init_trim2 = __esm({
54596
+ "../compiler/src/trim.ts"() {
54597
+ "use strict";
54598
+ init_src();
54599
+ MIN_ITEMS = 20;
54600
+ pathPattern = (p3) => new RegExp(
54601
+ "^" + p3.split(".").map(
54602
+ (k3) => k3 === "*" ? "(\\d+|\\*)" : k3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
54603
+ ).join("\\.") + "(\\.|$)"
54604
+ );
54605
+ tokens = (text) => new Set(
54606
+ (text.toLowerCase().match(/[a-z0-9][a-z0-9_-]*[a-z0-9]/g) ?? []).filter(
54607
+ (t2) => /[a-z]/.test(t2)
54608
+ )
54609
+ );
54610
+ }
54611
+ });
54612
+
52966
54613
  // ../compiler/src/calculations.ts
52967
- function objectLists(node, at2, out) {
54614
+ function objectLists(node, at3, out) {
52968
54615
  if (Array.isArray(node)) {
52969
- if (node.length > 0 && node.every(isItem3)) out.set(at2, node);
54616
+ if (node.length > 0 && node.every(isItem6)) out.set(at3, node);
52970
54617
  return;
52971
54618
  }
52972
- if (isItem3(node)) {
54619
+ if (isItem6(node)) {
52973
54620
  for (const [k3, v3] of Object.entries(node))
52974
- objectLists(v3, `${at2}.${k3}`, out);
54621
+ objectLists(v3, `${at3}.${k3}`, out);
52975
54622
  }
52976
54623
  }
52977
54624
  function findRateSources(ctx, exclude) {
52978
54625
  const out = [];
52979
- const visit = (node, at2) => {
52980
- if (at2 === exclude || at2.startsWith(`${exclude}.`)) return;
54626
+ const visit = (node, at3) => {
54627
+ if (at3 === exclude || at3.startsWith(`${exclude}.`)) return;
52981
54628
  if (Array.isArray(node)) {
52982
- node.forEach((n3, i2) => visit(n3, `${at2}.${i2}`));
54629
+ node.forEach((n3, i2) => visit(n3, `${at3}.${i2}`));
52983
54630
  return;
52984
54631
  }
52985
- if (!isItem3(node)) return;
54632
+ if (!isItem6(node)) return;
52986
54633
  const entries = Object.entries(node);
52987
54634
  if (entries.length > 0 && entries.every(([k3, v3]) => CODE.test(k3) && typeof v3 === "number")) {
52988
- out.push({ ref: at2, map: true });
54635
+ out.push({ ref: at3, map: true });
52989
54636
  return;
52990
54637
  }
52991
54638
  const code = entries.find(([, v3]) => typeof v3 === "string" && CODE.test(v3));
52992
54639
  const nums = entries.filter(([, v3]) => typeof v3 === "number");
52993
54640
  const rate = nums.find(([k3]) => /rate|per|fx/i.test(k3)) ?? (nums.length === 1 ? nums[0] : void 0);
52994
54641
  if (code && rate) {
52995
- out.push({ ref: at2, codeField: code[0], rateField: rate[0] });
54642
+ out.push({ ref: at3, codeField: code[0], rateField: rate[0] });
52996
54643
  return;
52997
54644
  }
52998
- for (const [k3, v3] of entries) visit(v3, `${at2}.${k3}`);
54645
+ for (const [k3, v3] of entries) visit(v3, `${at3}.${k3}`);
52999
54646
  };
53000
54647
  visit(ctx.steps, "steps");
53001
54648
  return out;
@@ -53019,12 +54666,14 @@ function learnCalculations(example, ctx) {
53019
54666
  const collect = (node) => {
53020
54667
  if (typeof node === "number") known.add(node);
53021
54668
  else if (Array.isArray(node)) node.forEach(collect);
53022
- else if (isItem3(node)) Object.values(node).forEach(collect);
54669
+ else if (isItem6(node)) Object.values(node).forEach(collect);
53023
54670
  };
53024
54671
  collect(ctx.steps);
53025
54672
  collect(ctx.inputs);
53026
54673
  const lists3 = /* @__PURE__ */ new Map();
53027
54674
  objectLists(ctx.steps, "steps", lists3);
54675
+ for (const ref of [...lists3.keys()])
54676
+ if (/\.results\.\d+(?:\.|$)/.test(ref)) lists3.delete(ref);
53028
54677
  const scopes = [];
53029
54678
  for (const [list, items] of lists3) {
53030
54679
  const key = keyField(items);
@@ -53044,9 +54693,13 @@ function learnCalculations(example, ctx) {
53044
54693
  break;
53045
54694
  }
53046
54695
  }
53047
- for (const line of example.split("\n")) {
54696
+ const plainLists = [...lists3.keys()];
54697
+ const groups = learnGroupCalculations(example, ctx, plainLists);
54698
+ out.push(...groups.calcs);
54699
+ for (const [i2, line] of example.split("\n").entries()) {
53048
54700
  for (const figure of calculatedIn(line, known)) {
53049
- const calc = explain(line, figure, scopes, ctx);
54701
+ if (groups.covered.has(`${i2}:${round2(figure)}`)) continue;
54702
+ const calc = explain(line, figure, scopes, ctx) ?? explainAcross(line, figure, ctx, plainLists);
53050
54703
  if (calc) out.push(calc);
53051
54704
  }
53052
54705
  }
@@ -53103,7 +54756,7 @@ function explain(line, figure, scopes, ctx) {
53103
54756
  convert,
53104
54757
  rateTable(convert.rates, ctx)
53105
54758
  );
53106
- if (v3 !== null && close(v3, figure)) {
54759
+ if (v3 !== null && close2(v3, figure)) {
53107
54760
  tries.push({ ...base, op: "each", field: field2, convert, key: scope.key });
53108
54761
  }
53109
54762
  }
@@ -53129,7 +54782,7 @@ function explain(line, figure, scopes, ctx) {
53129
54782
  for (const calc of tries) {
53130
54783
  if (calc.op === "each") return calc;
53131
54784
  const got = computeFigures(calc, ctx);
53132
- if (got && got.length === 1 && close(got[0].value, figure)) {
54785
+ if (got && got.length === 1 && close2(got[0].value, figure)) {
53133
54786
  return withUnits(calc);
53134
54787
  }
53135
54788
  }
@@ -53139,12 +54792,12 @@ function explain(line, figure, scopes, ctx) {
53139
54792
  function timeShifts(ctx) {
53140
54793
  const offsets = [];
53141
54794
  const zones = [];
53142
- const visit = (node, at2) => {
54795
+ const visit = (node, at3) => {
53143
54796
  if (typeof node === "string") {
53144
- if (parseOffset(node) !== null) offsets.push({ offsetRef: at2 });
53145
- else if (isTimeZone(node)) zones.push({ zoneRef: at2 });
53146
- } else if (isItem3(node)) {
53147
- for (const [k3, v3] of Object.entries(node)) visit(v3, `${at2}.${k3}`);
54797
+ if (parseOffset(node) !== null) offsets.push({ offsetRef: at3 });
54798
+ else if (isTimeZone(node)) zones.push({ zoneRef: at3 });
54799
+ } else if (isItem6(node)) {
54800
+ for (const [k3, v3] of Object.entries(node)) visit(v3, `${at3}.${k3}`);
53148
54801
  }
53149
54802
  };
53150
54803
  visit(ctx.steps, "steps");
@@ -53186,7 +54839,7 @@ function learnTime(example, scope, ctx) {
53186
54839
  return null;
53187
54840
  }
53188
54841
  function markCalculations(workflow, recorded, inputs) {
53189
- if (process.env.HOTPATH_CALCULATIONS === "0") return workflow;
54842
+ const calculate = process.env.HOTPATH_CALCULATIONS !== "0";
53190
54843
  const ctx = { inputs, steps: {} };
53191
54844
  for (const r2 of recorded) {
53192
54845
  ctx.steps[r2.id] = r2.field === "results" ? { results: r2.result } : { result: r2.result };
@@ -53194,23 +54847,39 @@ function markCalculations(workflow, recorded, inputs) {
53194
54847
  let changed = false;
53195
54848
  const steps = workflow.steps.map((s3) => {
53196
54849
  if (s3.type !== "llm") return s3;
53197
- const calculations = learnCalculations(s3.example, ctx);
53198
- if (calculations.length === 0) return s3;
54850
+ const calculations = calculate ? learnCalculations(s3.example, ctx) : [];
54851
+ const trim = calculations.length > 0 ? learnTrim({
54852
+ prompt: s3.prompt,
54853
+ example: s3.example,
54854
+ ctx,
54855
+ calcs: calculations,
54856
+ grounding: s3.guard.grounding
54857
+ }) : [];
54858
+ const sent = trim.length > 0 ? trimData(ctx, trim) ?? ctx : ctx;
54859
+ const inputChars = String(renderTemplate(s3.prompt, sent)).length;
53199
54860
  changed = true;
53200
- return { ...s3, calculations };
54861
+ return {
54862
+ ...s3,
54863
+ ...calculations.length > 0 ? { calculations } : {},
54864
+ ...trim.length > 0 ? { trim } : {},
54865
+ inputChars
54866
+ };
53201
54867
  });
53202
- return changed ? { ...workflow, steps } : workflow;
54868
+ return markDecisionBands(changed ? { ...workflow, steps } : workflow);
53203
54869
  }
53204
- var isItem3, CODE, KEYS, close, CLOCK;
54870
+ var isItem6, CODE, KEYS, close2, CLOCK;
53205
54871
  var init_calculations = __esm({
53206
54872
  "../compiler/src/calculations.ts"() {
53207
54873
  "use strict";
53208
54874
  init_src();
53209
54875
  init_derived();
53210
- isItem3 = (v3) => v3 !== null && typeof v3 === "object" && !Array.isArray(v3);
54876
+ init_group_calculations();
54877
+ init_decision_bands();
54878
+ init_trim2();
54879
+ isItem6 = (v3) => v3 !== null && typeof v3 === "object" && !Array.isArray(v3);
53211
54880
  CODE = /^[A-Z]{3}$/;
53212
54881
  KEYS = ["ref", "id", "number", "name", "title", "subject", "sku", "code"];
53213
- close = (a2, b3) => Math.abs(round2(a2) - round2(b3)) < 5e-3;
54882
+ close2 = (a2, b3) => Math.abs(round2(a2) - round2(b3)) < 5e-3;
53214
54883
  CLOCK = /(?<![\d.:])\d{1,2}[:.]\d{2}(?:\s*[ap]\.?m\b\.?)?(?!\d|:\d)/gi;
53215
54884
  }
53216
54885
  });
@@ -53264,11 +54933,11 @@ function errorText2(v3) {
53264
54933
  }
53265
54934
  return null;
53266
54935
  }
53267
- function lists2(v3, at2, out) {
53268
- if (Array.isArray(v3)) out.push([at2, v3]);
54936
+ function lists2(v3, at3, out) {
54937
+ if (Array.isArray(v3)) out.push([at3, v3]);
53269
54938
  else if (v3 !== null && typeof v3 === "object") {
53270
54939
  for (const [k3, x3] of Object.entries(v3))
53271
- lists2(x3, at2 ? `${at2}.${k3}` : k3, out);
54940
+ lists2(x3, at3 ? `${at3}.${k3}` : k3, out);
53272
54941
  }
53273
54942
  }
53274
54943
  function recordingProblems(trace2, workflow, recorded) {
@@ -53450,11 +55119,11 @@ function mergePaths(all) {
53450
55119
  const signatures = [];
53451
55120
  lists3.forEach((l2, i2) => {
53452
55121
  const sig = l2.slice(k3).map(keyOf).join(">");
53453
- const at2 = signatures.indexOf(sig);
53454
- if (at2 === -1) {
55122
+ const at3 = signatures.indexOf(sig);
55123
+ if (at3 === -1) {
53455
55124
  signatures.push(sig);
53456
55125
  groups.push([i2]);
53457
- } else groups[at2].push(i2);
55126
+ } else groups[at3].push(i2);
53458
55127
  });
53459
55128
  if (groups.length < 2) return null;
53460
55129
  const newest = all.length - 1;
@@ -53616,7 +55285,7 @@ function embedClosest(sub, sup) {
53616
55285
  }
53617
55286
  }
53618
55287
  if (!Number.isFinite(best[0][0])) return null;
53619
- const at2 = [];
55288
+ const at3 = [];
53620
55289
  let j2 = 0;
53621
55290
  for (let i2 = 0; i2 < n3; i2++) {
53622
55291
  while (true) {
@@ -53624,21 +55293,21 @@ function embedClosest(sub, sup) {
53624
55293
  if (take === best[i2][j2]) break;
53625
55294
  j2++;
53626
55295
  }
53627
- at2.push(j2++);
55296
+ at3.push(j2++);
53628
55297
  }
53629
- return at2;
55298
+ return at3;
53630
55299
  }
53631
55300
  function matchReordered(own, base) {
53632
55301
  const used = /* @__PURE__ */ new Set();
53633
- const at2 = [];
55302
+ const at3 = [];
53634
55303
  for (const key of own.keys) {
53635
55304
  const j2 = base.keys.findIndex((k3, ix) => k3 === key && !used.has(ix));
53636
55305
  if (j2 === -1) return null;
53637
55306
  used.add(j2);
53638
- at2.push(j2);
55307
+ at3.push(j2);
53639
55308
  }
53640
- const acting = at2.filter((_3, i2) => own.effects[i2]);
53641
- return acting.every((j2, i2) => i2 === 0 || j2 > acting[i2 - 1]) ? at2 : null;
55309
+ const acting = at3.filter((_3, i2) => own.effects[i2]);
55310
+ return acting.every((j2, i2) => i2 === 0 || j2 > acting[i2 - 1]) ? at3 : null;
53642
55311
  }
53643
55312
  function shapeOf(value, prefix = "", out = /* @__PURE__ */ new Set()) {
53644
55313
  if (Array.isArray(value)) {
@@ -53739,9 +55408,9 @@ function feeders(workflow, toolIds) {
53739
55408
  }
53740
55409
  return out;
53741
55410
  }
53742
- function richest(candidates2) {
53743
- const size = (c2) => c2.results.reduce((n3, r2) => n3 + countItems(r2.result), 0);
53744
- return candidates2.reduce((best, c2) => size(c2) >= size(best) ? c2 : best);
55411
+ function richest(candidates3) {
55412
+ const size2 = (c2) => c2.results.reduce((n3, r2) => n3 + countItems(r2.result), 0);
55413
+ return candidates3.reduce((best, c2) => size2(c2) >= size2(best) ? c2 : best);
53745
55414
  }
53746
55415
  function widenGuards(workflow, base, all) {
53747
55416
  if (all.length < 2 || !all.every(
@@ -53961,6 +55630,19 @@ function compileUsed(traces, compiledFrom, allowSplit) {
53961
55630
  });
53962
55631
  return map;
53963
55632
  });
55633
+ const written2 = all.flatMap(
55634
+ (c2) => c2.trace.calls.flatMap(
55635
+ (call) => Object.values(call.args).filter((v3) => typeof v3 === "string").flatMap((v3) => numbersInText(v3))
55636
+ )
55637
+ );
55638
+ const dataValues = /* @__PURE__ */ new Set();
55639
+ const collect = (v3) => {
55640
+ if (typeof v3 === "number") dataValues.add(v3);
55641
+ else if (Array.isArray(v3)) v3.forEach(collect);
55642
+ else if (v3 !== null && typeof v3 === "object")
55643
+ Object.values(v3).forEach(collect);
55644
+ };
55645
+ for (const c2 of all) for (const call of c2.trace.calls) collect(call.result);
53964
55646
  const conditions = /* @__PURE__ */ new Map();
53965
55647
  let i2 = 0;
53966
55648
  while (i2 < base.sig.length) {
@@ -53984,7 +55666,7 @@ function compileUsed(traces, compiledFrom, allowSplit) {
53984
55666
  return m3;
53985
55667
  };
53986
55668
  const groupIds = base.ids.slice(i2, end + 1);
53987
- const rule = learnRule(yesK.map(before), noK.map(before)) ?? learnInputRule(
55669
+ const rule = learnRule(yesK.map(before), noK.map(before)) ?? learnNumberRule(yesK.map(before), noK.map(before), written2, dataValues) ?? learnInputRule(
53988
55670
  yesK.map((k3) => all[k3].trace.meta.inputs),
53989
55671
  noK.map((k3) => all[k3].trace.meta.inputs)
53990
55672
  );
@@ -54453,11 +56135,22 @@ async function compileTaskInMemory(task, traceFile, options = {}) {
54453
56135
  `trace task is "${trace2.meta.task}" but you asked to compile "${task}" \u2014 check --trace`
54454
56136
  );
54455
56137
  }
56138
+ if (!trace2.calls.some((c2) => !c2.isError)) {
56139
+ throw new Error(
56140
+ `the recording of "${task}" (${path8.basename(resolved)}) has no tool call that worked: the agent stopped before doing the task (check its output for the error). Nothing was compiled; fix the cause and record it again.`
56141
+ );
56142
+ }
56143
+ const saved = await previousSaved(task);
56144
+ const readOnly = options.readOnly === true || saved.readOnly;
56145
+ if (!readOnly) {
56146
+ const problem = halfDoneRecording(trace2);
56147
+ if (problem) throw new HalfDoneRecordingError(task, resolved, problem);
56148
+ }
54456
56149
  const relative = path8.relative(repoRoot, resolved).replace(/\\/g, "/");
54457
56150
  const earlier = traceFile ? [] : await earlierTraces(task, resolved);
54458
56151
  const branched = compileTraces([...earlier, trace2], relative);
54459
56152
  const others = branched.used.length - 1;
54460
- const carried = (await previousRequirements(task)).filter(
56153
+ const carried = saved.require.filter(
54461
56154
  (r2) => !(options.require ?? []).includes(r2)
54462
56155
  );
54463
56156
  const typed = applyRequirements(
@@ -54485,7 +56178,10 @@ async function compileTaskInMemory(task, traceFile, options = {}) {
54485
56178
  )
54486
56179
  ),
54487
56180
  compiledFrom: others > 0 ? `${relative} (+${others} earlier recording${others === 1 ? "" : "s"})` : relative,
54488
- baseline: await agentBaseline(trace2)
56181
+ baseline: await agentBaseline(trace2),
56182
+ // a fresh recording is unconfirmed until the user says it is right
56183
+ confirmed: false,
56184
+ ...readOnly ? { readOnly: true } : {}
54489
56185
  });
54490
56186
  return {
54491
56187
  workflow,
@@ -54500,11 +56196,12 @@ async function compileTaskInMemory(task, traceFile, options = {}) {
54500
56196
  ...branched.notes,
54501
56197
  ...typed.applied,
54502
56198
  ...required2.applied,
54503
- ...strongNotes(workflow)
56199
+ ...strongNotes(workflow),
56200
+ ...decisionNotes(workflow)
54504
56201
  ]
54505
56202
  };
54506
56203
  }
54507
- async function previousRequirements(task) {
56204
+ async function previousSaved(task) {
54508
56205
  try {
54509
56206
  const raw = JSON.parse(
54510
56207
  await readFile3(
@@ -54512,9 +56209,12 @@ async function previousRequirements(task) {
54512
56209
  "utf8"
54513
56210
  )
54514
56211
  );
54515
- return Array.isArray(raw.require) ? raw.require.filter((r2) => typeof r2 === "string") : [];
56212
+ return {
56213
+ require: Array.isArray(raw.require) ? raw.require.filter((r2) => typeof r2 === "string") : [],
56214
+ readOnly: raw.readOnly === true
56215
+ };
54516
56216
  } catch {
54517
- return [];
56217
+ return { require: [], readOnly: false };
54518
56218
  }
54519
56219
  }
54520
56220
  async function earlierTraces(task, newest) {
@@ -54665,8 +56365,9 @@ function recordingWarnings(trace2, workflow, recorded) {
54665
56365
  );
54666
56366
  }
54667
56367
  warnings.push(...hedgeWarnings(workflow));
56368
+ warnings.push(...positionalWarnings(workflow));
54668
56369
  const actionTools = trace2.meta.tools.filter((t2) => t2.annotations?.readOnlyHint !== true).map((t2) => t2.name);
54669
- if (actionTools.length === 0) return warnings;
56370
+ if (actionTools.length === 0 || workflow.readOnly) return warnings;
54670
56371
  const acted = toolStepsOf(workflow.steps).some((s3) => s3.sideEffect);
54671
56372
  if (acted) return [...warnings, ...coverageProblems(workflow, recorded)];
54672
56373
  warnings.push(
@@ -54674,6 +56375,26 @@ function recordingWarnings(trace2, workflow, recorded) {
54674
56375
  );
54675
56376
  return warnings;
54676
56377
  }
56378
+ function positionalWarnings(workflow) {
56379
+ return (workflow.positional ?? []).map(
56380
+ (p3) => `${p3.steps.join(", ")} act on items of ${p3.list} by position (item 1, item 2\u2026). A new day's list has other items in those places, so this workflow is never replayed: the agent does the task each time. Record it again with the agent acting on the items one after another, in the list's order.`
56381
+ );
56382
+ }
56383
+ function decisionNotes(workflow) {
56384
+ return workflow.steps.flatMap((s3) => {
56385
+ if (s3.type !== "foreach" || !s3.decide) return [];
56386
+ const counts = /* @__PURE__ */ new Map();
56387
+ for (const e2 of s3.decide.examples) {
56388
+ const a2 = String(e2.choice.action);
56389
+ counts.set(a2, (counts.get(a2) ?? 0) + 1);
56390
+ }
56391
+ const seen = [...counts].map(([a2, n3]) => `${a2} \xD7${n3}`).join(", ");
56392
+ const once = [...counts].filter(([, n3]) => n3 === 1).map(([a2]) => a2);
56393
+ return [
56394
+ `${s3.id}: what to do with each ${s3.as} is decided by the replay model on each run, from the recorded decisions (${seen}); code checks its answer before any action runs.` + (once.length > 0 ? ` ${once.join(", ")} was recorded once: record another day where it happens to make the rule clearer.` : "")
56395
+ ];
56396
+ });
56397
+ }
54677
56398
  function hedgeWarnings(workflow) {
54678
56399
  const out = [];
54679
56400
  for (const step of workflow.steps) {
@@ -54735,8 +56456,17 @@ function formatWorkflow(workflow) {
54735
56456
  toolLine(step, indent);
54736
56457
  } else if (step.type === "foreach") {
54737
56458
  lines.push(
54738
- `${indent}${step.id} foreach ${step.as} in ${step.over} (max ${step.maxItems})${only(step.when)}`
56459
+ `${indent}${step.id} foreach ${step.as} in ${step.over} (max ${step.maxItems}${step.distinct ? `, once per distinct ${step.distinct.join(".")}` : ""})${only(step.when)}`
54739
56460
  );
56461
+ if (step.decide) {
56462
+ const choices = step.decide.actions.map((a2) => {
56463
+ const fields = Object.keys(a2.fields);
56464
+ return fields.length > 0 ? `${a2.tool}(${fields.join(", ")})` : a2.tool;
56465
+ }).join(" | ");
56466
+ lines.push(
56467
+ `${indent} decide per ${step.as} (llm ${step.decide.model}, ${step.decide.examples.length} recorded examples): ${choices} | none`
56468
+ );
56469
+ }
54740
56470
  for (const body of step.body) toolLine(body, `${indent} `);
54741
56471
  } else if (step.type === "branch") {
54742
56472
  lines.push(`${indent}${step.id} branch${only(step.when)}`);
@@ -54781,7 +56511,74 @@ function formatValue(value) {
54781
56511
  if (typeof value === "string") return value;
54782
56512
  return JSON.stringify(value);
54783
56513
  }
54784
- var repoRoot, tracesDir, workflowsDir, HEDGE;
56514
+ function isConfirmed(workflow) {
56515
+ return workflow.confirmed !== false;
56516
+ }
56517
+ function assertConfirmed(workflow) {
56518
+ if (!isConfirmed(workflow)) throw new UnconfirmedWorkflowError(workflow.task);
56519
+ }
56520
+ async function confirmWorkflow(task) {
56521
+ const workflow = { ...await loadWorkflow(task), confirmed: true };
56522
+ await saveWorkflow(workflow);
56523
+ return workflow;
56524
+ }
56525
+ function formatRecordingSummary(workflow) {
56526
+ const flat = workflow.steps.flatMap(
56527
+ (s3) => s3.type === "branch" ? [...s3.cases.flatMap((c2) => c2.steps), ...s3.else ?? []] : [s3]
56528
+ );
56529
+ const tools = flat.flatMap(
56530
+ (s3) => s3.type === "foreach" ? s3.body : s3.type === "tool" ? [s3] : []
56531
+ );
56532
+ const actions = tools.filter((t2) => t2.sideEffect);
56533
+ const reads2 = tools.filter((t2) => !t2.sideEffect);
56534
+ const lines = ["the recorded run did:"];
56535
+ for (const s3 of flat) {
56536
+ if (s3.type !== "foreach" || !s3.decide) continue;
56537
+ lines.push(` decided per item (${s3.decide.examples.length} recorded):`);
56538
+ for (const ex of s3.decide.examples.slice(0, 12)) {
56539
+ const name = s3.decide.key.reduce(
56540
+ (v3, k3) => v3?.[k3],
56541
+ ex.item
56542
+ );
56543
+ const { action, ...fields } = ex.choice;
56544
+ const extra = Object.keys(fields).length ? ` ${clip(JSON.stringify(fields))}` : "";
56545
+ lines.push(` ${formatValue(name)} \u2192 ${formatValue(action)}${extra}`);
56546
+ }
56547
+ if (s3.decide.examples.length > 12)
56548
+ lines.push(` \u2026 and ${s3.decide.examples.length - 12} more`);
56549
+ }
56550
+ for (const t2 of actions) {
56551
+ lines.push(` \u26A1 ${t2.tool}`);
56552
+ for (const [k3, v3] of Object.entries(t2.args)) {
56553
+ lines.push(
56554
+ ` ${k3}: ${clip(typeof v3 === "string" ? v3 : JSON.stringify(v3))}`
56555
+ );
56556
+ }
56557
+ }
56558
+ if (actions.length === 0) lines.push(" (no side-effect calls)");
56559
+ if (reads2.length > 0) {
56560
+ lines.push(` reads: ${reads2.map((t2) => t2.tool).join(", ")}`);
56561
+ }
56562
+ const llm = workflow.steps.filter((s3) => s3.type === "llm").length;
56563
+ if (llm > 0) lines.push(` ${llm} step(s) written by a model at run time`);
56564
+ return lines.join("\n");
56565
+ }
56566
+ function halfDoneRecording(trace2) {
56567
+ const actionTools = trace2.meta.tools.filter((t2) => t2.annotations?.readOnlyHint !== true).map((t2) => t2.name);
56568
+ if (actionTools.length === 0) return null;
56569
+ const acted = trace2.calls.some(
56570
+ (c2) => !c2.isError && actionTools.includes(c2.tool)
56571
+ );
56572
+ if (acted) return null;
56573
+ const counts = /* @__PURE__ */ new Map();
56574
+ for (const c2 of trace2.calls)
56575
+ counts.set(c2.tool, (counts.get(c2.tool) ?? 0) + 1);
56576
+ const made = [...counts].map(([tool, n3]) => n3 > 1 ? `${tool} \xD7${n3}` : tool).join(", ");
56577
+ const last = trace2.calls.at(-1);
56578
+ const ending = last?.isError === true ? `; its last call (${last.tool}) failed: ${clip(JSON.stringify(last.result)).slice(0, 160)}` : "";
56579
+ return `it made ${trace2.calls.length} call${trace2.calls.length === 1 ? "" : "s"} (${made}) and never called an action tool (${actionTools.join(", ")})${ending}`;
56580
+ }
56581
+ var repoRoot, tracesDir, workflowsDir, HEDGE, UnconfirmedWorkflowError, MAX_ARG_CHARS, clip, HalfDoneRecordingError;
54785
56582
  var init_compile_task = __esm({
54786
56583
  "../compiler/src/compile-task.ts"() {
54787
56584
  "use strict";
@@ -54797,6 +56594,32 @@ var init_compile_task = __esm({
54797
56594
  tracesDir = path8.join(repoRoot, "traces");
54798
56595
  workflowsDir = path8.join(repoRoot, "workflows");
54799
56596
  HEDGE = /\b(?:i |we )?(?:could not|couldn't|cannot|can't|did not|didn't|unable to|was not able to)\s+(?:\w+\s+){0,2}\w+|\bno [\w ]{0,20}(?:was|were) (?:retrieved|fetched|available|provided)|\bnot (?:verified|checked|confirmed)\b/i;
56597
+ UnconfirmedWorkflowError = class extends Error {
56598
+ constructor(task) {
56599
+ super(
56600
+ `workflow "${task}" has not been confirmed \u2014 check what it recorded with "hotpath show ${task}", then run "hotpath confirm ${task}" (or recompile with "hotpath compile ${task} --yes")`
56601
+ );
56602
+ this.task = task;
56603
+ this.name = "UnconfirmedWorkflowError";
56604
+ }
56605
+ task;
56606
+ };
56607
+ MAX_ARG_CHARS = 300;
56608
+ clip = (text) => text.length > MAX_ARG_CHARS ? `${text.slice(0, MAX_ARG_CHARS)}\u2026` : text;
56609
+ HalfDoneRecordingError = class extends Error {
56610
+ constructor(task, traceFile, problem) {
56611
+ super(
56612
+ `the recording of "${task}" (${path8.basename(traceFile)}) looks half done: ${problem}. Nothing was compiled. If the agent stopped early (an error, a timeout, a model that answered in text instead of acting), fix the cause and record it again. If this task only reads, compile it with: hotpath compile ${task} --read-only`
56613
+ );
56614
+ this.task = task;
56615
+ this.traceFile = traceFile;
56616
+ this.problem = problem;
56617
+ this.name = "HalfDoneRecordingError";
56618
+ }
56619
+ task;
56620
+ traceFile;
56621
+ problem;
56622
+ };
54800
56623
  }
54801
56624
  });
54802
56625
 
@@ -55075,12 +56898,12 @@ function getElementAtPath(obj, path36) {
55075
56898
  return path36.reduce((acc, key) => acc?.[key], obj);
55076
56899
  }
55077
56900
  function promiseAllObject(promisesObj) {
55078
- const keys = Object.keys(promisesObj);
55079
- const promises = keys.map((key) => promisesObj[key]);
56901
+ const keys2 = Object.keys(promisesObj);
56902
+ const promises = keys2.map((key) => promisesObj[key]);
55080
56903
  return Promise.all(promises).then((results) => {
55081
56904
  const resolvedObj = {};
55082
- for (let i2 = 0; i2 < keys.length; i2++) {
55083
- resolvedObj[keys[i2]] = results[i2];
56905
+ for (let i2 = 0; i2 < keys2.length; i2++) {
56906
+ resolvedObj[keys2[i2]] = results[i2];
55084
56907
  }
55085
56908
  return resolvedObj;
55086
56909
  });
@@ -56821,8 +58644,8 @@ var init_schemas2 = __esm({
56821
58644
  $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
56822
58645
  $ZodType.init(inst, def);
56823
58646
  const _normalized = cached2(() => {
56824
- const keys = Object.keys(def.shape);
56825
- for (const k3 of keys) {
58647
+ const keys2 = Object.keys(def.shape);
58648
+ for (const k3 of keys2) {
56826
58649
  if (!(def.shape[k3] instanceof $ZodType)) {
56827
58650
  throw new Error(`Invalid element at key "${k3}": expected a Zod schema`);
56828
58651
  }
@@ -56830,9 +58653,9 @@ var init_schemas2 = __esm({
56830
58653
  const okeys = optionalKeys(def.shape);
56831
58654
  return {
56832
58655
  shape: def.shape,
56833
- keys,
56834
- keySet: new Set(keys),
56835
- numKeys: keys.length,
58656
+ keys: keys2,
58657
+ keySet: new Set(keys2),
58658
+ numKeys: keys2.length,
56836
58659
  optionalKeys: new Set(okeys)
56837
58660
  };
56838
58661
  });
@@ -59806,11 +61629,11 @@ var init_schemas4 = __esm({
59806
61629
  ZodType2.init(inst, def);
59807
61630
  inst.enum = def.entries;
59808
61631
  inst.options = Object.values(def.entries);
59809
- const keys = new Set(Object.keys(def.entries));
61632
+ const keys2 = new Set(Object.keys(def.entries));
59810
61633
  inst.extract = (values, params) => {
59811
61634
  const newEntries = {};
59812
61635
  for (const value of values) {
59813
- if (keys.has(value)) {
61636
+ if (keys2.has(value)) {
59814
61637
  newEntries[value] = def.entries[value];
59815
61638
  } else
59816
61639
  throw new Error(`Key ${value} not found in enum`);
@@ -59825,7 +61648,7 @@ var init_schemas4 = __esm({
59825
61648
  inst.exclude = (values, params) => {
59826
61649
  const newEntries = { ...def.entries };
59827
61650
  for (const value of values) {
59828
- if (keys.has(value)) {
61651
+ if (keys2.has(value)) {
59829
61652
  delete newEntries[value];
59830
61653
  } else
59831
61654
  throw new Error(`Key ${value} not found in enum`);
@@ -62365,7 +64188,7 @@ function parseMapDef(def, refs) {
62365
64188
  if (refs.mapStrategy === "record") {
62366
64189
  return parseRecordDef(def, refs);
62367
64190
  }
62368
- const keys = parseDef(def.keyType._def, {
64191
+ const keys2 = parseDef(def.keyType._def, {
62369
64192
  ...refs,
62370
64193
  currentPath: [...refs.currentPath, "items", "items", "0"]
62371
64194
  }) || parseAnyDef(refs);
@@ -62378,7 +64201,7 @@ function parseMapDef(def, refs) {
62378
64201
  maxItems: 125,
62379
64202
  items: {
62380
64203
  type: "array",
62381
- items: [keys, values],
64204
+ items: [keys2, values],
62382
64205
  minItems: 2,
62383
64206
  maxItems: 2
62384
64207
  }
@@ -66182,7 +68005,7 @@ var require_fast_deep_equal = __commonJS({
66182
68005
  if (a2 === b3) return true;
66183
68006
  if (a2 && b3 && typeof a2 == "object" && typeof b3 == "object") {
66184
68007
  if (a2.constructor !== b3.constructor) return false;
66185
- var length, i2, keys;
68008
+ var length, i2, keys2;
66186
68009
  if (Array.isArray(a2)) {
66187
68010
  length = a2.length;
66188
68011
  if (length != b3.length) return false;
@@ -66193,13 +68016,13 @@ var require_fast_deep_equal = __commonJS({
66193
68016
  if (a2.constructor === RegExp) return a2.source === b3.source && a2.flags === b3.flags;
66194
68017
  if (a2.valueOf !== Object.prototype.valueOf) return a2.valueOf() === b3.valueOf();
66195
68018
  if (a2.toString !== Object.prototype.toString) return a2.toString() === b3.toString();
66196
- keys = Object.keys(a2);
66197
- length = keys.length;
68019
+ keys2 = Object.keys(a2);
68020
+ length = keys2.length;
66198
68021
  if (length !== Object.keys(b3).length) return false;
66199
68022
  for (i2 = length; i2-- !== 0; )
66200
- if (!Object.prototype.hasOwnProperty.call(b3, keys[i2])) return false;
68023
+ if (!Object.prototype.hasOwnProperty.call(b3, keys2[i2])) return false;
66201
68024
  for (i2 = length; i2-- !== 0; ) {
66202
- var key = keys[i2];
68025
+ var key = keys2[i2];
66203
68026
  if (!equal(a2[key], b3[key])) return false;
66204
68027
  }
66205
68028
  return true;
@@ -72526,12 +74349,12 @@ var require_readShebang = __commonJS({
72526
74349
  var fs6 = __require("fs");
72527
74350
  var shebangCommand = require_shebang_command();
72528
74351
  function readShebang(command) {
72529
- const size = 150;
72530
- const buffer = Buffer.alloc(size);
74352
+ const size2 = 150;
74353
+ const buffer = Buffer.alloc(size2);
72531
74354
  let fd;
72532
74355
  try {
72533
74356
  fd = fs6.openSync(command, "r");
72534
- fs6.readSync(fd, buffer, 0, size, 0);
74357
+ fs6.readSync(fd, buffer, 0, size2, 0);
72535
74358
  fs6.closeSync(fd);
72536
74359
  } catch (e2) {
72537
74360
  }
@@ -73876,6 +75699,14 @@ function scanCondition(when, uses, aliases) {
73876
75699
  scanText(when.prompt, uses, aliases, true);
73877
75700
  return;
73878
75701
  }
75702
+ if (when.kind === "all") {
75703
+ for (const c2 of when.of) scanCondition(c2, uses, aliases);
75704
+ return;
75705
+ }
75706
+ if (when.kind === "before" || when.kind === "after") {
75707
+ scanText(when.other, uses, aliases, false);
75708
+ scanAlias(when.other, uses, aliases);
75709
+ }
73879
75710
  const emptiness = when.kind === "nonEmpty" || when.kind === "empty";
73880
75711
  const target = emptiness ? resolveList(when.ref, aliases) : null;
73881
75712
  if (target && target !== "results") {
@@ -74102,6 +75933,144 @@ var init_guard_relax = __esm({
74102
75933
  }
74103
75934
  });
74104
75935
 
75936
+ // ../runtime/src/decisions.ts
75937
+ function keyOf2(item, path36) {
75938
+ let value = item;
75939
+ for (const p3 of path36) {
75940
+ value = value !== null && typeof value === "object" ? value[p3] : void 0;
75941
+ }
75942
+ return value;
75943
+ }
75944
+ function choiceText(decide) {
75945
+ return [
75946
+ ...decide.actions.map((a2) => {
75947
+ const fields = Object.entries(a2.fields).map(([k3, t2]) => `${k3}: ${t2}`);
75948
+ return fields.length > 0 ? `${a2.tool} (${fields.join(", ")})` : a2.tool;
75949
+ }),
75950
+ "none"
75951
+ ].join(" | ");
75952
+ }
75953
+ function decisionPrompt(decide, items, as, ctx, order = items.map((_3, i2) => i2)) {
75954
+ const data = String(renderTemplate(decide.prompt, ctx));
75955
+ const keyName = decide.key.join(".");
75956
+ const details = decide.details ? detailsPerItem(
75957
+ items,
75958
+ ctx.steps[decide.details.step]?.results,
75959
+ decide.details.distinct
75960
+ ) : items.map(() => void 0);
75961
+ const list = order.map(
75962
+ (at3, i2) => `${i2 + 1}. ${keyText(keyOf2(items[at3], decide.key))}: ${JSON.stringify(items[at3])}` + (details[at3] !== void 0 ? ` details ${JSON.stringify(details[at3])}` : "")
75963
+ ).join("\n");
75964
+ const examples = decide.examples.map((e2) => JSON.stringify(e2)).join("\n");
75965
+ const sample = JSON.stringify({
75966
+ [keyName]: keyText(keyOf2(items[order[0] ?? 0], decide.key)),
75967
+ action: decide.actions[0].tool,
75968
+ ...Object.fromEntries(
75969
+ Object.entries(decide.actions[0].fields).map(([k3, t2]) => [
75970
+ k3,
75971
+ t2 === "number" ? 0 : "\u2026"
75972
+ ])
75973
+ )
75974
+ });
75975
+ return [
75976
+ data,
75977
+ `Decide what to do with each ${as} (by ${keyName}), in this order:
75978
+ ${list}`,
75979
+ `How the recorded run decided, on another day's data (each ${as}, its details when it had some, and what was done):
75980
+ ${examples}`,
75981
+ `Possible actions: ${choiceText(decide)}`,
75982
+ `Decide each one from its own data in this run, following the same rule as the recorded decisions. Give the values each action needs from this run's data, never from the examples. Reply with only a JSON list, one object per ${as} in the order above, like ${sample}. No other text.`
75983
+ ].join("\n\n");
75984
+ }
75985
+ function parseDecisions(text, items, decide) {
75986
+ const raw = text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
75987
+ let parsed;
75988
+ try {
75989
+ parsed = JSON.parse(raw.slice(raw.indexOf("["), raw.lastIndexOf("]") + 1));
75990
+ } catch {
75991
+ parsed = void 0;
75992
+ }
75993
+ if (!Array.isArray(parsed)) {
75994
+ return {
75995
+ ok: false,
75996
+ error: `the answer is not a JSON list: ${JSON.stringify(text.slice(0, 80))}`
75997
+ };
75998
+ }
75999
+ if (parsed.length !== items.length) {
76000
+ return {
76001
+ ok: false,
76002
+ error: `one decision per item: ${items.length} items, ${parsed.length} decision${parsed.length === 1 ? "" : "s"}`
76003
+ };
76004
+ }
76005
+ const keyName = decide.key.join(".");
76006
+ const allowed = [...decide.actions.map((a2) => a2.tool), "none"];
76007
+ const decisions = [];
76008
+ for (const [i2, entry] of parsed.entries()) {
76009
+ const want = keyText(keyOf2(items[i2], decide.key));
76010
+ if (entry === null || typeof entry !== "object") {
76011
+ return { ok: false, error: `decision ${i2 + 1} is not an object` };
76012
+ }
76013
+ const d2 = entry;
76014
+ const got = d2[keyName] ?? keyOf2(d2, decide.key);
76015
+ if (got !== void 0 && keyText(got) !== want) {
76016
+ return {
76017
+ ok: false,
76018
+ error: `decision ${i2 + 1} is for ${keyText(got)}, item ${i2 + 1} is ${want}`
76019
+ };
76020
+ }
76021
+ if (typeof d2.action !== "string" || !allowed.includes(d2.action)) {
76022
+ return {
76023
+ ok: false,
76024
+ error: `${want}: ${JSON.stringify(d2.action)} is not one of ${allowed.join(", ")}`
76025
+ };
76026
+ }
76027
+ const action = decide.actions.find((a2) => a2.tool === d2.action);
76028
+ for (const [field2, type] of Object.entries(action?.fields ?? {})) {
76029
+ const v3 = d2[field2];
76030
+ const ok = type === "number" ? typeof v3 === "number" && Number.isFinite(v3) : typeof v3 === "string" && v3.trim() !== "";
76031
+ if (!ok)
76032
+ return {
76033
+ ok: false,
76034
+ error: `${want}: ${d2.action} needs ${field2} (${type})`
76035
+ };
76036
+ }
76037
+ decisions.push(d2);
76038
+ }
76039
+ return { ok: true, decisions };
76040
+ }
76041
+ function decisionText(d2, decide) {
76042
+ const fields = Object.keys(
76043
+ decide.actions.find((a2) => a2.tool === d2.action)?.fields ?? {}
76044
+ );
76045
+ return fields.length > 0 ? `${d2.action} ${JSON.stringify(Object.fromEntries(fields.map((k3) => [k3, d2[k3]])))}` : d2.action;
76046
+ }
76047
+ function compareDecisions(a2, b3, items, decide) {
76048
+ const out = [];
76049
+ for (const [i2, item] of items.entries()) {
76050
+ const x3 = a2[i2];
76051
+ const y2 = b3[i2];
76052
+ const fields = decide.actions.find((t2) => t2.tool === x3.action)?.fields ?? {};
76053
+ const same3 = x3.action === y2.action && Object.entries(fields).every(
76054
+ ([k3, type]) => type === "number" ? sameNumber(x3[k3], y2[k3]) : sameText(x3[k3], y2[k3])
76055
+ );
76056
+ if (!same3)
76057
+ out.push(
76058
+ `${keyText(keyOf2(item, decide.key))}: ${decisionText(x3, decide)} vs ${decisionText(y2, decide)}`
76059
+ );
76060
+ }
76061
+ return out;
76062
+ }
76063
+ var keyText, sameText, sameNumber;
76064
+ var init_decisions = __esm({
76065
+ "../runtime/src/decisions.ts"() {
76066
+ "use strict";
76067
+ init_src();
76068
+ keyText = (v3) => typeof v3 === "string" ? v3 : JSON.stringify(v3);
76069
+ sameText = (a2, b3) => String(a2).trim().replace(/\s+/g, " ").toLowerCase() === String(b3).trim().replace(/\s+/g, " ").toLowerCase();
76070
+ sameNumber = (a2, b3) => typeof a2 === "number" && typeof b3 === "number" && Math.abs(a2 - b3) <= 1e-6 * Math.max(1, Math.abs(a2), Math.abs(b3));
76071
+ }
76072
+ });
76073
+
74105
76074
  // ../runtime/src/checks.ts
74106
76075
  function selectionMissing(entry, ctx, text) {
74107
76076
  if (!entry.select) return null;
@@ -74141,10 +76110,10 @@ function selectionHints(grounding, ctx) {
74141
76110
  if (!entry.select) continue;
74142
76111
  const items = selectedItems(entry.select, ctx);
74143
76112
  if (items === null) continue;
74144
- const keys = items.map((i2) => String(i2[entry.select.key]));
76113
+ const keys2 = items.map((i2) => String(i2[entry.select.key]));
74145
76114
  const rule = entry.select.rules.map(ruleText).join(" and ");
74146
76115
  out.push(
74147
- keys.length === 0 ? `No item of ${entry.select.list.replace(/^steps\./, "")} is selected today (${rule}): say so.` : `The items to report today are exactly: ${keys.join(", ")} (the ones with ${rule}).`
76116
+ keys2.length === 0 ? `No item of ${entry.select.list.replace(/^steps\./, "")} is selected today (${rule}): say so.` : `The items to report today are exactly: ${keys2.join(", ")} (the ones with ${rule}).`
74148
76117
  );
74149
76118
  }
74150
76119
  return out;
@@ -74161,9 +76130,16 @@ function figuresPrompt(figures) {
74161
76130
  return "These figures were calculated by code from the data above. Use them exactly as written, do not recalculate them, and do not leave any out:\n" + figures.map((f3) => ` ${f3.text}`).join("\n");
74162
76131
  }
74163
76132
  function figureProblems(figures, ctx, text) {
74164
- const missing = figures.filter(
74165
- (f3) => f3.time !== void 0 ? !statesTime(text, f3.time) : !statesFigure(text, f3.value)
74166
- ).map((f3) => f3.time ?? formatFigure(f3.value));
76133
+ const missing = [
76134
+ ...figures.filter(
76135
+ (f3) => f3.time !== void 0 ? !statesTime(text, f3.time) : !statesFigure(text, f3.value)
76136
+ ).map((f3) => f3.time ?? formatFigure(f3.value)),
76137
+ // a top figure is its item as much as its number ("Soylent (4100)")
76138
+ ...figures.filter(
76139
+ (f3) => f3.name !== void 0 && f3.value !== 0 && // "none": any wording of nothing will do
76140
+ !text.toLowerCase().includes(f3.name.toLowerCase())
76141
+ ).map((f3) => f3.name)
76142
+ ];
74167
76143
  const inData = /* @__PURE__ */ new Set();
74168
76144
  const visit = (n3) => {
74169
76145
  if (typeof n3 === "number") inData.add(Math.abs(n3));
@@ -74194,8 +76170,8 @@ function emptyLists(calcs, grounding, ctx) {
74194
76170
  for (const entry of grounding ?? []) {
74195
76171
  if (entry.select) continue;
74196
76172
  for (const p3 of entry.paths) {
74197
- const at2 = p3.indexOf(".*");
74198
- if (at2 > 0) refs.add(p3.slice(0, at2));
76173
+ const at3 = p3.indexOf(".*");
76174
+ if (at3 > 0) refs.add(p3.slice(0, at3));
74199
76175
  }
74200
76176
  }
74201
76177
  return [...refs].filter((ref) => {
@@ -74211,7 +76187,7 @@ ${example}`.toLowerCase();
74211
76187
  }
74212
76188
  function latestItemFacts(readsIds, ctx) {
74213
76189
  const out = [];
74214
- const visit = (node, at2, depth) => {
76190
+ const visit = (node, at3, depth) => {
74215
76191
  if (Array.isArray(node)) {
74216
76192
  if (node.length >= 2 && node.every(
74217
76193
  (i2) => i2 !== null && typeof i2 === "object" && !Array.isArray(i2)
@@ -74225,7 +76201,7 @@ function latestItemFacts(readsIds, ctx) {
74225
76201
  (best, i2) => dateMs(i2[field2]) >= dateMs(best[field2]) ? i2 : best
74226
76202
  );
74227
76203
  out.push(
74228
- `The latest item of ${at2.replace(/^steps\./, "")} (the newest by its "${field2}", whatever its position) is: ${JSON.stringify(newest)}. When you say what is the latest or current state, use this item.`
76204
+ `The latest item of ${at3.replace(/^steps\./, "")} (the newest by its "${field2}", whatever its position) is: ${JSON.stringify(newest)}. When you say what is the latest or current state, use this item.`
74229
76205
  );
74230
76206
  }
74231
76207
  }
@@ -74233,7 +76209,7 @@ function latestItemFacts(readsIds, ctx) {
74233
76209
  }
74234
76210
  if (node !== null && typeof node === "object" && depth < 4) {
74235
76211
  for (const [k3, v3] of Object.entries(node))
74236
- visit(v3, `${at2}.${k3}`, depth + 1);
76212
+ visit(v3, `${at3}.${k3}`, depth + 1);
74237
76213
  }
74238
76214
  };
74239
76215
  for (const id of readsIds) {
@@ -74252,16 +76228,33 @@ function stepsRead(prompt) {
74252
76228
  )
74253
76229
  ];
74254
76230
  }
74255
- var URL_RE, EMAIL_RE, TIME_FIELD, ISO_DATE, dateMs;
76231
+ function sentData(step, ctx, full) {
76232
+ if (!step.trim?.length || process.env.HOTPATH_TRIM === "0")
76233
+ return { data: full, trimmed: false };
76234
+ if ((step.calculations ?? []).some((c2) => computeFigures(c2, ctx) === null))
76235
+ return { data: full, trimmed: false };
76236
+ const ctx2 = trimData(ctx, step.trim);
76237
+ if (!ctx2) return { data: full, trimmed: false };
76238
+ return { data: String(renderTemplate(step.prompt, ctx2)), trimmed: true };
76239
+ }
76240
+ function inputGrowth(stepId, chars, recordedChars) {
76241
+ if (!recordedChars || chars < recordedChars * GROWTH) return null;
76242
+ if (chars - recordedChars < GROWTH_MIN_CHARS) return null;
76243
+ const times = (chars / recordedChars).toFixed(1);
76244
+ return `\u26A0 ${stepId}: today's data for the model is ${chars.toLocaleString("en-US")} characters, ${times}\xD7 the recording's ${recordedChars.toLocaleString("en-US")}, so this step costs about ${times}\xD7 as much. If the report only needs figures from it, record a run whose report states them, so code computes them and the data is left out`;
76245
+ }
76246
+ var URL_RE, EMAIL_RE, TIME_FIELD, ISO_DATE3, dateMs, GROWTH, GROWTH_MIN_CHARS;
74256
76247
  var init_checks4 = __esm({
74257
76248
  "../runtime/src/checks.ts"() {
74258
76249
  "use strict";
74259
76250
  init_src();
74260
- URL_RE = /\bhttps?:\/\/[^\s<>"'`)\]]+/gi;
76251
+ URL_RE = /\bhttps?:\/\/[^\s<>"'`)\])】」』,。、;:!?—–…]+/gi;
74261
76252
  EMAIL_RE = /\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b/g;
74262
76253
  TIME_FIELD = /^(at|date|time|timestamp|datetime|\w+_at|\w+_date|\w+_time)$/i;
74263
- ISO_DATE = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}.*)?$/;
74264
- dateMs = (v3) => typeof v3 === "string" && ISO_DATE.test(v3) && !Number.isNaN(Date.parse(v3)) ? Date.parse(v3) : null;
76254
+ ISO_DATE3 = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}.*)?$/;
76255
+ dateMs = (v3) => typeof v3 === "string" && ISO_DATE3.test(v3) && !Number.isNaN(Date.parse(v3)) ? Date.parse(v3) : null;
76256
+ GROWTH = 3;
76257
+ GROWTH_MIN_CHARS = 4e3;
74265
76258
  }
74266
76259
  });
74267
76260
 
@@ -74571,16 +76564,16 @@ var init_transport = __esm({
74571
76564
  }
74572
76565
  });
74573
76566
 
74574
- // ../../node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js
74575
- async function getRandomValues(size) {
74576
- return (await crypto3).getRandomValues(new Uint8Array(size));
76567
+ // ../../node_modules/.pnpm/pkce-challenge@5.0.2/node_modules/pkce-challenge/dist/index.node.js
76568
+ async function getRandomValues(size2) {
76569
+ return (await crypto3).getRandomValues(new Uint8Array(size2));
74577
76570
  }
74578
- async function random(size) {
76571
+ async function random(size2) {
74579
76572
  const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
74580
76573
  const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
74581
76574
  let result = "";
74582
- while (result.length < size) {
74583
- const randomBytes3 = await getRandomValues(size - result.length);
76575
+ while (result.length < size2) {
76576
+ const randomBytes3 = await getRandomValues(size2 - result.length);
74584
76577
  for (const randomByte of randomBytes3) {
74585
76578
  if (randomByte < evenDistCutoff) {
74586
76579
  result += mask[randomByte % mask.length];
@@ -74611,7 +76604,7 @@ async function pkceChallenge(length) {
74611
76604
  }
74612
76605
  var crypto3;
74613
76606
  var init_index_node = __esm({
74614
- "../../node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js"() {
76607
+ "../../node_modules/.pnpm/pkce-challenge@5.0.2/node_modules/pkce-challenge/dist/index.node.js"() {
74615
76608
  crypto3 = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL
74616
76609
  globalThis.crypto ?? // Node.js >18
74617
76610
  import("node:crypto").then((m3) => m3.webcrypto);
@@ -75089,26 +77082,26 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
75089
77082
  }
75090
77083
  const nonInteractiveFlow = !provider.redirectUrl;
75091
77084
  if (authorizationCode !== void 0 || nonInteractiveFlow) {
75092
- const tokens2 = await fetchToken(provider, authorizationServerUrl, {
77085
+ const tokens3 = await fetchToken(provider, authorizationServerUrl, {
75093
77086
  metadata,
75094
77087
  resource,
75095
77088
  authorizationCode,
75096
77089
  fetchFn
75097
77090
  });
75098
77091
  await bindClientInformation();
75099
- await provider.saveTokens({ ...tokens2, issuer });
77092
+ await provider.saveTokens({ ...tokens3, issuer });
75100
77093
  return "AUTHORIZED";
75101
77094
  }
75102
- const tokens = discardIfIssuerMismatch(await provider.tokens(), issuer);
75103
- if (tokens?.refresh_token && tokens.issuer == null) {
77095
+ const tokens2 = discardIfIssuerMismatch(await provider.tokens(), issuer);
77096
+ if (tokens2?.refresh_token && tokens2.issuer == null) {
75104
77097
  console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged.");
75105
77098
  }
75106
- if (tokens?.refresh_token) {
77099
+ if (tokens2?.refresh_token) {
75107
77100
  try {
75108
77101
  const newTokens = await refreshAuthorization(authorizationServerUrl, {
75109
77102
  metadata,
75110
77103
  clientInformation,
75111
- refreshToken: tokens.refresh_token,
77104
+ refreshToken: tokens2.refresh_token,
75112
77105
  resource,
75113
77106
  addClientAuthentication: provider.addClientAuthentication,
75114
77107
  fetchFn
@@ -75414,7 +77407,7 @@ async function refreshAuthorization(authorizationServerUrl, { metadata, clientIn
75414
77407
  grant_type: "refresh_token",
75415
77408
  refresh_token: refreshToken
75416
77409
  });
75417
- const tokens = await executeTokenRequest(authorizationServerUrl, {
77410
+ const tokens2 = await executeTokenRequest(authorizationServerUrl, {
75418
77411
  metadata,
75419
77412
  tokenRequestParams,
75420
77413
  clientInformation,
@@ -75422,7 +77415,7 @@ async function refreshAuthorization(authorizationServerUrl, { metadata, clientIn
75422
77415
  resource,
75423
77416
  fetchFn
75424
77417
  });
75425
- return { refresh_token: refreshToken, ...tokens };
77418
+ return { refresh_token: refreshToken, ...tokens2 };
75426
77419
  }
75427
77420
  async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
75428
77421
  const readClientInformation = async () => {
@@ -75786,9 +77779,9 @@ var init_streamableHttp = __esm({
75786
77779
  async _commonHeaders() {
75787
77780
  const headers = {};
75788
77781
  if (this._authProvider) {
75789
- const tokens = await this._authProvider.tokens();
75790
- if (tokens) {
75791
- headers["Authorization"] = `Bearer ${tokens.access_token}`;
77782
+ const tokens2 = await this._authProvider.tokens();
77783
+ if (tokens2) {
77784
+ headers["Authorization"] = `Bearer ${tokens2.access_token}`;
75792
77785
  }
75793
77786
  }
75794
77787
  if (this._sessionId) {
@@ -76407,6 +78400,7 @@ function toolServerEnv(env) {
76407
78400
  }
76408
78401
  async function runTask(task, options) {
76409
78402
  const workflow = await loadWorkflow(task);
78403
+ if (!options.dryRun) assertConfirmed(workflow);
76410
78404
  try {
76411
78405
  return await runWorkflow(workflow, options);
76412
78406
  } catch (err) {
@@ -76450,7 +78444,14 @@ async function fallback(workflow, options, drift) {
76450
78444
  const agentDurationMs = Date.now() - agentStart;
76451
78445
  const agent = await readAgentRun(agentStart);
76452
78446
  const agentCostUsd = agent.costUsd;
76453
- const { workflow: next } = await compileTaskInMemory(task);
78447
+ const { workflow: compiled } = await compileTaskInMemory(task, void 0, {
78448
+ readOnly: true
78449
+ });
78450
+ const next = {
78451
+ ...compiled,
78452
+ confirmed: workflow.confirmed,
78453
+ readOnly: workflow.readOnly
78454
+ };
76454
78455
  const lostReads = lostReadOnlySteps(workflow, next);
76455
78456
  const lostActs = lostActions(workflow, next);
76456
78457
  const lostFacts = lostGrounding(workflow, next);
@@ -76580,6 +78581,16 @@ async function readAgentRun(since) {
76580
78581
  }
76581
78582
  }
76582
78583
  async function runWorkflow(workflow, options) {
78584
+ const positional = workflow.positional?.[0];
78585
+ if (positional) {
78586
+ const reason = `${positional.steps.join(", ")} act on items of ${positional.list} by position (item 1, item 2\u2026), which a new day's list has in other places: the agent does this task instead. Record it again so the compiler sees one action per item.`;
78587
+ throw new DriftError(
78588
+ positional.steps[0],
78589
+ reason,
78590
+ false,
78591
+ idleMetrics(positional.steps[0], reason)
78592
+ );
78593
+ }
76583
78594
  const missing = Object.entries(workflow.inputs).filter(
76584
78595
  ([name, def]) => def.required !== false && !(name in options.inputs)
76585
78596
  );
@@ -76638,6 +78649,8 @@ pass them as --input key=value`
76638
78649
  const reuse = options.reuse ?? process.env.HOTPATH_REUSE !== "0";
76639
78650
  const reusedSteps = [];
76640
78651
  const filledSteps = [];
78652
+ const trimmedSteps = [];
78653
+ const inputWarnings = [];
76641
78654
  const answers = reuse ? await loadAnswers(workflow.task) : {};
76642
78655
  const modelAnswers = [];
76643
78656
  const firstAttemptIssues = [];
@@ -76669,6 +78682,8 @@ pass them as --input key=value`
76669
78682
  ...repairedSteps.length > 0 ? { repairedSteps } : {},
76670
78683
  ...reusedSteps.length > 0 ? { reusedSteps } : {},
76671
78684
  ...filledSteps.length > 0 ? { filledSteps } : {},
78685
+ ...trimmedSteps.length > 0 ? { trimmedSteps } : {},
78686
+ ...inputWarnings.length > 0 ? { inputWarnings } : {},
76672
78687
  ...resumedActions.length > 0 ? { resumedActions } : {},
76673
78688
  ...firstAttemptIssues.length > 0 ? { firstAttemptIssues } : {},
76674
78689
  // opt-in: the text a guard rejected can hold customer data
@@ -76801,6 +78816,112 @@ pass them as --input key=value`
76801
78816
  }
76802
78817
  return answer === true;
76803
78818
  };
78819
+ const decideItems = async (spec, items, as) => {
78820
+ const details = spec.details ? detailsPerItem(
78821
+ items,
78822
+ ctx.steps[spec.details.step]?.results,
78823
+ spec.details.distinct
78824
+ ) : items.map(() => void 0);
78825
+ const keyOf3 = (it2) => String(
78826
+ spec.key.reduce(
78827
+ (n3, k3) => n3 !== null && typeof n3 === "object" ? n3[k3] : void 0,
78828
+ it2
78829
+ )
78830
+ );
78831
+ const byCode = items.map(() => null);
78832
+ const gaps = [];
78833
+ items.forEach((it2, i2) => {
78834
+ if (spec.bands) {
78835
+ const d2 = bandDecision(spec.bands, it2, details[i2]);
78836
+ if (d2) byCode[i2] = d2;
78837
+ const v3 = inOpenGap(spec.bands, it2, details[i2]);
78838
+ if (v3 !== null)
78839
+ gaps.push(`${keyOf3(it2)}: ${spec.bands.path.join(".")} ${v3}`);
78840
+ } else if (spec.table) {
78841
+ const a2 = tableDecision(spec.table, it2, details[i2]);
78842
+ if ("decision" in a2) byCode[i2] = a2.decision;
78843
+ else if ("gap" in a2) gaps.push(`${keyOf3(it2)}: ${a2.gap}`);
78844
+ }
78845
+ });
78846
+ const rulebook = spec.bands ? `the recorded bands (${bandsText(spec.bands)})` : `the recorded rules (${spec.table ? tableSize(spec.table) : 0} cases)`;
78847
+ if (gaps.length > 0) {
78848
+ return drift(
78849
+ `${gaps.length} ${as}${gaps.length === 1 ? "" : "s"} (${gaps.slice(0, 3).join("; ")}) fall between bands the recording never closed, in ${rulebook}: the agent decides, and its recording closes the gap`
78850
+ );
78851
+ }
78852
+ if ((spec.bands || spec.table) && byCode.every((d2) => d2 !== null)) {
78853
+ const decided = byCode;
78854
+ const counts2 = /* @__PURE__ */ new Map();
78855
+ for (const d2 of decided) {
78856
+ const v3 = spec.bands ? String(d2[spec.bands.field]) : d2.action;
78857
+ counts2.set(v3, (counts2.get(v3) ?? 0) + 1);
78858
+ }
78859
+ console.log(
78860
+ `\u25C7 ${step.id}: decided per ${as} by ${rulebook}: ` + [...counts2].map(([v3, n3]) => `${v3} \xD7${n3}`).join(", ")
78861
+ );
78862
+ return decided;
78863
+ }
78864
+ const byBands = byCode;
78865
+ const withBands = (ds) => ds.map((d2, i2) => byBands[i2] ?? d2);
78866
+ const first = withBands(await askDecisions(spec, items, as));
78867
+ if (process.env.HOTPATH_DECIDE_TWICE !== "0" && items.length > 0) {
78868
+ const order = items.map((_3, i2) => items.length - 1 - i2);
78869
+ const reversed = await askDecisions(spec, items, as, order);
78870
+ const second = withBands(
78871
+ order.map((_3, i2) => reversed[order.indexOf(i2)])
78872
+ );
78873
+ const differ = compareDecisions(first, second, items, spec);
78874
+ if (differ.length > 0) {
78875
+ return drift(
78876
+ `the replay model gave two different answers for ${differ.length} of ${items.length} ${as}${items.length === 1 ? "" : "s"} (${differ.slice(0, 3).join("; ")}${differ.length > 3 ? "; \u2026" : ""}): not sure enough to act, so the agent decides (HOTPATH_DECIDE_TWICE=0 asks once)`
78877
+ );
78878
+ }
78879
+ }
78880
+ const counts = /* @__PURE__ */ new Map();
78881
+ for (const d2 of first)
78882
+ counts.set(d2.action, (counts.get(d2.action) ?? 0) + 1);
78883
+ console.log(
78884
+ `\u25C7 ${step.id}: decided per ${as}: ${[...counts].map(([a2, n3]) => `${a2} \xD7${n3}`).join(", ")}`
78885
+ );
78886
+ return first;
78887
+ };
78888
+ const askDecisions = async (spec, items, as, order) => {
78889
+ const listed = order ? order.map((i2) => items[i2]) : items;
78890
+ const prompt = decisionPrompt(spec, items, as, ctx, order);
78891
+ let question = prompt;
78892
+ let error2 = "";
78893
+ for (let attempt = 0; attempt < 2; attempt++) {
78894
+ const result = await chat({
78895
+ model: CHEAP_MODEL,
78896
+ messages: [{ role: "user", content: question }],
78897
+ reasoningEffort: cheapReasoning(),
78898
+ maxTokens: cheapMaxTokens()
78899
+ });
78900
+ llmCalls += result.llmCalls;
78901
+ promptTokens += result.promptTokens;
78902
+ completionTokens += result.completionTokens;
78903
+ llmCostUsd += usdCost(
78904
+ CHEAP_MODEL,
78905
+ result.promptTokens,
78906
+ result.completionTokens
78907
+ );
78908
+ stepWaitMs += result.rateLimitWaitMs ?? 0;
78909
+ rateLimitWaitMs += result.rateLimitWaitMs ?? 0;
78910
+ modelAnswers.push(result.text ?? "");
78911
+ if (result.truncated) {
78912
+ await drift(
78913
+ `llm stopped at the ${cheapMaxTokens()}-token cap (HOTPATH_CHEAP_MAX_TOKENS) while deciding per ${as}`
78914
+ );
78915
+ }
78916
+ const parsed = parseDecisions(result.text ?? "", listed, spec);
78917
+ if (parsed.ok) return parsed.decisions;
78918
+ error2 = parsed.error;
78919
+ question = `${prompt}
78920
+
78921
+ Your previous answer could not be used: ${error2}. Answer again, exactly in the format asked.`;
78922
+ }
78923
+ return drift(`could not decide per ${as}: ${error2}`);
78924
+ };
76804
78925
  if (step.when) {
76805
78926
  if (!await decide(step.when)) {
76806
78927
  steps.push({
@@ -76857,10 +78978,21 @@ ${changed.map((n3) => ctx.inputs[n3]).join("\n")}` : dataPrompt
76857
78978
  return;
76858
78979
  }
76859
78980
  const layout = step.layout && process.env.HOTPATH_LAYOUT !== "0" ? step.layout : void 0;
76860
- const askedData = step.selective ? dataPrompt.replace(
78981
+ const sent = sentData(step, ctx, dataPrompt);
78982
+ if (sent.trimmed) trimmedSteps.push(step.id);
78983
+ const growth = inputGrowth(step.id, sent.data.length, step.inputChars);
78984
+ if (growth) {
78985
+ console.log(growth);
78986
+ inputWarnings.push({
78987
+ step: step.id,
78988
+ chars: sent.data.length,
78989
+ recordedChars: step.inputChars
78990
+ });
78991
+ }
78992
+ const askedData = step.selective ? sent.data.replace(
76861
78993
  "and cover every item in it.",
76862
78994
  "and work out the figures from it. " + SELECTIVE_NOTE
76863
- ) : dataPrompt;
78995
+ ) : sent.data;
76864
78996
  const requestTail = request.length > 0 ? `
76865
78997
 
76866
78998
  Today's request:
@@ -76976,7 +79108,7 @@ Use only the data above. Keep it to about ${lineCount(step.example)} lines.${req
76976
79108
  }
76977
79109
  let text = await ask(prompt);
76978
79110
  const todayItems = countItems(
76979
- Object.values(ctx.steps).map((s3) => s3.result)
79111
+ Object.values(ctx.steps).map((s3) => s3.result ?? s3.results)
76980
79112
  );
76981
79113
  let failure2 = checkLlmGuard(step.guard, text, todayItems);
76982
79114
  if (failure2) await drift(failure2);
@@ -77054,14 +79186,44 @@ Also: ${missing2.join("; ")}.`;
77054
79186
  }
77055
79187
  const all = list;
77056
79188
  if (all.length > step.maxItems) {
77057
- console.log(
77058
- `\u26A0 ${step.id}: ${all.length} items, running the first ${step.maxItems} (maxItems)`
79189
+ const rules = step.body.every(
79190
+ (b3) => b3.when !== void 0 && !conditionAsks(b3.when)
77059
79191
  );
79192
+ const picked = rules && !step.decide ? all.filter((item) => {
79193
+ const scoped = {
79194
+ ...ctx,
79195
+ vars: { ...ctx.vars, [step.as]: item }
79196
+ };
79197
+ return step.body.some(
79198
+ (b3) => checkCondition(b3.when, scoped) === true
79199
+ );
79200
+ }).length : all.length;
79201
+ if (picked > step.maxItems) {
79202
+ await drift(
79203
+ `${step.id}: ${picked} items to act on, more than maxItems (${step.maxItems}); the agent does it (raise maxItems in the workflow file to allow more)`
79204
+ );
79205
+ }
77060
79206
  }
77061
- const items = all.slice(0, step.maxItems);
79207
+ const items = all;
79208
+ const decisions = step.decide && items.length > 0 ? await decideItems(step.decide, items, step.as) : null;
77062
79209
  const results = [];
79210
+ const seen = [];
77063
79211
  for (const [i2, item] of items.entries()) {
77064
- ctx.vars = { ...ctx.vars, [step.as]: item };
79212
+ if (step.distinct) {
79213
+ const value = JSON.stringify(
79214
+ step.distinct.reduce(
79215
+ (v3, k3) => v3 !== null && typeof v3 === "object" ? v3[k3] : void 0,
79216
+ item
79217
+ )
79218
+ );
79219
+ if (seen.includes(value)) continue;
79220
+ seen.push(value);
79221
+ }
79222
+ ctx.vars = {
79223
+ ...ctx.vars,
79224
+ [step.as]: item,
79225
+ ...decisions ? { choice: decisions[i2] } : {}
79226
+ };
77065
79227
  let acted = false;
77066
79228
  for (const body of step.body) {
77067
79229
  if (body.when && !await decide(body.when)) continue;
@@ -77075,8 +79237,11 @@ Also: ${missing2.join("; ")}.`;
77075
79237
  const last = step.body[step.body.length - 1];
77076
79238
  if (acted) results.push(ctx.steps[last.id]?.result);
77077
79239
  }
77078
- if (ctx.vars) delete ctx.vars[step.as];
77079
- ctx.steps[step.id] = { results };
79240
+ if (ctx.vars) {
79241
+ delete ctx.vars[step.as];
79242
+ delete ctx.vars.choice;
79243
+ }
79244
+ ctx.steps[step.id] = { results: decisions ?? results };
77080
79245
  record2(true);
77081
79246
  return;
77082
79247
  }
@@ -77129,11 +79294,27 @@ function checkToolGuard(guard, value) {
77129
79294
  const where = error2?.instancePath ? `result${error2.instancePath}` : "result";
77130
79295
  return `${where} ${error2?.message ?? "does not match the recorded schema"}`;
77131
79296
  }
79297
+ function conditionAsks(when) {
79298
+ return when.kind === "ask";
79299
+ }
77132
79300
  function checkCondition(when, ctx) {
77133
79301
  if (when.kind === "ask") return null;
79302
+ if (when.kind === "all")
79303
+ return when.of.every((c2) => checkCondition(c2, ctx) === true);
77134
79304
  const value = lookupReference(when.ref, ctx);
79305
+ if (when.kind === "before" || when.kind === "after") {
79306
+ const other = lookupReference(when.other, ctx);
79307
+ const iso = (v3) => typeof v3 === "string" && /^\d{4}-\d{2}-\d{2}/.test(v3);
79308
+ if (!iso(value) || !iso(other)) return false;
79309
+ const [a2, b3] = [value.slice(0, 10), other.slice(0, 10)];
79310
+ return when.kind === "before" ? a2 < b3 : a2 > b3;
79311
+ }
77135
79312
  if (when.kind === "equals") return value === when.value;
77136
79313
  if (when.kind === "notEquals") return value !== when.value;
79314
+ if (when.kind === "above")
79315
+ return typeof value === "number" && value > when.value;
79316
+ if (when.kind === "below")
79317
+ return typeof value === "number" && value < when.value;
77137
79318
  const empty = value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0 || typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
77138
79319
  return when.kind === "empty" ? empty : !empty;
77139
79320
  }
@@ -77147,6 +79328,16 @@ function conditionText(when) {
77147
79328
  return `${when.ref} is not ${JSON.stringify(when.value)}`;
77148
79329
  case "notEquals":
77149
79330
  return `${when.ref} is ${JSON.stringify(when.value)}`;
79331
+ case "above":
79332
+ return `${when.ref} is not above ${when.value}`;
79333
+ case "below":
79334
+ return `${when.ref} is not below ${when.value}`;
79335
+ case "before":
79336
+ return `${when.ref} is not before ${when.other}`;
79337
+ case "after":
79338
+ return `${when.ref} is not after ${when.other}`;
79339
+ case "all":
79340
+ return `not all of: ${when.of.map(whenText).join(" and ")}`;
77150
79341
  case "ask":
77151
79342
  return `the model said no to: ${when.question}`;
77152
79343
  }
@@ -77219,10 +79410,10 @@ function checkGrounding(grounding, ctx, text) {
77219
79410
  return missing;
77220
79411
  }
77221
79412
  function expandWildcards(path36, ctx) {
77222
- const at2 = path36.indexOf(".*");
77223
- if (at2 < 0) return [path36];
77224
- const prefix = path36.slice(0, at2);
77225
- const rest = path36.slice(at2 + 2);
79413
+ const at3 = path36.indexOf(".*");
79414
+ if (at3 < 0) return [path36];
79415
+ const prefix = path36.slice(0, at3);
79416
+ const rest = path36.slice(at3 + 2);
77226
79417
  const list = lookupReference(prefix, ctx);
77227
79418
  if (!Array.isArray(list)) return [];
77228
79419
  return list.flatMap((_3, i2) => expandWildcards(`${prefix}.${i2}${rest}`, ctx));
@@ -77288,7 +79479,7 @@ function splitCommand(cmd) {
77288
79479
  function isPageRecord(v3) {
77289
79480
  return v3 !== null && typeof v3 === "object" && !Array.isArray(v3);
77290
79481
  }
77291
- var import_ajv3, import_cross_spawn2, repoRoot2, outDir, IN_PROCESS_SERVER, HOTPATH_SECRETS, DriftError, INPUT_NAME_RE, MAX_ANSWERS, answersFile, REPLY_ONLY, ajv, SELECTIVE_NOTE;
79482
+ var import_ajv3, import_cross_spawn2, repoRoot2, outDir, IN_PROCESS_SERVER, HOTPATH_SECRETS, DriftError, INPUT_NAME_RE, idleMetrics, MAX_ANSWERS, answersFile, REPLY_ONLY, ajv, SELECTIVE_NOTE;
77292
79483
  var init_runtime = __esm({
77293
79484
  "../runtime/src/runtime.ts"() {
77294
79485
  "use strict";
@@ -77299,6 +79490,7 @@ var init_runtime = __esm({
77299
79490
  import_cross_spawn2 = __toESM(require_cross_spawn(), 1);
77300
79491
  init_src2();
77301
79492
  init_src();
79493
+ init_decisions();
77302
79494
  init_checks4();
77303
79495
  init_journal();
77304
79496
  init_tool_backends();
@@ -77325,6 +79517,22 @@ var init_runtime = __esm({
77325
79517
  metrics;
77326
79518
  };
77327
79519
  INPUT_NAME_RE = /^[A-Za-z_][A-Za-z0-9_-]*$/;
79520
+ idleMetrics = (driftStep, reason) => ({
79521
+ durationMs: 0,
79522
+ llmCalls: 0,
79523
+ promptTokens: 0,
79524
+ completionTokens: 0,
79525
+ costUsd: 0,
79526
+ fallback: false,
79527
+ steps: [],
79528
+ connectMs: 0,
79529
+ toolMs: 0,
79530
+ llmMs: 0,
79531
+ rateLimitWaitMs: 0,
79532
+ toolCalls: [],
79533
+ driftStep,
79534
+ reason
79535
+ });
77328
79536
  MAX_ANSWERS = 50;
77329
79537
  answersFile = (task) => path11.join(repoRoot2, ".hotpath", "answers", `${assertTaskName(task)}.json`);
77330
79538
  REPLY_ONLY = "Reply with the text only: no introduction, no code fences, no notes about the text.";
@@ -79314,7 +81522,7 @@ var init_package = __esm({
79314
81522
  "../../package.json"() {
79315
81523
  package_default = {
79316
81524
  name: "hotpath",
79317
- version: "0.3.1",
81525
+ version: "0.4.0",
79318
81526
  description: "Record your AI agent once. Replay it faster and cheaper, with AI only where judgment is needed.",
79319
81527
  license: "Apache-2.0",
79320
81528
  repository: {
@@ -79424,9 +81632,9 @@ async function readLastCheck(dir) {
79424
81632
  return null;
79425
81633
  }
79426
81634
  }
79427
- async function writeLastCheck(dir, at2) {
81635
+ async function writeLastCheck(dir, at3) {
79428
81636
  await mkdir9(dir, { recursive: true, mode: 448 });
79429
- await writeFile8(checkFile(dir), JSON.stringify({ at: at2 }) + "\n", {
81637
+ await writeFile8(checkFile(dir), JSON.stringify({ at: at3 }) + "\n", {
79430
81638
  mode: 384
79431
81639
  });
79432
81640
  }
@@ -80192,8 +82400,8 @@ function compileCandidate(group, options = {}) {
80192
82400
  fromRuns: traces.length
80193
82401
  };
80194
82402
  }
80195
- function pick2(from, keys) {
80196
- return Object.fromEntries(Object.entries(from).filter(([k3]) => k3 in keys));
82403
+ function pick2(from, keys2) {
82404
+ return Object.fromEntries(Object.entries(from).filter(([k3]) => k3 in keys2));
80197
82405
  }
80198
82406
  async function shadowCheck(workflow, run, inputs) {
80199
82407
  const readOnly = (tool) => run.meta.tools.find((t2) => t2.name === tool)?.annotations?.readOnlyHint === true;
@@ -80336,7 +82544,7 @@ async function readCandidate(dirs, id) {
80336
82544
  return void 0;
80337
82545
  }
80338
82546
  }
80339
- async function learn(dirs, options = {}) {
82547
+ async function learn2(dirs, options = {}) {
80340
82548
  const hotAfter = options.hotAfter ?? DEFAULT_HOT_AFTER;
80341
82549
  const { runs, skipped } = await readRuns2(dirs.tracesDir);
80342
82550
  const fileOf = new Map(runs.map((r2) => [r2.trace, r2.file]));
@@ -83000,7 +85208,7 @@ function addDemoCommand(program2, afterCommand) {
83000
85208
  if (done === runs) {
83001
85209
  console.log("\nStep 2 of 3: hotpath learn (no model call)");
83002
85210
  }
83003
- const report = await learn(dirs, { hotAfter: runs, auto: true });
85211
+ const report = await learn2(dirs, { hotAfter: runs, auto: true });
83004
85212
  id = report.promoted[0] ?? report.paths.find((p3) => p3.live)?.id;
83005
85213
  if (id || done >= MAX_RUNS) {
83006
85214
  console.log(formatLearnReport(report));
@@ -83125,7 +85333,7 @@ run it with: hotpath run ${options.promote} --input <name>=<value>`
83125
85333
  const hotAfter = options.hotAfter ? parseHotAfter(options.hotAfter) : await configuredHotAfter(
83126
85334
  path26.join(repoRoot5, "hotpath.config.json")
83127
85335
  );
83128
- const report = await learn(dirs, { hotAfter, auto: options.auto });
85336
+ const report = await learn2(dirs, { hotAfter, auto: options.auto });
83129
85337
  console.log(formatLearnReport(report));
83130
85338
  await afterCommand();
83131
85339
  } catch (err) {
@@ -84016,10 +86224,10 @@ function apiKeyOf(req) {
84016
86224
  }
84017
86225
  async function readBody(req) {
84018
86226
  const chunks = [];
84019
- let size = 0;
86227
+ let size2 = 0;
84020
86228
  for await (const chunk of req) {
84021
- size += chunk.length;
84022
- if (size > MAX_BODY_BYTES) {
86229
+ size2 += chunk.length;
86230
+ if (size2 > MAX_BODY_BYTES) {
84023
86231
  throw new ProxyError(
84024
86232
  `request body over ${MAX_BODY_BYTES / 1024 / 1024} MB`
84025
86233
  );
@@ -84897,6 +87105,10 @@ function conditionShape(when) {
84897
87105
  if (when.kind === "ask") {
84898
87106
  return { kind: "ask", reads: when.prompt.match(TEMPLATE_RE2) ?? [] };
84899
87107
  }
87108
+ if (when.kind === "all")
87109
+ return { kind: "all", of: when.of.map(conditionShape) };
87110
+ if (when.kind === "before" || when.kind === "after")
87111
+ return { kind: when.kind, ref: when.ref, other: when.other };
84900
87112
  return "value" in when ? { kind: when.kind, ref: when.ref, value: redact2(when.value) } : { kind: when.kind, ref: when.ref };
84901
87113
  }
84902
87114
  function toolShape(step) {
@@ -86378,9 +88590,9 @@ var require_stringify = __commonJS({
86378
88590
  stack.push(value2);
86379
88591
  let stepback = indent;
86380
88592
  indent = indent + gap;
86381
- let keys = propertyList || Object.keys(value2);
88593
+ let keys2 = propertyList || Object.keys(value2);
86382
88594
  let partial2 = [];
86383
- for (const key of keys) {
88595
+ for (const key of keys2) {
86384
88596
  const propertyString = serializeProperty(key, value2);
86385
88597
  if (propertyString !== void 0) {
86386
88598
  let member = serializeKey(key) + ":";
@@ -86532,9 +88744,9 @@ var init_json_file = __esm({
86532
88744
  import { isDeepStrictEqual as isDeepStrictEqual5 } from "node:util";
86533
88745
  import os6 from "node:os";
86534
88746
  import path32 from "node:path";
86535
- function servers(data, ...keys) {
88747
+ function servers(data, ...keys2) {
86536
88748
  let node = data;
86537
- for (const key of keys) {
88749
+ for (const key of keys2) {
86538
88750
  if (typeof node !== "object" || node === null) return void 0;
86539
88751
  node = node[key];
86540
88752
  }
@@ -86640,8 +88852,8 @@ async function openClaudeCodeConfig(name, options) {
86640
88852
  if (project)
86641
88853
  places.push({ scope: "project", json: project, keys: ["mcpServers"] });
86642
88854
  if (user) places.push({ scope: "user", json: user, keys: ["mcpServers"] });
86643
- const candidates2 = options.scope ? places.filter((p3) => p3.scope === options.scope) : places;
86644
- const place = candidates2.find((p3) => entryOf(servers(p3.json.data, ...p3.keys), name)) ?? candidates2[0];
88855
+ const candidates3 = options.scope ? places.filter((p3) => p3.scope === options.scope) : places;
88856
+ const place = candidates3.find((p3) => entryOf(servers(p3.json.data, ...p3.keys), name)) ?? candidates3[0];
86645
88857
  if (!place) {
86646
88858
  throw new WrapError(
86647
88859
  `no Claude Code config found (looked for ${userFile}${options.config ? "" : ` and ${projectFile}`})`
@@ -86659,7 +88871,7 @@ async function openClaudeCodeConfig(name, options) {
86659
88871
  cwd,
86660
88872
  names: () => [
86661
88873
  ...new Set(
86662
- candidates2.flatMap(
88874
+ candidates3.flatMap(
86663
88875
  (p3) => Object.keys(servers(p3.json.data, ...p3.keys) ?? {})
86664
88876
  )
86665
88877
  )
@@ -86669,16 +88881,16 @@ async function openClaudeCodeConfig(name, options) {
86669
88881
  reloadHint: "Restart Claude Code (or start a new session) so it reconnects to the server."
86670
88882
  };
86671
88883
  }
86672
- async function writeServer(original, keys, name, entry) {
88884
+ async function writeServer(original, keys2, name, entry) {
86673
88885
  const fresh = await readJsonFile(original.file);
86674
88886
  if (!fresh.strict) {
86675
88887
  throw new WrapError(
86676
88888
  `${fresh.file} is no longer plain JSON; refusing to rewrite it`
86677
88889
  );
86678
88890
  }
86679
- const map = servers(fresh.data, ...keys);
88891
+ const map = servers(fresh.data, ...keys2);
86680
88892
  if (!map)
86681
- throw new WrapError(`${fresh.file} no longer has ${keys.join(".")}`);
88893
+ throw new WrapError(`${fresh.file} no longer has ${keys2.join(".")}`);
86682
88894
  map[name] = entry;
86683
88895
  await writeFileAtomic(fresh.file, stringifyLike(fresh.data, fresh.text));
86684
88896
  }
@@ -87483,10 +89695,14 @@ First steps:
87483
89695
  ).option(
87484
89696
  "--strict",
87485
89697
  "refuse a recording that has a warning: write nothing and exit 1 (then record the task again)"
89698
+ ).option("--yes", "confirm the recording without asking (CI, scripts)").option(
89699
+ "--read-only",
89700
+ "the task only reads: accept a recording with no action (kept by later compiles)"
87486
89701
  ).action(
87487
89702
  (task, options2) => guarded(async () => {
87488
89703
  const compiled = await compileTaskInMemory(task, options2.trace, {
87489
- require: options2.require
89704
+ require: options2.require,
89705
+ readOnly: options2.readOnly
87490
89706
  });
87491
89707
  const { workflow, notes } = compiled;
87492
89708
  const replayed = await verifyOnRecording(
@@ -87507,9 +89723,27 @@ First steps:
87507
89723
  console.log(formatCompileResult(workflow));
87508
89724
  for (const note of notes) console.log(`+ ${note}`);
87509
89725
  for (const warning of warnings) console.log(`\u26A0 ${warning}`);
89726
+ console.log(`
89727
+ ${formatRecordingSummary(workflow)}`);
89728
+ const ok = options2.yes || process.stdin.isTTY && await confirm("\nis this right? [y/N] ");
89729
+ if (ok) {
89730
+ await confirmWorkflow(task);
89731
+ console.log(`confirmed "${task}": it can now replay`);
89732
+ } else {
89733
+ console.log(
89734
+ `not confirmed: "${task}" will not replay until you run: hotpath confirm ${task}`
89735
+ );
89736
+ }
87510
89737
  await afterCommand();
87511
89738
  })
87512
89739
  );
89740
+ program2.command("confirm").description("Confirm a compiled workflow so it may replay").argument("<task>", "task name").action(
89741
+ (task) => guarded(async () => {
89742
+ const workflow = await confirmWorkflow(task);
89743
+ console.log(formatRecordingSummary(workflow));
89744
+ console.log(`confirmed "${task}": it can now replay`);
89745
+ })
89746
+ );
87513
89747
  program2.command("show").description("Show a workflow as a readable list of steps").argument("<task>", "task name").action(async (task) => {
87514
89748
  console.log(formatWorkflow(await loadWorkflow(task)));
87515
89749
  });