@ancha-labs/cli 0.4.15 → 0.4.17

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.
@@ -36,7 +36,7 @@ Add `--json` to every command. Runs print NDJSON events that end with `run_finis
36
36
  ancha agent upload
37
37
  ```
38
38
  - The install follows the project's own manifests and lockfiles; `agent.install` in `ancha.yaml` sets the command instead.
39
- 5. **Without production traces.** For an agent that uses NetSuite, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests from the questions an operator asks.
39
+ 5. **Without production traces.** For an agent that uses NetSuite, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests: 10 read tasks and 15 write workflows.
40
40
  - Your data: `ancha world import netsuite <your exports> --id <id>` reads REST record JSON, SuiteQL results and saved search CSV into `ancha/worlds/<id>.yaml`; check it with `ancha world validate`. To write the seed yourself, `ancha twins seed netsuite` lists its fields.
41
41
  - Your evals: `ancha test import <file> --world <id>` (JSONL, JSON, CSV or YAML with a question and an expected answer).
42
42
  - One test from a sentence: `ancha test new "<sentence>" --world <id>`.
@@ -21,7 +21,7 @@
21
21
  ancha agent upload
22
22
  ```
23
23
  - The install follows the project's own manifests and lockfiles; `agent.install` in `ancha.yaml` sets the command instead.
24
- 5. **Without production traces.** For an agent that uses NetSuite, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests from the questions an operator asks.
24
+ 5. **Without production traces.** For an agent that uses NetSuite, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests: 10 read tasks and 15 write workflows.
25
25
  - Your data: `ancha world import netsuite <your exports> --id <id>` reads REST record JSON, SuiteQL results and saved search CSV into `ancha/worlds/<id>.yaml`; check it with `ancha world validate`. To write the seed yourself, `ancha twins seed netsuite` lists its fields.
26
26
  - Your evals: `ancha test import <file> --world <id>` (JSONL, JSON, CSV or YAML with a question and an expected answer).
27
27
  - One test from a sentence: `ancha test new "<sentence>" --world <id>`.
@@ -29,7 +29,7 @@ Without `--on`, a project with `ancha.yaml` (or `--config`) runs in the workspac
29
29
  ancha agent upload
30
30
  ```
31
31
  - The install follows the project's own manifests and lockfiles; `agent.install` in `ancha.yaml` sets the command instead.
32
- 5. **Without production traces.** For an agent that uses NetSuite, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests from the questions an operator asks.
32
+ 5. **Without production traces.** For an agent that uses NetSuite, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests: 10 read tasks and 15 write workflows.
33
33
  - Your data: `ancha world import netsuite <your exports> --id <id>` reads REST record JSON, SuiteQL results and saved search CSV into `ancha/worlds/<id>.yaml`; check it with `ancha world validate`. To write the seed yourself, `ancha twins seed netsuite` lists its fields.
34
34
  - Your evals: `ancha test import <file> --world <id>` (JSONL, JSON, CSV or YAML with a question and an expected answer).
35
35
  - One test from a sentence: `ancha test new "<sentence>" --world <id>`.
@@ -75,6 +75,8 @@ Without `--on`, a project with `ancha.yaml` (or `--config`) runs in the workspac
75
75
 
76
76
  `ancha agent upload` (also `ancha doctor --on cloud`) checks the agent where its tests run, before any test exists. A fresh machine installs the project's dependencies and starts the agent once with a task, through the same launcher and variables as an attempt. An agent that uses NetSuite has 90 seconds to find one customer in NetSuite and reply with its name; any other agent has 20 seconds, and exiting 0 or showing any work in that time makes it ready. The result says what happened in one sentence: the NetSuite calls it made and the answer it gave, or what stopped it (credentials NetSuite refused, a NetSuite host outside Ancha, a model key its provider refused, an answer missing where your tests read it, no output at all) with the change that fixes it. One that exits with an error shows its exit code, the end of its log and, when the log names where it looks for its task, the `ancha.yaml` line that gives it there. An agent served over HTTP (`agent.url`) starts and answers its ready check. That marks the agent uploaded in the workspace's first steps, and the command prints the link to the upload.
77
77
 
78
+ The task's world includes tools found in your agent and the `twins` in the tests matched by your project's `scenes` globs, up to six tools with the agent's tools first. The result lists each tool and its call count. A tool with no calls gets a warning. If the check gave the agent no tools, name them with `ancha init --tools <tools>` or your tests' `twins`.
79
+
78
80
  The install follows the project's own files, Node and Python alike: a Node lockfile installs exactly what it locks, with its package manager, and a `package.json` without one runs `npm install`; `uv.lock` and `pyproject.toml` run `uv sync`, and `requirements.txt` installs with pip into `.venv`. `agent.install` in `ancha.yaml` sets the command instead, for example `agent: { install: "npm ci && npm run build" }`. The machine has Node 24 and Python 3.12 with their package managers. The install runs as its own user with public internet; the agent then runs as another, and its network reaches only its tools and its model providers.
79
81
 
80
82
  ## Run tests in the cloud
@@ -8,7 +8,7 @@ A world file (`ancha/worlds/<id>.yaml`) holds the records your agent's tools sta
8
8
  ancha world gen --dataset netsuite-pe --size m
9
9
  ```
10
10
 
11
- This writes the books of a private-equity portfolio company, `ancha/worlds/netsuite-pe-m.yaml`, and 25 operator questions with computed answers, `ancha/evals/netsuite-pe-m.jsonl`. It needs no model and no description: the same size always gives the same files. The company has four subsidiaries, US dollar and euro books, eighteen months of order to cash and procure to pay, and the problems an operator finds at close: duplicate bills, unapplied payments and credits, overdue receivables, three-way-match exceptions, journal entries waiting for approval. Sizes `s`, `m` and `l` hold about 1,500, 11,400 and 22,000 transactions. `ancha sandbox datasets` lists it with the starter datasets.
11
+ This writes the books of a private-equity portfolio company, `ancha/worlds/netsuite-pe-m.yaml`, and 10 read tasks and 15 write workflows with computed answers and final-state checks, `ancha/evals/netsuite-pe-m.jsonl`. It needs no model and no description: the same size always gives the same files. The company has four subsidiaries, US dollar and euro books, eighteen months of order to cash and procure to pay, and the problems an operator finds at close: duplicate bills, unapplied payments and credits, overdue receivables, three-way-match exceptions, journal entries waiting for approval. Sizes `s`, `m` and `l` hold about 1,500, 11,400 and 22,000 transactions. `ancha sandbox datasets` lists it with the starter datasets.
12
12
 
13
13
  ## Your NetSuite exports
14
14
 
@@ -54,7 +54,7 @@ Give your coding agent this recipe and an export of your records (a spreadsheet,
54
54
 
55
55
  ```text
56
56
  invalid ancha/worlds/our-books.yaml (our-books)
57
- netsuite: 4 subsidiaries, 2 currencies, 38 accounts, 400 customers, 180 vendors, 150 items, 11,429 transactions
57
+ netsuite: 4 subsidiaries, 2 currencies, 40 accounts, 400 customers, 180 vendors, 150 items, 11,431 transactions
58
58
  seed.netsuite.invoices[212]: INV12213 (id 40213, customer 1297 Jarvis Food Processing Co.): invoice is over-applied: applications total USD 11,641.54 against a total of USD 11,601.54 (over by USD 40.00)
59
59
  ```
60
60
 
@@ -17,7 +17,7 @@ A version 2 test names a world (`ancha/worlds/<id>.yaml`: the company, its peopl
17
17
  ```
18
18
 
19
19
  - The question is `question`, `input`, `prompt`, `query` or `task`; the expected answer is `expected`, `answer`, `ideal`, `output`, `reference` or `expected_output`. Optional: `id`, `read_only` (default true; false for an eval with `records`), `must_call` (`"METHOD /path"` or an MCP tool name), `numbers` (`[{ value, tolerance }]`), `contains`, `judge` (a rubric), `tags`, and `records`: the NetSuite state a write leaves, `[{ type, id or externalId, fields }]`. Other fields go in the test's header as comments.
20
- - Each eval becomes a test whose task is the question, with an `answer` check: the `numbers` and `contains` it gives, or the numbers, document numbers (`INV-1043`) and quoted text of its expected answer. Numbers the question states and dates are left out. A test also gets `netsuite.unchanged` over every record type when it only reads and the world has NetSuite, a `trace.called` check for each `must_call`, and a `netsuite.record` check for each of its `records`. A record named by `externalId` can be one the agent creates:
20
+ - Each eval becomes a test whose task is the question, with an `answer` check: the `numbers` and `contains` it gives, or the numbers, document numbers (`INV-1043`) and quoted text of its expected answer. Numbers the question states and dates are left out. A test also gets `netsuite.unchanged` over every record type when it only reads and the world has NetSuite, a `trace.called` check for each `must_call`, and a `netsuite.record` check for each of its `records`. Write evals can also give `counts: [{type, count}]` and `unchanged: {types, except: [{type, id | externalId}]}` to check record counts and protect other records. `includeSettlement: true` in a count includes zero-cash settlement records. A record check’s `apply` names the exact applied documents; `credit` names the exact credit sources, both as `[{doc, amount}]` (with `line` for line-level identities). A record named by `externalId` can be one the agent creates:
21
21
 
