@ancha-labs/cli 0.4.15 → 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
 
@@ -61080,8 +61080,10 @@ function evaluateTrace(trace, calls2, tools) {
61080
61080
  function finalAnswer(trace) {
61081
61081
  const entry2 = trace.findLast((e) => e.source === "agent" && e.service === "agent" && e.path === "/done");
61082
61082
  if (!entry2) return void 0;
61083
- const output2 = typeof entry2.request === "string" ? entry2.request : entry2.request?.output;
61084
- 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 } };
61085
61087
  }
61086
61088
  function evaluateAnswer(check3, trace) {
61087
61089
  const contains3 = asList(check3.contains), absent = asList(check3.not_contains), sensitive = check3.case === "sensitive";
@@ -61093,13 +61095,22 @@ function evaluateAnswer(check3, trace) {
61093
61095
  ];
61094
61096
  const expected = parts3.length ? `the final answer ${parts3.join("; ")}` : "a final answer";
61095
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
+ }
61096
61107
  if (!answer || answer.text.trim() === "") {
61097
61108
  return {
61098
61109
  passed: false,
61099
61110
  expected,
61100
61111
  actual: answer ? "an empty final answer" : "no final answer",
61101
61112
  evidence: answer ? [answer.seq] : [],
61102
- 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.`
61103
61114
  };
61104
61115
  }
61105
61116
  const text24 = comparableText(answer.text, sensitive);
@@ -61116,7 +61127,8 @@ function evaluateAnswer(check3, trace) {
61116
61127
  const explanation = [
61117
61128
  ...missing6.length ? [`The final answer does not contain ${quoted2(missing6)}.`] : [],
61118
61129
  ...unstated.length ? [`It states no number within ${unstated.map((n2) => `${plainNumber(n2.tolerance)} of ${n2.written}`).join(", nor within ")}: ${said}.`] : [],
61119
- ...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."] : []
61120
61132
  ].join(" ");
61121
61133
  return { passed: false, expected, actual, explanation, evidence: [answer.seq] };
61122
61134
  }
@@ -169059,7 +169071,8 @@ function record8(ctx, args) {
169059
169071
  }
169060
169072
  function unchanged(ctx, args) {
169061
169073
  const changes = sql(ctx).prepare("SELECT recordtype, id, operation FROM ns_history ORDER BY ordinal").all().filter((row2) => args.types.includes(row2.recordtype));
169062
- 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");
169063
169076
  }
169064
169077
  function count3(ctx, args) {
169065
169078
  const actual = recordIds(ctx, args.type).length;
@@ -169069,6 +169082,7 @@ var init_checks13 = __esm({
169069
169082
  "packages/server/src/twins/netsuite/checks.ts"() {
169070
169083
  "use strict";
169071
169084
  init_open_items();
169085
+ init_src();
169072
169086
  init_checks4();
169073
169087
  init_store5();
169074
169088
  }
@@ -174400,8 +174414,9 @@ var init_sessions = __esm({
174400
174414
  });
174401
174415
  }
174402
174416
  /**
174403
- * The runner records the agent's answer for it when the agent posted none (SPEC-053 F2): an HTTP agent's reply, or the
174404
- * 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.
174405
174420
  */
174406
174421
  answer(env, id14, answer) {
174407
174422
  return env.serialize(() => {
@@ -174409,7 +174424,7 @@ var init_sessions = __esm({
174409
174424
  if (state3 === "prepared") throw new AnchaError("SESSION_CONFLICT", "session has not started");
174410
174425
  if (state3 === "finished") throw new AnchaError("SESSION_CONFLICT", "session has finished");
174411
174426
  if (env.trace.list().some((entry2) => entry2.service === "agent" && entry2.path === "/done")) return { recorded: false };
174412
- 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 } } });
174413
174428
  return { recorded: true };
174414
174429
  });
174415
174430
  }
@@ -174778,10 +174793,13 @@ function sessionRoutes(opts, sessions) {
174778
174793
  } catch {
174779
174794
  throw new AnchaError("USAGE", "request must be a JSON object");
174780
174795
  }
174781
- fields10(input4, ["output", "source"]);
174796
+ fields10(input4, ["output", "source", "printed"]);
174782
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`);
174783
174798
  if (input4.source !== "reply" && input4.source !== "stdout") throw new AnchaError("USAGE", "source must be reply or stdout");
174784
- 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 } }));
174785
174803
  });
