@ancha-labs/cli 0.4.52 → 0.4.54

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.
@@ -94,7 +94,7 @@ agent:
94
94
  AGENT_TASK: '{"task": {{task_json}}}'
95
95
  ```
96
96
 
97
- `{{task_json}}` encodes the task as a JSON string, including quotes and newlines. The CLI, `ancha agent upload --json` and the console’s Get started upload result show the same explanation and mapping. Apply the mapping, then run `ancha agent upload` again.
97
+ `{{task_json}}` encodes the task as a JSON string, including quotes and newlines. The CLI, `ancha agent upload --json` and the console’s upload result show the same explanation and mapping. Apply the mapping, then run `ancha agent upload` again.
98
98
 
99
99
  ## Run tests in the cloud
100
100
 
@@ -114,6 +114,8 @@ ancha run --on cloud
114
114
  - `--agent`, `--seed`, `--strict`, `--allow-simulated`, `--min-pass-rate`, `--allow-unwrapped` and `--idempotency-key` mean what they mean on this computer. `--compare <baseline>` compares with a saved baseline: `ancha baseline save before --from <run id>`, fix the agent, then `--compare before`. A cloud run's keys come from the workspace, so `--pass-env` and `--inherit-env` belong to runs on this computer, and its results live in the workspace, so it takes no `--out` or `--upload`.
115
115
  - With `--json` the run announces acceptance with `run_submitted` (`run_detached` with `--detach`), carrying `target: "cloud"` and adding `defaulted: true` when the saved login chose cloud. A followed run prints NDJSON events and ends with `run_finished`: `url` is the result, `summary` the verdict with the attempt and check counts, and `next` the commands to run next. The exit codes are `ancha run`'s: 0 when every check passes, 1 when a check failed, 3 when an attempt could not run or be graded, 4 for an endpoint coverage error with `--strict`, or a verdict using simulated tool answers with `--strict` or in CI, and 2 for a cancelled run.
116
116
 
117
+ In a cloud attempt, each provider base URL points at the attempt's model gateway; `ANCHA_MODEL_URLS` maps each provider host to its gateway URL, so compare hosts rather than whole URLs. With `OPENROUTER_API_KEY`, Ancha fills `ANTHROPIC_AUTH_TOKEN` and `OPENAI_API_KEY` when the agent routes those clients to OpenRouter and holds no key of its own.
118
+
117
119
  ## Follow a run from anywhere
118
120
 
119
121
  A run keeps going when the command stops: Ctrl-C or a dropped connection ends only the following, and the command prints the `ancha wait` line to pick it up. `--detach` returns as soon as the run is accepted, with its id and link.
@@ -127,7 +129,7 @@ ancha runs show <run id> # the run and its attempts
127
129
 
128
130
  ## The first steps, done or not
129
131
 
130
- `ancha status` prints the workspace's three steps, the ones Get started shows, and the next command:
132
+ `ancha status` prints the workspace's three steps and the next command:
131
133
 
132
134
  - **Agent uploaded**: `ancha agent upload` started this project's agent with a task, or a cloud run graded it.
133
135
  - **Tests added**: the workspace holds a trace or a test made from one, or a cloud run ran this project's tests.
@@ -155,11 +157,13 @@ The agent's own keys, its model provider's for one, live in the workspace:
155
157
  export OPENAI_API_KEY=… # the value comes from this shell, never from arguments
156
158
  ancha secrets set OPENAI_API_KEY
157
159
  ancha secrets list # names only, never values
158
- ancha secrets unset OPENAI_API_KEY
160
+ ancha secrets unset OPENAI_API_KEY OPENROUTER_API_KEY
159
161
  ```
160
162
 
161
163
  Run in the agent's project, `ancha secrets set` also names each one under `agent.pass_env` in `ancha.yaml`. A secret's value has at least 8 characters; shorter settings belong under `agent.env`. A cloud run gives the agent those names with the values they had when the run was accepted, so a later change leaves accepted runs as they were. When the workspace lacks one, the run stops before any machine starts, with `CONFIG_INVALID` and the `ancha secrets set` command to run. Setting and removing secrets takes an admin key; the one `ancha login` saves is.
