@ancha-labs/cli 0.4.45 → 0.4.47

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
@@ -20459,6 +20459,9 @@ var init_zod = __esm({
20459
20459
  function isErrorCode(value5) {
20460
20460
  return typeof value5 === "string" && ERROR_CODES.includes(value5);
20461
20461
  }
20462
+ function isErrorKind(value5) {
20463
+ return typeof value5 === "string" && ERROR_KINDS.includes(value5);
20464
+ }
20462
20465
  function exitCodeFor(code2) {
20463
20466
  switch (code2) {
20464
20467
  case "CHECKS_FAILED":
@@ -20488,14 +20491,15 @@ function exitCodeFor(code2) {
20488
20491
  }
20489
20492
  function toErrorJson(e) {
20490
20493
  if (e instanceof AnchaError) {
20491
- const out = { code: e.code, message: e.message };
20494
+ const out = { code: e.code, kind: e.kind, message: e.message };
20495
+ if (e.reference !== void 0) out.reference = e.reference;
20492
20496
  if (e.hint !== void 0) out.hint = e.hint;
20493
20497
  if (e.docs !== void 0) out.docs = e.docs;
20494
20498
  return out;
20495
20499
  }
20496
- return { code: "INTERNAL", message: e instanceof Error ? e.message : String(e) };
20500
+ return { code: "INTERNAL", kind: "ours", message: e instanceof Error ? e.message : String(e) };
20497
20501
  }
20498
- var ERROR_CODES, AnchaError;
20502
+ var ERROR_CODES, ERROR_KINDS, KIND_OF, AnchaError;
20499
20503
  var init_errors3 = __esm({
20500
20504
  "packages/core/src/errors.ts"() {
20501
20505
  "use strict";
@@ -20515,14 +20519,35 @@ var init_errors3 = __esm({
20515
20519
  "UNIMPLEMENTED_ENDPOINT",
20516
20520
  "INTERNAL"
20517
20521
  ];
20522
+ ERROR_KINDS = ["fix", "retry", "ours"];
20523
+ KIND_OF = {
20524
+ USAGE: "fix",
20525
+ CONFIG_INVALID: "fix",
20526
+ SCENE_INVALID: "fix",
20527
+ AUTH_INVALID: "fix",
20528
+ AGENT_SPAWN_FAILED: "fix",
20529
+ AGENT_UNREACHABLE: "fix",
20530
+ ENV_NOT_FOUND: "fix",
20531
+ SESSION_UNAUTHORIZED: "fix",
20532
+ CHECKS_FAILED: "fix",
20533
+ SERVER_UNREACHABLE: "retry",
20534
+ SERVER_START_FAILED: "retry",
20535
+ SESSION_CONFLICT: "retry",
20536
+ UNIMPLEMENTED_ENDPOINT: "ours",
20537
+ INTERNAL: "ours"
20538
+ };
20518
20539
  AnchaError = class extends Error {
20519
20540
  code;
20541
+ kind;
20542
+ reference;
20520
20543
  hint;
20521
20544
  docs;
20522
20545
  constructor(code2, message8, opts = {}) {
20523
20546
  super(message8, opts.cause === void 0 ? void 0 : { cause: opts.cause });
20524
20547
  this.name = "AnchaError";
20525
20548
  this.code = code2;
20549
+ this.kind = opts.kind ?? KIND_OF[code2];
20550
+ if (opts.reference !== void 0) this.reference = opts.reference;
20526
20551
  if (opts.hint !== void 0) this.hint = opts.hint;
20527
20552
  if (opts.docs !== void 0) this.docs = opts.docs;
20528
20553
  }
@@ -71463,6 +71488,9 @@ import { createServer, request } from "node:http";
71463
71488
  import { request as secureRequest } from "node:https";
71464
71489
  import { isIP } from "node:net";
71465
71490
  import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib";
71491
+ function modelFailure(status5) {
71492
+ 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 };
71493
+ }
71466
71494
  function refusalMessage(body7, encoding) {
71467
71495
  let text26;
71468
71496
  try {
@@ -71724,135 +71752,145 @@ async function startIsolationGateway(options5) {
71724
71752
  headers.host = modelHost ?? new URL(exposedOrigin ?? upstream.origin).host;
71725
71753
  delete headers["x-ancha-client-origin"];
71726
71754
  if (transform3) headers["accept-encoding"] = "identity";
71727
- const target5 = (modelHost ? secureRequest : request)({
71728
- hostname: modelAddress?.address ?? upstream.hostname.replace(/^\[|\]$/g, ""),
71729
- port: modelHost ? 443 : upstream.port || 80,
71730
- path: targetPath,
71731
- method: req.method,
71732
- headers,
71733
- agent: false,
71734
- ...modelHost && { servername: modelHost, rejectUnauthorized: true, family: modelAddress.family }
71735
- }, (reply6) => {
71736
- const observe2 = (host, status5, message8) => {
71737
- try {
71738
- options5.onModelReply?.(host, status5, message8);
71739
- } catch {
71755
+ let target5;
71756
+ try {
71757
+ target5 = (modelHost ? secureRequest : request)({
71758
+ hostname: modelAddress?.address ?? upstream.hostname.replace(/^\[|\]$/g, ""),
71759
+ port: modelHost ? 443 : upstream.port || 80,
71760
+ path: targetPath,
71761
+ method: req.method,
71762
+ headers,
71763
+ agent: false,
71764
+ ...modelHost && { servername: modelHost, rejectUnauthorized: true, family: modelAddress.family }
71765
+ }, (reply6) => {
71766
+ if (!reply6.statusCode || reply6.statusCode < 100) {
71767
+ reply6.destroy();
71768
+ reject2(res, 502, "Tool connection failed.");
71769
+ return;
71740
71770
  }
71741
- };
71742
- if (!toolCall && modelHost !== void 0 && reply6.statusCode !== void 0) {
71743
- const host = modelHost, status5 = reply6.statusCode;
71744
- if (!MODEL_REFUSALS.has(status5)) observe2(host, status5);
71745
- else {
71771
+ const observe2 = (host, status5, message8) => {
71772
+ try {
71773
+ options5.onModelReply?.(host, status5, message8);
71774
+ } catch {
71775
+ }
71776
+ };
71777
+ if (!toolCall && modelHost !== void 0 && reply6.statusCode !== void 0) {
71778
+ const host = modelHost, status5 = reply6.statusCode;
71779
+ if (!MODEL_REFUSALS.has(status5)) observe2(host, status5);
71780
+ else {
71781
+ const chunks2 = [];
71782
+ let size3 = 0, told = false;
71783
+ const tell = () => {
71784
+ if (told) return;
71785
+ told = true;
71786
+ observe2(host, status5, size3 <= REFUSAL_BYTES ? refusalMessage(Buffer.concat(chunks2), reply6.headers["content-encoding"]?.toLowerCase()) : void 0);
71787
+ };
71788
+ reply6.on("data", (chunk) => {
71789
+ size3 += chunk.length;
71790
+ if (size3 <= REFUSAL_BYTES) chunks2.push(chunk);
71791
+ });
71792
+ reply6.once("end", tell);
71793
+ reply6.once("close", tell);
71794
+ }
71795
+ }
71796
+ if (reply6.statusCode && reply6.statusCode >= 300 && reply6.statusCode < 400) {
71797
+ reply6.destroy();
71798
+ reject2(res, 502, "Tool redirects are not allowed through the sandbox gateway.");
71799
+ return;
71800
+ }
71801
+ const responseHeaders = toolCall ? { "content-type": reply6.headers["content-type"] ?? "application/json" } : cleanHeaders(reply6.headers);
71802
+ if (toolCall?.via === "mcp" && typeof reply6.headers["mcp-session-id"] === "string" && /^[\x21-\x7e]{1,256}$/.test(reply6.headers["mcp-session-id"])) responseHeaders["mcp-session-id"] = reply6.headers["mcp-session-id"];
71803
+ const successful2 = reply6.statusCode !== void 0 && reply6.statusCode >= 200 && reply6.statusCode < 300;
71804
+ if (toolCall?.response === "session-delete" && successful2) route15.sessions.delete(toolCall.sessionId);
71805
+ if (toolCall && successful2 && (toolCall.response === "session-create" || toolCall.response === "session-get")) {
71746
71806
  const chunks2 = [];
71747
- let size3 = 0, told = false;
71748
- const tell = () => {
71749
- if (told) return;
71750
- told = true;
71751
- observe2(host, status5, size3 <= REFUSAL_BYTES ? refusalMessage(Buffer.concat(chunks2), reply6.headers["content-encoding"]?.toLowerCase()) : void 0);
71807
+ let size3 = 0, failed2 = false;
71808
+ const fail6 = () => {
71809
+ if (failed2) return;
71810
+ failed2 = true;
71811
+ reply6.destroy();
71812
+ if (!res.headersSent) reject2(res, 502, "Composio returned an invalid session response.");
71813
+ else res.destroy();
71752
71814
  };
71753
71815
  reply6.on("data", (chunk) => {
71754
71816
  size3 += chunk.length;
71755
- if (size3 <= REFUSAL_BYTES) chunks2.push(chunk);
71817
+ if (size3 > 1024 * 1024) fail6();
71818
+ else if (!failed2) chunks2.push(Buffer.from(chunk));
71756
71819
  });
71757
- reply6.once("end", tell);
71758
- reply6.once("close", tell);
71820
+ reply6.once("error", fail6);
71821
+ reply6.once("aborted", fail6);
71822
+ reply6.once("end", () => {
71823
+ if (failed2) return;
71824
+ try {
71825
+ const value5 = rewriteComposioSession(JSON.parse(Buffer.concat(chunks2).toString("utf8")), toolCall, route15, exposedOrigin);
71826
+ const body7 = JSON.stringify(value5);
71827
+ res.writeHead(reply6.statusCode, { "content-type": "application/json", "content-length": Buffer.byteLength(body7) });
71828
+ res.end(body7);
71829
+ } catch {
71830
+ fail6();
71831
+ }
71832
+ });
71833
+ return;
71759
71834
  }
71760
- }
71761
- if (reply6.statusCode && reply6.statusCode >= 300 && reply6.statusCode < 400) {
71762
- reply6.destroy();
71763
- reject2(res, 502, "Tool redirects are not allowed through the sandbox gateway.");
71764
- return;
71765
- }
71766
- const responseHeaders = toolCall ? { "content-type": reply6.headers["content-type"] ?? "application/json" } : cleanHeaders(reply6.headers);
71767
- if (toolCall?.via === "mcp" && typeof reply6.headers["mcp-session-id"] === "string" && /^[\x21-\x7e]{1,256}$/.test(reply6.headers["mcp-session-id"])) responseHeaders["mcp-session-id"] = reply6.headers["mcp-session-id"];
71768
- const successful2 = reply6.statusCode !== void 0 && reply6.statusCode >= 200 && reply6.statusCode < 300;
71769
- if (toolCall?.response === "session-delete" && successful2) route15.sessions.delete(toolCall.sessionId);
71770
- if (toolCall && successful2 && (toolCall.response === "session-create" || toolCall.response === "session-get")) {
71771
- const chunks2 = [];
71772
- let size3 = 0, failed2 = false;
71773
- const fail6 = () => {
71774
- if (failed2) return;
71775
- failed2 = true;
71776
- reply6.destroy();
71777
- if (!res.headersSent) reject2(res, 502, "Composio returned an invalid session response.");
71778
- else res.destroy();
71779
- };
71835
+ if (toolCall) {
71836
+ let received = 0;
71837
+ reply6.on("data", (chunk) => {
71838
+ received += chunk.length;
71839
+ if (received > BODY_LIMIT) {
71840
+ reply6.destroy();
71841
+ res.destroy();
71842
+ }
71843
+ });
71844
+ }
71845
+ if (!transform3) {
71846
+ res.writeHead(reply6.statusCode ?? 502, responseHeaders);
71847
+ reply6.pipe(res);
71848
+ reply6.on("error", () => res.destroy());
71849
+ return;
71850
+ }
71851
+ const chunks = [];
71852
+ let size2 = 0;
71780
71853
  reply6.on("data", (chunk) => {
71781
- size3 += chunk.length;
71782
- if (size3 > 1024 * 1024) fail6();
71783
- else if (!failed2) chunks2.push(Buffer.from(chunk));
71784
- });
71785
- reply6.once("error", fail6);
71786
- reply6.once("aborted", fail6);
71787
- reply6.once("end", () => {
71788
- if (failed2) return;
71854
+ size2 += chunk.length;
71855
+ if (size2 > BODY_LIMIT) {
71856
+ reply6.destroy();
71857
+ reject2(res, 502, "Tool response exceeded the sandbox gateway limit.");
71858
+ } else chunks.push(chunk);
71859
+ });
71860
+ reply6.on("error", () => {
71861
+ if (!res.headersSent) reject2(res, 502, "Tool connection failed.");
71862
+ else res.destroy();
71863
+ });
71864
+ reply6.on("end", () => {
71865
+ if (size2 > BODY_LIMIT) return;
71789
71866
  try {
71790
- const value5 = rewriteComposioSession(JSON.parse(Buffer.concat(chunks2).toString("utf8")), toolCall, route15, exposedOrigin);
71867
+ let value5 = JSON.parse(Buffer.concat(chunks).toString("utf8"));
71868
+ if (transform3 === "context" && reply6.statusCode === 200) {
71869
+ const connection4 = mapped(exposedOrigin ?? "");
71870
+ value5 = { ...value5, env: connection4.env, session: connection4.session };
71871
+ }
71872
+ if (transform3 === "socket" && reply6.statusCode === 200 && value5?.ok === true) {
71873
+ const grant = new URL(value5.url);
71874
+ const expected = loopbackOrigin(session2.eventsUrl);
71875
+ if (grant.protocol !== "ws:" || grant.hostname !== expected.hostname || grant.port !== expected.port || grant.search || grant.hash || grant.username || grant.password || !/^\/_ancha\/socket\/[a-f0-9]{64}$/.test(grant.pathname)) throw new Error("Invalid socket grant");
71876
+ for (const [path9, old] of socketGrants) if (old.expires <= Date.now()) socketGrants.delete(path9);
71877
+ if (socketGrants.size >= 128) throw new Error("Too many socket grants");
71878
+ socketGrants.set(grant.pathname, { url: grant, expires: Date.now() + 3e4 });
71879
+ value5 = { ...value5, url: (exposedOrigin ?? "").replace(/^http:/, "ws:") + grant.pathname };
71880
+ }
71791
71881
  const body7 = JSON.stringify(value5);
71792
- res.writeHead(reply6.statusCode, { "content-type": "application/json", "content-length": Buffer.byteLength(body7) });
71882
+ delete responseHeaders["content-encoding"];
71883
+ delete responseHeaders["content-length"];
71884
+ res.writeHead(reply6.statusCode ?? 502, { ...responseHeaders, "content-length": Buffer.byteLength(body7) });
71793
71885
  res.end(body7);
71794
71886
  } catch {
71795
- fail6();
71887
+ reject2(res, 502, "Tool context was not a valid bounded response.");
71796
71888
  }
71797
71889
  });
71798
- return;
71799
- }
71800
- if (toolCall) {
71801
- let received = 0;
71802
- reply6.on("data", (chunk) => {
71803
- received += chunk.length;
71804
- if (received > BODY_LIMIT) {
71805
- reply6.destroy();
71806
- res.destroy();
71807
- }
71808
- });
71809
- }
71810
- if (!transform3) {
71811
- res.writeHead(reply6.statusCode ?? 502, responseHeaders);
71812
- reply6.pipe(res);
71813
- reply6.on("error", () => res.destroy());
71814
- return;
71815
- }
71816
- const chunks = [];
71817
- let size2 = 0;
71818
- reply6.on("data", (chunk) => {
71819
- size2 += chunk.length;
71820
- if (size2 > BODY_LIMIT) {
71821
- reply6.destroy();
71822
- reject2(res, 502, "Tool response exceeded the sandbox gateway limit.");
71823
- } else chunks.push(chunk);
71824
- });
71825
- reply6.on("error", () => {
71826
- if (!res.headersSent) reject2(res, 502, "Tool connection failed.");
71827
- else res.destroy();
71828
71890
  });
71829
- reply6.on("end", () => {
71830
- if (size2 > BODY_LIMIT) return;
71831
- try {
71832
- let value5 = JSON.parse(Buffer.concat(chunks).toString("utf8"));
71833
- if (transform3 === "context" && reply6.statusCode === 200) {
71834
- const connection4 = mapped(exposedOrigin ?? "");
71835
- value5 = { ...value5, env: connection4.env, session: connection4.session };
71836
- }
71837
- if (transform3 === "socket" && reply6.statusCode === 200 && value5?.ok === true) {
71838
- const grant = new URL(value5.url);
71839
- const expected = loopbackOrigin(session2.eventsUrl);
71840
- if (grant.protocol !== "ws:" || grant.hostname !== expected.hostname || grant.port !== expected.port || grant.search || grant.hash || grant.username || grant.password || !/^\/_ancha\/socket\/[a-f0-9]{64}$/.test(grant.pathname)) throw new Error("Invalid socket grant");
71841
- for (const [path9, old] of socketGrants) if (old.expires <= Date.now()) socketGrants.delete(path9);
71842
- if (socketGrants.size >= 128) throw new Error("Too many socket grants");
71843
- socketGrants.set(grant.pathname, { url: grant, expires: Date.now() + 3e4 });
71844
- value5 = { ...value5, url: (exposedOrigin ?? "").replace(/^http:/, "ws:") + grant.pathname };
71845
- }
71846
- const body7 = JSON.stringify(value5);
71847
- delete responseHeaders["content-encoding"];
71848
- delete responseHeaders["content-length"];
71849
- res.writeHead(reply6.statusCode ?? 502, { ...responseHeaders, "content-length": Buffer.byteLength(body7) });
71850
- res.end(body7);
71851
- } catch {
71852
- reject2(res, 502, "Tool context was not a valid bounded response.");
71853
- }
71854
- });
71855
- });
71891
+ } catch {
71892
+ return reject2(res, 502, "Tool connection failed.");
71893
+ }
71856
71894
  upstreamRequests.add(target5);
71857
71895
  target5.once("close", () => upstreamRequests.delete(target5));
71858
71896
  target5.once("error", () => {
@@ -72065,6 +72103,7 @@ var init_runtime = __esm({
72065
72103
  concurrency: external_exports.number().int().positive(),
72066
72104
  seed: text13.nullable(),
72067
72105
  strict: external_exports.boolean(),
72106
+ simulatedAnswers: external_exports.enum(["allow", "fail"]).optional(),
72068
72107
  minPassRate: external_exports.number().min(0).max(1),
72069
72108
  allowUnwrapped: external_exports.array(text13),
72070
72109
  agentCommand: text13.nullable(),
@@ -72172,7 +72211,8 @@ function createComposioConnection(options5) {
72172
72211
  signal.removeEventListener("abort", abort);
72173
72212
  }
72174
72213
  }
72175
- const tag3 = (expiry, lease) => createHmac("sha256", options5.apiKey).update(`ancha-route:${expiry}:${lease}`).digest("hex").slice(0, 16);
72214
+ const tag3 = (expiry, lease, key5 = options5.apiKey) => createHmac("sha256", key5).update(`ancha-route:${expiry}:${lease}`).digest("hex").slice(0, 16);
72215
+ const signers = [options5.apiKey, ...options5.savedApiKey && options5.savedApiKey !== options5.apiKey ? [options5.savedApiKey] : []];
72176
72216
  async function sweep() {
72177
72217
  const signal = AbortSignal.timeout(5e3);
72178
72218
  let cursor4, deletions = 0;
@@ -72190,7 +72230,7 @@ function createComposioConnection(options5) {
72190
72230
  if (!config12.success || visited.has(config12.data.id)) continue;
72191
72231
  visited.add(config12.data.id);
72192
72232
  const match3 = /^ancha-route-(\d{10})-([a-z0-9]{12})-([a-f0-9]{16})$/.exec(config12.data.name);
72193
- if (!match3 || Number(match3[1]) * 1e3 >= Date.now() || !timingSafeEqual2(Buffer.from(match3[3]), Buffer.from(tag3(match3[1], match3[2])))) continue;
72233
+ if (!match3 || Number(match3[1]) * 1e3 >= Date.now() || !signers.some((key5) => timingSafeEqual2(Buffer.from(match3[3]), Buffer.from(tag3(match3[1], match3[2], key5))))) continue;
72194
72234
  const accounts2 = await call2(`/connected_accounts?${new URLSearchParams({ auth_config_ids: config12.data.id, limit: "50" })}`, "GET", void 0, signal);
72195
72235
  if (accounts2.status < 200 || accounts2.status >= 300) continue;
72196
72236
  const listed = pageSchema.safeParse(accounts2.data);
@@ -72342,6 +72382,26 @@ var init_composio_connection = __esm({
72342
72382
  }
72343
72383
  });
72344
72384
 
72385
+ // backend/src/execution/connection-route.ts
72386
+ function unusableRouteKey(value5) {
72387
+ const key5 = routeKey(value5);
72388
+ if (!key5 || /^[\x21-\x7e]+$/.test(key5)) return void 0;
72389
+ return /[\r\n]/.test(key5) ? "a line break" : /[ \t]/.test(key5) ? "a space or tab" : /[^\x00-\x7f]/.test(key5) ? "a character that is not plain ASCII, such as a curly quote" : "a control character";
72390
+ }
72391
+ var routeKey, unusableKeyReason;
72392
+ var init_connection_route = __esm({
72393
+ "backend/src/execution/connection-route.ts"() {
72394
+ "use strict";
72395
+ routeKey = (value5) => value5?.trim() ?? "";
72396
+ unusableKeyReason = (what, next2 = "run ancha agent upload again") => ({
72397
+ code: "route_key",
72398
+ level: "fail",
72399
+ message: `The workspace secret COMPOSIO_API_KEY contains ${what}, which an API key cannot carry in a request header.`,
72400
+ fix: `Export the Composio project\u2019s API key as COMPOSIO_API_KEY without that character, run ancha secrets set COMPOSIO_API_KEY, then ${next2}.`
72401
+ });
72402
+ }
72403
+ });
72404
+
72345
72405
  // backend/src/execution/ingress-client.ts
72346
72406
  import { createHash as createHash5, randomBytes as randomBytes2 } from "node:crypto";
72347
72407
  function ingressPath(path8, realm) {
@@ -72378,7 +72438,10 @@ async function startIngressClient(options5) {
72378
72438
  for (const toolkit of ["quickbooks", "netsuite"]) if (toolkits[toolkit] && twins.includes(toolkit)) activeToolkits[toolkit] = "composio";
72379
72439
  const qb = !!activeToolkits.quickbooks;
72380
72440
  const connection4 = qb ? env.services.quickbooks : { url: "http://127.0.0.1", token: "", accountId: "" };
72381
- if (!connection4 || qb && (!connection4.accountId || !connection4.token) || !descriptor2.secretValues.COMPOSIO_API_KEY) throw new AnchaError("CONFIG_INVALID", "Composio route credentials are required");
72441
+ const apiKey = routeKey(descriptor2.secretValues.COMPOSIO_API_KEY);
72442
+ if (!connection4 || qb && (!connection4.accountId || !connection4.token) || !apiKey) throw new AnchaError("CONFIG_INVALID", "Composio route credentials are required");
72443
+ const unusable = unusableRouteKey(apiKey);
72444
+ if (unusable) throw new AnchaError("CONFIG_INVALID", unusableKeyReason(unusable).message);
72382
72445
  const local2 = new URL(connection4.url);
72383
72446
  if (qb && (local2.protocol !== "http:" || local2.hostname !== "127.0.0.1" || local2.username || local2.password || local2.search || local2.hash || local2.pathname.replace(/\/$/, "") !== `/e/${env.id}/quickbooks`)) throw new Error("QuickBooks route must target its local world");
72384
72447
  const ns = activeToolkits.netsuite ? env.services.netsuite : void 0;
@@ -72497,7 +72560,8 @@ async function startIngressClient(options5) {
72497
72560
  const user9 = `ancha-${hash2(descriptor2.attemptId)}`;
72498
72561
  const lifecycle2 = createComposioConnection({
72499
72562
  ...options5.composio,
72500
- apiKey: descriptor2.secretValues.COMPOSIO_API_KEY,
72563
+ apiKey,
72564
+ savedApiKey: descriptor2.secretValues.COMPOSIO_API_KEY,
72501
72565
  user: user9,
72502
72566
  publicUrl,
72503
72567
  token: connection4.token,
@@ -72523,14 +72587,14 @@ async function startIngressClient(options5) {
72523
72587
  publicUrl,
72524
72588
  token: connection4.token,
72525
72589
  realm: connection4.accountId,
72526
- apiKey: descriptor2.secretValues.COMPOSIO_API_KEY,
72590
+ apiKey,
72527
72591
  attemptId: descriptor2.attemptId,
72528
72592
  agentKey,
72529
72593
  user: user9,
72530
72594
  connection: () => !qb || closed || failed2 || signal.aborted || Date.now() >= expires ? Promise.reject(new ComposioConnectionError(503, "ROUTE_CLOSED")) : lifecycle2.connection(),
72531
72595
  sessions: sessions2,
72532
72596
  narrowed: (toolkits2) => {
72533
- for (const toolkit of toolkits2) if (![agentKey, descriptor2.secretValues.COMPOSIO_API_KEY, connection4.token, ns?.token, publicUrl].some((secret) => secret && toolkit.includes(secret))) narrowed.add(toolkit);
72597
+ for (const toolkit of toolkits2) if (![agentKey, apiKey, connection4.token, ns?.token, publicUrl].some((secret) => secret && toolkit.includes(secret))) narrowed.add(toolkit);
72534
72598
  },
72535
72599
  signal: failure5.signal,
72536
72600
  get failed() {
@@ -72606,6 +72670,7 @@ var init_ingress_client = __esm({
72606
72670
  init_src();
72607
72671
  init_composio();
72608
72672
  init_composio_connection();
72673
+ init_connection_route();
72609
72674
  headersSchema = external_exports.record(external_exports.string(), external_exports.string());
72610
72675
  requestSchema = external_exports.strictObject({ rid: external_exports.string().min(1).max(256), method: external_exports.enum(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]), path: external_exports.string().max(8192), query: external_exports.string().max(8192), headers: headersSchema, body_b64: external_exports.string().max(87384) });
72611
72676
  batchSchema = external_exports.strictObject({ requests: external_exports.array(requestSchema).max(8) });
@@ -72666,6 +72731,12 @@ async function runRoutedTrial(spec, run5) {
72666
72731
  if (!spec.agent.routes?.quickbooks && !spec.agent.routes?.netsuite) return run5(spec);
72667
72732
  const descriptor2 = attemptDescriptor();
72668
72733
  const startedAt = performance.now();
72734
+ const unusable = unusableRouteKey(descriptor2.secretValues.COMPOSIO_API_KEY);
72735
+ if (unusable) {
72736
+ const { message: message8, fix } = unusableKeyReason(unusable, "run again");
72737
+ const result = await invalidTrial({ scene: spec.scene, trial: spec.trial, dir: spec.dir, startedAt, envId: spec.env.id, service: spec.agent.routes.quickbooks ? "quickbooks" : "netsuite", error: { code: "ROUTE_KEY_REJECTED", message: `${message8} ${fix}` } });
72738
+ return { ...result, harnessIssues: result.harnessIssues.map((issue9) => ({ ...issue9, code: "ROUTE_KEY_REJECTED" })) };
72739
+ }
72669
72740
  let sessionId, captured;
72670
72741
  const route15 = await startIngressClient({
72671
72742
  routes: spec.agent.routes,
@@ -72730,6 +72801,7 @@ var init_routed_trial = __esm({
72730
72801
  init_invalid_trial();
72731
72802
  init_runtime();
72732
72803
  init_ingress_client();
72804
+ init_connection_route();
72733
72805
  connections2 = /* @__PURE__ */ new WeakMap();
72734
72806
  captures = /* @__PURE__ */ new WeakMap();
72735
72807
  trialIngress = (env) => connections2.get(env);
@@ -87478,8 +87550,8 @@ function buildWwwAuthenticateHeader(errorCode, description2, requiredScopes, res
87478
87550
  function bearerAuthChallengeResponse(error64, options5) {
87479
87551
  const { requiredScopes = [], resourceMetadataUrl } = options5 ?? {};
87480
87552
  if (!(error64 instanceof OAuthError2)) {
87481
- const serverError = new OAuthError2(OAuthErrorCode.ServerError, "Internal Server Error");
87482
- return Response.json(serverError.toResponseObject(), { status: 500 });
87553
+ const serverError2 = new OAuthError2(OAuthErrorCode.ServerError, "Internal Server Error");
87554
+ return Response.json(serverError2.toResponseObject(), { status: 500 });
87483
87555
  }
87484
87556
  switch (error64.code) {
87485
87557
  case OAuthErrorCode.InvalidToken: {
@@ -128820,10 +128892,10 @@ var init_connect_registry = __esm({
128820
128892
  });
128821
128893
 
128822
128894
  // packages/server/src/twins/stripe/connect.ts
128823
- function requestAccount(ctx, header4, routeKey) {
128895
+ function requestAccount(ctx, header4, routeKey2) {
128824
128896
  if (header4 === void 0) return null;
128825
128897
  const id15 = header4.trim();
128826
- if (!ACCOUNT_SCOPED.has(routeKey)) unsupported8(`the Stripe-Account header on ${routeKey}`);
128898
+ if (!ACCOUNT_SCOPED.has(routeKey2)) unsupported8(`the Stripe-Account header on ${routeKey2}`);
128827
128899
  const account9 = load2(ctx, id15);
128828
128900
  if (!account9 || account9.object !== "account" || account9.deleted) {
128829
128901
  throw new StripeError(403, "invalid_request_error", `The provided key does not have access to account '${id15}' (or that account does not exist). Application access may have been revoked.`, { code: "account_invalid" });
@@ -225820,12 +225892,13 @@ async function recordAnswer(backend, envId, sessionId, output2, source, printed)
225820
225892
  }
225821
225893
  }
225822
225894
  function modelKeyIssue(refusal, given2) {
225895
+ const failure5 = modelFailure(refusal.status);
225823
225896
  return {
225824
225897
  kind: "model",
225825
225898
  owner: "harness",
225826
225899
  service: refusal.host,
225827
- code: "MODEL_KEY_REFUSED",
225828
- 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.`
225900
+ code: failure5.code,
225901
+ message: `${refusal.host} ${failure5.did} (${refusal.status}${refusal.message ? `: ${refusal.message}` : ""}), so the attempt tested nothing. ${failure5.fix ?? `Give the agent a working ${modelKeyName(refusal.host, given2)} and run again.`}`
225829
225902
  };
225830
225903
  }
225831
225904
  function recordStdout(backend, envId, sessionId, output2) {
@@ -225998,6 +226071,7 @@ var EXIT_COMMAND_NOT_FOUND2, unknownRoute18;
225998
226071
  var init_trial = __esm({
225999
226072
  "backend/src/runner/trial.ts"() {
226000
226073
  "use strict";
226074
+ init_gateway();
226001
226075
  init_routed_trial();
226002
226076
  init_slack_app();
226003
226077
  init_src();
@@ -226572,6 +226646,25 @@ init_backend();
226572
226646
  init_src();
226573
226647
  init_credentials2();
226574
226648
 
226649
+ // packages/cli/src/server-error.ts
226650
+ init_src();
226651
+ function serverError(status5, body7, fallback) {
226652
+ const value5 = body7 && typeof body7 === "object" ? body7.error : void 0;
226653
+ const error64 = value5 && typeof value5 === "object" ? value5 : {};
226654
+ const unauthorized = status5 === 401 && error64.code !== "AUTH_INVALID";
226655
+ const code2 = status5 === 401 ? "AUTH_INVALID" : isErrorCode(error64.code) ? error64.code : status5 === 403 ? "AUTH_INVALID" : status5 === 500 ? "INTERNAL" : status5 >= 502 && status5 <= 504 ? "SERVER_UNREACHABLE" : fallback.code ?? (status5 === 409 ? "SESSION_CONFLICT" : status5 === 422 ? "CONFIG_INVALID" : "USAGE");
226656
+ const opts = {};
226657
+ const hint = typeof error64.hint === "string" && !unauthorized ? error64.hint : fallback.hint ?? (typeof error64.hint === "string" ? error64.hint : void 0);
226658
+ if (hint !== void 0) opts.hint = hint;
226659
+ if (isErrorKind(error64.kind) && !unauthorized) opts.kind = error64.kind;
226660
+ else if (status5 === 429 || status5 >= 502 && status5 <= 504) opts.kind = "retry";
226661
+ else if (status5 === 500) opts.kind = "ours";
226662
+ if (typeof error64.reference === "string") opts.reference = error64.reference;
226663
+ const said = unauthorized ? void 0 : typeof error64.message === "string" ? error64.message : typeof value5 === "string" ? value5 : void 0;
226664
+ const result = new AnchaError(code2, said ?? fallback.message, opts);
226665
+ return typeof error64.step === "string" ? Object.assign(result, { step: error64.step }) : result;
226666
+ }
226667
+
226575
226668
  // packages/cli/src/run-upload.ts
226576
226669
  init_run_metadata();
226577
226670
  init_src();
@@ -226626,13 +226719,11 @@ async function uploadRun(ctx, workspace3, run5) {
226626
226719
  } catch (error64) {
226627
226720
  throw new AnchaError("SERVER_UNREACHABLE", `${workspace3} did not answer the upload`, { hint: `check the network, then ancha runs upload ${run5.runId}`, cause: error64 });
226628
226721
  }
226629
- if (response6.status === 401) throw authError3(workspace3, { status: 401, keySent: key5 !== void 0 });
226630
226722
  if (!response6.ok) {
226631
226723
  const body7 = await response6.json().catch(() => void 0);
226632
- const error64 = typeof body7?.error === "object" ? body7.error : { message: typeof body7?.error === "string" ? body7.error : void 0 };
226724
+ if (response6.status === 401) throw serverError(response6.status, body7, authError3(workspace3, { status: 401, keySent: key5 !== void 0 }));
226633
226725
  if (response6.status === 404) throw new AnchaError("USAGE", `${workspace3} doesn't take run uploads`, { hint: "upload to your hosted workspace: ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY" });
226634
- const code2 = response6.status >= 500 ? "SERVER_UNREACHABLE" : error64.code !== void 0 && isErrorCode(error64.code) ? error64.code : "USAGE";
226635
- throw new AnchaError(code2, error64.message ?? `the upload was refused (HTTP ${response6.status})`, { hint: error64.hint ?? `ancha runs upload ${run5.runId}` });
226726
+ throw serverError(response6.status, body7, { message: `the upload was refused (HTTP ${response6.status})`, hint: `ancha runs upload ${run5.runId}` });
226636
226727
  }
226637
226728
  const answer = await response6.json().catch(() => void 0);
226638
226729
  return { ...runNumberOf(answer?.runNumber) && { runNumber: runNumberOf(answer?.runNumber) }, url: httpUrl4(answer?.url) ?? `${new URL(workspace3).origin}/runs/${encodeURIComponent(run5.runId)}`, bytes: archive.length, files: manifest.files.length, ...answer?.replaced === true && { replaced: true } };
@@ -226714,6 +226805,10 @@ init_report();
226714
226805
 
226715
226806
  // packages/cli/src/output.ts
226716
226807
  init_src();
226808
+ function errorAction(error64) {
226809
+ const hint = error64.hint ?? (error64.kind === "retry" ? "nothing to change; run the same command again" : error64.kind === "ours" ? "this failed on Ancha's side, not in your setup" : "check the command and configuration, then run it again");
226810
+ return `${error64.kind}: ${hint.replaceAll("\n", "\n ")}${error64.reference ? ` (reference ${error64.reference})` : ""}`;
226811
+ }
226717
226812
  function terse(value5) {
226718
226813
  if (typeof value5 === "string") return /^[^\s"]+$/.test(value5) ? value5 : JSON.stringify(value5);
226719
226814
  return JSON.stringify(value5) ?? "undefined";
@@ -226810,7 +226905,7 @@ var Output = class {
226810
226905
  `);
226811
226906
  } else {
226812
226907
  const lines = [`error[${err2.code}]: ${err2.message.replaceAll("\n", "\n ")}`];
226813
- if (err2.hint !== void 0) lines.push(`hint: ${err2.hint.replaceAll("\n", "\n ")}`);
226908
+ lines.push(errorAction(e instanceof AnchaError ? err2 : { ...err2, hint: "a bug in the Ancha CLI, not in your setup" }));
226814
226909
  if (err2.docs !== void 0) lines.push(`docs: ${err2.docs}`);
226815
226910
  this.#io.stderr.write(`${lines.join("\n")}
226816
226911
  `);
@@ -227129,7 +227224,7 @@ hint: ${json37.hint}` : ""}`);
227129
227224
  }
227130
227225
  function keptUpload(upload6, runId) {
227131
227226
  if (!("error" in upload6)) return upload6;
227132
- return { error: { code: upload6.error.code, message: `the run finished, but its upload failed (${upload6.error.code})`, hint: `ancha runs upload ${runId} tries again and says why` }, ...upload6.required && { required: true } };
227227
+ return { error: { kind: upload6.error.kind, ...upload6.error.reference && { reference: upload6.error.reference }, code: upload6.error.code, message: `the run finished, but its upload failed (${upload6.error.code})`, hint: `ancha runs upload ${runId} tries again and says why` }, ...upload6.required && { required: true } };
227133
227228
  }
227134
227229
  async function executePreparedRun(ctx, input5, initial, ready3) {
227135
227230
  const writer = stateWriter(input5.outDir, initial);
@@ -227189,7 +227284,7 @@ async function executePreparedRun(ctx, input5, initial, ready3) {
227189
227284
  await writer.finish({
227190
227285
  state: interrupted2 ? "interrupted" : "failed",
227191
227286
  exitCode: exitCodeFor(code2),
227192
- error: { code: code2, message: interrupted2 ? "run interrupted" : `run failed (${code2}); partial artifacts may be available` }
227287
+ error: { kind: toErrorJson(error64).kind, code: code2, message: interrupted2 ? "run interrupted" : `run failed (${code2}); partial artifacts may be available` }
227193
227288
  });
227194
227289
  throw error64;
227195
227290
  }
@@ -91877,26 +91877,47 @@ function createMcpHandler(factory, options4 = {}) {
91877
91877
  }
91878
91878
 
91879
91879
  // packages/core/src/errors.ts
91880
+ var KIND_OF = {
91881
+ USAGE: "fix",
91882
+ CONFIG_INVALID: "fix",
91883
+ SCENE_INVALID: "fix",
91884
+ AUTH_INVALID: "fix",
91885
+ AGENT_SPAWN_FAILED: "fix",
91886
+ AGENT_UNREACHABLE: "fix",
91887
+ ENV_NOT_FOUND: "fix",
91888
+ SESSION_UNAUTHORIZED: "fix",
91889
+ CHECKS_FAILED: "fix",
91890
+ SERVER_UNREACHABLE: "retry",
91891
+ SERVER_START_FAILED: "retry",
91892
+ SESSION_CONFLICT: "retry",
91893
+ UNIMPLEMENTED_ENDPOINT: "ours",
91894
+ INTERNAL: "ours"
91895
+ };
91880
91896
  var AnchaError = class extends Error {
91881
91897
  code;
91898
+ kind;
91899
+ reference;
91882
91900
  hint;
91883
91901
  docs;
91884
91902
  constructor(code2, message8, opts = {}) {
91885
91903
  super(message8, opts.cause === void 0 ? void 0 : { cause: opts.cause });
91886
91904
  this.name = "AnchaError";
91887
91905
  this.code = code2;
91906
+ this.kind = opts.kind ?? KIND_OF[code2];
91907
+ if (opts.reference !== void 0) this.reference = opts.reference;
91888
91908
  if (opts.hint !== void 0) this.hint = opts.hint;
91889
91909
  if (opts.docs !== void 0) this.docs = opts.docs;
91890
91910
  }
91891
91911
  };
91892
91912
  function toErrorJson(e) {
91893
91913
  if (e instanceof AnchaError) {
91894
- const out = { code: e.code, message: e.message };
91914
+ const out = { code: e.code, kind: e.kind, message: e.message };
91915
+ if (e.reference !== void 0) out.reference = e.reference;
91895
91916
  if (e.hint !== void 0) out.hint = e.hint;
91896
91917
  if (e.docs !== void 0) out.docs = e.docs;
91897
91918
  return out;
91898
91919
  }
91899
- return { code: "INTERNAL", message: e instanceof Error ? e.message : String(e) };
91920
+ return { code: "INTERNAL", kind: "ours", message: e instanceof Error ? e.message : String(e) };
91900
91921
  }
91901
91922
 
91902
91923
  // packages/core/src/agent-routes.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ancha-labs/cli",
3
- "version": "0.4.45",
3
+ "version": "0.4.47",
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": {