174786
174804
  app2.post("/envs/:id/trials/:sid/agent", async (c) => {
174787
174805
  let input4;
@@ -174828,7 +174846,7 @@ var init_session_routes = __esm({
174828
174846
  init_src();
174829
174847
  init_feed();
174830
174848
  init_env_info();
174831
- MAX_ANSWER_CHARS = 16e3;
174849
+ MAX_ANSWER_CHARS = 64 * 1024;
174832
174850
  }
174833
174851
  });
174834
174852
 
@@ -177022,6 +177040,26 @@ import { lookup as lookup5 } from "node:dns/promises";
177022
177040
  import { createServer, request } from "node:http";
177023
177041
  import { request as secureRequest } from "node:https";
177024
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
+ }
177025
177063
  function loopbackOrigin(value4) {
177026
177064
  const url4 = new URL(value4);
177027
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");
@@ -177162,11 +177200,30 @@ async function startIsolationGateway(options4) {
177162
177200
  agent: false,
177163
177201
  ...modelHost && { servername: modelHost, rejectUnauthorized: true, family: modelAddress.family }
177164
177202
  }, (reply5) => {
177165
- if (modelHost !== void 0 && reply5.statusCode !== void 0) {
177203
+ const observe2 = (host, status4, message7) => {
177166
177204
  try {
177167
- options4.onModelReply?.(modelHost, reply5.statusCode);
177205
+ options4.onModelReply?.(host, status4, message7);
177168
177206
  } catch {
177169
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
+ }
177170
177227
  }
177171
177228
  if (reply5.statusCode && reply5.statusCode >= 300 && reply5.statusCode < 400) {
177172
177229
  reply5.destroy();
@@ -177278,12 +177335,14 @@ async function startIsolationGateway(options4) {
177278
177335
  return mapped(exposedOrigin);
177279
177336
  }, close };
177280
177337
  }
177281
- var BODY_LIMIT, HOP_HEADERS;
177338
+ var BODY_LIMIT, HOP_HEADERS, MODEL_REFUSALS, REFUSAL_BYTES;
177282
177339
  var init_gateway = __esm({
177283
177340
  "backend/src/execution/gateway.ts"() {
177284
177341
  "use strict";
177285
177342
  BODY_LIMIT = 8 * 1024 * 1024;
177286
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;
177287
177346
  }
177288
177347
  });
177289
177348
 
@@ -177587,7 +177646,7 @@ var init_agent_env = __esm({
177587
177646
  import { createHash as createHash53 } from "node:crypto";
177588
177647
  import { readdir, readFile as readFile3 } from "node:fs/promises";
177589
177648
  import { join as join4 } from "node:path";
177590
- import { gunzipSync, gzipSync } from "node:zlib";
177649
+ import { gunzipSync as gunzipSync2, gzipSync } from "node:zlib";
177591
177650
  function bundleSource(env) {
177592
177651
  return env.CI === "true" || env.GITHUB_ACTIONS ? "ci" : "cli";
177593
177652
  }
@@ -204027,38 +204086,38 @@ function withoutScriptBanners(lines) {
204027
204086
  if (end > start && YARN_DONE.test(lines[end - 1].trim())) end--;
204028
204087
  return lines.slice(start, end);
204029
204088
  }
204030
- function finalBlock(stdout) {
204031
- const lines = withoutScriptBanners(stdout.replace(ANSI, "").replace(/\r\n?/g, "\n").trimEnd().split("\n"));
204032
- const blank = lines.findLastIndex((line2) => line2.trim() === "");
204033
- let block2 = (blank >= 0 ? lines.slice(blank + 1) : lines.slice(-ANSWER_MAX_LINES)).join("\n");
204034
- if (Buffer.byteLength(block2) > ANSWER_MAX_BYTES) {
204035
- const bytes2 = Buffer.from(block2);
204036
- let end = bytes2.subarray(bytes2.length - ANSWER_MAX_BYTES).toString("utf8").replace(/^�+/, "");
204037
- const line2 = end.indexOf("\n");
204038
- if (line2 >= 0 && line2 < end.length - 1) end = end.slice(line2 + 1);
204039
- block2 = end;
204040
- }
204041
- 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();
204042
204091
  }
204043
- 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;
204044
204093
  var init_agent_output = __esm({
204045
204094
  "backend/src/runner/agent-output.ts"() {
204046
204095
  "use strict";
204047
- TAIL_CHARS = 64 * 1024;
204048
- ANSWER_MAX_BYTES = 8 * 1024;
204049
- ANSWER_MAX_LINES = 40;
204096
+ init_gateway();
204097
+ ANSWER_MAX_CHARS = 64 * 1024;
204098
+ STDOUT_MAX_CHARS = 2 * ANSWER_MAX_CHARS;
204050
204099
  OutputTail = class {
204100
+ max;
204051
204101
  #text = "";
204052
204102
  #cut = false;
204103
+ #length = 0;
204104
+ constructor(max = STDOUT_MAX_CHARS) {
204105
+ this.max = max;
204106
+ }
204053
204107
  push(text24) {
204054
204108
  this.#text += text24;
204055
- if (this.#text.length > TAIL_CHARS * 2) this.#trim();
204109
+ this.#length += text24.length;
204110
+ if (this.#text.length > this.max * 2) this.#trim();
204056
204111
  }
204057
204112
  #trim() {
204058
- if (this.#text.length <= TAIL_CHARS) return;
204059
- this.#text = this.#text.slice(-TAIL_CHARS);
204113
+ if (this.#text.length <= this.max) return;
204114
+ this.#text = this.#text.slice(-this.max);
204060
204115
  this.#cut = true;
204061
204116
  }
204117
+ /** How many characters were pushed in all. */
204118
+ length() {
204119
+ return this.#length;
204120
+ }
204062
204121
  /** What was kept; a first line cut in the middle is left out. */
204063
204122
  text() {
204064
204123
  this.#trim();
@@ -204067,15 +204126,23 @@ var init_agent_output = __esm({
204067
204126
  };
204068
204127
  ModelReplies = class {
204069
204128
  #counts = /* @__PURE__ */ new Map();
204070
- add(host, status4) {
204129
+ #last;
204130
+ add(host, status4, message7) {
204071
204131
  const key4 = `${host} ${status4}`;
204072
204132
  const reply5 = this.#counts.get(key4);
204073
- if (reply5) reply5.count++;
204074
- 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 } };
204075
204138
  }
204076
204139
  list() {
204077
204140
  return [...this.#counts.values()].map((reply5) => ({ ...reply5 }));
204078
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
+ }
204079
204146
  };
204080
204147
  ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
204081
204148
  NPM_SCRIPT = /^> (?:\S+@\S* )?[\w:.-]+(?: \/\S*)?$/;
@@ -204161,7 +204228,7 @@ function outputCopy(logFd) {
204161
204228
  closeSync2(stderr.fd);
204162
204229
  }
204163
204230
  },
204164
- tail: () => tail.text()
204231
+ output: () => ({ stdout: tail.text(), printed: tail.length() })
204165
204232
  };
204166
204233
  }
204167
204234
  function startAgentProcess(command, opts) {
@@ -204218,7 +204285,7 @@ function startAgentProcess(command, opts) {
204218
204285
  return { pid, exited, async stop() {
204219
204286
  terminate();
204220
204287
  await exited;
204221
- }, ...stdout && { output: () => ({ stdout: stdout.tail() }) } };
204288
+ }, ...stdout && { output: stdout.output } };
204222
204289
  }
204223
204290
  var KILL_GRACE_MS, GROUP_POLL_MS, COPY_MS;
204224
204291
  var init_process = __esm({
@@ -205013,7 +205080,7 @@ async function startContainedAgent(command, opts) {
205013
205080
  ]);
205014
205081
  await run4(["start", relayName]);
205015
205082
  const replies = new ModelReplies();
205016
- 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) });
205017
205084
  const script = isolationRelayScript({ port: RELAY_PORT, ...opts.runtime?.port && { agentPort: opts.runtime.port } });
205018
205085
  relayChild = spawn2("docker", ["--context", context3, "exec", "-i", relayName, "node", "-e", script], { env: dockerEnvironment(), stdio: ["pipe", "pipe", "pipe"] });
205019
205086
  relayChild.stderr.on("data", () => {
@@ -205105,7 +205172,7 @@ async function startContainedAgent(command, opts) {
205105
205172
  return { pid: child2.pid, exited, async stop() {
205106
205173
  await cleanup();
205107
205174
  await exited;
205108
- }, output: () => ({ stdout: tail.text(), modelReplies: replies.list() }) };
205175
+ }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), modelRefusal: replies.refusal() }) };
205109
205176
  } catch (error64) {
205110
205177
  opts.signal?.removeEventListener("abort", abort);
205111
205178
  await cleanup();
@@ -205291,7 +205358,7 @@ async function startVmAgent(command, opts, deps = {}) {
205291
205358
  ...opts.session && { session: opts.session },
205292
205359
  modelHosts,
205293
205360
  port: unsafe ? 0 : 18991,
205294
- onModelReply: (host, status4) => replies.add(host, status4)
205361
+ onModelReply: (host, status4, message7) => replies.add(host, status4, message7)
205295
205362
  });
205296
205363
  const mapped = gateway.rewrite(unsafe ? gateway.url : VM_GATEWAY_ORIGIN);
205297
205364
  const agentRuntime = { ...opts.runtime, ...taskFile !== void 0 && { taskFile }, ...opts.runtime?.attempt && { attempt: { ...opts.runtime.attempt, stateDir: paths2.state, records: records3 } } };
@@ -205413,7 +205480,7 @@ async function startVmAgent(command, opts, deps = {}) {
205413
205480
  return { pid: child2.pid, exited, async stop() {
205414
205481
  await cleanup();
205415
205482
  await exited;
205416
- }, output: () => ({ stdout: tail.text(), modelReplies: replies.list() }) };
205483
+ }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), modelRefusal: replies.refusal() }) };
205417
205484
  } catch (error64) {
205418
205485
  await cleanup();
205419
205486
  throw error64;
@@ -206212,6 +206279,34 @@ var init_per_event = __esm({
206212
206279
  }
206213
206280
  });
