@ancha-labs/cli 0.3.0 → 0.4.1

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/lib/worker.mjs CHANGED
@@ -29816,6 +29816,8 @@ var init_schema2 = __esm({
29816
29816
  allow_unwrapped: external_exports.literal(true).optional(),
29817
29817
  /** Changes something (a refund, an email): an unrecorded call is never answered by invention unless set to simulate. */
29818
29818
  write: external_exports.boolean().optional(),
29819
+ /** Only computes from its arguments (a calculator): a call production never made runs the tool itself, for real. */
29820
+ pure: external_exports.literal(true).optional(),
29819
29821
  description: external_exports.string().optional(),
29820
29822
  schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
29821
29823
  });
@@ -38359,6 +38361,7 @@ function toolIssues(scene2) {
38359
38361
  else if (!scene2.twins.includes(tool.twin)) issues.push({ path: `${path6}.twin`, message: `twin ${tool.twin} is not listed in twins`, hint: `add ${tool.twin} to twins, e.g. twins: [${tool.twin}]` });
38360
38362
  }
38361
38363
  if (tool.unrecorded === "twin" && tool.twin === void 0) issues.push({ path: `${path6}.unrecorded`, message: "unrecorded: twin needs the twin that answers", hint: `set ${path6}.twin, e.g. twin: slack` });
38364
+ if (tool.pure && tool.write) issues.push({ path: `${path6}.pure`, message: "a tool that changes something is not pure", hint: `remove ${path6}.pure, or ${path6}.write if it only computes from its arguments` });
38362
38365
  if (tool.observations !== void 0 && tool.recorded === void 0) {
38363
38366
  issues.push({ path: `${path6}.observations`, message: `${tool.observations} was not read`, hint: "load the scene from its file (ancha run, ancha scene validate), which reads the recorded calls next to it" });
38364
38367
  }
@@ -102909,7 +102912,7 @@ var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
102909
102912
  function isLeapYear(year) {
102910
102913
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
102911
102914
  }
102912
- const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
102915
+ const DATE2 = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
102913
102916
  const DAYS2 = [
102914
102917
  0,
102915
102918
  31,
@@ -102926,7 +102929,7 @@ var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
102926
102929
  31
102927
102930
  ];
