@ancha-labs/cli 0.4.14 → 0.4.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/worker.mjs CHANGED
@@ -20827,7 +20827,7 @@ var init_answer = __esm({
20827
20827
  not_contains: texts.optional().describe("Text the final answer must not contain"),
20828
20828
  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"),
20829
20829
  case: external_exports.enum(["insensitive", "sensitive"]).optional().describe("How contains and not_contains compare letters; default insensitive")
20830
- }).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");
20830
+ }).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");
20831
20831
  }
20832
20832
  });
20833
20833
 
@@ -40541,9 +40541,11 @@ function projectToolCalls(trace) {
40541
40541
  };
40542
40542
  });
40543
40543
  }
40544
+ var isAgentAnswer;
40544
40545
  var init_tool_call_trace = __esm({
40545
40546
  "packages/core/src/tool-call-trace.ts"() {
40546
40547
  "use strict";
40548
+ isAgentAnswer = (entry2) => entry2.source === "agent" && entry2.service === "agent" && entry2.path === "/done";
40547
40549
  }
40548
40550
  });
40549
40551
 
@@ -61078,8 +61080,10 @@ function evaluateTrace(trace, calls2, tools) {
61078
61080
  function finalAnswer(trace) {
61079
61081
  const entry2 = trace.findLast((e) => e.source === "agent" && e.service === "agent" && e.path === "/done");
61080
61082
  if (!entry2) return void 0;
61081
- const output2 = typeof entry2.request === "string" ? entry2.request : entry2.request?.output;
61082
- return { text: answerText(output2), seq: entry2.seq };
61083
+ const request2 = typeof entry2.request === "object" && entry2.request !== null ? entry2.request : void 0;
61084
+ const output2 = typeof entry2.request === "string" ? entry2.request : request2?.output;
61085
+ const source = request2?.source === "reply" || request2?.source === "stdout" ? request2.source : "done";
61086
+ return { text: answerText(output2), seq: entry2.seq, source, ...typeof request2?.printed === "number" && { printed: request2.printed } };
61083
61087
  }
61084
61088
  function evaluateAnswer(check3, trace) {
61085
61089
  const contains3 = asList(check3.contains), absent = asList(check3.not_contains), sensitive = check3.case === "sensitive";
@@ -61091,13 +61095,22 @@ function evaluateAnswer(check3, trace) {
61091
61095
  ];
61092
61096
  const expected = parts3.length ? `the final answer ${parts3.join("; ")}` : "a final answer";
61093
61097
  const answer = finalAnswer(trace);
61098
+ if (answer?.printed !== void 0) {
61099
+ return {
61100
+ passed: false,
61101
+ expected,
61102
+ actual: `${answer.printed.toLocaleString("en-US")} characters on stdout`,
61103
+ evidence: [answer.seq],
61104
+ 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>}.`
61105
+ };
61106
+ }
61094
61107
  if (!answer || answer.text.trim() === "") {
61095
61108
  return {
61096
61109
  passed: false,
61097
61110
  expected,
61098
61111
  actual: answer ? "an empty final answer" : "no final answer",
61099
61112
  evidence: answer ? [answer.seq] : [],
61100
- 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.`
61113
+ 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.`
61101
61114
  };
61102
61115
  }
61103
61116
  const text24 = comparableText(answer.text, sensitive);
@@ -61114,7 +61127,8 @@ function evaluateAnswer(check3, trace) {
61114
61127
  const explanation = [
61115
61128
  ...missing6.length ? [`The final answer does not contain ${quoted2(missing6)}.`] : [],
61116
61129
  ...unstated.length ? [`It states no number within ${unstated.map((n2) => `${plainNumber(n2.tolerance)} of ${n2.written}`).join(", nor within ")}: ${said}.`] : [],
61117
- ...present2.length ? [`It contains ${quoted2(present2)}, which it must not.`] : []
61130
+ ...present2.length ? [`It contains ${quoted2(present2)}, which it must not.`] : [],
61131
+ ...answer.source === "stdout" ? ["Its answer is everything it printed on stdout."] : answer.source === "reply" ? ["Its answer is its HTTP reply."] : []
61118
61132
  ].join(" ");
61119
61133
  return { passed: false, expected, actual, explanation, evidence: [answer.seq] };
61120
61134
  }
@@ -169057,7 +169071,8 @@ function record8(ctx, args) {
169057
169071
  }
169058
169072
  function unchanged(ctx, args) {
169059
169073
  const changes = sql(ctx).prepare("SELECT recordtype, id, operation FROM ns_history ORDER BY ordinal").all().filter((row2) => args.types.includes(row2.recordtype));
169060
- return checkOutcome(changes.length === 0, `no writes to ${args.types.join(", ")}`, changes.length ? JSON.stringify(changes) : "no committed writes");
169074
+ 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(", ");
169075
+ return checkOutcome(changes.length === 0, `no writes to ${types}`, changes.length ? JSON.stringify(changes) : "no committed writes");
169061
169076
  }
169062
169077
  function count3(ctx, args) {
169063
169078
  const actual = recordIds(ctx, args.type).length;
@@ -169067,6 +169082,7 @@ var init_checks13 = __esm({
169067
169082
  "packages/server/src/twins/netsuite/checks.ts"() {
169068
169083
  "use strict";
169069
169084
  init_open_items();
169085
+ init_src();
169070
169086
  init_checks4();
169071
169087
  init_store5();
169072
169088
  }
@@ -174398,8 +174414,9 @@ var init_sessions = __esm({
174398
174414
  });
174399
174415
  }
174400
174416
  /**
174401
- * The runner records the agent's answer for it when the agent posted none (SPEC-053 F2): an HTTP agent's reply, or the
174402
- * final block of its stdout. The same `POST /done` entry, with that source; never a second answer.
174417
+ * The runner records the agent's answer for it when the agent posted none (SPEC-053 F2): an HTTP agent's reply, or its
174418
+ * stdout (SPEC-056 A), or how much it printed when that is too long to be an answer. The same `POST /done` entry, with
174419
+ * that source; never a second answer.
174403
174420
  */
174404
174421
  answer(env, id14, answer) {
174405
174422
  return env.serialize(() => {
@@ -174407,7 +174424,7 @@ var init_sessions = __esm({
174407
174424
  if (state3 === "prepared") throw new AnchaError("SESSION_CONFLICT", "session has not started");
174408
174425
  if (state3 === "finished") throw new AnchaError("SESSION_CONFLICT", "session has finished");
174409
174426
  if (env.trace.list().some((entry2) => entry2.service === "agent" && entry2.path === "/done")) return { recorded: false };
174410
- env.trace.record({ source: "agent", service: "agent", method: "POST", path: "/done", status: 200, request: { output: answer.output, source: answer.source } });
174427
+ 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 } } });
174411
174428
  return { recorded: true };
174412
174429
  });
174413
174430
  }
@@ -174776,10 +174793,13 @@ function sessionRoutes(opts, sessions) {
174776
174793
  } catch {
174777
174794
  throw new AnchaError("USAGE", "request must be a JSON object");
174778
174795
  }
174779
- fields10(input4, ["output", "source"]);
174796
+ fields10(input4, ["output", "source", "printed"]);
174780
174797
  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`);
174781
174798
  if (input4.source !== "reply" && input4.source !== "stdout") throw new AnchaError("USAGE", "source must be reply or stdout");
174782
- return c.json(await sessions.answer(opts.manager.get(c.req.param("id")), c.req.param("sid"), { output: input4.output, source: input4.source }));
174799
+ if (input4.printed !== void 0 && (input4.source !== "stdout" || input4.output !== "" || typeof input4.printed !== "number" || !Number.isSafeInteger(input4.printed) || input4.printed <= 0)) {
174800
+ throw new AnchaError("USAGE", "printed is how many characters stdout held, with source stdout and an empty output");
174801
+ }
174802
+ 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 } }));
174783
174803
  });