206214
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
+
206215
206310
  // backend/src/runner/trial.ts
206216
206311
  import { setTimeout as sleep8 } from "node:timers/promises";
206217
206312
  import { closeSync as closeSync6, openSync as openSync6, writeSync as writeSync6 } from "node:fs";
@@ -206221,16 +206316,29 @@ function answersFrom(agent, source) {
206221
206316
  const mode = agent.answer ?? "auto";
206222
206317
  return mode === "auto" || mode === "stdout" && source === "stdout";
206223
206318
  }
206224
- async function recordAnswer(backend, envId, sessionId, output2, source) {
206225
- 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;
206226
206321
  try {
206227
- await backend.recordAnswer(envId, sessionId, { output: output2, source });
206322
+ await backend.recordAnswer(envId, sessionId, { output: output2, source, ...printed !== void 0 && { printed } });
206228
206323
  return void 0;
206229
206324
  } catch (error64) {
206230
206325
  if (unknownRoute18(error64)) return void 0;
206231
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)}` };
206232
206327
  }
206233
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
+ }
206234
206342
  async function runTrial(spec) {
206235
206343
  const { backend, env, scene: scene2, trial, dir, signal, inheritedEnv = process.env } = spec;
206236
206344
  const agent = scene2.agent_input && spec.agent.mode !== "endpoint" ? { ...spec.agent, taskInput: sceneTaskInput(scene2, spec.agent.taskInput) } : spec.agent;
@@ -206325,7 +206433,7 @@ async function runTrial(spec) {
206325
206433
  const playOutIssues = [];
206326
206434
  const ended = exit === "timeout" || exit === "done" || exit === "exited" && exitCode === 0;
206327
206435
  if (ended && failure5 === void 0 && !signal?.aborted && answersFrom(agent, "stdout")) {
206328
- const issue6 = await recordAnswer(backend, env.id, session2.id, finalBlock(output2?.stdout ?? ""), "stdout");
206436
+ const issue6 = await recordStdout(backend, env.id, session2.id, output2);
206329
206437
  if (issue6 !== void 0) playOutIssues.push(issue6);
206330
206438
  }
206331
206439
  let playOut;
@@ -206338,6 +206446,7 @@ async function runTrial(spec) {
206338
206446
  }
206339
206447
  const capture3 = await captureTrialAfterFailure(failure5, backend, env.id, session2.id, dir, scene2, { ...spec.judge, ...signal !== void 0 && { signal } }, void 0, spec.onCaptured);
206340
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 ?? {})));
206341
206450
  if (failure5 !== void 0) throw failure5.error;
206342
206451
  signal?.throwIfAborted();
206343
206452
  return {
@@ -206377,6 +206486,7 @@ var init_trial = __esm({
206377
206486
  init_per_event();
206378
206487
  init_budget();
206379
206488
  init_agent_output();
206489
+ init_agent_outcome();
206380
206490
  init_agent_env();
206381
206491
  EXIT_COMMAND_NOT_FOUND2 = 127;
206382
206492
  unknownRoute18 = (error64) => error64 instanceof AnchaError && error64.code === "USAGE" && error64.message.startsWith("no such route");
@@ -206843,6 +206953,14 @@ var init_baselines = __esm({
206843
206953
  }
206844
206954
  });
206845
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
+
206846
206964
  // packages/cli/src/runner/worker.ts
206847
206965
  init_src();
206848
206966
 
@@ -206960,11 +207078,12 @@ init_report2();
206960
207078
 
206961
207079
  // packages/cli/src/cloud-bundle.ts
206962
207080
  init_src();
206963
- init_baselines();
206964
207081
  import { basename as basename5, resolve as resolve12 } from "node:path";
207082
+ init_baselines();
206965
207083
 
206966
207084
  // backend/src/cloud/bundle.ts
206967
207085
  init_src();
207086
+ init_connection_tools();
206968
207087
  init_jobs_contract();
206969
207088
 
206970
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.15",
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": {