102928
102931
  function date10(str3) {
102929
- const matches7 = DATE.exec(str3);
102932
+ const matches7 = DATE2.exec(str3);
102930
102933
  if (!matches7) return false;
102931
102934
  const year = +matches7[1];
102932
102935
  const month = +matches7[2];
@@ -118089,7 +118092,7 @@ function readWorldSnapshot(bytes2) {
118089
118092
  init_src();
118090
118093
 
118091
118094
  // packages/server/src/agent-tools/simulate.ts
118092
- var SYSTEM = `You stand in for one tool of an AI agent's application, in a test made from a production trace. Production recorded some calls to this tool. Answer the new call exactly as the real tool would at this point: consistent with what production recorded and with the writes the agent already made in this test, in the same shape as production's results (the same top-level fields, with values of the same types). The call happens at time.now: a time the tool reports for this call (when a reading was taken, when something was posted) is time.now. When time has passed since production's last answer, answer as the tool would by then: what changes over time (a status, a measurement) moves on the way the recorded answers, the writes and the tool's calls in other production runs imply; those runs' times are already on this run's timeline. Invent nothing the tool would not know. If the real tool would fail on this call (an unknown id, invalid arguments), answer with its error instead. Reply with JSON: {"result_json": "<the result as a JSON string>"} or {"error": "<the error message>"}.`;
118095
+ var SYSTEM = `You stand in for one tool of an AI agent's application, in a test made from a production trace. Production recorded some calls to this tool. Answer the new call exactly as the real tool would at this point: consistent with what production recorded, with the calls the agent already made in this test and their answers (calls_in_this_test, writes included), and with the records that mention this call's values (records_that_mention_these_values: what other tools answered about the same thing), in the same shape as production's results (the same top-level fields, with values of the same types). The call happens at time.now: a time the tool reports for this call (when a reading was taken, when something was posted) is time.now. When time has passed since production's last answer, answer as the tool would by then: what changes over time (a status, a measurement) moves on the way the recorded answers, the writes and the tool's calls in other production runs imply; those runs' times are already on this run's timeline. Invent nothing the tool would not know. If the real tool would fail on this call (an unknown id, invalid arguments), answer with its error instead. Reply with JSON: {"result_json": "<the result as a JSON string>"} or {"error": "<the error message>"}.`;
118093
118096
  var SCHEMA5 = { name: "tool_answer", schema: { type: "object", additionalProperties: false, properties: { result_json: { type: "string" }, error: { type: "string" } } } };
118094
118097
  function shape(value4) {
118095
118098
  if (Array.isArray(value4)) return `[${value4.length ? shape(value4[0]) : ""}]`;
@@ -118111,12 +118114,15 @@ function sameShape(result, recorded2) {
118111
118114
  async function simulate(model, request2, signal) {
118112
118115
  const recorded2 = (request2.tool?.recorded ?? []).map((o) => ({ args: o.args, at: o.at, ...o.error !== void 0 ? { error: o.error } : { result: o.result } }));
118113
118116
  const results = recorded2.filter((o) => "result" in o).map((o) => o.result);
118117
+ const known2 = results.length ? results : (request2.tool?.examples ?? []).filter((o) => o.error === void 0 && o.result !== void 0).map((o) => o.result);
118118
+ const text21 = known2.length > 0 && known2.every((r) => typeof r === "string");
118114
118119
  const user8 = JSON.stringify({
118115
118120
  tool: { name: request2.name, ...request2.tool?.description && { description: request2.tool.description }, ...request2.tool?.schema && { arguments: request2.tool.schema }, ...request2.tool?.write && { changes_something: true } },
118116
118121
  production_recorded: recorded2.slice(-20),
118117
118122
  ...request2.tool?.examples?.length && { other_production_runs_of_this_agent: request2.tool.examples.slice(-30) },
118118
- ...results.length && { result_shape: shape(results[0]) },
118119
- writes_in_this_test: request2.writes.slice(-20),
118123
+ ...known2.length && { result_shape: shape(known2[0]) },
118124
+ calls_in_this_test: request2.calls.slice(-30),
118125
+ ...request2.records?.length && { records_that_mention_these_values: request2.records },
118120
118126
  call: { arguments: request2.args, ...request2.repeat && { production_made_this_exact_call: request2.repeat.recorded, this_is_call_number: request2.repeat.call } },
118121
118127
  // Time moves on as the agent waits: a status read later may say what a real one would say by then.
118122
118128
  ...request2.time && { time: {
@@ -118124,7 +118130,7 @@ async function simulate(model, request2, signal) {
118124
118130
  ...request2.time.now_ms > request2.time.last_recorded_ms && { seconds_since_productions_last_answer: Math.round((request2.time.now_ms - request2.time.last_recorded_ms) / 1e3) }
118125
118131
  } }
118126
118132
  });
118127
- let inputTokens = 0, outputTokens = 0, costUsd = 0, model_, feedback = "";
118133
+ let inputTokens = 0, outputTokens = 0, costUsd = 0, model_, feedback = "", last = "";
118128
118134
  for (let attempt = 0; attempt < 2; attempt++) {
118129
118135
  const answer = await model.complete({ kind: "simulate", person: request2.name, system: SYSTEM, user: feedback ? `${user8}
118130
118136
 
@@ -118134,18 +118140,23 @@ ${feedback}` : user8, schema: SCHEMA5, temperature: 0, maxTokens: 1200 }, signal
118134
118140
  costUsd += answer.costUsd;
118135
118141
  model_ = answer.model;
118136
118142
  const out = answer.output;
118143
+ last = JSON.stringify(out ?? null).slice(0, 200);
118137
118144
  if (typeof out?.error === "string" && out.error && out.result_json === void 0) return { error: out.error, inputTokens, outputTokens, costUsd, model: model_ };
118138
118145
  let result;
118139
118146
  try {
118140
118147
  result = JSON.parse(String(out?.result_json));
118141
118148
  } catch {
118142
- feedback = "Your result_json was not valid JSON. Answer again.";
118143
- continue;
118149
+ if (!text21 || typeof out?.result_json !== "string") {
118150
+ feedback = "Your result_json was not valid JSON. Answer again.";
118151
+ continue;
118152
+ }
118153
+ result = out.result_json;
118144
118154
  }
118145
- if (sameShape(result, results)) return { result, inputTokens, outputTokens, costUsd, model: model_ };
118146
- feedback = `Your result has the shape ${shape(result)}, but production's results have the shape ${shape(results[0])}. Answer again in that shape.`;
118155
+ if (text21 && typeof result !== "string" && typeof out?.result_json === "string") result = out.result_json;
118156
+ if (sameShape(result, known2)) return { result, inputTokens, outputTokens, costUsd, model: model_ };
118157
+ feedback = `Your result has the shape ${shape(result)}, but production's results have the shape ${shape(known2[0])}. Answer again in that shape.`;
118147
118158
  }
118148
- throw new PeopleModelError(`the simulated answer to ${request2.name} did not have the shape of production's results`);
118159
+ throw new PeopleModelError(`the simulated answer to ${request2.name} did not have the shape of production's results (the model's last answer: ${last})`);
118149
118160
  }
118150
118161
 
118151
118162
  // packages/server/src/agent-tools/index.ts
@@ -118174,6 +118185,29 @@ var getState = (ctx, k) => ctx.store.db.prepare("SELECT v FROM agent_tool_state
118174
118185
  var setState = (ctx, k, v) => ctx.store.db.prepare("INSERT INTO agent_tool_state (k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v=excluded.v").run(k, v);
118175
118186
  var SIMULATION_LIMIT = () => Number(process.env.ANCHA_SIMULATE_MAX ?? 30);
118176
118187
  var simulationOn = (ctx) => process.env.ANCHA_SIMULATE !== "0" && ctx.model !== void 0;
118188
+ var ID_LIKE = /^(?=.*[\d@])[A-Za-z0-9][\w.:@#/+-]{3,63}$/;
118189
+ var DATE = /^\d{4}-\d{2}-\d{2}/;
118190
+ function idValues(value4, out = /* @__PURE__ */ new Set()) {
118191
+ if (Array.isArray(value4)) for (const v of value4) idValues(v, out);
118192
+ else if (value4 && typeof value4 === "object") for (const v of Object.values(value4)) idValues(v, out);
118193
+ else if ((typeof value4 === "string" || typeof value4 === "number" && Number.isInteger(value4)) && ID_LIKE.test(String(value4)) && !DATE.test(String(value4))) out.add(String(value4));
118194
+ return out;
118195
+ }
118196
+ var RECORDS_SHOWN = 20;
118197
+ function recordsMentioning(ctx, name5, args) {
118198
+ const ids2 = [...idValues(args)].map((id12) => new RegExp(`(^|[^A-Za-z0-9])${id12.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}([^A-Za-z0-9]|$)`));
118199
+ if (!ids2.length) return [];
118200
+ const records2 = [];
118201
+ const add = (tool, o, here) => {
118202
+ const answer = o.error !== void 0 ? { error: o.error } : { result: o.result };
118203
+ const text21 = JSON.stringify([o.args, answer]);
118204
+ if (ids2.some((id12) => id12.test(text21))) records2.push({ tool, args: o.args ?? {}, ...answer, conversation: here ? "this one" : o.trace ?? "another" });
118205
+ };
118206
+ const others = Object.entries(ctx.scene.tools ?? {}).filter(([tool]) => tool !== name5);
118207
+ for (const [tool] of others) for (const o of recorded(ctx, tool)) add(tool, o, true);
118208
+ for (const [tool, t] of others) for (const o of [...t.examples ?? []].reverse()) add(tool, o, false);
118209
+ return records2.slice(0, RECORDS_SHOWN);
118210
+ }
118177
118211
  function keepUp(ctx) {
118178
118212
  const behind = withRead(ctx, () => Number(getState(ctx, "reached") ?? 0)) - ctx.clock.elapsedMs();
118179
118213
  if (behind > 0) ctx.clock.advance(behind);
@@ -118201,13 +118235,19 @@ function decide(ctx, name5, args) {
118201
118235
  setState(ctx, "reached", String(Math.max(reached, o.endMs)));
118202
118236
  return o.error !== void 0 ? { source: "replayed", error: o.error, ...o.raw !== void 0 && { raw: o.raw, wrap: o.wrap } } : { source: "replayed", result: o.result, ...o.raw !== void 0 && { raw: o.raw, wrap: o.wrap } };
118203
118237
  }
118238
+ if (!same2.length && !tool?.write) {
118239
+ const elsewhere = [...tool?.examples ?? []].reverse().find((o) => o.error === void 0 && o.result !== void 0 && canonical2(o.args) === key3);
118240
+ if (elsewhere) return { source: "replayed-elsewhere", result: elsewhere.result };
118241
+ }
118204
118242
  if (tool?.twin !== void 0 || policy === "twin") return { source: "twin", passthrough: true };
118243
+ if (tool?.pure) return { source: "ran", passthrough: true };
118205
118244
  const repeat = same2.length ? { recorded: same2.length, call: n + 1 } : void 0;
118206
118245
  const last = same2.at(-1) ?? recorded(ctx, name5).at(-1), took = last ? last.endMs - last.atMs : 0;
118207
118246
  if (policy === "simulate" && simulationOn(ctx)) {
118208
118247
  if (Number(getState(ctx, "simulated") ?? 0) >= SIMULATION_LIMIT()) return { source: "failed", error: `Ancha has no recorded answer for this call, and this test reached its limit of ${SIMULATION_LIMIT()} simulated answers` };
118209
118248
  const lastRecordedMs = Math.max(0, ...recorded(ctx, name5).map((o) => o.endMs));
118210
- return { simulate: { name: name5, tool, args, ...repeat && { repeat }, time: { now_ms: Math.max(reached, ctx.clock.elapsedMs()), last_recorded_ms: lastRecordedMs, start: ctx.scene.start_time } }, cacheKey: callKey, reached, took };
118249
+ const records2 = recordsMentioning(ctx, name5, args);
118250
+ return { simulate: { name: name5, tool, args, ...repeat && { repeat }, ...records2.length && { records: records2 }, time: { now_ms: Math.max(reached, ctx.clock.elapsedMs()), last_recorded_ms: lastRecordedMs, start: ctx.scene.start_time } }, cacheKey: callKey, reached, took };
118211
118251
  }
118212
118252
  if (repeat && !tool?.write) {
118213
118253
  const o = same2.at(-1);
@@ -118217,14 +118257,14 @@ function decide(ctx, name5, args) {
118217
118257
  const unsimulated = policy === "simulate" && !simulationOn(ctx) ? process.env.ANCHA_SIMULATE === "0" ? "; simulation is off (ANCHA_SIMULATE=0)" : "; there is no model to simulate one with (set OPENROUTER_API_KEY)" : "";
118218
118258
  return { source: "failed", error: `Ancha has no recorded answer for this call: ${why}${unsimulated}` };
118219
118259
  }
118220
- function noteWrite(ctx, name5, args, a) {
118221
- if (!ctx.scene.tools?.[name5]?.write || a.passthrough) return;
118222
- const writes2 = JSON.parse(getState(ctx, "writes") ?? "[]");
118223
- writes2.push({ tool: name5, args, ...a.error !== void 0 ? { error: a.error } : { result: a.result } });
118224
- setState(ctx, "writes", JSON.stringify(writes2.slice(-50)));
118260
+ function noteCall(ctx, name5, args, a) {
118261
+ if (a.passthrough) return;
118262
+ const calls2 = JSON.parse(getState(ctx, "calls") ?? "[]");
118263
+ calls2.push({ tool: name5, args, ...ctx.scene.tools?.[name5]?.write && { changes_something: true }, ...a.error !== void 0 ? { error: a.error } : { result: a.result } });
118264
+ setState(ctx, "calls", JSON.stringify(calls2.slice(-50)));
118225
118265
  }
118226
118266
  function toolsToWrap(ctx) {
118227
- return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => t.twin === void 0 && !t.mcp && !t.allow_unwrapped).map(([name5]) => name5).sort();
118267
+ return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => t.twin === void 0 && !t.mcp && !t.pure && !t.allow_unwrapped).map(([name5]) => name5).sort();
118228
118268
  }
118229
118269
  function registration(ctx, names3) {
118230
118270
  const before = JSON.parse(getState(ctx, "wrapped") ?? "[]");
@@ -118272,14 +118312,14 @@ function agentToolsService() {
118272
118312
  const ctx = c.env.ctx, args = body6.args ?? {};
118273
118313
  const decision2 = withMutation(ctx, () => decide(ctx, name5, args));
118274
118314
  if (!("simulate" in decision2)) {
118275
- withMutation(ctx, () => noteWrite(ctx, name5, args, decision2));
118315
+ withMutation(ctx, () => noteCall(ctx, name5, args, decision2));
118276
118316
  keepUp(ctx);
118277
118317
  return c.json(decision2);
118278
118318
  }
118279
118319
  let answered;
118280
118320
  try {
118281
- const writes2 = withRead(ctx, () => JSON.parse(getState(ctx, "writes") ?? "[]"));
118282
- const sim = await simulate(ctx.model, { ...decision2.simulate, writes: writes2 }, c.req.raw.signal);
118321
+ const calls2 = withRead(ctx, () => JSON.parse(getState(ctx, "calls") ?? "[]"));
118322
+ const sim = await simulate(ctx.model, { ...decision2.simulate, calls: calls2 }, c.req.raw.signal);
118283
118323
  answered = { source: "simulated", ...sim.error !== void 0 ? { error: sim.error } : { result: sim.result }, cost_usd: Math.round(sim.costUsd * 1e6) / 1e6 };
118284
118324
  } catch (error63) {
118285
118325
  answered = { source: "failed", error: `Ancha has no recorded answer for this call and could not simulate one: ${error63 instanceof Error ? error63.message : String(error63)}` };
@@ -118291,11 +118331,11 @@ function agentToolsService() {
118291
118331
  setState(ctx, `sim:${decision2.cacheKey}`, JSON.stringify({ answer: { ...answered, cost_usd: void 0 }, reached: now10 }));
118292
118332
  setState(ctx, "simulated", String(Number(getState(ctx, "simulated") ?? 0) + 1));
118293
118333
  }
118294
- noteWrite(ctx, name5, args, answered);
118334
+ noteCall(ctx, name5, args, answered);
118295
118335
  return answered;
118296
118336
  });
118297
118337
  keepUp(ctx);
118298
- return c.json(answer);
118338
+ return answer.source === "failed" ? c.json(answer, 200, { [SETUP_ISSUE_HEADER]: "1" }) : c.json(answer);
118299
118339
  });
118300
118340
  app2.all("*", (c) => c.json({ error: `not a route of Ancha's tool service: ${c.req.method} ${new URL(c.req.url).pathname}` }, 404));
118301
118341
  return {
@@ -147576,7 +147616,7 @@ function credentials29(ctx) {
147576
147616
  var iso11 = (ms) => ms === null ? null : new Date(ms).toISOString();
147577
147617
  function dumpState29(ctx) {
147578
147618
  const people3 = users2(ctx), name5 = (id12) => id12 === null ? null : people3.find((u) => u.account_id === id12)?.name ?? null;
147579
- const issues = rows5(ctx, "jira_issues"), keyOf = (id12) => issues.find((i) => i.id === id12)?.key ?? null;
147619
+ const issues = rows5(ctx, "jira_issues"), keyOf2 = (id12) => issues.find((i) => i.id === id12)?.key ?? null;
147580
147620
  const sprints = rows5(ctx, "jira_sprints");
147581
147621
  return {
147582
147622
  site: `${site(ctx).name}.atlassian.net`,
@@ -147596,7 +147636,7 @@ function dumpState29(ctx) {
147596
147636
  assignee: name5(i.assignee),
147597
147637
  reporter: name5(i.reporter),
147598
147638
  labels: i.labels,
147599
- parent: i.parent_id === null ? null : keyOf(i.parent_id),
147639
+ parent: i.parent_id === null ? null : keyOf2(i.parent_id),
147600
147640
  sprints: i.sprint_ids.map((id12) => sprints.find((s) => s.id === id12)?.name),
147601
147641
  story_points: i.story_points,
147602
147642
  due: i.due,
@@ -147606,7 +147646,7 @@ function dumpState29(ctx) {
147606
147646
  watchers: i.watchers.map(name5),
147607
147647
  links: links(ctx).filter((l) => l.outward === i.id || l.inward === i.id).map((l) => {
147608
147648
  const t = LINK_TYPES.find((x) => x.name === l.type);
147609
- return l.outward === i.id ? `${t.outward} ${keyOf(l.inward)}` : `${t.inward} ${keyOf(l.outward)}`;
147649
+ return l.outward === i.id ? `${t.outward} ${keyOf2(l.inward)}` : `${t.inward} ${keyOf2(l.outward)}`;
147610
147650
  }),
147611
147651
  comments: rows5(ctx, "jira_comments", "WHERE issue_id = ?", i.id).map((c) => ({ author: name5(c.author), body: adfToText(c.body), created: iso11(c.created_ms) }))
147612
147652
  }))
@@ -150508,7 +150548,7 @@ function paginate7(call2, key3, items, render, sideload = () => ({})) {
150508
150548
  var PRIORITY_RANK = { low: 1, normal: 2, high: 3, urgent: 4 };
150509
150549
  function sortTickets(ctx, tickets, field4, descending) {
150510
150550
  const name5 = (id12) => id12 === null ? "" : getUser7(ctx, id12)?.name ?? "";
150511
- const keyOf = {
150551
+ const keyOf2 = {
150512
150552
  id: (ticket2) => ticket2.id,
150513
150553
  created_at: (ticket2) => ticket2.created_ms,
150514
150554
  updated_at: (ticket2) => ticket2.updated_ms,
@@ -150522,7 +150562,7 @@ function sortTickets(ctx, tickets, field4, descending) {
150522
150562
  group: (ticket2) => ticket2.group_id ?? 0,
150523
150563
  ticket_type: (ticket2) => ticket2.type ?? ""
150524
150564
  };
150525
- const key3 = keyOf[field4];
150565
+ const key3 = keyOf2[field4];
150526
150566
  if (!key3) throw badRequest(`cannot sort by ${field4}`);
150527
150567
  return [...tickets].sort((a, b) => {
150528
150568
  const x = key3(a), y = key3(b);
@@ -161002,6 +161042,68 @@ function sceneFingerprint(scene2) {
161002
161042
  return createHash51("sha256").update(JSON.stringify(canonical5(scene2))).digest("hex");
161003
161043
  }
161004
161044
 
161045
+ // backend/src/actions.ts
161046
+ var writeTools = (scene2) => new Set(Object.entries(scene2.tools ?? {}).filter(([, tool]) => tool.write).map(([name5]) => name5));
161047
+ function actionsOf(scene2, trace) {
161048
+ const writes2 = writeTools(scene2);
161049
+ return trace.flatMap((entry3) => {
161050
+ if (entry3.service !== "tools" || entry3.source !== "agent" || !entry3.path.startsWith("/tools/")) return [];
161051
+ const tool = decodeURIComponent(entry3.path.slice("/tools/".length));
161052
+ if (!writes2.has(tool)) return [];
161053
+ const response5 = entry3.response ?? {};
161054
+ return [{ tool, args: entry3.request?.args ?? {}, source: typeof response5.source === "string" ? response5.source : "unknown", ...typeof response5.error === "string" && { error: response5.error } }];
161055
+ });
161056
+ }
161057
+ function answersOf(trace) {
161058
+ const answers = {};
161059
+ for (const entry3 of trace) {
161060
+ if (entry3.service !== "tools" || entry3.source !== "agent" || !entry3.path.startsWith("/tools/")) continue;
161061
+ const source = entry3.response?.source;
161062
+ if (typeof source === "string") answers[source] = (answers[source] ?? 0) + 1;
161063
+ }
161064
+ return answers;
161065
+ }
161066
+ function answerCounts(trials) {
161067
+ const counted2 = trials.filter((trial) => trial.answers !== void 0);
161068
+ if (!counted2.length) return void 0;
161069
+ const bySource = {};
161070
+ for (const trial of counted2) for (const [source, n] of Object.entries(trial.answers)) bySource[source] = (bySource[source] ?? 0) + n;
161071
+ return { of: counted2.length, simulatedIn: counted2.filter((trial) => (trial.answers.simulated ?? 0) > 0).length, bySource };
161072
+ }
161073
+ function canonicalJson2(value4) {
161074
+ if (Array.isArray(value4)) return `[${value4.map(canonicalJson2).join(",")}]`;
161075
+ if (value4 && typeof value4 === "object") return `{${Object.keys(value4).sort().map((key3) => `${JSON.stringify(key3)}:${canonicalJson2(value4[key3])}`).join(",")}}`;
161076
+ return JSON.stringify(value4 ?? null);
161077
+ }
161078
+ var keyOf = (action) => `${action.tool} ${canonicalJson2(action.args)}`;
161079
+ function actionCounts(trials) {
161080
+ const counted2 = trials.filter((trial) => trial.actions !== void 0);
161081
+ if (!counted2.length) return void 0;
161082
+ const made = /* @__PURE__ */ new Map();
161083
+ for (const trial of counted2) {
161084
+ for (const key3 of new Set(trial.actions.map(keyOf))) {
161085
+ const action = trial.actions.find((a) => keyOf(a) === key3);
161086
+ const entry3 = made.get(key3) ?? { tool: action.tool, args: action.args, trials: 0 };
161087
+ entry3.trials++;
161088
+ made.set(key3, entry3);
161089
+ }
161090
+ }
161091
+ return { of: counted2.length, made: [...made.values()].sort((a, b) => b.trials - a.trials || a.tool.localeCompare(b.tool)) };
161092
+ }
161093
+ function actionChanges(before, after) {
161094
+ if (!before?.of || !after?.of) return [];
161095
+ const was = new Map(before.made.map((a) => [keyOf(a), a])), now10 = new Map(after.made.map((a) => [keyOf(a), a]));
161096
+ const share = (c) => c.trials / c.of;
161097
+ return [.../* @__PURE__ */ new Set([...was.keys(), ...now10.keys()])].map((key3) => {
161098
+ const action = now10.get(key3) ?? was.get(key3);
161099
+ return { tool: action.tool, args: action.args, before: { trials: was.get(key3)?.trials ?? 0, of: before.of }, after: { trials: now10.get(key3)?.trials ?? 0, of: after.of } };
161100
+ }).filter((c) => c.before.trials * c.after.of !== c.after.trials * c.before.of).sort((a, b) => Math.abs(share(b.after) - share(b.before)) - Math.abs(share(a.after) - share(a.before)) || a.tool.localeCompare(b.tool));
161101
+ }
161102
+ function actionLabel(action) {
161103
+ const args = canonicalJson2(action.args);
161104
+ return `${action.tool} ${args.length > 120 ? `${args.slice(0, 117)}...` : args}`;
161105
+ }
161106
+
161005
161107
  // backend/src/report.ts
161006
161108
  init_src();
161007
161109
  var MAX_FAILURES_PER_SCENE = 20;
@@ -161053,7 +161155,7 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
161053
161155
  if (harnessIssues.length < MAX_FAILURES_PER_SCENE) harnessIssues.push({ ...issue5, sceneId, trial: t.trial });
161054
161156
  }
161055
161157
  if (!t.passed && t.exit !== "invalid" && !exitedCleanly(t) && agentIssues.length < MAX_FAILURES_PER_SCENE) {
161056
- agentIssues.push({ sceneId, trial: t.trial, exit: t.exit, exitCode: t.exitCode, realMs: t.realMs, log: join6(t.dir, "agent.log"), logTail: t.logTail });
161158
+ agentIssues.push({ sceneId, trial: t.trial, exit: t.exit, exitCode: t.exitCode, realMs: t.realMs, log: join6(t.dir, "agent.log"), logTail: t.logTail, ...t.invocations !== void 0 && { invocations: t.invocations } });
161057
161159
  }
161058
161160
  for (const c of t.checks) {
161059
161161
  const tally = checks[c.id] ??= { passed: 0, total: 0, required: c.required };
@@ -161089,6 +161191,7 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
161089
161191
  }
161090
161192
  }
161091
161193
  const passed = counts.passed;
161194
+ const actions = actionCounts(trials.filter(trialValid)), answers = answerCounts(trials.filter(trialValid));
161092
161195
  return {
161093
161196
  sceneId,
161094
161197
  counts,
@@ -161106,6 +161209,8 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
161106
161209
  coverageGaps: [...gaps2.values()],
161107
161210
  meanRealMs: trials.length === 0 ? 0 : Math.round(totalMs / trials.length),
161108
161211
  agentCalls: agentCalls2,
161212
+ ...actions !== void 0 && { actions },
161213
+ ...answers !== void 0 && { answers },
161109
161214
  trialsDetail: trials.map((t) => ({ trial: t.trial, passed: outcomeOf2(t) === "passed", valid: trialValid(t), ...outcomeOf2(t) === "skipped" ? { outcome: "skipped" } : t.outcome ? { outcome: t.outcome } : {}, ...t.checks.some((c) => c.status === "skipped") && { skippedJudges: t.checks.filter((c) => c.status === "skipped").length }, exit: t.exit, exitCode: t.exitCode, realMs: t.realMs, ...t.simMs !== void 0 && { simMs: t.simMs }, ...t.playOut !== void 0 && { playOut: t.playOut }, ...t.sessionId !== void 0 && { sessionId: t.sessionId }, dir: t.dir }))
161110
161215
  };
161111
161216
  }
@@ -161159,6 +161264,8 @@ function formatRateDelta(value4) {
161159
161264
  return `${value4 > 0 ? "+" : value4 < 0 ? "-" : ""}${rounded === 0 && magnitude > 0 ? magnitude.toPrecision(3) : rounded} pp`;
161160
161265
  }
161161
161266
  var SUMMARY_GAPS_SHOWN = 10;
161267
+ var SUMMARY_ACTIONS_SHOWN = 8;
161268
+ var ANSWER_SOURCES = [["replayed", "replayed"], ["replayed-elsewhere", "replayed from another conversation"], ["twin", "by twins"], ["ran", "ran the tool itself"], ["simulated", "simulated"], ["failed", "failed"]];
161162
161269
  var duration8 = (ms) => ms < 1e3 ? `${ms}ms` : `${(ms / 1e3).toFixed(1)}s`;
161163
161270
  function howItEnded(i) {
161164
161271
  switch (i.exit) {
@@ -161166,8 +161273,10 @@ function howItEnded(i) {
161166
161273
  return `timed out after ${duration8(i.realMs)} and was killed`;
161167
161274
  case "spawn_failed":
161168
161275
  return i.exitCode === null ? "could not be started" : `failed to start (exit code ${i.exitCode})`;
161169
- default:
161170
- return i.exitCode === null ? `was killed by a signal after ${duration8(i.realMs)}` : `exited with code ${i.exitCode} after ${duration8(i.realMs)}`;
161276
+ default: {
161277
+ const when11 = i.invocations?.failed ? `on ${i.invocations.failed} of ${i.invocations.total} events` : `after ${duration8(i.realMs)}`;
161278
+ return i.exitCode === null ? `was killed by a signal ${when11}` : `exited with code ${i.exitCode} ${when11}`;
161279
+ }
161171
161280
  }
161172
161281
  }
161173
161282
  var shellWord = (dir) => /^[\w./@%+=:,-]+$/.test(dir) ? dir : `'${dir.replaceAll("'", `'\\''`)}'`;
@@ -161212,6 +161321,17 @@ function renderSummaryText(s, opts = {}) {
161212
161321
  if (scene2.coverageGaps.length > SUMMARY_GAPS_SHOWN) {
161213
161322
  lines.push(` \u2026 ${scene2.coverageGaps.length - SUMMARY_GAPS_SHOWN} more coverage gap(s)`);
161214
161323
  }
161324
+ if (scene2.answers !== void 0) {
161325
+ const { of, simulatedIn, bySource } = scene2.answers;
161326
+ const named3 = ANSWER_SOURCES.filter(([source]) => bySource[source]).map(([source, label5]) => `${bySource[source]} ${label5}`);
161327
+ if (named3.length) lines.push(` tool answers: ${named3.join(", ")}; ${simulatedIn}/${of} verdicts rest on simulated answers`);
161328
+ }
161329
+ if (scene2.actions !== void 0) {
161330
+ const { of, made } = scene2.actions, trials = `${of} valid ${of === 1 ? "trial" : "trials"}`;
161331
+ lines.push(made.length ? ` writes, in how many of ${trials}:` : ` writes: none in ${trials}`);
161332
+ for (const action of made.slice(0, SUMMARY_ACTIONS_SHOWN)) lines.push(` ${action.trials}/${of} ${actionLabel(action)}`);
161333
+ if (made.length > SUMMARY_ACTIONS_SHOWN) lines.push(` \u2026 ${made.length - SUMMARY_ACTIONS_SHOWN} more`);
161334
+ }
161215
161335
  }
161216
161336
  lines.push("");
161217
161337
  if (s.comparison !== void 0) {
@@ -161221,6 +161341,8 @@ function renderSummaryText(s, opts = {}) {
161221
161341
  for (const scene2 of s.comparison.scenes) {
161222
161342
  lines.push(` ${scene2.sceneId}: ${pct(scene2.before)}% \u2192 ${pct(scene2.after)}% (${formatRateDelta(scene2.delta)})${scene2.beforeTrials === void 0 || scene2.afterTrials === void 0 ? "" : `; ${scene2.beforeTrials} \u2192 ${scene2.afterTrials} trials`}`);
161223
161343
  for (const check3 of (scene2.checks ?? []).filter((c) => c.delta > 0 || !c.required)) lines.push(` ${check3.delta > 0 ? "improved" : "optional, dropped"}: ${check3.check} ${counts(check3)}`);
161344
+ for (const action of (scene2.actions ?? []).slice(0, SUMMARY_ACTIONS_SHOWN)) lines.push(` write: ${actionLabel(action)} ${action.before.trials}/${action.before.of} \u2192 ${action.after.trials}/${action.after.of} trials`);
161345
+ if ((scene2.actions ?? []).length > SUMMARY_ACTIONS_SHOWN) lines.push(` \u2026 ${scene2.actions.length - SUMMARY_ACTIONS_SHOWN} more changed writes`);
161224
161346
  }
161225
161347
  }
161226
161348
  lines.push(`${s.pytest && !s.pytest.graded && !s.pytest.invalid ? s.pytest.outcome + " (ungraded)" : s.verdict} (minimum pass rate ${pct(s.minPassRate)}%) run ${s.runId}`);
@@ -161535,7 +161657,7 @@ async function reproductionOf(summary, scenePaths, cwd, runDir) {
161535
161657
  return here === void 0 ? [] : [{ check: check3, production: result, failed: here.total - here.passed, total: here.total }];
161536
161658
  });
161537
161659
  const failedThere = checks.filter((c) => c.production === "failed");
161538
- const verdict = failedThere.length > 0 ? failedThere.every((c) => c.failed * 2 > c.total) ? "reproduced" : failedThere.some((c) => c.failed > 0) ? "partly" : "not-reproduced" : checks.some((c) => c.production === "passed" && c.failed > 0) ? "differs" : "matches";
161660
+ const verdict = failedThere.length > 0 ? failedThere.every((c) => c.failed * 2 > c.total) ? "reproduced" : failedThere.some((c) => c.failed > 0) ? "partly" : "not-reproduced" : checks.some((c) => c.production === "passed" && c.failed > 0) ? "differs" : checks.some((c) => c.production === "passed") ? "matches" : "unknown";
161539
161661
  const added = Object.keys(scene2.checks).filter((check3) => !(check3 in production2.checks));
161540
161662
  const counts = {};
161541
161663
  for (const a of answers.filter((x) => x.scene === scene2.sceneId)) for (const [source, n] of Object.entries(a.counts)) counts[source] = (counts[source] ?? 0) + n;
@@ -161548,7 +161670,8 @@ var SAY = {
161548
161670
  partly: "production's failure happens here in part",
161549
161671
  "not-reproduced": "production's failure did not happen here: the agent is fixed, or the world differs from production (see questions.json next to the scene)",
161550
161672
  matches: "this run matches production, which passed these checks",
161551
- differs: "checks production passed failed here: a regression, or the world differs from production (see questions.json)"
161673
+ differs: "checks production passed failed here: a regression, or the world differs from production (see questions.json)",
161674
+ unknown: "set OPENROUTER_API_KEY and run again: a model grades these checks on production's record and on this run"
161552
161675
  };
161553
161676
  function renderReproduction(reproductions) {
161554
161677
  return reproductions.map((r) => {
@@ -161560,9 +161683,11 @@ function renderReproduction(reproductions) {
161560
161683
  ...rows7,
161561
161684
  `=> ${SAY[r.verdict]}`,
161562
161685
  ...also.length > 0 ? [` also failing here, though production passed: ${also.join(", ")}`] : [],
161686
+ // A failure here on a check production is not graded on yet is neither a match nor a regression: say how to grade both.
161687
+ ...r.verdict !== "unknown" && r.checks.some((c) => c.production === "unknown" && c.failed > 0) ? [` set OPENROUTER_API_KEY to grade ${r.checks.filter((c) => c.production === "unknown" && c.failed > 0).map((c) => c.check).join(", ")} on production's record and here`] : [],
161563
161688
  ...r.added.length > 0 ? [` checks added after saving, with no production result: ${r.added.join(", ")}`] : [],
161564
161689
  // How much of the run stood on production's own answers (TRACE_PLAN_V2 §8.6).
161565
- ...r.answers ? [` answers to the agent's tools: ${["replayed", "twin", "simulated", "failed"].filter((s) => r.answers[s]).map((s) => `${r.answers[s]} ${s}`).join(", ")}${r.answers.simulated ? "; simulated answers took the agent where production never went (ancha explain lists them)" : ""}`] : []
161690
+ ...r.answers ? [` answers to the agent's tools: ${["replayed", "replayed-elsewhere", "twin", "ran", "simulated", "failed"].filter((s) => r.answers[s]).map((s) => `${r.answers[s]} ${s}`).join(", ")}${r.answers.simulated ? "; simulated answers took the agent where production never went (ancha explain lists them)" : ""}`] : []
161566
161691
  ].join("\n");
161567
161692
  }).join("\n\n");
161568
161693
  }
@@ -184854,11 +184979,11 @@ _a6 = brand_privateBedrockClient;
184854
184979
 
184855
184980
  // backend/src/judge/openrouter.ts
184856
184981
  var DEFAULT_JUDGE_MODEL = "anthropic/claude-haiku-5.5";
184857
- async function requestGrade(apiKey, model, rubric, evidence, signal) {
184982
+ async function requestGrade(apiKey, model, rubric, evidence, signal, baseUrl = "https://openrouter.ai/api/v1") {
184858
184983
  signal?.throwIfAborted();
184859
184984
  const client = new OpenAI({
184860
184985
  apiKey,
184861
- baseURL: "https://openrouter.ai/api/v1",
184986
+ baseURL: baseUrl,
184862
184987
  adminAPIKey: null,
184863
184988
  organization: null,
184864
184989
  project: null,
@@ -185007,7 +185132,7 @@ async function evaluateJudges(scene2, capture3, options3) {
185007
185132
  continue;
185008
185133
  }
185009
185134
  try {
185010
- const response5 = await requestGrade(key3, model, check3.judge.replaceAll(key3, "[redacted]"), evidence.json, options3.signal);
185135
+ const response5 = await requestGrade(key3, model, check3.judge.replaceAll(key3, "[redacted]"), evidence.json, options3.signal, options3.baseUrl);
185011
185136
  options3.signal?.throwIfAborted();
185012
185137
  const choice4 = response5.choices[0];
185013
185138
  if (response5.choices.length !== 1 || choice4?.finish_reason !== "stop" || choice4.message.refusal || typeof choice4.message.content !== "string") throw new Error("missing, refused or truncated structured grade");
@@ -185698,7 +185823,7 @@ async function runPerEventTrial(spec) {
185698
185823
  signal?.throwIfAborted();
185699
185824
  const logFd = openSync3(join14(dir, "agent.log"), "w");
185700
185825
  const startedAt = performance.now();
185701
- let timedOut = false, spawnFailed = false, firstFailure = null, invocations = 0;
185826
+ let timedOut = false, spawnFailed = false, firstFailure, invocations = 0, failedInvocations = 0;
185702
185827
  let failure4;
185703
185828
  try {
185704
185829
  await backend.startTrial(env.id, session.id);
@@ -185736,8 +185861,9 @@ async function runPerEventTrial(spec) {
185736
185861
  spawnFailed = true;
185737
185862
  writeSync3(logFd, `ancha: could not start the agent: ${outcome3.error.message}
185738
185863
  `);
185739
- } else if (outcome3.kind === "exit" && outcome3.code !== 0) {
185740
- firstFailure ??= outcome3.code;
185864
+ } else if (outcome3.kind === "exit" && outcome3.code !== 0 && !timedOut) {
185865
+ failedInvocations++;
185866
+ if (firstFailure === void 0) firstFailure = outcome3.code;
185741
185867
  if (outcome3.code === EXIT_COMMAND_NOT_FOUND) spawnFailed = true;
185742
185868
  }
185743
185869
  } finally {
@@ -185772,7 +185898,7 @@ async function runPerEventTrial(spec) {
185772
185898
  if (failure4 !== void 0) throw failure4.error;
185773
185899
  signal?.throwIfAborted();
185774
185900
  const exit = spawnFailed ? "spawn_failed" : timedOut ? "timeout" : "exited";
185775
- const exitCode = spawnFailed ? EXIT_COMMAND_NOT_FOUND : firstFailure ?? 0;
185901
+ const exitCode = spawnFailed ? EXIT_COMMAND_NOT_FOUND : firstFailure === void 0 ? 0 : firstFailure;
185776
185902
  return {
185777
185903
  valid: !harnessIssues.some((issue5) => issue5.owner === "harness"),
185778
185904
  harnessIssues,
@@ -185785,8 +185911,9 @@ async function runPerEventTrial(spec) {
185785
185911
  realMs,
185786
185912
  simMs,
185787
185913
  checks,
185788
- logTail: exit === "exited" && exitCode === 0 ? [] : await logTail2(join14(dir, "agent.log")),
185789
- passed: checks.every((c) => !c.required || c.passed),
185914
+ invocations: { total: invocations, failed: failedInvocations },
185915
+ logTail: exit === "exited" && failedInvocations === 0 ? [] : await logTail2(join14(dir, "agent.log")),
185916
+ passed: failedInvocations === 0 && checks.every((c) => !c.required || c.passed),
185790
185917
  trace,
185791
185918
  dir,
185792
185919
  taskDelivery
@@ -186190,6 +186317,8 @@ async function executeRun(opts) {
186190
186317
  }
186191
186318
  result.caseId = item2.id;
186192
186319
  result.attemptId = attempt.id;
186320
+ if (writeTools(item2.scene).size) result.actions = actionsOf(item2.scene, result.trace);
186321
+ if (Object.keys(item2.scene.tools ?? {}).length) result.answers = answersOf(result.trace);
186193
186322
  if (result.exit !== "invalid") {
186194
186323
  if (!observedAgentExit && result.exit === "spawn_failed") halt.spawnFailure = result;
186195
186324
  observedAgentExit = true;
@@ -186322,7 +186451,8 @@ function compareSummaries(current, baseline) {
186322
186451
  droppedChecks.push(delta);
186323
186452
  }
186324
186453
  }
186325
- return { sceneId: scene2.sceneId, before: beforeScene.passed / beforeTrials, after: scene2.passed / afterTrials, delta: Number(numerator) / Number(denominator), beforeTrials, afterTrials, ...checks.length > 0 && { checks } };
186454
+ const actions = actionChanges(beforeScene.actions, scene2.actions);
186455
+ return { sceneId: scene2.sceneId, before: beforeScene.passed / beforeTrials, after: scene2.passed / afterTrials, delta: Number(numerator) / Number(denominator), beforeTrials, afterTrials, ...checks.length > 0 && { checks }, ...actions.length > 0 && { actions } };
186326
186456
  });
186327
186457
  return { baselineRunId: baseline.runId, regressed, droppedChecks, scenes };
186328
186458
  }