@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.
- package/lib/ancha.mjs +806 -293
- package/lib/assets/harbor/companion.mjs +63 -23
- package/lib/mcp-entry.mjs +2 -0
- package/lib/worker.mjs +169 -42
- package/lib/world-server.mjs +63 -23
- package/package.json +1 -1
package/lib/world-server.mjs
CHANGED
|
@@ -88535,7 +88535,7 @@ var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
88535
88535
|
function isLeapYear(year) {
|
|
88536
88536
|
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
88537
88537
|
}
|
|
88538
|
-
const
|
|
88538
|
+
const DATE2 = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
|
|
88539
88539
|
const DAYS2 = [
|
|
88540
88540
|
0,
|
|
88541
88541
|
31,
|
|
@@ -88552,7 +88552,7 @@ var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
88552
88552
|
31
|
|
88553
88553
|
];
|
|
88554
88554
|
function date10(str3) {
|
|
88555
|
-
const matches7 =
|
|
88555
|
+
const matches7 = DATE2.exec(str3);
|
|
88556
88556
|
if (!matches7) return false;
|
|
88557
88557
|
const year = +matches7[1];
|
|
88558
88558
|
const month = +matches7[2];
|
|
@@ -100676,6 +100676,8 @@ var SceneToolSchema = external_exports.strictObject({
|
|
|
100676
100676
|
allow_unwrapped: external_exports.literal(true).optional(),
|
|
100677
100677
|
/** Changes something (a refund, an email): an unrecorded call is never answered by invention unless set to simulate. */
|
|
100678
100678
|
write: external_exports.boolean().optional(),
|
|
100679
|
+
/** Only computes from its arguments (a calculator): a call production never made runs the tool itself, for real. */
|
|
100680
|
+
pure: external_exports.literal(true).optional(),
|
|
100679
100681
|
description: external_exports.string().optional(),
|
|
100680
100682
|
schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
|
|
100681
100683
|
});
|
|
@@ -101847,6 +101849,7 @@ function toolIssues(scene2) {
|
|
|
101847
101849
|
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}]` });
|
|
101848
101850
|
}
|
|
101849
101851
|
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` });
|
|
101852
|
+
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` });
|
|
101850
101853
|
if (tool.observations !== void 0 && tool.recorded === void 0) {
|
|
101851
101854
|
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" });
|
|
101852
101855
|
}
|
|
@@ -114752,7 +114755,7 @@ function readWorldSnapshot(bytes2) {
|
|
|
114752
114755
|
}
|
|
114753
114756
|
|
|
114754
114757
|
// packages/server/src/agent-tools/simulate.ts
|
|
114755
|
-
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
|
|
114758
|
+
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>"}.`;
|
|
114756
114759
|
var SCHEMA5 = { name: "tool_answer", schema: { type: "object", additionalProperties: false, properties: { result_json: { type: "string" }, error: { type: "string" } } } };
|
|
114757
114760
|
function shape(value4) {
|
|
114758
114761
|
if (Array.isArray(value4)) return `[${value4.length ? shape(value4[0]) : ""}]`;
|
|
@@ -114774,12 +114777,15 @@ function sameShape(result, recorded2) {
|
|
|
114774
114777
|
async function simulate(model, request, signal) {
|
|
114775
114778
|
const recorded2 = (request.tool?.recorded ?? []).map((o) => ({ args: o.args, at: o.at, ...o.error !== void 0 ? { error: o.error } : { result: o.result } }));
|
|
114776
114779
|
const results = recorded2.filter((o) => "result" in o).map((o) => o.result);
|
|
114780
|
+
const known2 = results.length ? results : (request.tool?.examples ?? []).filter((o) => o.error === void 0 && o.result !== void 0).map((o) => o.result);
|
|
114781
|
+
const text21 = known2.length > 0 && known2.every((r) => typeof r === "string");
|
|
114777
114782
|
const user8 = JSON.stringify({
|
|
114778
114783
|
tool: { name: request.name, ...request.tool?.description && { description: request.tool.description }, ...request.tool?.schema && { arguments: request.tool.schema }, ...request.tool?.write && { changes_something: true } },
|
|
114779
114784
|
production_recorded: recorded2.slice(-20),
|
|
114780
114785
|
...request.tool?.examples?.length && { other_production_runs_of_this_agent: request.tool.examples.slice(-30) },
|
|
114781
|
-
...
|
|
114782
|
-
|
|
114786
|
+
...known2.length && { result_shape: shape(known2[0]) },
|
|
114787
|
+
calls_in_this_test: request.calls.slice(-30),
|
|
114788
|
+
...request.records?.length && { records_that_mention_these_values: request.records },
|
|
114783
114789
|
call: { arguments: request.args, ...request.repeat && { production_made_this_exact_call: request.repeat.recorded, this_is_call_number: request.repeat.call } },
|
|
114784
114790
|
// Time moves on as the agent waits: a status read later may say what a real one would say by then.
|
|
114785
114791
|
...request.time && { time: {
|
|
@@ -114787,7 +114793,7 @@ async function simulate(model, request, signal) {
|
|
|
114787
114793
|
...request.time.now_ms > request.time.last_recorded_ms && { seconds_since_productions_last_answer: Math.round((request.time.now_ms - request.time.last_recorded_ms) / 1e3) }
|
|
114788
114794
|
} }
|
|
114789
114795
|
});
|
|
114790
|
-
let inputTokens = 0, outputTokens = 0, costUsd = 0, model_, feedback = "";
|
|
114796
|
+
let inputTokens = 0, outputTokens = 0, costUsd = 0, model_, feedback = "", last = "";
|
|
114791
114797
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
114792
114798
|
const answer = await model.complete({ kind: "simulate", person: request.name, system: SYSTEM, user: feedback ? `${user8}
|
|
114793
114799
|
|
|
@@ -114797,18 +114803,23 @@ ${feedback}` : user8, schema: SCHEMA5, temperature: 0, maxTokens: 1200 }, signal
|
|
|
114797
114803
|
costUsd += answer.costUsd;
|
|
114798
114804
|
model_ = answer.model;
|
|
114799
114805
|
const out = answer.output;
|
|
114806
|
+
last = JSON.stringify(out ?? null).slice(0, 200);
|
|
114800
114807
|
if (typeof out?.error === "string" && out.error && out.result_json === void 0) return { error: out.error, inputTokens, outputTokens, costUsd, model: model_ };
|
|
114801
114808
|
let result;
|
|
114802
114809
|
try {
|
|
114803
114810
|
result = JSON.parse(String(out?.result_json));
|
|
114804
114811
|
} catch {
|
|
114805
|
-
|
|
114806
|
-
|
|
114812
|
+
if (!text21 || typeof out?.result_json !== "string") {
|
|
114813
|
+
feedback = "Your result_json was not valid JSON. Answer again.";
|
|
114814
|
+
continue;
|
|
114815
|
+
}
|
|
114816
|
+
result = out.result_json;
|
|
114807
114817
|
}
|
|
114808
|
-
if (
|
|
114809
|
-
|
|
114818
|
+
if (text21 && typeof result !== "string" && typeof out?.result_json === "string") result = out.result_json;
|
|
114819
|
+
if (sameShape(result, known2)) return { result, inputTokens, outputTokens, costUsd, model: model_ };
|
|
114820
|
+
feedback = `Your result has the shape ${shape(result)}, but production's results have the shape ${shape(known2[0])}. Answer again in that shape.`;
|
|
114810
114821
|
}
|
|
114811
|
-
throw new PeopleModelError(`the simulated answer to ${request.name} did not have the shape of production's results`);
|
|
114822
|
+
throw new PeopleModelError(`the simulated answer to ${request.name} did not have the shape of production's results (the model's last answer: ${last})`);
|
|
114812
114823
|
}
|
|
114813
114824
|
|
|
114814
114825
|
// packages/server/src/agent-tools/index.ts
|
|
@@ -114837,6 +114848,29 @@ var getState = (ctx, k) => ctx.store.db.prepare("SELECT v FROM agent_tool_state
|
|
|
114837
114848
|
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);
|
|
114838
114849
|
var SIMULATION_LIMIT = () => Number(process.env.ANCHA_SIMULATE_MAX ?? 30);
|
|
114839
114850
|
var simulationOn = (ctx) => process.env.ANCHA_SIMULATE !== "0" && ctx.model !== void 0;
|
|
114851
|
+
var ID_LIKE = /^(?=.*[\d@])[A-Za-z0-9][\w.:@#/+-]{3,63}$/;
|
|
114852
|
+
var DATE = /^\d{4}-\d{2}-\d{2}/;
|
|
114853
|
+
function idValues(value4, out = /* @__PURE__ */ new Set()) {
|
|
114854
|
+
if (Array.isArray(value4)) for (const v of value4) idValues(v, out);
|
|
114855
|
+
else if (value4 && typeof value4 === "object") for (const v of Object.values(value4)) idValues(v, out);
|
|
114856
|
+
else if ((typeof value4 === "string" || typeof value4 === "number" && Number.isInteger(value4)) && ID_LIKE.test(String(value4)) && !DATE.test(String(value4))) out.add(String(value4));
|
|
114857
|
+
return out;
|
|
114858
|
+
}
|
|
114859
|
+
var RECORDS_SHOWN = 20;
|
|
114860
|
+
function recordsMentioning(ctx, name5, args) {
|
|
114861
|
+
const ids2 = [...idValues(args)].map((id12) => new RegExp(`(^|[^A-Za-z0-9])${id12.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}([^A-Za-z0-9]|$)`));
|
|
114862
|
+
if (!ids2.length) return [];
|
|
114863
|
+
const records2 = [];
|
|
114864
|
+
const add = (tool, o, here) => {
|
|
114865
|
+
const answer = o.error !== void 0 ? { error: o.error } : { result: o.result };
|
|
114866
|
+
const text21 = JSON.stringify([o.args, answer]);
|
|
114867
|
+
if (ids2.some((id12) => id12.test(text21))) records2.push({ tool, args: o.args ?? {}, ...answer, conversation: here ? "this one" : o.trace ?? "another" });
|
|
114868
|
+
};
|
|
114869
|
+
const others = Object.entries(ctx.scene.tools ?? {}).filter(([tool]) => tool !== name5);
|
|
114870
|
+
for (const [tool] of others) for (const o of recorded(ctx, tool)) add(tool, o, true);
|
|
114871
|
+
for (const [tool, t] of others) for (const o of [...t.examples ?? []].reverse()) add(tool, o, false);
|
|
114872
|
+
return records2.slice(0, RECORDS_SHOWN);
|
|
114873
|
+
}
|
|
114840
114874
|
function keepUp(ctx) {
|
|
114841
114875
|
const behind = withRead(ctx, () => Number(getState(ctx, "reached") ?? 0)) - ctx.clock.elapsedMs();
|
|
114842
114876
|
if (behind > 0) ctx.clock.advance(behind);
|
|
@@ -114864,13 +114898,19 @@ function decide(ctx, name5, args) {
|
|
|
114864
114898
|
setState(ctx, "reached", String(Math.max(reached, o.endMs)));
|
|
114865
114899
|
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 } };
|
|
114866
114900
|
}
|
|
114901
|
+
if (!same2.length && !tool?.write) {
|
|
114902
|
+
const elsewhere = [...tool?.examples ?? []].reverse().find((o) => o.error === void 0 && o.result !== void 0 && canonical2(o.args) === key3);
|
|
114903
|
+
if (elsewhere) return { source: "replayed-elsewhere", result: elsewhere.result };
|
|
114904
|
+
}
|
|
114867
114905
|
if (tool?.twin !== void 0 || policy === "twin") return { source: "twin", passthrough: true };
|
|
114906
|
+
if (tool?.pure) return { source: "ran", passthrough: true };
|
|
114868
114907
|
const repeat = same2.length ? { recorded: same2.length, call: n + 1 } : void 0;
|
|
114869
114908
|
const last = same2.at(-1) ?? recorded(ctx, name5).at(-1), took = last ? last.endMs - last.atMs : 0;
|
|
114870
114909
|
if (policy === "simulate" && simulationOn(ctx)) {
|
|
114871
114910
|
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` };
|
|
114872
114911
|
const lastRecordedMs = Math.max(0, ...recorded(ctx, name5).map((o) => o.endMs));
|
|
114873
|
-
|
|
114912
|
+
const records2 = recordsMentioning(ctx, name5, args);
|
|
114913
|
+
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 };
|
|
114874
114914
|
}
|
|
114875
114915
|
if (repeat && !tool?.write) {
|
|
114876
114916
|
const o = same2.at(-1);
|
|
@@ -114880,14 +114920,14 @@ function decide(ctx, name5, args) {
|
|
|
114880
114920
|
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)" : "";
|
|
114881
114921
|
return { source: "failed", error: `Ancha has no recorded answer for this call: ${why}${unsimulated}` };
|
|
114882
114922
|
}
|
|
114883
|
-
function
|
|
114884
|
-
if (
|
|
114885
|
-
const
|
|
114886
|
-
|
|
114887
|
-
setState(ctx, "
|
|
114923
|
+
function noteCall(ctx, name5, args, a) {
|
|
114924
|
+
if (a.passthrough) return;
|
|
114925
|
+
const calls2 = JSON.parse(getState(ctx, "calls") ?? "[]");
|
|
114926
|
+
calls2.push({ tool: name5, args, ...ctx.scene.tools?.[name5]?.write && { changes_something: true }, ...a.error !== void 0 ? { error: a.error } : { result: a.result } });
|
|
114927
|
+
setState(ctx, "calls", JSON.stringify(calls2.slice(-50)));
|
|
114888
114928
|
}
|
|
114889
114929
|
function toolsToWrap(ctx) {
|
|
114890
|
-
return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => t.twin === void 0 && !t.mcp && !t.allow_unwrapped).map(([name5]) => name5).sort();
|
|
114930
|
+
return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => t.twin === void 0 && !t.mcp && !t.pure && !t.allow_unwrapped).map(([name5]) => name5).sort();
|
|
114891
114931
|
}
|
|
114892
114932
|
function registration(ctx, names3) {
|
|
114893
114933
|
const before = JSON.parse(getState(ctx, "wrapped") ?? "[]");
|
|
@@ -114935,14 +114975,14 @@ function agentToolsService() {
|
|
|
114935
114975
|
const ctx = c.env.ctx, args = body6.args ?? {};
|
|
114936
114976
|
const decision2 = withMutation(ctx, () => decide(ctx, name5, args));
|
|
114937
114977
|
if (!("simulate" in decision2)) {
|
|
114938
|
-
withMutation(ctx, () =>
|
|
114978
|
+
withMutation(ctx, () => noteCall(ctx, name5, args, decision2));
|
|
114939
114979
|
keepUp(ctx);
|
|
114940
114980
|
return c.json(decision2);
|
|
114941
114981
|
}
|
|
114942
114982
|
let answered;
|
|
114943
114983
|
try {
|
|
114944
|
-
const
|
|
114945
|
-
const sim = await simulate(ctx.model, { ...decision2.simulate,
|
|
114984
|
+
const calls2 = withRead(ctx, () => JSON.parse(getState(ctx, "calls") ?? "[]"));
|
|
114985
|
+
const sim = await simulate(ctx.model, { ...decision2.simulate, calls: calls2 }, c.req.raw.signal);
|
|
114946
114986
|
answered = { source: "simulated", ...sim.error !== void 0 ? { error: sim.error } : { result: sim.result }, cost_usd: Math.round(sim.costUsd * 1e6) / 1e6 };
|
|
114947
114987
|
} catch (error63) {
|
|
114948
114988
|
answered = { source: "failed", error: `Ancha has no recorded answer for this call and could not simulate one: ${error63 instanceof Error ? error63.message : String(error63)}` };
|
|
@@ -114954,11 +114994,11 @@ function agentToolsService() {
|
|
|
114954
114994
|
setState(ctx, `sim:${decision2.cacheKey}`, JSON.stringify({ answer: { ...answered, cost_usd: void 0 }, reached: now10 }));
|
|
114955
114995
|
setState(ctx, "simulated", String(Number(getState(ctx, "simulated") ?? 0) + 1));
|
|
114956
114996
|
}
|
|
114957
|
-
|
|
114997
|
+
noteCall(ctx, name5, args, answered);
|
|
114958
114998
|
return answered;
|
|
114959
114999
|
});
|
|
114960
115000
|
keepUp(ctx);
|
|
114961
|
-
return c.json(answer);
|
|
115001
|
+
return answer.source === "failed" ? c.json(answer, 200, { [SETUP_ISSUE_HEADER]: "1" }) : c.json(answer);
|
|
114962
115002
|
});
|
|
114963
115003
|
app2.all("*", (c) => c.json({ error: `not a route of Ancha's tool service: ${c.req.method} ${new URL(c.req.url).pathname}` }, 404));
|
|
114964
115004
|
return {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ancha-labs/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Simulation playgrounds for agents: run your agent against stateful replicas of Slack, GitHub, Datadog and more, locally or hosted at app.ancha.io.",
|
|
6
6
|
"bugs": {
|