174784
174804
  app2.post("/envs/:id/trials/:sid/agent", async (c) => {
174785
174805
  let input4;
@@ -174826,7 +174846,7 @@ var init_session_routes = __esm({
174826
174846
  init_src();
174827
174847
  init_feed();
174828
174848
  init_env_info();
174829
- MAX_ANSWER_CHARS = 16e3;
174849
+ MAX_ANSWER_CHARS = 64 * 1024;
174830
174850
  }
174831
174851
  });
174832
174852
 
@@ -177020,6 +177040,26 @@ import { lookup as lookup5 } from "node:dns/promises";
177020
177040
  import { createServer, request } from "node:http";
177021
177041
  import { request as secureRequest } from "node:https";
177022
177042
  import { isIP as isIP3 } from "node:net";
177043
+ import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib";
177044
+ function refusalMessage(body6, encoding) {
177045
+ let text24;
177046
+ try {
177047
+ const raw3 = encoding === "gzip" || encoding === "x-gzip" ? gunzipSync(body6) : encoding === "deflate" ? inflateSync(body6) : encoding === "br" ? brotliDecompressSync(body6) : !encoding || encoding === "identity" ? body6 : void 0;
177048
+ if (raw3 === void 0) return void 0;
177049
+ text24 = raw3.toString("utf8");
177050
+ } catch {
177051
+ return void 0;
177052
+ }
177053
+ let message7 = text24;
177054
+ try {
177055
+ const json33 = JSON.parse(text24);
177056
+ const error64 = json33?.error;
177057
+ message7 = 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 : text24;
177058
+ } catch {
177059
+ }
177060
+ const line2 = String(message7).replace(/\b(sk|rk|pk)-[\w*-]{4,}/g, "$1-\u2026").replace(/\s+/g, " ").trim();
177061
+ return line2 === "" ? void 0 : line2.length > 300 ? `${line2.slice(0, 299)}\u2026` : line2;
177062
+ }
177023
177063
  function loopbackOrigin(value4) {
177024
177064
  const url4 = new URL(value4);
177025
177065
  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");
@@ -177160,11 +177200,30 @@ async function startIsolationGateway(options4) {
177160
177200
  agent: false,
177161
177201
  ...modelHost && { servername: modelHost, rejectUnauthorized: true, family: modelAddress.family }
177162
177202
  }, (reply5) => {
177163
- if (modelHost !== void 0 && reply5.statusCode !== void 0) {
177203
+ const observe2 = (host, status4, message7) => {
177164
177204
  try {
177165
- options4.onModelReply?.(modelHost, reply5.statusCode);
177205
+ options4.onModelReply?.(host, status4, message7);
177166
177206
  } catch {
177167
177207
  }
177208
+ };
177209
+ if (modelHost !== void 0 && reply5.statusCode !== void 0) {
177210
+ const host = modelHost, status4 = reply5.statusCode;
177211
+ if (!MODEL_REFUSALS.has(status4)) observe2(host, status4);
177212
+ else {
177213
+ const chunks2 = [];
177214
+ let size3 = 0, told = false;
177215
+ const tell = () => {
177216
+ if (told) return;
177217
+ told = true;
177218
+ observe2(host, status4, size3 <= REFUSAL_BYTES ? refusalMessage(Buffer.concat(chunks2), reply5.headers["content-encoding"]?.toLowerCase()) : void 0);
177219
+ };
177220
+ reply5.on("data", (chunk) => {
177221
+ size3 += chunk.length;
177222
+ if (size3 <= REFUSAL_BYTES) chunks2.push(chunk);
177223
+ });
177224
+ reply5.once("end", tell);
177225
+ reply5.once("close", tell);
177226
+ }
177168
177227
  }
177169
177228
  if (reply5.statusCode && reply5.statusCode >= 300 && reply5.statusCode < 400) {
177170
177229
  reply5.destroy();
@@ -177276,12 +177335,14 @@ async function startIsolationGateway(options4) {
177276
177335
  return mapped(exposedOrigin);
177277
177336
  }, close };
177278
177337
  }
177279
- var BODY_LIMIT, HOP_HEADERS;
177338
+ var BODY_LIMIT, HOP_HEADERS, MODEL_REFUSALS, REFUSAL_BYTES;
177280
177339
  var init_gateway = __esm({
177281
177340
  "backend/src/execution/gateway.ts"() {
177282
177341
  "use strict";
177283
177342
  BODY_LIMIT = 8 * 1024 * 1024;
177284
177343
  HOP_HEADERS = /* @__PURE__ */ new Set(["connection", "proxy-connection", "proxy-authenticate", "proxy-authorization", "keep-alive", "te", "trailer", "transfer-encoding", "upgrade"]);
177344
+ MODEL_REFUSALS = /* @__PURE__ */ new Set([401, 402, 403, 429]);
177345
+ REFUSAL_BYTES = 4096;
177285
177346
  }
177286
177347
  });
177287
177348
 
@@ -177585,7 +177646,7 @@ var init_agent_env = __esm({
177585
177646
  import { createHash as createHash53 } from "node:crypto";
177586
177647
  import { readdir, readFile as readFile3 } from "node:fs/promises";
177587
177648
  import { join as join4 } from "node:path";
177588
- import { gunzipSync, gzipSync } from "node:zlib";
177649
+ import { gunzipSync as gunzipSync2, gzipSync } from "node:zlib";
177589
177650
  function bundleSource(env) {
177590
177651
  return env.CI === "true" || env.GITHUB_ACTIONS ? "ci" : "cli";
177591
177652
  }
@@ -203703,7 +203764,7 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
203703
203764
  }
203704
203765
  }
203705
203766
  for (const e of projectToolCalls(t.trace)) {
203706
- if (e.source === "agent") agentCalls2++;
203767
+ if (e.source === "agent" && !isAgentAnswer(e)) agentCalls2++;
203707
203768
  if (e.gap === true) {
203708
203769
  const key4 = JSON.stringify([e.service, e.method, e.path]);
203709
203770
  const gap6 = gaps2.get(key4);
@@ -204025,38 +204086,38 @@ function withoutScriptBanners(lines) {
204025
204086
  if (end > start && YARN_DONE.test(lines[end - 1].trim())) end--;
204026
204087
  return lines.slice(start, end);
204027
204088
  }
204028
- function finalBlock(stdout) {
204029
- const lines = withoutScriptBanners(stdout.replace(ANSI, "").replace(/\r\n?/g, "\n").trimEnd().split("\n"));
204030
- const blank = lines.findLastIndex((line2) => line2.trim() === "");
204031
- let block2 = (blank >= 0 ? lines.slice(blank + 1) : lines.slice(-ANSWER_MAX_LINES)).join("\n");
204032
- if (Buffer.byteLength(block2) > ANSWER_MAX_BYTES) {
204033
- const bytes2 = Buffer.from(block2);
204034
- let end = bytes2.subarray(bytes2.length - ANSWER_MAX_BYTES).toString("utf8").replace(/^�+/, "");
204035
- const line2 = end.indexOf("\n");
204036
- if (line2 >= 0 && line2 < end.length - 1) end = end.slice(line2 + 1);
204037
- block2 = end;
204038
- }
204039
- return block2.replace(/^\s*\n/, "").trimEnd();
204089
+ function stdoutAnswer(stdout) {
204090
+ return withoutScriptBanners(stdout.replace(ANSI, "").replace(/\r\n?/g, "\n").trimEnd().split("\n")).join("\n").trimEnd();
204040
204091
  }
204041
- var TAIL_CHARS, ANSWER_MAX_BYTES, ANSWER_MAX_LINES, OutputTail, ModelReplies, ANSI, NPM_SCRIPT, NPM_COMMAND, YARN_RUN, YARN_COMMAND, YARN_DONE;
204092
+ var ANSWER_MAX_CHARS, STDOUT_MAX_CHARS, OutputTail, ModelReplies, ANSI, NPM_SCRIPT, NPM_COMMAND, YARN_RUN, YARN_COMMAND, YARN_DONE;
204042
204093
  var init_agent_output = __esm({
204043
204094
  "backend/src/runner/agent-output.ts"() {
204044
204095
  "use strict";
204045
- TAIL_CHARS = 64 * 1024;
204046
- ANSWER_MAX_BYTES = 8 * 1024;
204047
- ANSWER_MAX_LINES = 40;
204096
+ init_gateway();
204097
+ ANSWER_MAX_CHARS = 64 * 1024;
204098
+ STDOUT_MAX_CHARS = 2 * ANSWER_MAX_CHARS;
204048
204099
  OutputTail = class {
204100
+ max;
204049
204101
  #text = "";
204050
204102
  #cut = false;
204103
+ #length = 0;
204104
+ constructor(max = STDOUT_MAX_CHARS) {
204105
+ this.max = max;
204106
+ }
204051
204107
  push(text24) {
204052
204108
  this.#text += text24;
204053
- if (this.#text.length > TAIL_CHARS * 2) this.#trim();
204109
+ this.#length += text24.length;
204110
+ if (this.#text.length > this.max * 2) this.#trim();
204054
204111
  }
204055
204112
  #trim() {
204056
- if (this.#text.length <= TAIL_CHARS) return;
204057
- this.#text = this.#text.slice(-TAIL_CHARS);
204113
+ if (this.#text.length <= this.max) return;
204114
+ this.#text = this.#text.slice(-this.max);
204058
204115
  this.#cut = true;
204059
204116
  }
204117
+ /** How many characters were pushed in all. */
204118
+ length() {
204119
+ return this.#length;
204120
+ }
204060
204121
  /** What was kept; a first line cut in the middle is left out. */
204061
204122
  text() {
204062
204123
  this.#trim();
@@ -204065,15 +204126,23 @@ var init_agent_output = __esm({
204065
204126
  };
204066
204127
  ModelReplies = class {
204067
204128
  #counts = /* @__PURE__ */ new Map();
204068
- add(host, status4) {
204129
+ #last;
204130
+ add(host, status4, message7) {
204069
204131
  const key4 = `${host} ${status4}`;
204070
204132
  const reply5 = this.#counts.get(key4);
204071
- if (reply5) reply5.count++;
204072
- else if (this.#counts.size < 100) this.#counts.set(key4, { host, status: status4, count: 1 });
204133
+ if (reply5) {
204134
+ reply5.count++;
204135
+ if (message7 !== void 0) reply5.message ??= message7;
204136
+ } else if (this.#counts.size < 100) this.#counts.set(key4, { host, status: status4, count: 1, ...message7 !== void 0 && { message: message7 } });
204137
+ this.#last = { host, status: status4, ...message7 !== void 0 && { message: message7 } };
204073
204138
  }
204074
204139
  list() {
204075
204140
  return [...this.#counts.values()].map((reply5) => ({ ...reply5 }));
204076
204141
  }
204142
+ /** The last reply, when it refused the key: the provider stopped the agent there. */
204143
+ refusal() {
204144
+ return this.#last !== void 0 && MODEL_REFUSALS.has(this.#last.status) ? { ...this.#last } : void 0;
204145
+ }
204077
204146
  };
204078
204147
  ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
204079
204148
  NPM_SCRIPT = /^> (?:\S+@\S* )?[\w:.-]+(?: \/\S*)?$/;
@@ -204159,7 +204228,7 @@ function outputCopy(logFd) {
204159
204228
  closeSync2(stderr.fd);
204160
204229
  }
204161
204230
  },
204162
- tail: () => tail.text()
204231
+ output: () => ({ stdout: tail.text(), printed: tail.length() })
204163
204232
  };
204164
204233
  }
204165
204234
  function startAgentProcess(command, opts) {
@@ -204216,7 +204285,7 @@ function startAgentProcess(command, opts) {
204216
204285
  return { pid, exited, async stop() {
204217
204286
  terminate();
204218
204287
  await exited;
204219
- }, ...stdout && { output: () => ({ stdout: stdout.tail() }) } };
204288
+ }, ...stdout && { output: stdout.output } };
204220
204289
  }
204221
204290
  var KILL_GRACE_MS, GROUP_POLL_MS, COPY_MS;
204222
204291
  var init_process = __esm({
@@ -205011,7 +205080,7 @@ async function startContainedAgent(command, opts) {
205011
205080
  ]);
205012
205081
  await run4(["start", relayName]);
205013
205082
  const replies = new ModelReplies();
205014
- gateway = await startIsolationGateway({ env: opts.env, session: opts.session, modelHosts: policy.modelHosts, onModelReply: (host, status5) => replies.add(host, status5) });
205083
+ gateway = await startIsolationGateway({ env: opts.env, session: opts.session, modelHosts: policy.modelHosts, onModelReply: (host, status5, message7) => replies.add(host, status5, message7) });
205015
205084
  const script = isolationRelayScript({ port: RELAY_PORT, ...opts.runtime?.port && { agentPort: opts.runtime.port } });
205016
205085
  relayChild = spawn2("docker", ["--context", context3, "exec", "-i", relayName, "node", "-e", script], { env: dockerEnvironment(), stdio: ["pipe", "pipe", "pipe"] });
205017
205086
  relayChild.stderr.on("data", () => {
@@ -205103,7 +205172,7 @@ async function startContainedAgent(command, opts) {
205103
205172
  return { pid: child2.pid, exited, async stop() {
205104
205173
  await cleanup();
205105
205174
  await exited;
205106
- }, output: () => ({ stdout: tail.text(), modelReplies: replies.list() }) };
205175
+ }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), modelRefusal: replies.refusal() }) };
205107
205176
  } catch (error64) {
205108
205177
  opts.signal?.removeEventListener("abort", abort);
205109
205178
  await cleanup();
@@ -205289,7 +205358,7 @@ async function startVmAgent(command, opts, deps = {}) {
205289
205358
  ...opts.session && { session: opts.session },
205290
205359
  modelHosts,
205291
205360
  port: unsafe ? 0 : 18991,
205292
- onModelReply: (host, status4) => replies.add(host, status4)
205361
+ onModelReply: (host, status4, message7) => replies.add(host, status4, message7)
205293
205362
  });
205294
205363
  const mapped = gateway.rewrite(unsafe ? gateway.url : VM_GATEWAY_ORIGIN);
205295
205364
  const agentRuntime = { ...opts.runtime, ...taskFile !== void 0 && { taskFile }, ...opts.runtime?.attempt && { attempt: { ...opts.runtime.attempt, stateDir: paths2.state, records: records3 } } };
@@ -205411,7 +205480,7 @@ async function startVmAgent(command, opts, deps = {}) {
205411
205480
  return { pid: child2.pid, exited, async stop() {
205412
205481
  await cleanup();
205413
205482
  await exited;
205414
- }, output: () => ({ stdout: tail.text(), modelReplies: replies.list() }) };
205483
+ }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), modelRefusal: replies.refusal() }) };
205415
205484
  } catch (error64) {
205416
205485
  await cleanup();
205417
205486
  throw error64;
@@ -206210,6 +206279,34 @@ var init_per_event = __esm({
206210
206279
  }
206211
206280
  });
206212
206281
 
206282
+ // backend/src/agent-outcome.ts
206283
+ function modelKeyName(host, given2) {
206284
+ const [pattern, usual] = PROVIDER_KEYS[host] ?? [/(?!)/, "NAME"];
206285
+ return given2.find((name5) => pattern.test(name5) && /KEY|TOKEN/.test(name5)) ?? usual;
206286
+ }
206287
+ var PROVIDER_KEYS;
206288
+ var init_agent_outcome = __esm({
206289
+ "backend/src/agent-outcome.ts"() {
206290
+ "use strict";
206291
+ init_src();
206292
+ init_agent_fix();
206293
+ init_gateway();
206294
+ PROVIDER_KEYS = {
206295
+ "api.anthropic.com": [/ANTHROPIC|CLAUDE/, "ANTHROPIC_API_KEY"],
206296
+ "api.openai.com": [/OPENAI/, "OPENAI_API_KEY"],
206297
+ "openrouter.ai": [/OPENROUTER/, "OPENROUTER_API_KEY"],
206298
+ "generativelanguage.googleapis.com": [/GEMINI|GOOGLE/, "GEMINI_API_KEY"],
206299
+ "api.groq.com": [/GROQ/, "GROQ_API_KEY"],
206300
+ "api.mistral.ai": [/MISTRAL/, "MISTRAL_API_KEY"],
206301
+ "api.together.xyz": [/TOGETHER/, "TOGETHER_API_KEY"],
206302
+ "api.fireworks.ai": [/FIREWORKS/, "FIREWORKS_API_KEY"],
206303
+ "api.deepseek.com": [/DEEPSEEK/, "DEEPSEEK_API_KEY"],
206304
+ "api.x.ai": [/XAI|GROK/, "XAI_API_KEY"],
206305
+ "api.cohere.com": [/COHERE|CO_API/, "COHERE_API_KEY"]
206306
+ };
206307
+ }
206308
+ });
206309
+
206213
206310
  // backend/src/runner/trial.ts
206214
206311
  import { setTimeout as sleep8 } from "node:timers/promises";
206215
206312
  import { closeSync as closeSync6, openSync as openSync6, writeSync as writeSync6 } from "node:fs";
@@ -206219,16 +206316,29 @@ function answersFrom(agent, source) {
206219
206316
  const mode = agent.answer ?? "auto";
206220
206317
  return mode === "auto" || mode === "stdout" && source === "stdout";
206221
206318
  }
206222
- async function recordAnswer(backend, envId, sessionId, output2, source) {
206223
- if (output2.trim() === "" || backend.recordAnswer === void 0) return void 0;
206319
+ async function recordAnswer(backend, envId, sessionId, output2, source, printed) {
206320
+ if (output2.trim() === "" && printed === void 0 || backend.recordAnswer === void 0) return void 0;
206224
206321
  try {
206225
- await backend.recordAnswer(envId, sessionId, { output: output2, source });
206322
+ await backend.recordAnswer(envId, sessionId, { output: output2, source, ...printed !== void 0 && { printed } });
206226
206323
  return void 0;
206227
206324
  } catch (error64) {
206228
206325
  if (unknownRoute18(error64)) return void 0;
206229
206326
  return { kind: "world", owner: "harness", service: "agent", message: `the agent's answer from its ${source === "reply" ? "reply" : "stdout"} could not be recorded: ${error64 instanceof Error ? error64.message : String(error64)}` };
206230
206327
  }
206231
206328
  }
206329
+ function modelKeyIssue(refusal, given2) {
206330
+ return {
206331
+ kind: "model",
206332
+ owner: "harness",
206333
+ service: refusal.host,
206334
+ code: "MODEL_KEY_REFUSED",
206335
+ message: `${refusal.host} refused the agent's model key (${refusal.status}${refusal.message ? `: ${refusal.message}` : ""}), so the attempt tested nothing. Give the agent a working ${modelKeyName(refusal.host, given2)} and run again.`
206336
+ };
206337
+ }
206338
+ function recordStdout(backend, envId, sessionId, output2) {
206339
+ const answer = stdoutAnswer(output2?.stdout ?? ""), printed = output2?.printed ?? output2?.stdout.length ?? 0;
206340
+ return printed > STDOUT_MAX_CHARS || answer.length > ANSWER_MAX_CHARS ? recordAnswer(backend, envId, sessionId, "", "stdout", printed) : recordAnswer(backend, envId, sessionId, answer, "stdout");
206341
+ }
206232
206342
  async function runTrial(spec) {
206233
206343
  const { backend, env, scene: scene2, trial, dir, signal, inheritedEnv = process.env } = spec;
206234
206344
  const agent = scene2.agent_input && spec.agent.mode !== "endpoint" ? { ...spec.agent, taskInput: sceneTaskInput(scene2, spec.agent.taskInput) } : spec.agent;
@@ -206323,7 +206433,7 @@ async function runTrial(spec) {
206323
206433
  const playOutIssues = [];
206324
206434
  const ended = exit === "timeout" || exit === "done" || exit === "exited" && exitCode === 0;
206325
206435
  if (ended && failure5 === void 0 && !signal?.aborted && answersFrom(agent, "stdout")) {
206326
- const issue6 = await recordAnswer(backend, env.id, session2.id, finalBlock(output2?.stdout ?? ""), "stdout");
206436
+ const issue6 = await recordStdout(backend, env.id, session2.id, output2);
206327
206437
  if (issue6 !== void 0) playOutIssues.push(issue6);
206328
206438
  }
206329
206439
  let playOut;
@@ -206336,6 +206446,7 @@ async function runTrial(spec) {
206336
206446
  }
206337
206447
  const capture3 = await captureTrialAfterFailure(failure5, backend, env.id, session2.id, dir, scene2, { ...spec.judge, ...signal !== void 0 && { signal } }, void 0, spec.onCaptured);
206338
206448
  const { checks: checks2, trace, simMs } = capture3, harnessIssues = [...capture3.harnessIssues, ...playOutIssues];
206449
+ if (output2?.modelRefusal !== void 0) harnessIssues.push(modelKeyIssue(output2.modelRefusal, Object.keys(agent.env ?? {})));
206339
206450
  if (failure5 !== void 0) throw failure5.error;
206340
206451
  signal?.throwIfAborted();
206341
206452
  return {
@@ -206375,6 +206486,7 @@ var init_trial = __esm({
206375
206486
  init_per_event();
206376
206487
  init_budget();
206377
206488
  init_agent_output();
206489
+ init_agent_outcome();
206378
206490
  init_agent_env();
206379
206491
  EXIT_COMMAND_NOT_FOUND2 = 127;
206380
206492
  unknownRoute18 = (error64) => error64 instanceof AnchaError && error64.code === "USAGE" && error64.message.startsWith("no such route");
@@ -206841,6 +206953,14 @@ var init_baselines = __esm({
206841
206953
  }
206842
206954
  });
206843
206955
 
206956
+ // backend/src/kit/connection-tools.ts
206957
+ var init_connection_tools = __esm({
206958
+ "backend/src/kit/connection-tools.ts"() {
206959
+ "use strict";
206960
+ init_src();
206961
+ }
206962
+ });
206963
+
206844
206964
  // packages/cli/src/runner/worker.ts
206845
206965
  init_src();
206846
206966
 
@@ -206958,11 +207078,12 @@ init_report2();
206958
207078
 
206959
207079
  // packages/cli/src/cloud-bundle.ts
206960
207080
  init_src();
206961
- init_baselines();
206962
207081
  import { basename as basename5, resolve as resolve12 } from "node:path";
207082
+ init_baselines();
206963
207083
 
206964
207084
  // backend/src/cloud/bundle.ts
206965
207085
  init_src();
207086
+ init_connection_tools();
206966
207087
  init_jobs_contract();
206967
207088
 
206968
207089
  // backend/src/cloud/dependencies.ts
@@ -92098,7 +92098,7 @@ var AnswerCheckSchema = external_exports.strictObject({
92098
92098
  not_contains: texts.optional().describe("Text the final answer must not contain"),
92099
92099
  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"),
92100
92100
  case: external_exports.enum(["insensitive", "sensitive"]).optional().describe("How contains and not_contains compare letters; default insensitive")
92101
- }).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");
92101
+ }).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");
92102
92102
  function expectedNumber(number7) {
92103
92103
  const read6 = typeof number7.value === "number" ? { value: number7.value, decimals: decimalsOf(number7.value) } : readNumbers(number7.value)[0];
92104
92104
  return { value: read6.value, tolerance: number7.tolerance ?? 0.5 * 10 ** -read6.decimals };
@@ -107361,8 +107361,10 @@ var ANSWER_QUOTE = 300;
107361
107361
  function finalAnswer(trace) {
107362
107362
  const entry2 = trace.findLast((e) => e.source === "agent" && e.service === "agent" && e.path === "/done");
107363
107363
  if (!entry2) return void 0;
107364
- const output2 = typeof entry2.request === "string" ? entry2.request : entry2.request?.output;
107365
- return { text: answerText(output2), seq: entry2.seq };
107364
+ const request = typeof entry2.request === "object" && entry2.request !== null ? entry2.request : void 0;
107365
+ const output2 = typeof entry2.request === "string" ? entry2.request : request?.output;
107366
+ const source = request?.source === "reply" || request?.source === "stdout" ? request.source : "done";
107367
+ return { text: answerText(output2), seq: entry2.seq, source, ...typeof request?.printed === "number" && { printed: request.printed } };
107366
107368
  }
107367
107369
  function evaluateAnswer(check3, trace) {
107368
107370
  const contains3 = asList(check3.contains), absent = asList(check3.not_contains), sensitive = check3.case === "sensitive";
@@ -107374,13 +107376,22 @@ function evaluateAnswer(check3, trace) {
107374
107376
  ];
107375
107377
  const expected = parts3.length ? `the final answer ${parts3.join("; ")}` : "a final answer";
107376
107378
  const answer = finalAnswer(trace);
107379
+ if (answer?.printed !== void 0) {
107380
+ return {
107381
+ passed: false,
107382
+ expected,
107383
+ actual: `${answer.printed.toLocaleString("en-US")} characters on stdout`,
107384
+ evidence: [answer.seq],
107385
+ 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>}.`
107386
+ };
107387
+ }
107377
107388
  if (!answer || answer.text.trim() === "") {
107378
107389
  return {
107379
107390
  passed: false,
107380
107391
  expected,
107381
107392
  actual: answer ? "an empty final answer" : "no final answer",
107382
107393
  evidence: answer ? [answer.seq] : [],
107383
- 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.`
107394
+ 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.`
107384
107395
  };
107385
107396
  }
107386
107397
  const text23 = comparableText(answer.text, sensitive);
@@ -107397,7 +107408,8 @@ function evaluateAnswer(check3, trace) {
107397
107408
  const explanation = [
107398
107409
  ...missing6.length ? [`The final answer does not contain ${quoted2(missing6)}.`] : [],
107399
107410
  ...unstated.length ? [`It states no number within ${unstated.map((n2) => `${plainNumber(n2.tolerance)} of ${n2.written}`).join(", nor within ")}: ${said}.`] : [],
107400
- ...present2.length ? [`It contains ${quoted2(present2)}, which it must not.`] : []
107411
+ ...present2.length ? [`It contains ${quoted2(present2)}, which it must not.`] : [],
107412
+ ...answer.source === "stdout" ? ["Its answer is everything it printed on stdout."] : answer.source === "reply" ? ["Its answer is its HTTP reply."] : []
107401
107413
  ].join(" ");
107402
107414
  return { passed: false, expected, actual, explanation, evidence: [answer.seq] };
107403
107415
  }
@@ -167300,7 +167312,8 @@ function record8(ctx, args) {
167300
167312
  }
167301
167313
  function unchanged(ctx, args) {
167302
167314
  const changes = sql(ctx).prepare("SELECT recordtype, id, operation FROM ns_history ORDER BY ordinal").all().filter((row2) => args.types.includes(row2.recordtype));
167303
- return checkOutcome(changes.length === 0, `no writes to ${args.types.join(", ")}`, changes.length ? JSON.stringify(changes) : "no committed writes");
167315
+ 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(", ");
167316
+ return checkOutcome(changes.length === 0, `no writes to ${types}`, changes.length ? JSON.stringify(changes) : "no committed writes");
167304
167317
  }
167305
167318
  function count3(ctx, args) {
167306
167319
  const actual = recordIds(ctx, args.type).length;
@@ -168807,8 +168820,9 @@ var TrialSessions = class {
168807
168820
  });
168808
168821
  }
168809
168822
  /**
168810
- * The runner records the agent's answer for it when the agent posted none (SPEC-053 F2): an HTTP agent's reply, or the
168811
- * final block of its stdout. The same `POST /done` entry, with that source; never a second answer.
168823
+ * The runner records the agent's answer for it when the agent posted none (SPEC-053 F2): an HTTP agent's reply, or its
168824
+ * stdout (SPEC-056 A), or how much it printed when that is too long to be an answer. The same `POST /done` entry, with
168825
+ * that source; never a second answer.
168812
168826
  */
168813
168827
  answer(env, id14, answer) {
168814
168828
  return env.serialize(() => {
@@ -168816,7 +168830,7 @@ var TrialSessions = class {
168816
168830
  if (state2 === "prepared") throw new AnchaError("SESSION_CONFLICT", "session has not started");
168817
168831
  if (state2 === "finished") throw new AnchaError("SESSION_CONFLICT", "session has finished");
168818
168832
  if (env.trace.list().some((entry2) => entry2.service === "agent" && entry2.path === "/done")) return { recorded: false };
168819
- env.trace.record({ source: "agent", service: "agent", method: "POST", path: "/done", status: 200, request: { output: answer.output, source: answer.source } });
168833
+ 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 } } });
168820
168834
  return { recorded: true };
168821
168835
  });
168822
168836
  }
@@ -169131,7 +169145,7 @@ function parseStartOptions(value4) {
169131
169145
  if (input4.delivery !== void 0) parseOptions({ mode: "endpoint", delivery: input4.delivery });
169132
169146
  return input4;
169133
169147
  }
169134
- var MAX_ANSWER_CHARS = 16e3;
169148
+ var MAX_ANSWER_CHARS = 64 * 1024;
169135
169149
  function sessionRoutes(opts, sessions) {
169136
169150
  const app2 = new Hono3();
169137
169151
  const token4 = (header3) => /^Bearer\s+(\S+)\s*$/i.exec(header3 ?? "")?.[1];
@@ -169165,10 +169179,13 @@ function sessionRoutes(opts, sessions) {
169165
169179
  } catch {
169166
169180
  throw new AnchaError("USAGE", "request must be a JSON object");
169167
169181
  }
169168
- fields10(input4, ["output", "source"]);
169182
+ fields10(input4, ["output", "source", "printed"]);
169169
169183
  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`);
169170
169184
  if (input4.source !== "reply" && input4.source !== "stdout") throw new AnchaError("USAGE", "source must be reply or stdout");
169171
- return c.json(await sessions.answer(opts.manager.get(c.req.param("id")), c.req.param("sid"), { output: input4.output, source: input4.source }));
169185
+ if (input4.printed !== void 0 && (input4.source !== "stdout" || input4.output !== "" || typeof input4.printed !== "number" || !Number.isSafeInteger(input4.printed) || input4.printed <= 0)) {
169186
+ throw new AnchaError("USAGE", "printed is how many characters stdout held, with source stdout and an empty output");
169187
+ }
169188
+ 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 } }));
169172
169189
  });
169173
169190
  app2.post("/envs/:id/trials/:sid/agent", async (c) => {
169174
169191
  let input4;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ancha-labs/cli",
3
- "version": "0.4.14",
3
+ "version": "0.4.16",
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": {