22
22
  ```json
23
23
  {"id": "approve-bf-2207", "question": "Approve the Bluefield Logistics bill BF-2207.", "records": [{"type": "vendorBill", "externalId": "BF-2207", "fields": {"approvalStatus": {"id": "2"}}}]}
@@ -29,7 +29,7 @@ A version 2 test names a world (`ancha/worlds/<id>.yaml`: the company, its peopl
29
29
 
30
30
  ## Checks on the final answer
31
31
 
32
- An `answer` check reads the agent's final answer: what it posts to `ANCHA_DONE_URL` as `{"output": …}` (`entry()` in `@ancha-labs/tools` posts what the agent returns), else an HTTP agent's reply, else the last block it prints on stdout (after its last blank line); `agent.answer` in `ancha.yaml` picks one. A JSON answer is read as `key: value` lines. Ancha grades it with no model, on this computer and in the cloud, so it uses no model credit.
32
+ An `answer` check reads the agent's final answer: what it posts to `ANCHA_DONE_URL` as `{"output": …}` (`entry()` in `@ancha-labs/tools` posts what the agent returns), else an HTTP agent's reply, else what it prints on stdout (its logs go to stderr); `agent.answer` in `ancha.yaml` picks one. A JSON answer is read as `key: value` lines. Ancha grades it with no model, on this computer and in the cloud, so it uses no model credit.
33
33
 
34
34
  ```yaml
35
35
  checks:
@@ -27,7 +27,7 @@ Requirements: Node 24 or newer. Install once with `npm install -g @ancha-labs/cl
27
27
  ancha agent upload
28
28
  ```
29
29
  - The install follows the project's own manifests and lockfiles; `agent.install` in `ancha.yaml` sets the command instead.
30
- 5. **Without production traces.** For an agent that uses NetSuite, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests from the questions an operator asks.
30
+ 5. **Without production traces.** For an agent that uses NetSuite, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests: 10 read tasks and 15 write workflows.
31
31
  - Your data: `ancha world import netsuite <your exports> --id <id>` reads REST record JSON, SuiteQL results and saved search CSV into `ancha/worlds/<id>.yaml`; check it with `ancha world validate`. To write the seed yourself, `ancha twins seed netsuite` lists its fields.
32
32
  - Your evals: `ancha test import <file> --world <id>` (JSONL, JSON, CSV or YAML with a question and an expected answer).
33
33
  - One test from a sentence: `ancha test new "<sentence>" --world <id>`.
