@ancha-labs/cli 0.3.0 → 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.
@@ -84991,6 +84991,8 @@ var SceneToolSchema = external_exports.strictObject({
84991
84991
  allow_unwrapped: external_exports.literal(true).optional(),
84992
84992
  /** Changes something (a refund, an email): an unrecorded call is never answered by invention unless set to simulate. */
84993
84993
  write: external_exports.boolean().optional(),
84994
+ /** Only computes from its arguments (a calculator): a call production never made runs the tool itself, for real. */
84995
+ pure: external_exports.literal(true).optional(),
84994
84996
  description: external_exports.string().optional(),
84995
84997
  schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
84996
84998
  });
@@ -86162,6 +86164,7 @@ function toolIssues(scene2) {
86162
86164
  else if (!scene2.twins.includes(tool.twin)) issues.push({ path: `${path4}.twin`, message: `twin ${tool.twin} is not listed in twins`, hint: `add ${tool.twin} to twins, e.g. twins: [${tool.twin}]` });
86163
86165
  }
86164
86166
  if (tool.unrecorded === "twin" && tool.twin === void 0) issues.push({ path: `${path4}.unrecorded`, message: "unrecorded: twin needs the twin that answers", hint: `set ${path4}.twin, e.g. twin: slack` });
86167
+ if (tool.pure && tool.write) issues.push({ path: `${path4}.pure`, message: "a tool that changes something is not pure", hint: `remove ${path4}.pure, or ${path4}.write if it only computes from its arguments` });
86165
86168
  if (tool.observations !== void 0 && tool.recorded === void 0) {
86166
86169
  issues.push({ path: `${path4}.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" });
86167
86170
  }
@@ -98368,7 +98371,7 @@ function readWorldSnapshot(bytes2) {
98368
98371
  }
98369
98372
 
98370
98373
  // packages/server/src/agent-tools/simulate.ts
98371
- 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>"}.`;
98374
+ 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>"}.`;
98372
98375
  var SCHEMA5 = { name: "tool_answer", schema: { type: "object", additionalProperties: false, properties: { result_json: { type: "string" }, error: { type: "string" } } } };
98373
98376
  function shape(value4) {
98374
98377
  if (Array.isArray(value4)) return `[${value4.length ? shape(value4[0]) : ""}]`;
@@ -98390,12 +98393,15 @@ function sameShape(result, recorded2) {
98390
98393
  async function simulate(model, request4, signal) {
98391
98394
  const recorded2 = (request4.tool?.recorded ?? []).map((o) => ({ args: o.args, at: o.at, ...o.error !== void 0 ? { error: o.error } : { result: o.result } }));
98392
98395
  const results = recorded2.filter((o) => "result" in o).map((o) => o.result);
98396
+ const known2 = results.length ? results : (request4.tool?.examples ?? []).filter((o) => o.error === void 0 && o.result !== void 0).map((o) => o.result);
98397
+ const text21 = known2.length > 0 && known2.every((r) => typeof r === "string");
98393
98398
  const user8 = JSON.stringify({
98394
98399
  tool: { name: request4.name, ...request4.tool?.description && { description: request4.tool.description }, ...request4.tool?.schema && { arguments: request4.tool.schema }, ...request4.tool?.write && { changes_something: true } },
98395
98400
  production_recorded: recorded2.slice(-20),
98396
98401
  ...request4.tool?.examples?.length && { other_production_runs_of_this_agent: request4.tool.examples.slice(-30) },
98397
- ...results.length && { result_shape: shape(results[0]) },
98398
- writes_in_this_test: request4.writes.slice(-20),
98402
+ ...known2.length && { result_shape: shape(known2[0]) },
98403
+ calls_in_this_test: request4.calls.slice(-30),
98404
+ ...request4.records?.length && { records_that_mention_these_values: request4.records },
98399
98405
  call: { arguments: request4.args, ...request4.repeat && { production_made_this_exact_call: request4.repeat.recorded, this_is_call_number: request4.repeat.call } },
98400
98406
  // Time moves on as the agent waits: a status read later may say what a real one would say by then.
98401
98407
  ...request4.time && { time: {
@@ -98403,7 +98409,7 @@ async function simulate(model, request4, signal) {
98403
98409
  ...request4.time.now_ms > request4.time.last_recorded_ms && { seconds_since_productions_last_answer: Math.round((request4.time.now_ms - request4.time.last_recorded_ms) / 1e3) }
98404
98410
  } }
98405
98411
  });
98406
- let inputTokens = 0, outputTokens = 0, costUsd = 0, model_, feedback = "";
98412
+ let inputTokens = 0, outputTokens = 0, costUsd = 0, model_, feedback = "", last = "";
98407
98413
  for (let attempt = 0; attempt < 2; attempt++) {
98408
98414
  const answer = await model.complete({ kind: "simulate", person: request4.name, system: SYSTEM, user: feedback ? `${user8}
98409
98415
 
@@ -98413,18 +98419,23 @@ ${feedback}` : user8, schema: SCHEMA5, temperature: 0, maxTokens: 1200 }, signal
98413
98419
  costUsd += answer.costUsd;
98414
98420
  model_ = answer.model;
98415
98421
  const out = answer.output;
98422
+ last = JSON.stringify(out ?? null).slice(0, 200);
98416
98423
  if (typeof out?.error === "string" && out.error && out.result_json === void 0) return { error: out.error, inputTokens, outputTokens, costUsd, model: model_ };
98417
98424
  let result;
98418
98425
  try {
98419
98426
  result = JSON.parse(String(out?.result_json));
98420
98427
  } catch {
98421
- feedback = "Your result_json was not valid JSON. Answer again.";
98422
- continue;
98428
+ if (!text21 || typeof out?.result_json !== "string") {
98429
+ feedback = "Your result_json was not valid JSON. Answer again.";
98430
+ continue;
98431
+ }
98432
+ result = out.result_json;
98423
98433
  }
98424
- if (sameShape(result, results)) return { result, inputTokens, outputTokens, costUsd, model: model_ };
98425
- feedback = `Your result has the shape ${shape(result)}, but production's results have the shape ${shape(results[0])}. Answer again in that shape.`;
98434
+ if (text21 && typeof result !== "string" && typeof out?.result_json === "string") result = out.result_json;
98435
+ if (sameShape(result, known2)) return { result, inputTokens, outputTokens, costUsd, model: model_ };
98436
+ feedback = `Your result has the shape ${shape(result)}, but production's results have the shape ${shape(known2[0])}. Answer again in that shape.`;
98426
98437
  }
98427
- throw new PeopleModelError(`the simulated answer to ${request4.name} did not have the shape of production's results`);
98438
+ throw new PeopleModelError(`the simulated answer to ${request4.name} did not have the shape of production's results (the model's last answer: ${last})`);
98428
98439
  }
98429
98440
 
98430
98441
  // packages/server/src/agent-tools/index.ts
@@ -98453,6 +98464,29 @@ var getState = (ctx, k) => ctx.store.db.prepare("SELECT v FROM agent_tool_state
98453
98464
  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);
98454
98465
  var SIMULATION_LIMIT = () => Number(process.env.ANCHA_SIMULATE_MAX ?? 30);
98455
98466
  var simulationOn = (ctx) => process.env.ANCHA_SIMULATE !== "0" && ctx.model !== void 0;
98467
+ var ID_LIKE = /^(?=.*[\d@])[A-Za-z0-9][\w.:@#/+-]{3,63}$/;
98468
+ var DATE = /^\d{4}-\d{2}-\d{2}/;
98469
+ function idValues(value4, out = /* @__PURE__ */ new Set()) {
98470
+ if (Array.isArray(value4)) for (const v of value4) idValues(v, out);
98471
+ else if (value4 && typeof value4 === "object") for (const v of Object.values(value4)) idValues(v, out);
98472
+ else if ((typeof value4 === "string" || typeof value4 === "number" && Number.isInteger(value4)) && ID_LIKE.test(String(value4)) && !DATE.test(String(value4))) out.add(String(value4));
98473
+ return out;
98474
+ }
98475
+ var RECORDS_SHOWN = 20;
98476
+ function recordsMentioning(ctx, name5, args) {
98477
+ const ids2 = [...idValues(args)].map((id12) => new RegExp(`(^|[^A-Za-z0-9])${id12.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}([^A-Za-z0-9]|$)`));
98478
+ if (!ids2.length) return [];
98479
+ const records2 = [];
98480
+ const add = (tool, o, here) => {
98481
+ const answer = o.error !== void 0 ? { error: o.error } : { result: o.result };
98482
+ const text21 = JSON.stringify([o.args, answer]);
98483
+ if (ids2.some((id12) => id12.test(text21))) records2.push({ tool, args: o.args ?? {}, ...answer, conversation: here ? "this one" : o.trace ?? "another" });
98484
+ };
98485
+ const others = Object.entries(ctx.scene.tools ?? {}).filter(([tool]) => tool !== name5);
98486
+ for (const [tool] of others) for (const o of recorded(ctx, tool)) add(tool, o, true);
98487
+ for (const [tool, t] of others) for (const o of [...t.examples ?? []].reverse()) add(tool, o, false);
98488
+ return records2.slice(0, RECORDS_SHOWN);
98489
+ }
98456
98490
  function keepUp(ctx) {
98457
98491
  const behind = withRead(ctx, () => Number(getState(ctx, "reached") ?? 0)) - ctx.clock.elapsedMs();
98458
98492
  if (behind > 0) ctx.clock.advance(behind);
@@ -98480,13 +98514,19 @@ function decide(ctx, name5, args) {
98480
98514
  setState(ctx, "reached", String(Math.max(reached, o.endMs)));
98481
98515
  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 } };
98482
98516
  }
98517
+ if (!same2.length && !tool?.write) {
98518
+ const elsewhere = [...tool?.examples ?? []].reverse().find((o) => o.error === void 0 && o.result !== void 0 && canonical2(o.args) === key3);
98519
+ if (elsewhere) return { source: "replayed-elsewhere", result: elsewhere.result };
98520
+ }
98483
98521
  if (tool?.twin !== void 0 || policy === "twin") return { source: "twin", passthrough: true };
98522
+ if (tool?.pure) return { source: "ran", passthrough: true };
98484
98523
  const repeat = same2.length ? { recorded: same2.length, call: n + 1 } : void 0;
98485
98524
  const last = same2.at(-1) ?? recorded(ctx, name5).at(-1), took = last ? last.endMs - last.atMs : 0;
98486
98525
  if (policy === "simulate" && simulationOn(ctx)) {
98487
98526
  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` };
98488
98527
  const lastRecordedMs = Math.max(0, ...recorded(ctx, name5).map((o) => o.endMs));
98489
- 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 };
98528
+ const records2 = recordsMentioning(ctx, name5, args);
98529
+ 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 };
98490
98530
  }
98491
98531
  if (repeat && !tool?.write) {
98492
98532
  const o = same2.at(-1);
@@ -98496,14 +98536,14 @@ function decide(ctx, name5, args) {
98496
98536
  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)" : "";
98497
98537
  return { source: "failed", error: `Ancha has no recorded answer for this call: ${why}${unsimulated}` };
98498
98538
  }
98499
- function noteWrite(ctx, name5, args, a) {
98500
- if (!ctx.scene.tools?.[name5]?.write || a.passthrough) return;
98501
- const writes2 = JSON.parse(getState(ctx, "writes") ?? "[]");
98502
- writes2.push({ tool: name5, args, ...a.error !== void 0 ? { error: a.error } : { result: a.result } });
98503
- setState(ctx, "writes", JSON.stringify(writes2.slice(-50)));
98539
+ function noteCall(ctx, name5, args, a) {
98540
+ if (a.passthrough) return;
98541
+ const calls2 = JSON.parse(getState(ctx, "calls") ?? "[]");
98542
+ calls2.push({ tool: name5, args, ...ctx.scene.tools?.[name5]?.write && { changes_something: true }, ...a.error !== void 0 ? { error: a.error } : { result: a.result } });
98543
+ setState(ctx, "calls", JSON.stringify(calls2.slice(-50)));
98504
98544
  }
98505
98545
  function toolsToWrap(ctx) {
98506
- return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => t.twin === void 0 && !t.mcp && !t.allow_unwrapped).map(([name5]) => name5).sort();
98546
+ return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => t.twin === void 0 && !t.mcp && !t.pure && !t.allow_unwrapped).map(([name5]) => name5).sort();
98507
98547
  }
98508
98548
  function registration(ctx, names3) {
98509
98549
  const before = JSON.parse(getState(ctx, "wrapped") ?? "[]");
@@ -98551,14 +98591,14 @@ function agentToolsService() {
98551
98591
  const ctx = c.env.ctx, args = body6.args ?? {};
98552
98592
  const decision2 = withMutation(ctx, () => decide(ctx, name5, args));
98553
98593
  if (!("simulate" in decision2)) {
98554
- withMutation(ctx, () => noteWrite(ctx, name5, args, decision2));
98594
+ withMutation(ctx, () => noteCall(ctx, name5, args, decision2));
98555
98595
  keepUp(ctx);
98556
98596
  return c.json(decision2);
98557
98597
  }
98558
98598
  let answered;
98559
98599
  try {
98560
- const writes2 = withRead(ctx, () => JSON.parse(getState(ctx, "writes") ?? "[]"));
98561
- const sim = await simulate(ctx.model, { ...decision2.simulate, writes: writes2 }, c.req.raw.signal);
98600
+ const calls2 = withRead(ctx, () => JSON.parse(getState(ctx, "calls") ?? "[]"));
98601
+ const sim = await simulate(ctx.model, { ...decision2.simulate, calls: calls2 }, c.req.raw.signal);
98562
98602
  answered = { source: "simulated", ...sim.error !== void 0 ? { error: sim.error } : { result: sim.result }, cost_usd: Math.round(sim.costUsd * 1e6) / 1e6 };
98563
98603
  } catch (error63) {
98564
98604
  answered = { source: "failed", error: `Ancha has no recorded answer for this call and could not simulate one: ${error63 instanceof Error ? error63.message : String(error63)}` };
@@ -98570,11 +98610,11 @@ function agentToolsService() {
98570
98610
  setState(ctx, `sim:${decision2.cacheKey}`, JSON.stringify({ answer: { ...answered, cost_usd: void 0 }, reached: now10 }));
98571
98611
  setState(ctx, "simulated", String(Number(getState(ctx, "simulated") ?? 0) + 1));
98572
98612
  }
98573
- noteWrite(ctx, name5, args, answered);
98613
+ noteCall(ctx, name5, args, answered);
98574
98614
  return answered;
98575
98615
  });
98576
98616
  keepUp(ctx);
98577
- return c.json(answer);
98617
+ return answer.source === "failed" ? c.json(answer, 200, { [SETUP_ISSUE_HEADER]: "1" }) : c.json(answer);
98578
98618
  });
98579
98619
  app2.all("*", (c) => c.json({ error: `not a route of Ancha's tool service: ${c.req.method} ${new URL(c.req.url).pathname}` }, 404));
98580
98620
  return {
@@ -153006,7 +153046,7 @@ var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
153006
153046
  function isLeapYear(year) {
153007
153047
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
153008
153048
  }
153009
- const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
153049
+ const DATE2 = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
153010
153050
  const DAYS2 = [
153011
153051
  0,
153012
153052
  31,
@@ -153023,7 +153063,7 @@ var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
153023
153063
  31
153024
153064
  ];
153025
153065
  function date10(str3) {
153026
- const matches7 = DATE.exec(str3);
153066
+ const matches7 = DATE2.exec(str3);
153027
153067
  if (!matches7) return false;
153028
153068
  const year = +matches7[1];
153029
153069
  const month = +matches7[2];
package/lib/mcp-entry.mjs CHANGED
@@ -65459,6 +65459,8 @@ var SceneToolSchema = external_exports.strictObject({
65459
65459
  allow_unwrapped: external_exports.literal(true).optional(),
65460
65460
  /** Changes something (a refund, an email): an unrecorded call is never answered by invention unless set to simulate. */
65461
65461
  write: external_exports.boolean().optional(),
65462
+ /** Only computes from its arguments (a calculator): a call production never made runs the tool itself, for real. */
65463
+ pure: external_exports.literal(true).optional(),
65462
65464
  description: external_exports.string().optional(),
65463
65465
  schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
65464
65466
  });