162
164
 
165
+ `ancha secrets unset NAME [NAME ...]` removes each named variable and reports each result. All names are validated before removal; a name that is not saved leaves the other removals running. With `--json`, one result lists `removed`, `notSaved` when present, and the remaining `names` when returned by the workspace. A single removal keeps `removed` as a name; several names return an array.
166
+
163
167
  ## Tools reached through Composio
164
168
 
165
169
  An agent that runs QuickBooks or NetSuite tools through Composio keeps its client code in cloud runs. QuickBooks calls go through Composio's servers to the world's QuickBooks. `NETSUITE_RUN_SUITEQL_QUERY` through `session.execute` or `tools.execute` runs against the world's NetSuite through the attempt's gateway.
@@ -187476,6 +187476,18 @@ function reject2(response6, status4 = 403, message9 = "This destination is outsi
187476
187476
  response6.writeHead(status4, { "content-type": "application/json", "connection": "close" });
187477
187477
  response6.end(JSON.stringify({ error: message9 }));
187478
187478
  }
187479
+ function refusedRpc(body7) {
187480
+ try {
187481
+ const value5 = JSON.parse(body7?.toString("utf8") ?? "");
187482
+ if (!value5 || typeof value5 !== "object" || Array.isArray(value5)) return {};
187483
+ const { method: method2, params: params10 } = value5;
187484
+ if (typeof method2 !== "string" || method2.match(/^[A-Za-z][A-Za-z0-9_./-]{0,63}$/)?.[0] !== method2) return {};
187485
+ const name5 = method2 === "tools/call" ? params10?.name : void 0;
187486
+ return { rpc: method2, ...typeof name5 === "string" && name5.match(/^[A-Z][A-Z0-9_]{0,79}$/)?.[0] === name5 && { slug: name5 } };
187487
+ } catch {
187488
+ return {};
187489
+ }
187490
+ }
187479
187491
  async function startIsolationGateway(options4) {
187480
187492
  options4.signal?.throwIfAborted();
187481
187493
  const env = structuredClone(options4.env), session2 = options4.session && structuredClone(options4.session);
@@ -187506,6 +187518,7 @@ async function startIsolationGateway(options4) {
187506
187518
  const modelHosts = new Set((options4.modelHosts ?? []).map(normalizeModelHost));
187507
187519
  const sockets = /* @__PURE__ */ new Set();
187508
187520
  const upstreamRequests = /* @__PURE__ */ new Set();
187521
+ const modelCounts = {};
187509
187522
  const modelActivity = /* @__PURE__ */ new Set();
187510
187523
  const localRequests = /* @__PURE__ */ new Set();
187511
187524
  let exposedOrigin, closed = false;
@@ -187535,7 +187548,8 @@ async function startIsolationGateway(options4) {
187535
187548
  } catch (error64) {
187536
187549
  const reason2 = error64 instanceof RouteRefusal ? error64.reason : "JSON";
187537
187550
  const toolkit = (error64 instanceof RouteRefusal ? error64.toolkit : void 0) ?? (reason2 === "NETSUITE_TOOL" || /NETSUITE_/.test(toolBody?.toString("utf8") ?? "") || /NETSUITE_/.test(req.url ?? "") || route15?.toolkits && !route15.toolkits.quickbooks ? "netsuite" : "quickbooks");
187538
- route15?.record({ leg: "platform", op: "refused", toolkit, via: composioVia((req.url ?? "").slice("/_tool/composio".length)), method: ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"].includes(req.method ?? "") ? req.method : "OTHER", status: 403, ms: Math.round(performance.now() - toolStarted), reason: reason2 });
187551
+ const via = composioVia((req.url ?? "").slice("/_tool/composio".length));
187552
+ route15?.record({ leg: "platform", op: "refused", toolkit, via, method: ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"].includes(req.method ?? "") ? req.method : "OTHER", ...req.method === "POST" && via === "mcp" && refusedRpc(toolBody), status: 403, ms: Math.round(performance.now() - toolStarted), reason: reason2 });
187539
187553
  refuseComposio(res, reason2, toolkit);
187540
187554
  return;
187541
187555
  }
@@ -187597,12 +187611,25 @@ async function startIsolationGateway(options4) {
187597
187611
  if (!path6) return reject2(res);
187598
187612
  let upstream;
187599
187613
  let modelHost;
187614
+ let recordModelStatus;
187600
187615
  let modelAddress;
187601
187616
  let targetPath = req.url;
187602
187617
  let transform3;
187603
187618
  const model = /^\/_model\/([a-zA-Z0-9.-]+)(\/.*)?$/.exec(path6);
187604
187619
  if (toolCall || model && modelHosts.has(model[1].toLowerCase())) {
187605
187620
  modelHost = toolCall ? "backend.composio.dev" : model[1].toLowerCase();
187621
+ if (!toolCall && modelHost && (modelCounts[modelHost] || Object.keys(modelCounts).length < 8)) {
187622
+ const count9 = modelCounts[modelHost] ??= { requests: 0, ok: 0, refused: 0, other: 0 };
187623
+ count9.requests++;
187624
+ let recorded2 = false;
187625
+ recordModelStatus = (status4) => {
187626
+ if (recorded2) return;
187627
+ recorded2 = true;
187628
+ count9[status4 >= 200 && status4 < 300 ? "ok" : status4 === 401 || status4 === 403 ? "refused" : "other"]++;
187629
+ };
187630
+ res.once("finish", () => recordModelStatus?.(res.statusCode));
187631
+ res.once("close", () => recordModelStatus?.(502));
187632
+ }
187606
187633
  const activityCallback = toolCall ? toolCall.op === "execute" ? options4.onModelActivity ?? route15.activity : void 0 : options4.onModelActivity;
187607
187634
  if (toolCall) {
187608
187635
  const call2 = toolCall, endWindow = call2.op === "execute" ? route15.begin() : void 0;
@@ -187707,6 +187734,7 @@ async function startIsolationGateway(options4) {
187707
187734
  };
187708
187735
  if (!toolCall && modelHost !== void 0 && reply6.statusCode !== void 0) {
187709
187736
  const host = modelHost, status4 = reply6.statusCode;
187737
+ recordModelStatus?.(status4);
187710
187738
  if (!MODEL_REFUSALS.has(status4)) observe2(host, status4);
187711
187739
  else {
187712
187740
  const chunks2 = [];
@@ -187939,7 +187967,7 @@ ${Object.entries(reply6.headers).map(([name5, value5]) => `${name5}: ${value5}`)
187939
187967
  if (exposedOrigin !== url4 && exposedOrigin !== parsed4.origin) throw new Error("Sandbox relay origin is already configured");
187940
187968
  exposedOrigin = parsed4.origin;
187941
187969
  return mapped(exposedOrigin);
187942
- }, close: close2 };
187970
+ }, modelRequests: () => Object.fromEntries(Object.entries(modelCounts).map(([host, counts2]) => [host, { ...counts2 }])), close: close2 };
187943
187971
  }
187944
187972
 
187945
187973
  // backend/src/agent-input.ts
package/lib/worker.mjs CHANGED
@@ -71497,7 +71497,14 @@ import { createServer, request } from "node:http";
71497
71497
  import { request as secureRequest } from "node:https";
71498
71498
  import { isIP } from "node:net";
71499
71499
  import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib";
71500
- function modelFailure(status5) {
71500
+ function modelFailure(status5, message8) {
71501
+ if (status5 === 402 && /in-flight/i.test(message8 ?? "")) return {
71502
+ code: "MODEL_CREDITS_EXHAUSTED",
71503
+ kind: "fix",
71504
+ outcome: "The model key's credits do not cover the requests running at once",
71505
+ did: "says the model key's credits do not cover the requests running at once",
71506
+ fix: "Add credits in the model provider account, or run fewer attempts at once (ancha run --concurrency 1, or parallel: 1 in ancha.yaml)."
71507
+ };
71501
71508
  return status5 === 429 ? { code: "MODEL_RATE_LIMITED", kind: "retry", outcome: "The model provider rate-limited the key", did: "rate-limited the agent's model key", fix: "Wait a little, then run the same command again." } : status5 === 402 ? { code: "MODEL_CREDITS_EXHAUSTED", kind: "fix", outcome: "The model key is out of credits", did: "says the agent's model key is out of credits", fix: "Add credits in the model provider account, then run again." } : { code: "MODEL_KEY_REFUSED", kind: "fix", outcome: "The model key was refused", did: "refused the agent's model key", fix: void 0 };
71502
71509
  }
71503
71510
  function refusalMessage(body7, encoding) {
@@ -71562,6 +71569,18 @@ function reject2(response6, status5 = 403, message8 = "This destination is outsi
71562
71569
  response6.writeHead(status5, { "content-type": "application/json", "connection": "close" });
71563
71570
  response6.end(JSON.stringify({ error: message8 }));
71564
71571
  }
71572
+ function refusedRpc(body7) {
71573
+ try {
71574
+ const value5 = JSON.parse(body7?.toString("utf8") ?? "");
71575
+ if (!value5 || typeof value5 !== "object" || Array.isArray(value5)) return {};
71576
+ const { method: method2, params: params10 } = value5;
71577
+ if (typeof method2 !== "string" || method2.match(/^[A-Za-z][A-Za-z0-9_./-]{0,63}$/)?.[0] !== method2) return {};
71578
+ const name5 = method2 === "tools/call" ? params10?.name : void 0;
71579
+ return { rpc: method2, ...typeof name5 === "string" && name5.match(/^[A-Z][A-Z0-9_]{0,79}$/)?.[0] === name5 && { slug: name5 } };
71580
+ } catch {
71581
+ return {};
71582
+ }
71583
+ }
71565
71584
  async function startIsolationGateway(options5) {
71566
71585
  options5.signal?.throwIfAborted();
71567
71586
  const env = structuredClone(options5.env), session2 = options5.session && structuredClone(options5.session);
@@ -71592,6 +71611,7 @@ async function startIsolationGateway(options5) {
71592
71611
  const modelHosts = new Set((options5.modelHosts ?? []).map(normalizeModelHost));
71593
71612
  const sockets = /* @__PURE__ */ new Set();
71594
71613
  const upstreamRequests = /* @__PURE__ */ new Set();
71614
+ const modelCounts = {};
71595
71615
  const modelActivity = /* @__PURE__ */ new Set();
71596
71616
  const localRequests = /* @__PURE__ */ new Set();
71597
71617
  let exposedOrigin, closed = false;
@@ -71621,7 +71641,8 @@ async function startIsolationGateway(options5) {
71621
71641
  } catch (error64) {
71622
71642
  const reason2 = error64 instanceof RouteRefusal ? error64.reason : "JSON";
71623
71643
  const toolkit = (error64 instanceof RouteRefusal ? error64.toolkit : void 0) ?? (reason2 === "NETSUITE_TOOL" || /NETSUITE_/.test(toolBody?.toString("utf8") ?? "") || /NETSUITE_/.test(req.url ?? "") || route15?.toolkits && !route15.toolkits.quickbooks ? "netsuite" : "quickbooks");
71624
- route15?.record({ leg: "platform", op: "refused", toolkit, via: composioVia((req.url ?? "").slice("/_tool/composio".length)), method: ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"].includes(req.method ?? "") ? req.method : "OTHER", status: 403, ms: Math.round(performance.now() - toolStarted), reason: reason2 });
71644
+ const via = composioVia((req.url ?? "").slice("/_tool/composio".length));
71645
+ route15?.record({ leg: "platform", op: "refused", toolkit, via, method: ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"].includes(req.method ?? "") ? req.method : "OTHER", ...req.method === "POST" && via === "mcp" && refusedRpc(toolBody), status: 403, ms: Math.round(performance.now() - toolStarted), reason: reason2 });
71625
71646
  refuseComposio(res, reason2, toolkit);
71626
71647
  return;
71627
71648
  }
@@ -71683,12 +71704,25 @@ async function startIsolationGateway(options5) {
71683
71704
  if (!path8) return reject2(res);
71684
71705
  let upstream;
71685
71706
  let modelHost;
71707
+ let recordModelStatus;
71686
71708
  let modelAddress;
71687
71709
  let targetPath = req.url;
71688
71710
  let transform3;
71689
71711
  const model = /^\/_model\/([a-zA-Z0-9.-]+)(\/.*)?$/.exec(path8);
71690
71712
  if (toolCall || model && modelHosts.has(model[1].toLowerCase())) {
71691
71713
  modelHost = toolCall ? "backend.composio.dev" : model[1].toLowerCase();
71714
+ if (!toolCall && modelHost && (modelCounts[modelHost] || Object.keys(modelCounts).length < 8)) {
71715
+ const count11 = modelCounts[modelHost] ??= { requests: 0, ok: 0, refused: 0, other: 0 };
71716
+ count11.requests++;
71717
+ let recorded2 = false;
71718
+ recordModelStatus = (status5) => {
71719
+ if (recorded2) return;
71720
+ recorded2 = true;
71721
+ count11[status5 >= 200 && status5 < 300 ? "ok" : status5 === 401 || status5 === 403 ? "refused" : "other"]++;
71722
+ };
71723
+ res.once("finish", () => recordModelStatus?.(res.statusCode));
71724
+ res.once("close", () => recordModelStatus?.(502));
71725
+ }
71692
71726
  const activityCallback = toolCall ? toolCall.op === "execute" ? options5.onModelActivity ?? route15.activity : void 0 : options5.onModelActivity;
71693
71727
  if (toolCall) {
71694
71728
  const call2 = toolCall, endWindow = call2.op === "execute" ? route15.begin() : void 0;
@@ -71793,6 +71827,7 @@ async function startIsolationGateway(options5) {
71793
71827
  };
71794
71828
  if (!toolCall && modelHost !== void 0 && reply6.statusCode !== void 0) {
71795
71829
  const host = modelHost, status5 = reply6.statusCode;
71830
+ recordModelStatus?.(status5);
71796
71831
  if (!MODEL_REFUSALS.has(status5)) observe2(host, status5);
71797
71832
  else {
71798
71833
  const chunks2 = [];
@@ -72025,7 +72060,7 @@ ${Object.entries(reply6.headers).map(([name5, value5]) => `${name5}: ${value5}`)
72025
72060
  if (exposedOrigin !== url4 && exposedOrigin !== parsed4.origin) throw new Error("Sandbox relay origin is already configured");
72026
72061
  exposedOrigin = parsed4.origin;
72027
72062
  return mapped(exposedOrigin);
72028
- }, close: close2 };
72063
+ }, modelRequests: () => Object.fromEntries(Object.entries(modelCounts).map(([host, counts2]) => [host, { ...counts2 }])), close: close2 };
72029
72064
  }
72030
72065
  var BODY_LIMIT, HOP_HEADERS, MODEL_REFUSALS, REFUSAL_BYTES;
72031
72066
  var init_gateway = __esm({
@@ -73585,8 +73620,10 @@ function likelyFix(logTail3, context3 = {}) {
73585
73620
  const task2 = taskFix(logTail3.join("\n"), context3.command);
73586
73621
  if (task2 !== void 0 || context3.withheld !== void 0) return task2 ?? context3.withheld;
73587
73622
  if (logTail3.some((line2) => /^Not logged in · Please run \/login\b/.test(line2.trim()))) {
73588
- return `Claude Code had no key (its /login stays on your computer): through OpenRouter, start agent.command with ANTHROPIC_AUTH_TOKEN="$OPENROUTER_API_KEY" and set ANTHROPIC_BASE_URL: https://openrouter.ai/api under agent.env; with an Anthropic key, ${context3.target === "cloud" ? "run ancha secrets set ANTHROPIC_API_KEY in the project" : "set ANTHROPIC_API_KEY in this shell and list it under agent.pass_env in ancha.yaml"}`;
73623
+ return context3.target === "cloud" ? "Claude Code had no key (its /login stays on your computer): through OpenRouter, set ANTHROPIC_BASE_URL: https://openrouter.ai/api under agent.env and run ancha secrets set OPENROUTER_API_KEY in the project (Claude Code gets it as ANTHROPIC_AUTH_TOKEN); with an Anthropic key, run ancha secrets set ANTHROPIC_API_KEY in the project" : 'Claude Code had no key (its /login stays on your computer): through OpenRouter, start agent.command with ANTHROPIC_AUTH_TOKEN="$OPENROUTER_API_KEY" and set ANTHROPIC_BASE_URL: https://openrouter.ai/api under agent.env; with an Anthropic key, set ANTHROPIC_API_KEY in this shell and list it under agent.pass_env in ancha.yaml';
73589
73624
  }
73625
+ const model = logTail3.map((line2) => MODEL_ID_REFUSED.map((pattern) => pattern.exec(line2)?.[1]).find(Boolean)).find(Boolean);
73626
+ if (model !== void 0) return `its model ${model} is not a model id the provider serves: use an id from the provider's model list (openrouter.ai/models for OpenRouter) where the agent sets its model: agent.env, agent.command or its code`;
73590
73627
  const errors2 = logTail3.filter((line2) => /error|exception|fatal|panic|missing|required|usage|not set|not found|cannot|can't/i.test(line2));
73591
73628
  for (const lines of [errors2, logTail3]) {
73592
73629
  const fix = lines.length === 0 ? void 0 : keyFix(lines, context3) ?? missingFix(lines.join("\n"), context3);
@@ -73594,7 +73631,7 @@ function likelyFix(logTail3, context3 = {}) {
73594
73631
  }
73595
73632
  return void 0;
73596
73633
  }
73597
- var TASK_WORD, TASK_NAME, TASK_FLAG, CREDENTIAL, MISSING, twinVariables, escape2;
73634
+ var TASK_WORD, TASK_NAME, TASK_FLAG, CREDENTIAL, MISSING, twinVariables, escape2, MODEL_ID_REFUSED;
73598
73635
  var init_agent_fix = __esm({
73599
73636
  "backend/src/agent-fix.ts"() {
73600
73637
  "use strict";
@@ -73606,6 +73643,7 @@ var init_agent_fix = __esm({
73606
73643
  CREDENTIAL = /(?<![A-Za-z0-9_])([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*_(?:KEY|TOKEN|SECRET|PASSWORD))(?![A-Za-z0-9_])/g;
73607
73644
  MISSING = /missing|not set|unset|undefined|required|must be set|no .*(?:key|token)|KeyError|not found|empty|expected/i;
73608
73645
  escape2 = (text26) => text26.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
73646
+ MODEL_ID_REFUSED = [/([\w.:/@-]+)['"`]? is not a valid model ID/i, /The model [`'"]?([\w.:/@-]+)[`'"]? does not exist/i, /not_found_error\W+(?:message\W+)?model: ([\w.:/@-]+)/i];
73609
73647
  }
73610
73648
  });
73611
73649
 
@@ -223966,6 +224004,27 @@ var init_process = __esm({
223966
224004
  });
223967
224005
 
223968
224006
  // backend/src/execution/contained-env.ts
224007
+ function modelSettings(values3, modelUrls) {
224008
+ const settings = [];
224009
+ for (const name5 of ["ANTHROPIC_BASE_URL", "OPENAI_BASE_URL", "OPENROUTER_BASE_URL"]) {
224010
+ const value5 = values3[name5];
224011
+ if (!value5) continue;
224012
+ const mapped = Object.entries(modelUrls).find(([, url4]) => value5 === url4 || value5.startsWith(url4 + "/") || value5.startsWith(url4 + "?") || value5.startsWith(url4 + "#"));
224013
+ if (mapped) {
224014
+ settings.push({ name: name5, via: "ancha", host: mapped[0] });
224015
+ continue;
224016
+ }
224017
+ let host;
224018
+ try {
224019
+ const parsed4 = new URL(value5).hostname;
224020
+ host = parsed4.length <= 253 ? parsed4 || void 0 : void 0;
224021
+ } catch {
224022
+ }
224023
+ settings.push({ name: name5, ...host && { host } });
224024
+ }
224025
+ for (const name5 of ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY", "OPENAI_API_KEY", "OPENROUTER_API_KEY"]) settings.push({ name: name5, set: !!values3[name5] });
224026
+ return settings;
224027
+ }
223969
224028
  function vmEnvironmentNames(agent) {
223970
224029
  const execution2 = agent.execution === void 0 ? void 0 : parseExecutionPolicy(agent.execution);
223971
224030
  const env = [.../* @__PURE__ */ new Set([...agent.passEnv ?? [], ...execution2?.mode === "container" ? execution2.env : []])].sort();
@@ -224000,6 +224059,11 @@ function containedEnvironment(input5) {
224000
224059
  if (openRouter && !values3.OPENAI_API_KEY && (values3.OPENROUTER_API_KEY || !openAi)) values3.OPENAI_BASE_URL ??= openRouter + "/api/v1";
224001
224060
  if (openAi) values3.OPENAI_BASE_URL ??= openAi + "/v1";
224002
224061
  if (mapped.modelUrls["api.anthropic.com"]) values3.ANTHROPIC_BASE_URL ??= mapped.modelUrls["api.anthropic.com"];
224062
+ if (openRouter && values3.OPENROUTER_API_KEY) {
224063
+ const routed = (value5) => value5 === openRouter || value5?.startsWith(openRouter + "/") || value5?.startsWith(openRouter + "?") || value5?.startsWith(openRouter + "#");
224064
+ if (routed(values3.ANTHROPIC_BASE_URL) && !values3.ANTHROPIC_AUTH_TOKEN && !values3.ANTHROPIC_API_KEY) values3.ANTHROPIC_AUTH_TOKEN = values3.OPENROUTER_API_KEY;
224065
+ if (routed(values3.OPENAI_BASE_URL) && !values3.OPENAI_API_KEY) values3.OPENAI_API_KEY = values3.OPENROUTER_API_KEY;
224066
+ }
224003
224067
  for (const [base6, api4] of [["OPENROUTER_BASE_URL", "OPENROUTER_API_BASE"], ["OPENAI_BASE_URL", "OPENAI_API_BASE"], ["ANTHROPIC_BASE_URL", "ANTHROPIC_API_BASE"]]) {
224004
224068
  if (values3[base6]) values3[api4] ??= values3[base6];
224005
224069
  }
@@ -225093,6 +225157,7 @@ async function startVmAgent(command, opts, deps = {}) {
225093
225157
  if (Object.entries(values3).some(([name5, value5]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name5) || value5?.includes("\0")) || Buffer.byteLength(JSON.stringify(values3)) + Buffer.byteLength(command) > 262144) {
225094
225158
  throw new AnchaError("CONFIG_INVALID", "Agent launch environment and command must fit within 256 KiB and contain valid variable names.");
225095
225159
  }
225160
+ const settings = modelSettings(values3, mapped.modelUrls);
225096
225161
  await mkdir7(opts.dir, { recursive: true });
225097
225162
  await writeFile9(join17(opts.dir, "execution.json"), JSON.stringify({ mode: "vm", runtime: runtime2, contained: !unsafe, network: unsafe ? "local-test" : "loopback-with-scoped-gateway", project: "prepared-copy", scratch: "fresh-per-attempt", credentials: "explicit-only", modelHosts, uid: descriptor2.uid, gid: descriptor2.gid, pids: 1024 }, null, 2) + "\n", { mode: 384 });
225098
225163
  opts.signal?.throwIfAborted();
@@ -225200,7 +225265,7 @@ async function startVmAgent(command, opts, deps = {}) {
225200
225265
  return { pid: child3.pid, exited, async stop() {
225201
225266
  await cleanup();
225202
225267
  await exited;
225203
- }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), sessionRefusals: refusals.list(), modelRefusal: replies.refusal() }) };
225268
+ }, output: () => ({ stdout: tail.text(), printed: tail.length(), model: { settings, requests: gateway2.modelRequests() }, modelReplies: replies.list(), sessionRefusals: refusals.list(), modelRefusal: replies.refusal() }) };
225204
225269
  } catch (error64) {
225205
225270
  await cleanup();
225206
225271
  throw error64;
@@ -225495,13 +225560,14 @@ async function runEndpointTrial(spec) {
225495
225560
  if (failure5) throw failure5.error;
225496
225561
  signal?.throwIfAborted();
225497
225562
  const { checks: checks2, trace: trace2, simMs, harnessIssues } = capture3;
225498
- const result = completion;
225563
+ const result = completion, model = child3?.output?.().model;
225499
225564
  return {
225500
225565
  sceneId: scene2.id,
225501
225566
  trial,
225502
225567
  envId: env.id,
225503
225568
  sessionId: session2.id,
225504
225569
  ...result,
225570
+ ...model && { model },
225505
225571
  realMs: Math.round(performance.now() - startedAt),
225506
225572
  simMs,
225507
225573
  checks: checks2,
@@ -225723,6 +225789,7 @@ async function runHttpTaskTrial(spec) {
225723
225789
  signal?.throwIfAborted();
225724
225790
  if (controlFailure) throw controlFailure.error;
225725
225791
  const issues = [...capture3.harnessIssues, ...failure5 ? [{ kind: "delivery", owner: "harness", service: "agent-input", message: failure5 }] : [], ...answerIssue ? [answerIssue] : []];
225792
+ const model = child3?.output?.().model;
225726
225793
  const exit = !ready3 ? "spawn_failed" : timedOut ? "timeout" : "done";
225727
225794
  return {
225728
225795
  sceneId: scene2.id,
@@ -225731,6 +225798,7 @@ async function runHttpTaskTrial(spec) {
225731
225798
  sessionId: session2.id,
225732
225799
  exit,
225733
225800
  exitCode: null,
225801
+ ...model && { model },
225734
225802
  realMs: Math.round(performance.now() - started2),
225735
225803
  simMs: capture3.simMs,
225736
225804
  checks: capture3.checks,
@@ -225936,7 +226004,7 @@ async function recordAnswer(backend, envId, sessionId, output2, source, printed)
225936
226004
  }
225937
226005
  }
225938
226006
  function modelKeyIssue(refusal, given2) {
225939
- const failure5 = modelFailure(refusal.status);
226007
+ const failure5 = modelFailure(refusal.status, refusal.message);
225940
226008
  return {
225941
226009
  kind: "model",
225942
226010
  owner: "harness",
@@ -226101,6 +226169,7 @@ async function runTrialInner(spec) {
226101
226169
  simMs,
226102
226170
  ...playOut !== void 0 && playOut.toMs > playOut.fromMs && { playOut },
226103
226171
  checks: checks2,
226172
+ ...output2?.model && { model: output2.model },
226104
226173
  ...output2?.modelReplies?.length && { modelReplies: output2.modelReplies },
226105
226174
  ...output2?.sessionRefusals?.length && { sessionRefusals: output2.sessionRefusals },
226106
226175
  logTail: exit === "idle" || exit === "done" || exit === "exited" && exitCode === 0 ? [] : await logTail(join21(dir, "agent.log")),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ancha-labs/cli",
3
- "version": "0.4.52",
3
+ "version": "0.4.54",
4
4
  "type": "module",
5
5
  "description": "Simulation playgrounds for agents: run your agent against stateful replicas of Slack, GitHub, Datadog and more, each attempt on a fresh cloud machine in your app.ancha.io workspace, or on your computer.",
6
6
  "bugs": {