@@ -68,7 +68,7 @@ Requirements: Node 24 or newer. Install once with `npm install -g @ancha-labs/cl
68
68
  `ancha init --agent "node agent.mjs"`, with your own start command, writes:
69
69
  - `ancha.yaml`: how to start the agent, how many trials, which tests;
70
70
  - `scenes/starter/`: a starter test that checks the agent reaches each tool, with two reference companions (`oracle.mjs` passes, `null.mjs` makes no calls);
71
- - for an agent that uses NetSuite, in a project with no tests and no `traces/` folder: `ancha/worlds/netsuite-pe-m.yaml`, the NetSuite books of a private-equity portfolio company, and 25 tests in `ancha/tests/` from the questions an operator asks (their evals in `ancha/evals/`). `--data netsuite-pe:s` or `--data netsuite-pe:l` writes another size, `--data none` leaves them out;
71
+ - for an agent that uses NetSuite, in a project with no tests and no `traces/` folder: `ancha/worlds/netsuite-pe-m.yaml`, the NetSuite books of a private-equity portfolio company, and 25 tests in `ancha/tests/`: 10 read tasks and 15 write workflows (their evals in `ancha/evals/`). `--data netsuite-pe:s` or `--data netsuite-pe:l` writes another size, `--data none` leaves them out;
72
72
  - `.claude/skills/ancha/SKILL.md` and an Ancha section in `AGENTS.md`, for coding agents;
73
73
  - `.ancha/` in `.gitignore`: run history, traces and fake tokens never belong in git.
74
74
 
@@ -24,7 +24,7 @@ The import lists the questions the trace leaves open, each with the default the
24
24
  - `tools.simulate_writes`: the writes a test simulates when the agent makes one production never made; the others fail.
25
25
  - `tools.pure`: tools that only compute from their arguments; a test runs them itself.
26
26
  - `tools.run`: tools that can run their own code in a test, over a store the agent fills from `records.jsonl`. Production's answers are replayed until something changes; a call production never made, a write, and every call after a write run the tool itself. It also lists the tools the agent's model was given that production never called; a test does not require the agent to wrap those.
27
- - `checks.success`: the required end state for the user's request, kept alongside the checks of what went wrong.
27
+ - `checks.success`: the required end state for the user's request: what a correct run leaves changed, leaves unchanged and tells the user. For a run that went wrong it is the right action, and the import asks for it plainly; every check of the test judges against the answer, and it stays required. `success:` in the import's output says which end state the test uses.
28
28
  - `github.members.<org>`: who was a member of the GitHub organization when the run started, as logins or `none`. The import asks when the agent removed someone's direct access to the organization's repositories; a member keeps read access to all of them.
29
29
 
30
30
  Reimporting into the workspace keeps the latest saved answers, including `task` and `--expect`. Offline imports keep the answers saved in the destination test folder. `--answer task=default` restores one default; `--reset-answers` starts with the trace defaults. Pull preserves checks you add and their membership in `pass`; a conflicting check ID names the check to rename.
@@ -76413,7 +76413,7 @@ var AnswerCheckSchema = external_exports.strictObject({
76413
76413
  not_contains: texts.optional().describe("Text the final answer must not contain"),
76414
76414
  numbers: external_exports.array(AnswerNumberSchema).min(1).optional().describe("Numbers the final answer must state, each within its tolerance; thousands separators, currency codes and symbols, minus signs and parentheses for negatives are read"),
76415
76415
  case: external_exports.enum(["insensitive", "sensitive"]).optional().describe("How contains and not_contains compare letters; default insensitive")
76416
- }).describe("Checks the agent's final answer (what it posts to ANCHA_DONE_URL, its HTTP reply, or the last block it prints on stdout): the text and numbers it states");
76416
+ }).describe("Checks the agent's final answer (what it posts to ANCHA_DONE_URL, its HTTP reply, or what it prints on stdout): the text and numbers it states");
76417
76417
  function expectedNumber(number7) {
76418
76418
  const read6 = typeof number7.value === "number" ? { value: number7.value, decimals: decimalsOf(number7.value) } : readNumbers(number7.value)[0];
76419
76419
  return { value: read6.value, tolerance: number7.tolerance ?? 0.5 * 10 ** -read6.decimals };
@@ -79642,10 +79642,10 @@ var BetterStackSeedSchema = external_exports.strictObject({
79642
79642
  open2.add(entry2.source);
79643
79643
  }
79644
79644
  });
79645
- seed43.onCall.forEach((calendar3, i) => calendar3.users.forEach((user8, j) => {
79645
+ seed43.onCall.forEach((calendar4, i) => calendar4.users.forEach((user8, j) => {
79646
79646
  if (!people3.has(user8)) issue6(["onCall", i, "users", j], `${user8} is not a user`);
79647
79647
  }));
79648
- if (seed43.onCall.filter((calendar3) => calendar3.default).length > 1) issue6(["onCall"], "only one default calendar");
79648
+ if (seed43.onCall.filter((calendar4) => calendar4.default).length > 1) issue6(["onCall"], "only one default calendar");
79649
79649
  seed43.statusPages.forEach((page18, i) => {
79650
79650
  const names5 = new Set(page18.resources.map((resource2) => resource2.publicName));
79651
79651
  page18.resources.forEach((resource2, j) => {
@@ -86334,10 +86334,14 @@ var NetsuiteRecordCheckSchema = external_exports.strictObject({
86334
86334
  id: id8.optional(),
86335
86335
  externalId: text11.optional(),
86336
86336
  fields: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
86337
- apply: external_exports.array(application).optional()
86337
+ apply: external_exports.array(application).optional(),
86338
+ credit: external_exports.array(application).optional()
86338
86339
  }).refine((check3) => check3.id === void 0 !== (check3.externalId === void 0), { message: "name the record with id or with externalId, not both", path: ["id"] });
86339
- var NetsuiteUnchangedCheckSchema = external_exports.strictObject({ types: external_exports.array(external_exports.enum(netsuiteRecordTypes)).min(1) });
86340
- var NetsuiteCountCheckSchema = external_exports.strictObject({ type: external_exports.enum(netsuiteRecordTypes), count: external_exports.number().int().min(0) });
86340
+ var NetsuiteUnchangedCheckSchema = external_exports.strictObject({
86341
+ types: external_exports.array(external_exports.enum(netsuiteRecordTypes)).min(1),
86342
+ except: external_exports.array(external_exports.strictObject({ type: external_exports.enum(netsuiteRecordTypes), id: id8.optional(), externalId: text11.optional() }).refine((check3) => check3.id === void 0 !== (check3.externalId === void 0), { message: "name the record with id or with externalId, not both" })).optional()
86343
+ });
86344
+ var NetsuiteCountCheckSchema = external_exports.strictObject({ type: external_exports.enum(netsuiteRecordTypes), count: external_exports.number().int().min(0), includeSettlement: external_exports.boolean().optional() });
86341
86345
 
86342
86346
  // packages/core/src/scene/schema.ts
86343
86347
  var SUPPORTED_TWINS = ["slack", "github", "datadog", "pagerduty", "linkedin-ads", "salesforce", "gong", "hubspot", "ga4", "google-ads", "chatgpt-ads", "open-meteo", "google-drive", "gmail", "amazon-s3", "linear", "okta", "stripe", "clerk", "better-stack", "notion", "attio", "dropbox", "resend", "microsoft-word", "outlook", "shopify", "lob", "paypal", "jira", "kalshi", "intercom", "zendesk", "google-calendar", "twilio", "asana", "discord", "sentry", "airtable", "netsuite", "carrier-portal"];
@@ -91104,8 +91108,10 @@ var ANSWER_QUOTE = 300;
91104
91108
  function finalAnswer(trace) {
91105
91109
  const entry2 = trace.findLast((e) => e.source === "agent" && e.service === "agent" && e.path === "/done");
91106
91110
  if (!entry2) return void 0;
91107
- const output2 = typeof entry2.request === "string" ? entry2.request : entry2.request?.output;
91108
- return { text: answerText(output2), seq: entry2.seq };
91111
+ const request4 = typeof entry2.request === "object" && entry2.request !== null ? entry2.request : void 0;
91112
+ const output2 = typeof entry2.request === "string" ? entry2.request : request4?.output;
91113
+ const source = request4?.source === "reply" || request4?.source === "stdout" ? request4.source : "done";
91114
+ return { text: answerText(output2), seq: entry2.seq, source, ...typeof request4?.printed === "number" && { printed: request4.printed } };
91109
91115
  }
91110
91116
  function evaluateAnswer(check3, trace) {
91111
91117
  const contains3 = asList(check3.contains), absent = asList(check3.not_contains), sensitive = check3.case === "sensitive";
@@ -91117,13 +91123,22 @@ function evaluateAnswer(check3, trace) {
91117
91123
  ];
91118
91124
  const expected = parts3.length ? `the final answer ${parts3.join("; ")}` : "a final answer";
91119
91125
  const answer = finalAnswer(trace);
91126
+ if (answer?.printed !== void 0) {
91127
+ return {
91128
+ passed: false,
91129
+ expected,
91130
+ actual: `${answer.printed.toLocaleString("en-US")} characters on stdout`,
91131
+ evidence: [answer.seq],
91132
+ explanation: `The agent printed ${answer.printed.toLocaleString("en-US")} characters on stdout, more than an answer can be, so it gave no final answer. An agent prints its logs on stderr, or posts its answer to ANCHA_DONE_URL, body {"output": <its answer>}.`
91133
+ };
91134
+ }
91120
91135
  if (!answer || answer.text.trim() === "") {
91121
91136
  return {
91122
91137
  passed: false,
91123
91138
  expected,
91124
91139
  actual: answer ? "an empty final answer" : "no final answer",
91125
91140
  evidence: answer ? [answer.seq] : [],
91126
- explanation: `The agent gave ${answer ? "an empty" : "no"} final answer. An agent answers with a POST to ANCHA_DONE_URL, body {"output": <its answer>}, or by printing it last on stdout.`
91141
+ explanation: `The agent gave ${answer ? "an empty" : "no"} final answer. An agent answers with a POST to ANCHA_DONE_URL, body {"output": <its answer>}, or by printing it on stdout.`
91127
91142
  };
91128
91143
  }
91129
91144
  const text23 = comparableText(answer.text, sensitive);
@@ -91140,7 +91155,8 @@ function evaluateAnswer(check3, trace) {
91140
91155
  const explanation = [
91141
91156
  ...missing6.length ? [`The final answer does not contain ${quoted2(missing6)}.`] : [],
91142
91157
  ...unstated.length ? [`It states no number within ${unstated.map((n2) => `${plainNumber(n2.tolerance)} of ${n2.written}`).join(", nor within ")}: ${said}.`] : [],
91143
- ...present2.length ? [`It contains ${quoted2(present2)}, which it must not.`] : []
91158
+ ...present2.length ? [`It contains ${quoted2(present2)}, which it must not.`] : [],
91159
+ ...answer.source === "stdout" ? ["Its answer is everything it printed on stdout."] : answer.source === "reply" ? ["Its answer is its HTTP reply."] : []
91144
91160
  ].join(" ");
91145
91161
  return { passed: false, expected, actual, explanation, evidence: [answer.seq] };
91146
91162
  }
@@ -107386,7 +107402,7 @@ var catalogRoutes3 = [
107386
107402
  return json8({ elements: entities.filter((e) => e.facet === q.get("facet")).map((e) => ({ urn: e.urn, facetUrn: e.facet, name: e.name })) });
107387
107403
  } }
107388
107404
  ];
107389
- function calendar(raw3) {
107405
+ function calendar2(raw3) {
107390
107406
  const match3 = /^\((?:year:(\d{4}),month:(\d{1,2}),day:(\d{1,2})|day:(\d{1,2}),month:(\d{1,2}),year:(\d{4}))\)$/.exec(raw3);
107391
107407
  if (!match3) invalid8("Date must be (year:YYYY,month:M,day:D) or (day:D,month:M,year:YYYY)");
107392
107408
  const y = match3[1] ?? match3[6], m = match3[2] ?? match3[5], d = match3[3] ?? match3[4], date10 = `${y}-${m.padStart(2, "0")}-${d.padStart(2, "0")}`;
@@ -107408,7 +107424,7 @@ var analyticsRoutes = [{ method: "GET", path: "/rest/adAnalytics", notes: "analy
107408
107424
  if (!["DAILY", "ALL"].includes(q.get("timeGranularity") ?? "")) gap2(`timeGranularity ${q.get("timeGranularity")}`);
107409
107425
  const range2 = /^\(start:(\([^()]+\))(?:,end:(\([^()]+\)))?\)$/.exec(q.get("dateRange") ?? "");
107410
107426
  if (!range2) invalid8("dateRange requires start and optional end tuples");
107411
- const start = calendar(range2[1]), end = range2[2] ? calendar(range2[2]) : c.env.ctx.clock.now().toISOString().slice(0, 10);
107427
+ const start = calendar2(range2[1]), end = range2[2] ? calendar2(range2[2]) : c.env.ctx.clock.now().toISOString().slice(0, 10);
107412
107428
  if (end < start) invalid8("dateRange.end precedes start");
107413
107429
  const selectedFields2 = q.get("fields")?.split(",") ?? ["impressions", "clicks"];
107414
107430
  const allowed2 = ["pivotValues", "dateRange", "impressions", "clicks", "oneClickLeads", "costInLocalCurrency"];
@@ -117586,9 +117602,9 @@ function seed21(ctx) {
117586
117602
  entry2.resolved?.by ?? null
117587
117603
  );
117588
117604
  }
117589
- for (const calendar3 of input4.onCall) {
117590
- const users5 = calendar3.users.map((email11) => db3.prepare("SELECT id FROM bs_users WHERE email = ?").get(email11).id);
117591
- db3.prepare("INSERT INTO bs_calendars (id, name, is_default, users) VALUES (?, ?, ?, ?)").run(nextId3(ctx, "calendar"), calendar3.name, calendar3.default ? 1 : 0, JSON.stringify(users5));
117605
+ for (const calendar4 of input4.onCall) {
117606
+ const users5 = calendar4.users.map((email11) => db3.prepare("SELECT id FROM bs_users WHERE email = ?").get(email11).id);
117607
+ db3.prepare("INSERT INTO bs_calendars (id, name, is_default, users) VALUES (?, ?, ?, ?)").run(nextId3(ctx, "calendar"), calendar4.name, calendar4.default ? 1 : 0, JSON.stringify(users5));
117592
117608
  }
117593
117609
  for (const page18 of input4.statusPages) {
117594
117610
  const id14 = nextId3(ctx, "page");
@@ -117644,9 +117660,9 @@ function dumpState20(ctx) {
117644
117660
  resolvedBy: row2.resolved_by,
117645
117661
  ...row2.summary && { summary: row2.summary }
117646
117662
  })),
117647
- onCall: db3.prepare("SELECT * FROM bs_calendars ORDER BY rowid").all().map((calendar3) => ({
117648
- name: calendar3.name,
117649
- users: JSON.parse(calendar3.users).map((id14) => db3.prepare("SELECT email FROM bs_users WHERE id = ?").get(id14)?.email ?? id14)
117663
+ onCall: db3.prepare("SELECT * FROM bs_calendars ORDER BY rowid").all().map((calendar4) => ({
117664
+ name: calendar4.name,
117665
+ users: JSON.parse(calendar4.users).map((id14) => db3.prepare("SELECT email FROM bs_users WHERE id = ?").get(id14)?.email ?? id14)
117650
117666
  })),
117651
117667
  statusPages: db3.prepare("SELECT * FROM bs_pages ORDER BY rowid").all().map((page18) => ({
117652
117668
  id: page18.id,
@@ -131067,7 +131083,7 @@ function feeFor(series2, count4, price3, taker) {
131067
131083
  const exact = rate * series2.fee_multiplier * (count4 / 100) * (price3 / ONE) * (1 - price3 / ONE);
131068
131084
  return Math.ceil(exact * 100 - 1e-9) * 1e4;
131069
131085
  }
131070
- function ledger(ctx, now11) {
131086
+ function ledger2(ctx, now11) {
131071
131087
  const db3 = ctx.store.db, positions2 = /* @__PURE__ */ new Map();
131072
131088
  let cash = db3.prepare("SELECT COALESCE(SUM(amount), 0) AS total FROM kx_deposits WHERE at_ms <= ?").get(now11).total;
131073
131089
  for (const fill of db3.prepare("SELECT * FROM kx_fills WHERE created_ms <= ? ORDER BY created_ms, rowid").all(now11)) {
@@ -131106,7 +131122,7 @@ function ledger(ctx, now11) {
131106
131122
  }
131107
131123
  var collateral = (order5) => (order5.initial - order5.filled) * (order5.book_side === "bid" ? order5.price : ONE - order5.price);
131108
131124
  function balances(ctx, now11) {
131109
- const { cash, positions: positions2 } = ledger(ctx, now11);
131125
+ const { cash, positions: positions2 } = ledger2(ctx, now11);
131110
131126
  const held = restingOrders(ctx, now11).reduce((total2, order5) => total2 + collateral(order5), 0);
131111
131127
  let value4 = 0;
131112
131128
  for (const entry2 of positions2.values()) if (entry2.position) value4 += Math.abs(entry2.position) * (entry2.position > 0 ? getMarket(ctx, entry2.ticker).last_price : ONE - getMarket(ctx, entry2.ticker).last_price);
@@ -131151,7 +131167,7 @@ function seed32(ctx) {
131151
131167
  });
131152
131168
  });
131153
131169
  input4.orders.forEach((entry2, i) => {
131154
- const id14 = seededUuid(`order:${i}`), created3 = at3(entry2.created), series2 = seriesOfMarket(ctx, getMarket(ctx, entry2.market)), positionBefore = ledger(ctx, created3).positions.get(entry2.market)?.position ?? 0;
131170
+ const id14 = seededUuid(`order:${i}`), created3 = at3(entry2.created), series2 = seriesOfMarket(ctx, getMarket(ctx, entry2.market)), positionBefore = ledger2(ctx, created3).positions.get(entry2.market)?.position ?? 0;
131155
131171
  const legacy2 = legacySide(entry2.side, positionBefore);
131156
131172
  db3.prepare(`INSERT INTO kx_orders (id, client_order_id, ticker, book_side, side, action, outcome_side, price, initial, filled, time_in_force, post_only, stp, cancel_on_pause, expiration_ms, created_ms, updated_ms, canceled_ms,
131157
131173
  taker_cost, maker_cost, taker_fees, maker_fees) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, 0, 'taker_at_cross', 0, NULL, ?, ?, ?, 0, 0, 0, 0)`).run(id14, entry2.clientOrderId ?? null, entry2.market, entry2.side, legacy2.side, legacy2.action, legacy2.outcome, price3(entry2.price), count4(entry2.count), entry2.timeInForce, created3, created3, entry2.canceled === void 0 ? null : at3(entry2.canceled));
@@ -131632,7 +131648,7 @@ function positions(call2) {
131632
131648
  choice2(settlement, "settlement_status", ["all", "settled", "unsettled"]);
131633
131649
  for (const name5 of counts) choice2(name5, "count_filter", ["position", "total_traded"]);
131634
131650
  const ticker2 = params10.get("ticker"), eventTicker = params10.get("event_ticker");
131635
- const entries3 = [...ledger(ctx, now11).positions.values()].filter((entry2) => {
131651
+ const entries3 = [...ledger2(ctx, now11).positions.values()].filter((entry2) => {
131636
131652
  const market2 = getMarket(ctx, entry2.ticker);
131637
131653
  return (settlement === "all" || settlement === "settled" === (entry2.settlement !== void 0)) && (!ticker2 || entry2.ticker === ticker2) && (!eventTicker || market2.event === eventTicker) && (!counts.length || counts.some((name5) => name5 === "position" ? entry2.position !== 0 : entry2.traded !== 0));
131638
131654
  });
@@ -131694,7 +131710,7 @@ function settlements(call2) {
131694
131710
  const ctx = call2.ctx, now11 = ctx.clock.nowMs(), params10 = query8(call2, ["limit", "cursor", "ticker", "event_ticker", "min_ts", "max_ts", "subaccount"]), ticker2 = params10.get("ticker"), eventTicker = params10.get("event_ticker");
131695
131711
  primary2(params10.get("subaccount"));
131696
131712
  const within = timeRange2(params10, "min_ts", "max_ts");
131697
- const rows7 = [...ledger(ctx, now11).positions.values()].filter((entry2) => entry2.settlement && (!ticker2 || entry2.ticker === ticker2) && (!eventTicker || getMarket(ctx, entry2.ticker).event === eventTicker) && within(entry2.settlement.at)).sort((a, b) => b.settlement.at - a.settlement.at);
131713
+ const rows7 = [...ledger2(ctx, now11).positions.values()].filter((entry2) => entry2.settlement && (!ticker2 || entry2.ticker === ticker2) && (!eventTicker || getMarket(ctx, entry2.ticker).event === eventTicker) && within(entry2.settlement.at)).sort((a, b) => b.settlement.at - a.settlement.at);
131698
131714
  const result = page11(call2, rows7, 200, 100);
131699
131715
  return json22({
131700
131716
  settlements: result.items.map((entry2) => ({
@@ -147148,7 +147164,7 @@ function bindValue(value4) {
147148
147164
  }
147149
147165
  var pad2 = (n2, width = 2) => String(n2).padStart(width, "0");
147150
147166
  var MONTHS2 = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
147151
- function calendar2(y, m, d) {
147167
+ function calendar3(y, m, d) {
147152
147168
  const date10 = /* @__PURE__ */ new Date(0);
147153
147169
  date10.setUTCFullYear(y, m - 1, d);
147154
147170
  date10.setUTCHours(0, 0, 0, 0);
@@ -147158,7 +147174,7 @@ function calendar2(y, m, d) {
147158
147174
  function isoDate(text23) {
147159
147175
  const match3 = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text23);
147160
147176
  if (!match3) invalid24("Expected a YYYY-MM-DD world date.");
147161
- calendar2(+match3[1], +match3[2], +match3[3]);
147177
+ calendar3(+match3[1], +match3[2], +match3[3]);
147162
147178
  return text23;
147163
147179
  }
147164
147180
  function dateModel(model) {
@@ -147198,7 +147214,7 @@ function parseDate2(value4, model) {
147198
147214
  const values2 = new Map(tokens3.map((t, i) => [t, match3[i + 1]]));
147199
147215
  if (!values2.has("YYYY") || !values2.has("DD") || !["MM", "MON", "MONTH"].some((t) => values2.has(t))) invalid24("TO_DATE requires year, month and day.", true);
147200
147216
  const month = values2.has("MM") ? Number(values2.get("MM")) : MONTHS2.findIndex((m) => values2.has("MON") ? m.slice(0, 3).toLowerCase() === values2.get("MON").toLowerCase() : m.toLowerCase() === values2.get("MONTH").toLowerCase()) + 1;
147201
- const date10 = calendar2(Number(values2.get("YYYY")), month, Number(values2.get("DD")));
147217
+ const date10 = calendar3(Number(values2.get("YYYY")), month, Number(values2.get("DD")));
147202
147218
  let hour2 = Number(values2.get("HH24") ?? values2.get("HH12") ?? values2.get("HH") ?? 0);
147203
147219
  const minute2 = Number(values2.get("MI") ?? 0), second = Number(values2.get("SS") ?? 0);
147204
147220
  if (values2.has("HH12") || values2.has("HH")) {
@@ -151039,14 +151055,29 @@ function record8(ctx, args) {
151039
151055
  }
151040
151056
  const applied = composite2 ? [...byLine.values()].sort((a, b) => a.doc - b.doc || a.line - b.line) : applications(ctx, id14).map((a) => ({ doc: a.doc, amount: a.amount })).sort((a, b) => a.doc - b.doc);
151041
151057
  const wanted = args.apply?.map((a) => composite2 ? { ...a, line: a.line ?? 0 } : { ...a }).sort((a, b) => a.doc - b.doc || (a.line ?? 0) - (b.line ?? 0));
151042
- return checkOutcome(matches8(actual, args.fields ?? {}) && (wanted === void 0 || isDeepStrictEqual(applied, wanted)), expected, JSON.stringify({ record: actual, apply: applied }));
151058
+ const creditLines = args.credit?.some((a) => a.line !== void 0);
151059
+ const credits = /* @__PURE__ */ new Map();
151060
+ for (const a of edges(ctx, id14).filter((a2) => a2.source !== id14)) {
151061
+ const key4 = creditLines ? `${a.source}:${a.sourceline}` : String(a.source);
151062
+ const item2 = credits.get(key4) ?? { doc: a.source, ...creditLines && { line: a.sourceline }, amount: 0 };
151063
+ item2.amount = Math.round((item2.amount + a.amount) * 100) / 100;
151064
+ credits.set(key4, item2);
151065
+ }
151066
+ const sort = (a, b) => a.doc - b.doc || (a.line ?? 0) - (b.line ?? 0);
151067
+ const credited = [...credits.values()].sort(sort);
151068
+ const wantedCredits = args.credit?.map((a) => creditLines ? { ...a, line: a.line ?? 0 } : { ...a }).sort(sort);
151069
+ const creditExpected = args.credit === void 0 ? "" : ` and credits ${JSON.stringify(args.credit)}`;
151070
+ return checkOutcome(matches8(actual, args.fields ?? {}) && (wanted === void 0 || isDeepStrictEqual(applied, wanted)) && (wantedCredits === void 0 || isDeepStrictEqual(credited, wantedCredits)), expected + creditExpected, JSON.stringify({ record: actual, apply: applied, credit: credited }));
151043
151071
  }
151044
151072
  function unchanged(ctx, args) {
151045
- const changes = sql(ctx).prepare("SELECT recordtype, id, operation FROM ns_history ORDER BY ordinal").all().filter((row2) => args.types.includes(row2.recordtype));
151046
- return checkOutcome(changes.length === 0, `no writes to ${args.types.join(", ")}`, changes.length ? JSON.stringify(changes) : "no committed writes");
151073
+ const allowed2 = (args.except ?? []).map((r2) => ({ type: r2.type, id: r2.id ?? byExternalId(ctx, r2.type, r2.externalId) }));
151074
+ const changes = sql(ctx).prepare("SELECT recordtype, id, operation FROM ns_history ORDER BY ordinal").all().filter((row2) => args.types.includes(row2.recordtype) && !allowed2.some((r2) => r2.type === row2.recordtype && r2.id === row2.id));
151075
+ const types = args.types.length >= netsuiteRecordTypes.length && netsuiteRecordTypes.every((type) => args.types.includes(type)) ? "NetSuite records" : args.types.length > 4 ? `${args.types.slice(0, 3).join(", ")} and ${args.types.length - 3} more record types` : args.types.join(", ");
151076
+ const except = args.except?.length ? ` except ${args.except.map((r2) => `${r2.type} ${r2.id ?? `eid:${r2.externalId}`}`).join(", ")}` : "";
151077
+ return checkOutcome(changes.length === 0, `no writes to ${types}${except}`, changes.length ? JSON.stringify(changes) : except ? "no other committed writes" : "no committed writes");
151047
151078
  }
151048
151079
  function count3(ctx, args) {
151049
- const actual = recordIds(ctx, args.type).length;
151080
+ const actual = args.includeSettlement && isTx(args.type) ? sql(ctx).prepare("SELECT COUNT(*) AS count FROM ns_transactions WHERE recordtype = ?").get(args.type).count : recordIds(ctx, args.type).length;
151050
151081
  return checkOutcome(actual === args.count, `${args.count} ${args.type} records`, `${actual} records`);
151051
151082
  }
151052
151083
 
@@ -152550,8 +152581,9 @@ var TrialSessions = class {
152550
152581
  });
152551
152582
  }
152552
152583
  /**
152553
- * The runner records the agent's answer for it when the agent posted none (SPEC-053 F2): an HTTP agent's reply, or the
152554
- * final block of its stdout. The same `POST /done` entry, with that source; never a second answer.
152584
+ * The runner records the agent's answer for it when the agent posted none (SPEC-053 F2): an HTTP agent's reply, or its
152585
+ * stdout (SPEC-056 A), or how much it printed when that is too long to be an answer. The same `POST /done` entry, with
152586
+ * that source; never a second answer.
152555
152587
  */
152556
152588
  answer(env, id14, answer) {
152557
152589
  return env.serialize(() => {
@@ -152559,7 +152591,7 @@ var TrialSessions = class {
152559
152591
  if (state2 === "prepared") throw new AnchaError("SESSION_CONFLICT", "session has not started");
152560
152592
  if (state2 === "finished") throw new AnchaError("SESSION_CONFLICT", "session has finished");
152561
152593
  if (env.trace.list().some((entry2) => entry2.service === "agent" && entry2.path === "/done")) return { recorded: false };
152562
- env.trace.record({ source: "agent", service: "agent", method: "POST", path: "/done", status: 200, request: { output: answer.output, source: answer.source } });
152594
+ env.trace.record({ source: "agent", service: "agent", method: "POST", path: "/done", status: 200, request: { output: answer.output, source: answer.source, ...answer.printed !== void 0 && { printed: answer.printed } } });
152563
152595
  return { recorded: true };
152564
152596
  });
152565
152597
  }
@@ -152874,7 +152906,7 @@ function parseStartOptions(value4) {
152874
152906
  if (input4.delivery !== void 0) parseOptions({ mode: "endpoint", delivery: input4.delivery });
152875
152907
  return input4;
152876
152908
  }
152877
- var MAX_ANSWER_CHARS = 16e3;
152909
+ var MAX_ANSWER_CHARS = 64 * 1024;
152878
152910
  function sessionRoutes(opts, sessions) {
152879
152911
  const app2 = new Hono3();
152880
152912
  const token4 = (header3) => /^Bearer\s+(\S+)\s*$/i.exec(header3 ?? "")?.[1];
@@ -152908,10 +152940,13 @@ function sessionRoutes(opts, sessions) {
152908
152940
  } catch {
152909
152941
  throw new AnchaError("USAGE", "request must be a JSON object");
152910
152942
  }
152911
- fields10(input4, ["output", "source"]);
152943
+ fields10(input4, ["output", "source", "printed"]);
152912
152944
  if (typeof input4.output !== "string" || input4.output.length > MAX_ANSWER_CHARS) throw new AnchaError("USAGE", `output must be a string of at most ${MAX_ANSWER_CHARS} characters`);
152913
152945
  if (input4.source !== "reply" && input4.source !== "stdout") throw new AnchaError("USAGE", "source must be reply or stdout");
152914
- return c.json(await sessions.answer(opts.manager.get(c.req.param("id")), c.req.param("sid"), { output: input4.output, source: input4.source }));
152946
+ if (input4.printed !== void 0 && (input4.source !== "stdout" || input4.output !== "" || typeof input4.printed !== "number" || !Number.isSafeInteger(input4.printed) || input4.printed <= 0)) {
152947
+ throw new AnchaError("USAGE", "printed is how many characters stdout held, with source stdout and an empty output");
152948
+ }
152949
+ return c.json(await sessions.answer(opts.manager.get(c.req.param("id")), c.req.param("sid"), { output: input4.output, source: input4.source, ...input4.printed !== void 0 && { printed: input4.printed } }));
152915
152950
  });
152916
152951
  app2.post("/envs/:id/trials/:sid/agent", async (c) => {
152917
152952
  let input4;
@@ -170938,8 +170973,30 @@ import { lookup as lookup5 } from "node:dns/promises";
170938
170973
  import { createServer, request } from "node:http";
170939
170974
  import { request as secureRequest } from "node:https";
170940
170975
  import { isIP as isIP2 } from "node:net";
170976
+ import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib";
170941
170977
  var BODY_LIMIT = 8 * 1024 * 1024;
170942
170978
  var HOP_HEADERS = /* @__PURE__ */ new Set(["connection", "proxy-connection", "proxy-authenticate", "proxy-authorization", "keep-alive", "te", "trailer", "transfer-encoding", "upgrade"]);
170979
+ var MODEL_REFUSALS = /* @__PURE__ */ new Set([401, 402, 403, 429]);
170980
+ var REFUSAL_BYTES = 4096;
170981
+ function refusalMessage(body6, encoding) {
170982
+ let text23;
170983
+ try {
170984
+ const raw3 = encoding === "gzip" || encoding === "x-gzip" ? gunzipSync(body6) : encoding === "deflate" ? inflateSync(body6) : encoding === "br" ? brotliDecompressSync(body6) : !encoding || encoding === "identity" ? body6 : void 0;
170985
+ if (raw3 === void 0) return void 0;
170986
+ text23 = raw3.toString("utf8");
170987
+ } catch {
170988
+ return void 0;
170989
+ }
170990
+ let message8 = text23;
170991
+ try {
170992
+ const json33 = JSON.parse(text23);
170993
+ const error64 = json33?.error;
170994
+ message8 = typeof error64 === "string" ? error64 : typeof error64?.message === "string" ? error64.message : typeof json33?.message === "string" ? json33.message : typeof json33?.detail === "string" ? json33.detail : typeof error64?.type === "string" ? error64.type : typeof error64?.code === "string" ? error64.code : text23;
170995
+ } catch {
170996
+ }
170997
+ const line2 = String(message8).replace(/\b(sk|rk|pk)-[\w*-]{4,}/g, "$1-\u2026").replace(/\s+/g, " ").trim();
170998
+ return line2 === "" ? void 0 : line2.length > 300 ? `${line2.slice(0, 299)}\u2026` : line2;
170999
+ }
170943
171000
  function loopbackOrigin(value4) {
170944
171001
  const url4 = new URL(value4);
170945
171002
  if (url4.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url4.hostname) || url4.username || url4.password) throw new Error("Isolation gateway requires a local HTTP tool server");
@@ -171080,11 +171137,30 @@ async function startIsolationGateway(options3) {
171080
171137
  agent: false,
171081
171138
  ...modelHost && { servername: modelHost, rejectUnauthorized: true, family: modelAddress.family }
171082
171139
  }, (reply5) => {
171083
- if (modelHost !== void 0 && reply5.statusCode !== void 0) {
171140
+ const observe2 = (host, status4, message8) => {
171084
171141
  try {
171085
- options3.onModelReply?.(modelHost, reply5.statusCode);
171142
+ options3.onModelReply?.(host, status4, message8);
171086
171143
  } catch {
171087
171144
  }
171145
+ };
171146
+ if (modelHost !== void 0 && reply5.statusCode !== void 0) {
171147
+ const host = modelHost, status4 = reply5.statusCode;
171148
+ if (!MODEL_REFUSALS.has(status4)) observe2(host, status4);
171149
+ else {
171150
+ const chunks2 = [];
171151
+ let size3 = 0, told = false;
171152
+ const tell = () => {
171153
+ if (told) return;
171154
+ told = true;
171155
+ observe2(host, status4, size3 <= REFUSAL_BYTES ? refusalMessage(Buffer.concat(chunks2), reply5.headers["content-encoding"]?.toLowerCase()) : void 0);
171156
+ };
171157
+ reply5.on("data", (chunk) => {
171158
+ size3 += chunk.length;
171159
+ if (size3 <= REFUSAL_BYTES) chunks2.push(chunk);
171160
+ });
171161
+ reply5.once("end", tell);
171162
+ reply5.once("close", tell);
171163
+ }
171088
171164
  }
171089
171165
  if (reply5.statusCode && reply5.statusCode >= 300 && reply5.statusCode < 400) {
171090
171166
  reply5.destroy();
@@ -193,7 +193,7 @@ class AnchaAgent(BaseInstalledAgent):
193
193
  ran = time.monotonic() - getattr(self, 'ran_from', time.monotonic())
194
194
  limit = max(1, min(max(60, math.ceil(2 * ran)), max(60, math.ceil(self.attempt['timeoutMs'] / 1000))))
195
195
  for _ in range(2):
196
- began = time.monotonic()
196
+ began = time.monotonic(); capture = None
197
197
  try:
198
198
  capture = await asyncio.shield(environment.service_exec('node /opt/ancha/companion.mjs capture',service='tools',timeout_sec=limit))
199
199
  check(capture,'Could not collect final tool state')
@@ -201,10 +201,22 @@ class AnchaAgent(BaseInstalledAgent):
201
201
  return
202
202
  except BaseException as exc:
203
203
  timed_out = isinstance(exc, (TimeoutError, asyncio.TimeoutError)) or time.monotonic() - began >= limit - 1
204
- CAPTURES[self.aid] = {'captureError':'Final tool state could not be collected','invalidReason':'capture_timeout' if timed_out else 'capture_failed'}
204
+ CAPTURES[self.aid] = {'captureError':'Final tool state could not be collected','invalidReason':'capture_timeout' if timed_out else 'capture_failed',
205
+ 'detail':capture_detail(capture, exc, timed_out, limit)}
205
206
  if CANCELLED or isinstance(exc, asyncio.CancelledError): return
206
207
 
207
208
 
209
+ def capture_detail(result, exc, timed_out, limit):
210
+ """Why the final capture failed, in one line: the world's own error, the end of its output, or the exception."""
211
+ if timed_out: return f'no answer within {limit} s'
212
+ if result is not None and getattr(result, 'return_code', 0) != 0:
213
+ out = (getattr(result, 'stdout', None) or '').strip()
214
+ try: message = json.loads(out).get('error')
215
+ except (ValueError, TypeError, AttributeError): message = None
216
+ return safe(message or out or (getattr(result, 'stderr', None) or '').strip() or f'exit {result.return_code}')[-300:]
217
+ return safe(f'{type(exc).__name__}: {exc}')[:300]
218
+
219
+
208
220
  def render(template, info, attempt):
209
221
  import re
210
222
  values={'task':attempt['prompt'],'env.id':info['id'],'trial':str(attempt['number']),
@@ -235,8 +247,10 @@ def final_event(aid, error):
235
247
  status='completed';fields['outcome']='invalid'
236
248
  fields['invalidReason']='people_model_failed' if any(issue.get('service')=='people' for issue in issues) else 'harness_failed'
237
249
  elif capture and status=='completed':
238
- # The agent finished; only the final capture failed. Complete, but invalid: not graded, not an error.
250
+ # The agent finished; only the final capture failed. Complete, but invalid: not graded, not an error. Why it
251
+ # failed stays with the attempt as a harness issue.
239
252
  fields['outcome']='invalid';fields['invalidReason']=capture.get('invalidReason','capture_failed')
253
+ if capture.get('detail'): fields['harnessIssues']=[{'owner':'harness','service':'tools','kind':'capture','message':f"{capture['captureError']}: {capture['detail']}"}]
240
254
  elif capture and status!='stopped':
241
255
  status='error';fields['error']=capture['captureError']
242
256
  if error and fields.get('outcome')!='invalid': fields['error']=safe(error.exception_message)[:2000]
@@ -2152,7 +2152,7 @@ function starterCount(tool, key, state) {
2152
2152
  }
2153
2153
 
2154
2154
  // frontend/src/generated/coding-agent-skill.ts
2155
- var codingAgentSkill = "---\nname: ancha\ndescription: Test, debug and fix an AI agent (a Slack bot, a support or on-call agent) against stateful replicas of the tools it uses, built from its production traces, and prove a fix with graded runs in the cloud. Use when asked to test an agent with Ancha, or in a repository that has ancha.yaml.\n---\n\n# Ancha\n\nAncha gives an AI agent the other side of its job: stateful replicas of the tools it uses (Slack, GitHub, Datadog, PagerDuty and more), seeded with one fictional company or rebuilt from a production trace, and checks that grade every attempt from the agent's calls and the world's end state. The verdict comes from the world, not from mocks you wrote yourself. `ancha run --on cloud` runs each attempt on a fresh machine of its own in Ancha's cloud.\n\n## Run the CLI\n\nBefore the CLI is installed, run every command as `npx -y @ancha-labs/cli <command>`. After `npm install -g @ancha-labs/cli` (Node 24 or newer), run `ancha <command>`. Never run `npx` with the bare name `ancha`: that npm name is not this package.\n\nAdd `--json` to every command. Runs print NDJSON events that end with `run_finished`; `ancha traces upload` prints the tests it made. `env list` and `sandbox list` return arrays; trace commands use the fields described in `ancha docs traces`. `ancha schema <kind> --json` prints the JSON Schema of `ancha.yaml`, test files (`scene.yaml`) and these outputs. If your command can time out, give `ancha run` an `--idempotency-key <key>`: running it again with the same key returns the same run instead of starting another.\n\n## First steps\n\n<!-- ancha:first-steps -->\n1. **Install the CLI and sign in.** It needs Node 24 or newer. Approve this computer in the browser, once.\n ```sh\n ancha --version || npm install -g @ancha-labs/cli\n ancha login\n ```\n2. **Set up the project.** Run it in the agent's project: it finds the command that starts the agent and how the agent takes its task, and writes both to `ancha.yaml`. It installs and runs nothing.\n ```sh\n ancha init\n ```\n - To name the command yourself: `ancha init --agent \"<the command that starts your agent>\"`.\n - To name its tools yourself (NetSuite, Slack, ...): `ancha init --tools netsuite,slack`.\n3. **Store the key it needs.** The agent's own model key, read from your shell, never from an argument: it is stored in your workspace and named under `agent.pass_env` in `ancha.yaml`, so the agent gets it in every cloud attempt.\n ```sh\n ancha secrets set ANTHROPIC_API_KEY\n ```\n4. **Upload your agent.** A fresh machine in the cloud installs the project's dependencies and starts the agent once with a task. It says the agent is ready, or shows the end of its log.\n ```sh\n ancha agent upload\n ```\n - The install follows the project's own manifests and lockfiles; `agent.install` in `ancha.yaml` sets the command instead.\n5. **Without production traces.** For an agent that uses NetSuite, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests from the questions an operator asks.\n - Your data: `ancha world import netsuite <your exports> --id <id>` reads REST record JSON, SuiteQL results and saved search CSV into `ancha/worlds/<id>.yaml`; check it with `ancha world validate`. To write the seed yourself, `ancha twins seed netsuite` lists its fields.\n - Your evals: `ancha test import <file> --world <id>` (JSONL, JSON, CSV or YAML with a question and an expected answer).\n - One test from a sentence: `ancha test new \"<sentence>\" --world <id>`.\n6. **Upload traces.** A file or a folder of traces, runs that went fine and runs that failed: each trace becomes a test, in `scenes/from-traces/` and in your workspace.\n ```sh\n ancha traces upload ./traces\n ```\n - From Langfuse or LangSmith, with your keys on this computer: `ancha traces upload --from langfuse --limit 50`, or `--from langsmith`.\n - A trace of a run that went wrong can say what went wrong: `ancha traces upload <trace file> --expect \"<what went wrong>\"`, or for a test already made, `ancha pull <test id> --expect \"<what went wrong>\"`.\n - Traces your agent already sent to your workspace: `ancha traces`, then `ancha pull <trace id>`.\n - A test lists what one trace cannot settle: answer with `ancha pull <test id> --answer <question>=<answer>`.\n7. **Point the agent at the test's tools.** In a test, the agent calls Ancha instead of production:\n - Its clients for Slack, GitHub and the other tools Ancha replicates take the URLs and credentials Ancha supplies: `ancha connect <tool>` prints the settings.\n - Its own functions: wrap them with `wrapTools` from `@ancha-labs/tools` (`ancha.wrap_tools` in Python), or serve them over MCP.\n8. **Run your tests.** Every test, each attempt on a fresh machine. The run grades each attempt check by check and ends with the link to its result.\n ```sh\n ancha run\n ```\n - Your agent and its worlds run in the cloud, each attempt on a fresh machine of its own; a run keeps going when your laptop closes, and its results land in Runs.\n - `--attempts <n>` sets how many attempts each test gets, `--concurrency <n>` how many run at once.\n - `ancha wait <run id>` follows a run again from any terminal; `ancha explain <run id>` shows why a check failed.\n - `ancha status` shows which of these steps your workspace has done.\n9. **Fix the agent and keep the test.** Keep the failing run as the reference, fix the agent, and run again: exit 0 means every check passes and nothing regressed.\n ```sh\n ancha baseline save before --from <run id>\n ancha run --compare before\n ```\n - Commit `scenes/from-traces/` so every run, in CI too, keeps it fixed.\n10. **Run it on this computer.** While you develop, `ancha run --on local` runs the agent and its worlds on this computer, with the same checks.\n ```sh\n ancha run --on local --attempts 1\n ```\n - Here the agent gets the keys in `agent.pass_env` from your shell, and model-graded checks need `OPENROUTER_API_KEY`.\n<!-- /ancha:first-steps -->\n\n## Cloud runs\n\n- `ancha run --on cloud` sends the project as one bundle: the agent's files, without hidden directories, dependencies or credential-like files, and its tests with their worlds and checks, which stay with the grader and never reach the agent. Each attempt's machine installs the dependencies, runs the agent and grades it with the same engine as a run on this computer. `--attempts <n>` sets the attempts per test, `--concurrency <n>` how many run at once.\n- The agent gets the workspace's secrets for the names in `agent.pass_env`, and its network reaches its tools and its model providers. Model-graded checks and the people in a world run on the workspace's model credit.\n- The `run_finished` event carries `url` (the result in the workspace) and `summary`, with `counts` of the attempts: requested, completed, invalid, skipped and cancelled. Interrupting the command stops the following, never the run: `ancha wait <run id>` follows it again, and `--detach` returns once the run is accepted.\n- `ancha explain <run id> --json` shows each failed check: what was expected, what happened, and the calls and world events behind it. Read it before guessing from the code; many bugs only show up with the world's data and timing.\n- When every attempt ended before the agent did anything (it exited within seconds without a call, or its command could not start), the run, `ancha wait` and `ancha explain` say that first: \"Your agent didn't run\", the end of its log once, and the likely fix read from it, such as the `agent.env` line that gives the agent its task under the name it reads. `agentNeverRan` in the JSON carries the same. Make that fix first: the failed checks follow from it, and `ancha explain <run id> --all` lists them.\n- `ancha status --json` shows the workspace's three steps (agent uploaded, tests added, tests run in the cloud) and the next command. In CI, `ANCHA_SERVER_URL` and `ANCHA_API_KEY` replace the login. More: `ancha docs cloud`.\n\n## An app, not a command\n\nIf the AI feature lives inside an app (a web app or API server with its database, workers and scheduled jobs), don't wrap it in `agent.command`. Ancha starts the app once per attempt with `agent.start`, waits for `agent.ready_url`, delivers the tools' events to `agent.url`, and a scene's `world_rules.app_calls` call the app's own routes, such as its cron jobs, at a time. Read `ancha docs apps` before writing `ancha.yaml`. The start script gives the app a clean database, cache and seed every attempt: a new world has new URLs and tokens, and stale rows or sync cursors make an app silently do nothing.\n\n## More from production traces\n\n`ancha traces upload <file or folder> --json` sends the traces to the workspace, which rebuilds each one's world and checks, and writes each test to `scenes/from-traces/<name>/scene.yaml`: runs that went fine and runs that failed. `--from langfuse` or `--from langsmith` takes the newest traces there instead (`--limit`, `--since`), with the keys in this shell. For one trace of a failure, `--expect \"<what went wrong>\"` adds a check for it. A test lists the questions one trace cannot settle, each with the default it uses. Ask the user for the answers; don't guess them. Pass them with `ancha pull <test id> --answer <question>=<value>`. `ancha import --offline <trace file> --json` makes the tests on this computer instead, one per conversation, and uploads nothing; there, `--answer` and `--force` go on the import.\n\nA test from a run that failed should fail the same way production did. If it doesn't, run it on this computer: `ancha traces diff <trace file> latest` shows the calls production made and the attempt didn't, and the import also lists the app's own setup calls, which the start script or an `app_call` has to make.\n\nIf the user's workspace takes traces (their agents send them to it), each trace becomes a test there: `ancha pull --all --json` writes every test that is turned on (`--agent <name>` for one agent's), `ancha traces --failed --json` lists the ones where production failed a check, `ancha traces show <id> --json` previews the test, and `ancha pull <id> --json` writes one, with `--answer` for its questions. Checks you add to a pulled `scene.yaml` stay when you pull a newer version; any other edit stops the pull. More: `ancha docs traces`.\n\n## Other tests\n\nThe starter test `ancha init` writes when `scenes/` holds no tests only proves that the agent reaches each tool. For the agent's real job beyond its traces, `ancha test new \"<the test in one sentence>\" --json` drafts a test with people for the project's world (`ancha init --intent \"<company and scenario>\"` makes the world and a first test). Review its checks before you run it. To write a seed yourself, `ancha twins seed <tool> --json` prints the tool's fields, an example that validates as written, and the checks a test can make on it. More: `ancha docs scenes`.\n\n## The rule\n\nFix the agent, not the tests or their checks. `ancha.yaml` says how to start the agent and give it its task and keys: change it for that, never to make a check pass. The exception is a check that is wrong for the real API, such as a method the official SDK never sends. Then don't quietly edit it: tell the user, show the evidence (the call from `ancha explain`, the vendor's documentation), and change it only with their agreement.\n\nNever give the agent under test the tests, checks, seeds or reference companions (`oracle.mjs`, `null.mjs`), and never point it at a real SaaS API.\n\n## What the agent gets\n\nEach attempt gives the agent its tools as environment variables, with fake credentials that only work against the replicas:\n\n- Slack: `SLACK_API_URL` (ends in `/api/`), `SLACK_BOT_TOKEN`\n- GitHub: `GITHUB_API_URL`, `GITHUB_TOKEN`\n- Datadog: `DATADOG_API_URL`, `DD_API_KEY`, `DD_APP_KEY`\n- PagerDuty: `PAGERDUTY_API_URL`, `PAGERDUTY_API_TOKEN`, `PAGERDUTY_FROM_EMAIL`, `PAGERDUTY_ROUTING_KEY`\n- the same pattern for the other tools in the world; `ANCHA_TASK` carries a command-line task, and `ANCHA_TASK_FILE` names a file holding it. An agent that reads its task under another name gets it with `agent.env: { MY_TASK: \"{{task}}\" }` (`{{task_file}}` for the file); `ancha init` writes that line when it finds the name.\n\n`ancha connect <tool> --lang ts|py` prints the SDK settings. `ancha twins coverage <tool>` lists the endpoints each replica implements.\n\nGoogle clients (`googleapis`, `@googleapis/*`) take the replica's URL in each call's options: `drive.files.list(params, { rootUrl: process.env.GOOGLE_DRIVE_API_URL + '/' })`. A `rootUrl` set on the client keeps only the host; Ancha still routes those calls by their token, but the client sends file uploads to www.googleapis.com.\n\nThe agent's own keys are the names in `agent.pass_env` in `ancha.yaml`, such as `agent.pass_env: [OPENAI_API_KEY]`, and `agent.env` sets fixed values, such as the path of a key file. In the cloud each name comes from the workspace's secrets (`ancha secrets set NAME`). `ancha run --on local` starts the agent on this computer instead, with this computer's network and those names from this shell (or `--pass-env NAME`); `--on docker` seals it in a container (`agent.execution: { mode: container, image: node:24-slim }`, which needs Docker). An agent without its model key stops at its first model call.\n\n## When something fails\n\n- Exit 1: a check failed or the comparison regressed (a single check's drop counts, see `comparison.droppedChecks`). Run `ancha explain <run id> --json`.\n- Exit 2: usage, config, test file or authentication error, or a cancelled cloud run. `AUTH_INVALID` means `ancha login` again or a valid `ANCHA_API_KEY`; `CONFIG_INVALID` naming a workspace secret means `ancha secrets set NAME`. Read the `hint`.\n- Exit 3: infrastructure, or an attempt the harness couldn't run or grade. It counts as invalid, never as a failed check, so it's not the agent's fault; run again, and `ancha agent upload --json` if it repeats.\n- Exit 4, only with `--strict`: an endpoint coverage error or a verdict using simulated tool answers. The summary names the tests, trials and evaluated checks using those answers. `ancha explain` lists endpoint errors; `ancha twins coverage <tool>` shows the endpoint inventory.\n\nRead the error's stable `code` and `message`, then follow its `hint` when provided. More: `ancha docs`, `ancha docs <topic>` for setup, run, traces, explain, compare, scenes, integrations, cloud and playgrounds, and https://docs.ancha.io/coding-agents.\n\nTell the user what you ran, where it ran, the pass rate, the evidence and the result link. Never claim a fix until `ancha run --compare` exits 0.\n";
2155
+ var codingAgentSkill = "---\nname: ancha\ndescription: Test, debug and fix an AI agent (a Slack bot, a support or on-call agent) against stateful replicas of the tools it uses, built from its production traces, and prove a fix with graded runs in the cloud. Use when asked to test an agent with Ancha, or in a repository that has ancha.yaml.\n---\n\n# Ancha\n\nAncha gives an AI agent the other side of its job: stateful replicas of the tools it uses (Slack, GitHub, Datadog, PagerDuty and more), seeded with one fictional company or rebuilt from a production trace, and checks that grade every attempt from the agent's calls and the world's end state. The verdict comes from the world, not from mocks you wrote yourself. `ancha run --on cloud` runs each attempt on a fresh machine of its own in Ancha's cloud.\n\n## Run the CLI\n\nBefore the CLI is installed, run every command as `npx -y @ancha-labs/cli <command>`. After `npm install -g @ancha-labs/cli` (Node 24 or newer), run `ancha <command>`. Never run `npx` with the bare name `ancha`: that npm name is not this package.\n\nAdd `--json` to every command. Runs print NDJSON events that end with `run_finished`; `ancha traces upload` prints the tests it made. `env list` and `sandbox list` return arrays; trace commands use the fields described in `ancha docs traces`. `ancha schema <kind> --json` prints the JSON Schema of `ancha.yaml`, test files (`scene.yaml`) and these outputs. If your command can time out, give `ancha run` an `--idempotency-key <key>`: running it again with the same key returns the same run instead of starting another.\n\n## First steps\n\n<!-- ancha:first-steps -->\n1. **Install the CLI and sign in.** It needs Node 24 or newer. Approve this computer in the browser, once.\n ```sh\n ancha --version || npm install -g @ancha-labs/cli\n ancha login\n ```\n2. **Set up the project.** Run it in the agent's project: it finds the command that starts the agent and how the agent takes its task, and writes both to `ancha.yaml`. It installs and runs nothing.\n ```sh\n ancha init\n ```\n - To name the command yourself: `ancha init --agent \"<the command that starts your agent>\"`.\n - To name its tools yourself (NetSuite, Slack, ...): `ancha init --tools netsuite,slack`.\n3. **Store the key it needs.** The agent's own model key, read from your shell, never from an argument: it is stored in your workspace and named under `agent.pass_env` in `ancha.yaml`, so the agent gets it in every cloud attempt.\n ```sh\n ancha secrets set ANTHROPIC_API_KEY\n ```\n4. **Upload your agent.** A fresh machine in the cloud installs the project's dependencies and starts the agent once with a task. It says the agent is ready, or shows the end of its log.\n ```sh\n ancha agent upload\n ```\n - The install follows the project's own manifests and lockfiles; `agent.install` in `ancha.yaml` sets the command instead.\n5. **Without production traces.** For an agent that uses NetSuite, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests: 10 read tasks and 15 write workflows.\n - Your data: `ancha world import netsuite <your exports> --id <id>` reads REST record JSON, SuiteQL results and saved search CSV into `ancha/worlds/<id>.yaml`; check it with `ancha world validate`. To write the seed yourself, `ancha twins seed netsuite` lists its fields.\n - Your evals: `ancha test import <file> --world <id>` (JSONL, JSON, CSV or YAML with a question and an expected answer).\n - One test from a sentence: `ancha test new \"<sentence>\" --world <id>`.\n6. **Upload traces.** A file or a folder of traces, runs that went fine and runs that failed: each trace becomes a test, in `scenes/from-traces/` and in your workspace.\n ```sh\n ancha traces upload ./traces\n ```\n - From Langfuse or LangSmith, with your keys on this computer: `ancha traces upload --from langfuse --limit 50`, or `--from langsmith`.\n - A trace of a run that went wrong can say what went wrong: `ancha traces upload <trace file> --expect \"<what went wrong>\"`, or for a test already made, `ancha pull <test id> --expect \"<what went wrong>\"`.\n - Traces your agent already sent to your workspace: `ancha traces`, then `ancha pull <trace id>`.\n - A test lists what one trace cannot settle: answer with `ancha pull <test id> --answer <question>=<answer>`.\n7. **Point the agent at the test's tools.** In a test, the agent calls Ancha instead of production:\n - Its clients for Slack, GitHub and the other tools Ancha replicates take the URLs and credentials Ancha supplies: `ancha connect <tool>` prints the settings.\n - Its own functions: wrap them with `wrapTools` from `@ancha-labs/tools` (`ancha.wrap_tools` in Python), or serve them over MCP.\n8. **Run your tests.** Every test, each attempt on a fresh machine. The run grades each attempt check by check and ends with the link to its result.\n ```sh\n ancha run\n ```\n - Your agent and its worlds run in the cloud, each attempt on a fresh machine of its own; a run keeps going when your laptop closes, and its results land in Runs.\n - `--attempts <n>` sets how many attempts each test gets, `--concurrency <n>` how many run at once.\n - `ancha wait <run id>` follows a run again from any terminal; `ancha explain <run id>` shows why a check failed.\n - `ancha status` shows which of these steps your workspace has done.\n9. **Fix the agent and keep the test.** Keep the failing run as the reference, fix the agent, and run again: exit 0 means every check passes and nothing regressed.\n ```sh\n ancha baseline save before --from <run id>\n ancha run --compare before\n ```\n - Commit `scenes/from-traces/` so every run, in CI too, keeps it fixed.\n10. **Run it on this computer.** While you develop, `ancha run --on local` runs the agent and its worlds on this computer, with the same checks.\n ```sh\n ancha run --on local --attempts 1\n ```\n - Here the agent gets the keys in `agent.pass_env` from your shell, and model-graded checks need `OPENROUTER_API_KEY`.\n<!-- /ancha:first-steps -->\n\n## Cloud runs\n\n- `ancha run --on cloud` sends the project as one bundle: the agent's files, without hidden directories, dependencies or credential-like files, and its tests with their worlds and checks, which stay with the grader and never reach the agent. Each attempt's machine installs the dependencies, runs the agent and grades it with the same engine as a run on this computer. `--attempts <n>` sets the attempts per test, `--concurrency <n>` how many run at once.\n- The agent gets the workspace's secrets for the names in `agent.pass_env`, and its network reaches its tools and its model providers. Model-graded checks and the people in a world run on the workspace's model credit.\n- The `run_finished` event carries `url` (the result in the workspace) and `summary`, with `counts` of the attempts: requested, completed, invalid, skipped and cancelled. Interrupting the command stops the following, never the run: `ancha wait <run id>` follows it again, and `--detach` returns once the run is accepted.\n- `ancha explain <run id> --json` shows each failed check: what was expected, what happened, and the calls and world events behind it. Read it before guessing from the code; many bugs only show up with the world's data and timing.\n- When every attempt ended before the agent did anything (it exited within seconds without a call, or its command could not start), the run, `ancha wait` and `ancha explain` say that first: \"Your agent didn't run\", the end of its log once, and the likely fix read from it, such as the `agent.env` line that gives the agent its task under the name it reads. `agentNeverRan` in the JSON carries the same. Make that fix first: the failed checks follow from it, and `ancha explain <run id> --all` lists them.\n- `ancha status --json` shows the workspace's three steps (agent uploaded, tests added, tests run in the cloud) and the next command. In CI, `ANCHA_SERVER_URL` and `ANCHA_API_KEY` replace the login. More: `ancha docs cloud`.\n\n## An app, not a command\n\nIf the AI feature lives inside an app (a web app or API server with its database, workers and scheduled jobs), don't wrap it in `agent.command`. Ancha starts the app once per attempt with `agent.start`, waits for `agent.ready_url`, delivers the tools' events to `agent.url`, and a scene's `world_rules.app_calls` call the app's own routes, such as its cron jobs, at a time. Read `ancha docs apps` before writing `ancha.yaml`. The start script gives the app a clean database, cache and seed every attempt: a new world has new URLs and tokens, and stale rows or sync cursors make an app silently do nothing.\n\n## More from production traces\n\n`ancha traces upload <file or folder> --json` sends the traces to the workspace, which rebuilds each one's world and checks, and writes each test to `scenes/from-traces/<name>/scene.yaml`: runs that went fine and runs that failed. `--from langfuse` or `--from langsmith` takes the newest traces there instead (`--limit`, `--since`), with the keys in this shell. For one trace of a failure, `--expect \"<what went wrong>\"` adds a check for it. A test lists the questions one trace cannot settle, each with the default it uses. Ask the user for the answers; don't guess them. Pass them with `ancha pull <test id> --answer <question>=<value>`. `ancha import --offline <trace file> --json` makes the tests on this computer instead, one per conversation, and uploads nothing; there, `--answer` and `--force` go on the import.\n\nA test from a run that failed should fail the same way production did. If it doesn't, run it on this computer: `ancha traces diff <trace file> latest` shows the calls production made and the attempt didn't, and the import also lists the app's own setup calls, which the start script or an `app_call` has to make.\n\nIf the user's workspace takes traces (their agents send them to it), each trace becomes a test there: `ancha pull --all --json` writes every test that is turned on (`--agent <name>` for one agent's), `ancha traces --failed --json` lists the ones where production failed a check, `ancha traces show <id> --json` previews the test, and `ancha pull <id> --json` writes one, with `--answer` for its questions. Checks you add to a pulled `scene.yaml` stay when you pull a newer version; any other edit stops the pull. More: `ancha docs traces`.\n\n## Other tests\n\nThe starter test `ancha init` writes when `scenes/` holds no tests only proves that the agent reaches each tool. For the agent's real job beyond its traces, `ancha test new \"<the test in one sentence>\" --json` drafts a test with people for the project's world (`ancha init --intent \"<company and scenario>\"` makes the world and a first test). Review its checks before you run it. To write a seed yourself, `ancha twins seed <tool> --json` prints the tool's fields, an example that validates as written, and the checks a test can make on it. More: `ancha docs scenes`.\n\n## The rule\n\nFix the agent, not the tests or their checks. `ancha.yaml` says how to start the agent and give it its task and keys: change it for that, never to make a check pass. The exception is a check that is wrong for the real API, such as a method the official SDK never sends. Then don't quietly edit it: tell the user, show the evidence (the call from `ancha explain`, the vendor's documentation), and change it only with their agreement.\n\nNever give the agent under test the tests, checks, seeds or reference companions (`oracle.mjs`, `null.mjs`), and never point it at a real SaaS API.\n\n## What the agent gets\n\nEach attempt gives the agent its tools as environment variables, with fake credentials that only work against the replicas:\n\n- Slack: `SLACK_API_URL` (ends in `/api/`), `SLACK_BOT_TOKEN`\n- GitHub: `GITHUB_API_URL`, `GITHUB_TOKEN`\n- Datadog: `DATADOG_API_URL`, `DD_API_KEY`, `DD_APP_KEY`\n- PagerDuty: `PAGERDUTY_API_URL`, `PAGERDUTY_API_TOKEN`, `PAGERDUTY_FROM_EMAIL`, `PAGERDUTY_ROUTING_KEY`\n- the same pattern for the other tools in the world; `ANCHA_TASK` carries a command-line task, and `ANCHA_TASK_FILE` names a file holding it. An agent that reads its task under another name gets it with `agent.env: { MY_TASK: \"{{task}}\" }` (`{{task_file}}` for the file); `ancha init` writes that line when it finds the name.\n\n`ancha connect <tool> --lang ts|py` prints the SDK settings. `ancha twins coverage <tool>` lists the endpoints each replica implements.\n\nGoogle clients (`googleapis`, `@googleapis/*`) take the replica's URL in each call's options: `drive.files.list(params, { rootUrl: process.env.GOOGLE_DRIVE_API_URL + '/' })`. A `rootUrl` set on the client keeps only the host; Ancha still routes those calls by their token, but the client sends file uploads to www.googleapis.com.\n\nThe agent's own keys are the names in `agent.pass_env` in `ancha.yaml`, such as `agent.pass_env: [OPENAI_API_KEY]`, and `agent.env` sets fixed values, such as the path of a key file. In the cloud each name comes from the workspace's secrets (`ancha secrets set NAME`). `ancha run --on local` starts the agent on this computer instead, with this computer's network and those names from this shell (or `--pass-env NAME`); `--on docker` seals it in a container (`agent.execution: { mode: container, image: node:24-slim }`, which needs Docker). An agent without its model key stops at its first model call.\n\n## When something fails\n\n- Exit 1: a check failed or the comparison regressed (a single check's drop counts, see `comparison.droppedChecks`). Run `ancha explain <run id> --json`.\n- Exit 2: usage, config, test file or authentication error, or a cancelled cloud run. `AUTH_INVALID` means `ancha login` again or a valid `ANCHA_API_KEY`; `CONFIG_INVALID` naming a workspace secret means `ancha secrets set NAME`. Read the `hint`.\n- Exit 3: infrastructure, or an attempt the harness couldn't run or grade. It counts as invalid, never as a failed check, so it's not the agent's fault; run again, and `ancha agent upload --json` if it repeats.\n- Exit 4, only with `--strict`: an endpoint coverage error or a verdict using simulated tool answers. The summary names the tests, trials and evaluated checks using those answers. `ancha explain` lists endpoint errors; `ancha twins coverage <tool>` shows the endpoint inventory.\n\nRead the error's stable `code` and `message`, then follow its `hint` when provided. More: `ancha docs`, `ancha docs <topic>` for setup, run, traces, explain, compare, scenes, integrations, cloud and playgrounds, and https://docs.ancha.io/coding-agents.\n\nTell the user what you ran, where it ran, the pass rate, the evidence and the result link. Never claim a fix until `ancha run --compare` exits 0.\n";
2156
2156
 
2157
2157
  // frontend/src/workspace-pages.ts
2158
2158
  var startSentence = "Set up Ancha for this agent: read https://app.ancha.io/llms.txt and follow its first steps.";