@ancha-labs/cli 0.4.44 → 0.4.46

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/ancha.mjs CHANGED
@@ -108101,10 +108101,10 @@ var init_connect_registry = __esm({
108101
108101
  });
108102
108102
 
108103
108103
  // packages/server/src/twins/stripe/connect.ts
108104
- function requestAccount(ctx, header4, routeKey) {
108104
+ function requestAccount(ctx, header4, routeKey2) {
108105
108105
  if (header4 === void 0) return null;
108106
108106
  const id15 = header4.trim();
108107
- if (!ACCOUNT_SCOPED.has(routeKey)) unsupported8(`the Stripe-Account header on ${routeKey}`);
108107
+ if (!ACCOUNT_SCOPED.has(routeKey2)) unsupported8(`the Stripe-Account header on ${routeKey2}`);
108108
108108
  const account9 = load2(ctx, id15);
108109
108109
  if (!account9 || account9.object !== "account" || account9.deleted) {
108110
108110
  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" });
@@ -231293,7 +231293,7 @@ var init_jobs_contract = __esm({
231293
231293
  CLOUD_MODEL_HOSTS = ["openrouter.ai", "api.openai.com", "api.anthropic.com", "generativelanguage.googleapis.com", "api.groq.com", "api.mistral.ai", "api.together.xyz", "api.fireworks.ai", "api.deepseek.com", "api.x.ai", "api.cohere.com"];
231294
231294
  DEFAULT_MODEL_HOSTS = ["openrouter.ai", "api.openai.com", "api.anthropic.com"];
231295
231295
  MODEL_KEY_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "GOOGLE_API_KEY", "OPENROUTER_API_KEY", "AZURE_OPENAI_API_KEY", "MISTRAL_API_KEY", "GROQ_API_KEY", "DEEPSEEK_API_KEY", "XAI_API_KEY", "COHERE_API_KEY", "TOGETHER_API_KEY", "FIREWORKS_API_KEY"];
231296
- PROBE_OUTCOMES = ["answered", "refused", "outside_host", "unserved", "crashed", "idle", "no_answer", "wrong_answer", "model_key", "missing_secret"];
231296
+ PROBE_OUTCOMES = ["answered", "refused", "outside_host", "unserved", "crashed", "idle", "no_answer", "wrong_answer", "model_key", "missing_secret", "route_key"];
231297
231297
  ANSWER_SOURCES = ["done", "reply", "stdout"];
231298
231298
  HEARTBEAT_MS = 1e4;
231299
231299
  AGENT_UID = 10001;
@@ -232034,135 +232034,145 @@ async function startIsolationGateway(options5) {
232034
232034
  headers.host = modelHost ?? new URL(exposedOrigin ?? upstream.origin).host;
232035
232035
  delete headers["x-ancha-client-origin"];
232036
232036
  if (transform3) headers["accept-encoding"] = "identity";
232037
- const target6 = (modelHost ? secureRequest : request)({
232038
- hostname: modelAddress?.address ?? upstream.hostname.replace(/^\[|\]$/g, ""),
232039
- port: modelHost ? 443 : upstream.port || 80,
232040
- path: targetPath,
232041
- method: req.method,
232042
- headers,
232043
- agent: false,
232044
- ...modelHost && { servername: modelHost, rejectUnauthorized: true, family: modelAddress.family }
232045
- }, (reply6) => {
232046
- const observe2 = (host, status6, message8) => {
232047
- try {
232048
- options5.onModelReply?.(host, status6, message8);
232049
- } catch {
232037
+ let target6;
232038
+ try {
232039
+ target6 = (modelHost ? secureRequest : request)({
232040
+ hostname: modelAddress?.address ?? upstream.hostname.replace(/^\[|\]$/g, ""),
232041
+ port: modelHost ? 443 : upstream.port || 80,
232042
+ path: targetPath,
232043
+ method: req.method,
232044
+ headers,
232045
+ agent: false,
232046
+ ...modelHost && { servername: modelHost, rejectUnauthorized: true, family: modelAddress.family }
232047
+ }, (reply6) => {
232048
+ if (!reply6.statusCode || reply6.statusCode < 100) {
232049
+ reply6.destroy();
232050
+ reject3(res, 502, "Tool connection failed.");
232051
+ return;
232050
232052
  }
232051
- };
232052
- if (!toolCall && modelHost !== void 0 && reply6.statusCode !== void 0) {
232053
- const host = modelHost, status6 = reply6.statusCode;
232054
- if (!MODEL_REFUSALS.has(status6)) observe2(host, status6);
232055
- else {
232053
+ const observe2 = (host, status6, message8) => {
232054
+ try {
232055
+ options5.onModelReply?.(host, status6, message8);
232056
+ } catch {
232057
+ }
232058
+ };
232059
+ if (!toolCall && modelHost !== void 0 && reply6.statusCode !== void 0) {
232060
+ const host = modelHost, status6 = reply6.statusCode;
232061
+ if (!MODEL_REFUSALS.has(status6)) observe2(host, status6);
232062
+ else {
232063
+ const chunks2 = [];
232064
+ let size3 = 0, told = false;
232065
+ const tell = () => {
232066
+ if (told) return;
232067
+ told = true;
232068
+ observe2(host, status6, size3 <= REFUSAL_BYTES ? refusalMessage(Buffer.concat(chunks2), reply6.headers["content-encoding"]?.toLowerCase()) : void 0);
232069
+ };
232070
+ reply6.on("data", (chunk) => {
232071
+ size3 += chunk.length;
232072
+ if (size3 <= REFUSAL_BYTES) chunks2.push(chunk);
232073
+ });
232074
+ reply6.once("end", tell);
232075
+ reply6.once("close", tell);
232076
+ }
232077
+ }
232078
+ if (reply6.statusCode && reply6.statusCode >= 300 && reply6.statusCode < 400) {
232079
+ reply6.destroy();
232080
+ reject3(res, 502, "Tool redirects are not allowed through the sandbox gateway.");
232081
+ return;
232082
+ }
232083
+ const responseHeaders = toolCall ? { "content-type": reply6.headers["content-type"] ?? "application/json" } : cleanHeaders(reply6.headers);
232084
+ 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"];
232085
+ const successful2 = reply6.statusCode !== void 0 && reply6.statusCode >= 200 && reply6.statusCode < 300;
232086
+ if (toolCall?.response === "session-delete" && successful2) route15.sessions.delete(toolCall.sessionId);
232087
+ if (toolCall && successful2 && (toolCall.response === "session-create" || toolCall.response === "session-get")) {
232056
232088
  const chunks2 = [];
232057
- let size3 = 0, told = false;
232058
- const tell = () => {
232059
- if (told) return;
232060
- told = true;
232061
- observe2(host, status6, size3 <= REFUSAL_BYTES ? refusalMessage(Buffer.concat(chunks2), reply6.headers["content-encoding"]?.toLowerCase()) : void 0);
232089
+ let size3 = 0, failed2 = false;
232090
+ const fail9 = () => {
232091
+ if (failed2) return;
232092
+ failed2 = true;
232093
+ reply6.destroy();
232094
+ if (!res.headersSent) reject3(res, 502, "Composio returned an invalid session response.");
232095
+ else res.destroy();
232062
232096
  };
232063
232097
  reply6.on("data", (chunk) => {
232064
232098
  size3 += chunk.length;
232065
- if (size3 <= REFUSAL_BYTES) chunks2.push(chunk);
232099
+ if (size3 > 1024 * 1024) fail9();
232100
+ else if (!failed2) chunks2.push(Buffer.from(chunk));
232066
232101
  });
232067
- reply6.once("end", tell);
232068
- reply6.once("close", tell);
232102
+ reply6.once("error", fail9);
232103
+ reply6.once("aborted", fail9);
232104
+ reply6.once("end", () => {
232105
+ if (failed2) return;
232106
+ try {
232107
+ const value6 = rewriteComposioSession(JSON.parse(Buffer.concat(chunks2).toString("utf8")), toolCall, route15, exposedOrigin);
232108
+ const body8 = JSON.stringify(value6);
232109
+ res.writeHead(reply6.statusCode, { "content-type": "application/json", "content-length": Buffer.byteLength(body8) });
232110
+ res.end(body8);
232111
+ } catch {
232112
+ fail9();
232113
+ }
232114
+ });
232115
+ return;
232069
232116
  }
232070
- }
232071
- if (reply6.statusCode && reply6.statusCode >= 300 && reply6.statusCode < 400) {
232072
- reply6.destroy();
232073
- reject3(res, 502, "Tool redirects are not allowed through the sandbox gateway.");
232074
- return;
232075
- }
232076
- const responseHeaders = toolCall ? { "content-type": reply6.headers["content-type"] ?? "application/json" } : cleanHeaders(reply6.headers);
232077
- 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"];
232078
- const successful2 = reply6.statusCode !== void 0 && reply6.statusCode >= 200 && reply6.statusCode < 300;
232079
- if (toolCall?.response === "session-delete" && successful2) route15.sessions.delete(toolCall.sessionId);
232080
- if (toolCall && successful2 && (toolCall.response === "session-create" || toolCall.response === "session-get")) {
232081
- const chunks2 = [];
232082
- let size3 = 0, failed2 = false;
232083
- const fail9 = () => {
232084
- if (failed2) return;
232085
- failed2 = true;
232086
- reply6.destroy();
232087
- if (!res.headersSent) reject3(res, 502, "Composio returned an invalid session response.");
232088
- else res.destroy();
232089
- };
232117
+ if (toolCall) {
232118
+ let received = 0;
232119
+ reply6.on("data", (chunk) => {
232120
+ received += chunk.length;
232121
+ if (received > BODY_LIMIT) {
232122
+ reply6.destroy();
232123
+ res.destroy();
232124
+ }
232125
+ });
232126
+ }
232127
+ if (!transform3) {
232128
+ res.writeHead(reply6.statusCode ?? 502, responseHeaders);
232129
+ reply6.pipe(res);
232130
+ reply6.on("error", () => res.destroy());
232131
+ return;
232132
+ }
232133
+ const chunks = [];
232134
+ let size2 = 0;
232090
232135
  reply6.on("data", (chunk) => {
232091
- size3 += chunk.length;
232092
- if (size3 > 1024 * 1024) fail9();
232093
- else if (!failed2) chunks2.push(Buffer.from(chunk));
232136
+ size2 += chunk.length;
232137
+ if (size2 > BODY_LIMIT) {
232138
+ reply6.destroy();
232139
+ reject3(res, 502, "Tool response exceeded the sandbox gateway limit.");
232140
+ } else chunks.push(chunk);
232094
232141
  });
232095
- reply6.once("error", fail9);
232096
- reply6.once("aborted", fail9);
232097
- reply6.once("end", () => {
232098
- if (failed2) return;
232142
+ reply6.on("error", () => {
232143
+ if (!res.headersSent) reject3(res, 502, "Tool connection failed.");
232144
+ else res.destroy();
232145
+ });
232146
+ reply6.on("end", () => {
232147
+ if (size2 > BODY_LIMIT) return;
232099
232148
  try {
232100
- const value6 = rewriteComposioSession(JSON.parse(Buffer.concat(chunks2).toString("utf8")), toolCall, route15, exposedOrigin);
232149
+ let value6 = JSON.parse(Buffer.concat(chunks).toString("utf8"));
232150
+ if (transform3 === "context" && reply6.statusCode === 200) {
232151
+ const connection4 = mapped(exposedOrigin ?? "");
232152
+ value6 = { ...value6, env: connection4.env, session: connection4.session };
232153
+ }
232154
+ if (transform3 === "socket" && reply6.statusCode === 200 && value6?.ok === true) {
232155
+ const grant = new URL(value6.url);
232156
+ const expected = loopbackOrigin(session2.eventsUrl);
232157
+ 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");
232158
+ for (const [path10, old] of socketGrants) if (old.expires <= Date.now()) socketGrants.delete(path10);
232159
+ if (socketGrants.size >= 128) throw new Error("Too many socket grants");
232160
+ socketGrants.set(grant.pathname, { url: grant, expires: Date.now() + 3e4 });
232161
+ value6 = { ...value6, url: (exposedOrigin ?? "").replace(/^http:/, "ws:") + grant.pathname };
232162
+ }
232101
232163
  const body8 = JSON.stringify(value6);
232102
- res.writeHead(reply6.statusCode, { "content-type": "application/json", "content-length": Buffer.byteLength(body8) });
232164
+ delete responseHeaders["content-encoding"];
232165
+ delete responseHeaders["content-length"];
232166
+ res.writeHead(reply6.statusCode ?? 502, { ...responseHeaders, "content-length": Buffer.byteLength(body8) });
232103
232167
  res.end(body8);
232104
232168
  } catch {
232105
- fail9();
232106
- }
232107
- });
232108
- return;
232109
- }
232110
- if (toolCall) {
232111
- let received = 0;
232112
- reply6.on("data", (chunk) => {
232113
- received += chunk.length;
232114
- if (received > BODY_LIMIT) {
232115
- reply6.destroy();
232116
- res.destroy();
232169
+ reject3(res, 502, "Tool context was not a valid bounded response.");
232117
232170
  }
232118
232171
  });
232119
- }
232120
- if (!transform3) {
232121
- res.writeHead(reply6.statusCode ?? 502, responseHeaders);
232122
- reply6.pipe(res);
232123
- reply6.on("error", () => res.destroy());
232124
- return;
232125
- }
232126
- const chunks = [];
232127
- let size2 = 0;
232128
- reply6.on("data", (chunk) => {
232129
- size2 += chunk.length;
232130
- if (size2 > BODY_LIMIT) {
232131
- reply6.destroy();
232132
- reject3(res, 502, "Tool response exceeded the sandbox gateway limit.");
232133
- } else chunks.push(chunk);
232134
- });
232135
- reply6.on("error", () => {
232136
- if (!res.headersSent) reject3(res, 502, "Tool connection failed.");
232137
- else res.destroy();
232138
232172
  });
232139
- reply6.on("end", () => {
232140
- if (size2 > BODY_LIMIT) return;
232141
- try {
232142
- let value6 = JSON.parse(Buffer.concat(chunks).toString("utf8"));
232143
- if (transform3 === "context" && reply6.statusCode === 200) {
232144
- const connection4 = mapped(exposedOrigin ?? "");
232145
- value6 = { ...value6, env: connection4.env, session: connection4.session };
232146
- }
232147
- if (transform3 === "socket" && reply6.statusCode === 200 && value6?.ok === true) {
232148
- const grant = new URL(value6.url);
232149
- const expected = loopbackOrigin(session2.eventsUrl);
232150
- 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");
232151
- for (const [path10, old] of socketGrants) if (old.expires <= Date.now()) socketGrants.delete(path10);
232152
- if (socketGrants.size >= 128) throw new Error("Too many socket grants");
232153
- socketGrants.set(grant.pathname, { url: grant, expires: Date.now() + 3e4 });
232154
- value6 = { ...value6, url: (exposedOrigin ?? "").replace(/^http:/, "ws:") + grant.pathname };
232155
- }
232156
- const body8 = JSON.stringify(value6);
232157
- delete responseHeaders["content-encoding"];
232158
- delete responseHeaders["content-length"];
232159
- res.writeHead(reply6.statusCode ?? 502, { ...responseHeaders, "content-length": Buffer.byteLength(body8) });
232160
- res.end(body8);
232161
- } catch {
232162
- reject3(res, 502, "Tool context was not a valid bounded response.");
232163
- }
232164
- });
232165
- });
232173
+ } catch {
232174
+ return reject3(res, 502, "Tool connection failed.");
232175
+ }
232166
232176
  upstreamRequests.add(target6);
232167
232177
  target6.once("close", () => upstreamRequests.delete(target6));
232168
232178
  target6.once("error", () => {
@@ -232490,7 +232500,8 @@ function createComposioConnection(options5) {
232490
232500
  signal.removeEventListener("abort", abort);
232491
232501
  }
232492
232502
  }
232493
- const tag3 = (expiry, lease) => createHmac13("sha256", options5.apiKey).update(`ancha-route:${expiry}:${lease}`).digest("hex").slice(0, 16);
232503
+ const tag3 = (expiry, lease, key5 = options5.apiKey) => createHmac13("sha256", key5).update(`ancha-route:${expiry}:${lease}`).digest("hex").slice(0, 16);
232504
+ const signers = [options5.apiKey, ...options5.savedApiKey && options5.savedApiKey !== options5.apiKey ? [options5.savedApiKey] : []];
232494
232505
  async function sweep() {
232495
232506
  const signal = AbortSignal.timeout(5e3);
232496
232507
  let cursor4, deletions = 0;
@@ -232508,7 +232519,7 @@ function createComposioConnection(options5) {
232508
232519
  if (!config12.success || visited.has(config12.data.id)) continue;
232509
232520
  visited.add(config12.data.id);
232510
232521
  const match3 = /^ancha-route-(\d{10})-([a-z0-9]{12})-([a-f0-9]{16})$/.exec(config12.data.name);
232511
- if (!match3 || Number(match3[1]) * 1e3 >= Date.now() || !timingSafeEqual12(Buffer.from(match3[3]), Buffer.from(tag3(match3[1], match3[2])))) continue;
232522
+ if (!match3 || Number(match3[1]) * 1e3 >= Date.now() || !signers.some((key5) => timingSafeEqual12(Buffer.from(match3[3]), Buffer.from(tag3(match3[1], match3[2], key5))))) continue;
232512
232523
  const accounts2 = await call4(`/connected_accounts?${new URLSearchParams({ auth_config_ids: config12.data.id, limit: "50" })}`, "GET", void 0, signal);
232513
232524
  if (accounts2.status < 200 || accounts2.status >= 300) continue;
232514
232525
  const listed2 = pageSchema.safeParse(accounts2.data);
@@ -232651,7 +232662,7 @@ var init_composio_connection = __esm({
232651
232662
  status;
232652
232663
  slug;
232653
232664
  constructor(status6, slug16) {
232654
- super(`Composio did not create the attempt's test connection (${status6} ${slug16}): check that the workspace secret COMPOSIO_API_KEY is a project API key that may create auth configs and connected accounts.`);
232665
+ super(status6 === 401 || status6 === 403 ? `Composio did not create the attempt's test connection (${status6} ${slug16}): check that the workspace secret COMPOSIO_API_KEY is a project API key that may create auth configs and connected accounts.` : `Composio did not create the attempt's test connection (${status6} ${slug16}); run again.`);
232655
232666
  this.name = "ComposioConnectionError";
232656
232667
  this.status = status6;
232657
232668
  this.slug = slug16;
@@ -232660,6 +232671,77 @@ var init_composio_connection = __esm({
232660
232671
  }
232661
232672
  });
232662
232673
 
232674
+ // backend/src/execution/connection-route.ts
232675
+ function routedTools(routes2) {
232676
+ return ["quickbooks", "netsuite"].filter((tool) => routes2?.[tool] === "composio");
232677
+ }
232678
+ function routedProbeTask(routes2) {
232679
+ const systems = routedTools(routes2).map((tool) => tool === "netsuite" ? "NetSuite (NETSUITE_RUN_SUITEQL_QUERY)" : "QuickBooks (QUICKBOOKS_QUERY_ENTITIES)");
232680
+ return `Ancha connection check: read one customer in each of these systems and reply with their names: ${systems.join(", ")}. Change nothing.`;
232681
+ }
232682
+ function unusableRouteKey(value6) {
232683
+ const key5 = routeKey(value6);
232684
+ if (!key5 || /^[\x21-\x7e]+$/.test(key5)) return void 0;
232685
+ 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";
232686
+ }
232687
+ function connectionRouteEvidence(routes2, summary, trace2, log3) {
232688
+ const tools2 = routedTools(routes2);
232689
+ if (!tools2.length) return { details: [] };
232690
+ const counts2 = tools2.map((tool) => ({ tool, route: summary?.[tool] }));
232691
+ const details = counts2.map(({ tool, route: route15 }) => `${tool === "netsuite" ? "NetSuite" : "QuickBooks"} via Composio: ${route15?.executions ?? 0} execution${route15?.executions === 1 ? "" : "s"}, ${route15?.reached ?? 0} reached the world, ${route15?.refused ?? 0} refused${route15?.via ? ` \xB7 via direct ${route15.via.direct} / session ${route15.via.session} / MCP ${route15.via.mcp}` : ""}`);
232692
+ if (routeKeyRejected(trace2)) return { details, reason: { ...ROUTE_KEY_REASON } };
232693
+ const refused2 = trace2.filter((entry3) => entry3.routeEvent?.leg === "platform" && entry3.routeEvent.op === "refused");
232694
+ for (const entry3 of refused2.slice(0, 5)) {
232695
+ const event3 = entry3.routeEvent;
232696
+ if (event3.leg !== "platform") continue;
232697
+ details.push(`refused: ${event3.method} ${event3.slug ?? "Composio call"}${event3.via ? ` via ${event3.via}` : ""} (${event3.reason ?? "REFUSED"})`);
232698
+ }
232699
+ const first2 = refused2[0];
232700
+ if (first2 || counts2.some(({ route: route15 }) => (route15?.refused ?? 0) > 0)) return { details, reason: {
232701
+ code: "refused",
232702
+ level: "fail",
232703
+ message: "The Composio route refused a call.",
232704
+ fix: first2?.issue?.message ?? "Use the tools declared in agent.routes through COMPOSIO_BASE_URL."
232705
+ } };
232706
+ const platformCalled = trace2.some((entry3) => entry3.routeEvent?.leg === "platform") || counts2.some(({ route: route15 }) => (route15?.executions ?? 0) > 0 || (route15?.sessions ?? 0) > 0);
232707
+ if (!platformCalled && /\b(?:backend|api)\.composio\.(?:dev|ai)\b/i.test(log3)) return { details, reason: {
232708
+ code: "outside_host",
232709
+ level: "fail",
232710
+ message: "The agent called Composio\u2019s own API host without reaching the Ancha gateway.",
232711
+ fix: "The Composio client pins its API URL. Configure the client to take its API URL from COMPOSIO_BASE_URL, then run ancha agent upload again."
232712
+ } };
232713
+ const missed = counts2.filter(({ route: route15 }) => (route15?.executions ?? 0) > (route15?.reached ?? 0));
232714
+ const issue9 = trace2.find((entry3) => entry3.issue?.code === "ROUTE_NOT_REACHED" || entry3.issue?.code === "ROUTE_ARGUMENTS")?.issue;
232715
+ if (missed.length) return { details, reason: {
232716
+ code: "unserved",
232717
+ level: "warning",
232718
+ message: `The check\u2019s Composio executions did not reach ${missed.map(({ tool }) => tool === "netsuite" ? "NetSuite" : "QuickBooks").join(" or ")}.`,
232719
+ fix: issue9?.code === "ROUTE_ARGUMENTS" ? "Send NETSUITE_RUN_SUITEQL_QUERY its SuiteQL query in q, with integer limit and offset when paging." : issue9?.message ?? "Run ancha agent upload again."
232720
+ } };
232721
+ if (counts2.some(({ route: route15 }) => !route15?.reached)) return { details };
232722
+ return { details, reason: { code: "answered", level: "pass", message: "The agent\u2019s Composio executions reached each routed world." } };
232723
+ }
232724
+ var ROUTE_KEY_REASON, routeKeyRejected, routeKey, unusableKeyReason;
232725
+ var init_connection_route = __esm({
232726
+ "backend/src/execution/connection-route.ts"() {
232727
+ "use strict";
232728
+ ROUTE_KEY_REASON = {
232729
+ code: "route_key",
232730
+ level: "fail",
232731
+ message: "Composio did not accept the workspace secret COMPOSIO_API_KEY: it answered 401 to the agent\u2019s call through the route.",
232732
+ fix: "Export the Composio project\u2019s API key as COMPOSIO_API_KEY, run ancha secrets set COMPOSIO_API_KEY, then run ancha agent upload again."
232733
+ };
232734
+ routeKeyRejected = (entries4) => entries4.some((entry3) => entry3.issue?.code === "ROUTE_KEY_REJECTED");
232735
+ routeKey = (value6) => value6?.trim() ?? "";
232736
+ unusableKeyReason = (what, next2 = "run ancha agent upload again") => ({
232737
+ code: "route_key",
232738
+ level: "fail",
232739
+ message: `The workspace secret COMPOSIO_API_KEY contains ${what}, which an API key cannot carry in a request header.`,
232740
+ fix: `Export the Composio project\u2019s API key as COMPOSIO_API_KEY without that character, run ancha secrets set COMPOSIO_API_KEY, then ${next2}.`
232741
+ });
232742
+ }
232743
+ });
232744
+
232663
232745
  // backend/src/execution/ingress-client.ts
232664
232746
  import { createHash as createHash61, randomBytes as randomBytes6 } from "node:crypto";
232665
232747
  function ingressPath(path9, realm) {
@@ -232696,7 +232778,10 @@ async function startIngressClient(options5) {
232696
232778
  for (const toolkit of ["quickbooks", "netsuite"]) if (toolkits[toolkit] && twins.includes(toolkit)) activeToolkits[toolkit] = "composio";
232697
232779
  const qb = !!activeToolkits.quickbooks;
232698
232780
  const connection4 = qb ? env2.services.quickbooks : { url: "http://127.0.0.1", token: "", accountId: "" };
232699
- if (!connection4 || qb && (!connection4.accountId || !connection4.token) || !descriptor3.secretValues.COMPOSIO_API_KEY) throw new AnchaError("CONFIG_INVALID", "Composio route credentials are required");
232781
+ const apiKey = routeKey(descriptor3.secretValues.COMPOSIO_API_KEY);
232782
+ if (!connection4 || qb && (!connection4.accountId || !connection4.token) || !apiKey) throw new AnchaError("CONFIG_INVALID", "Composio route credentials are required");
232783
+ const unusable = unusableRouteKey(apiKey);
232784
+ if (unusable) throw new AnchaError("CONFIG_INVALID", unusableKeyReason(unusable).message);
232700
232785
  const local2 = new URL(connection4.url);
232701
232786
  if (qb && (local2.protocol !== "http:" || local2.hostname !== "127.0.0.1" || local2.username || local2.password || local2.search || local2.hash || local2.pathname.replace(/\/$/, "") !== `/e/${env2.id}/quickbooks`)) throw new Error("QuickBooks route must target its local world");
232702
232787
  const ns = activeToolkits.netsuite ? env2.services.netsuite : void 0;
@@ -232815,7 +232900,8 @@ async function startIngressClient(options5) {
232815
232900
  const user9 = `ancha-${hash6(descriptor3.attemptId)}`;
232816
232901
  const lifecycle2 = createComposioConnection({
232817
232902
  ...options5.composio,
232818
- apiKey: descriptor3.secretValues.COMPOSIO_API_KEY,
232903
+ apiKey,
232904
+ savedApiKey: descriptor3.secretValues.COMPOSIO_API_KEY,
232819
232905
  user: user9,
232820
232906
  publicUrl,
232821
232907
  token: connection4.token,
@@ -232841,14 +232927,14 @@ async function startIngressClient(options5) {
232841
232927
  publicUrl,
232842
232928
  token: connection4.token,
232843
232929
  realm: connection4.accountId,
232844
- apiKey: descriptor3.secretValues.COMPOSIO_API_KEY,
232930
+ apiKey,
232845
232931
  attemptId: descriptor3.attemptId,
232846
232932
  agentKey,
232847
232933
  user: user9,
232848
232934
  connection: () => !qb || closed || failed2 || signal.aborted || Date.now() >= expires ? Promise.reject(new ComposioConnectionError(503, "ROUTE_CLOSED")) : lifecycle2.connection(),
232849
232935
  sessions: sessions2,
232850
232936
  narrowed: (toolkits2) => {
232851
- for (const toolkit of toolkits2) if (![agentKey, descriptor3.secretValues.COMPOSIO_API_KEY, connection4.token, ns?.token, publicUrl].some((secret) => secret && toolkit.includes(secret))) narrowed.add(toolkit);
232937
+ for (const toolkit of toolkits2) if (![agentKey, apiKey, connection4.token, ns?.token, publicUrl].some((secret) => secret && toolkit.includes(secret))) narrowed.add(toolkit);
232852
232938
  },
232853
232939
  signal: failure6.signal,
232854
232940
  get failed() {
@@ -232879,7 +232965,7 @@ async function startIngressClient(options5) {
232879
232965
  if (reached) counts2[toolkit].reached++;
232880
232966
  }
232881
232967
  if (event3.op === "refused") counts2[toolkit].refused++;
232882
- record32({ ...event3, toolkit, relayHash: hash6(id15) }, event3.status, event3.op === "refused" ? issue9("ROUTE_REFUSED", refusedDetail(event3.reason, toolkit), toolkit, event3.reason === "NO_WORLD" ? "agent" : "harness") : event3.op === "execute" && !reached && event3.reason === "ARGUMENTS" ? issue9("ROUTE_ARGUMENTS", "The agent's NETSUITE_RUN_SUITEQL_QUERY arguments were invalid; it got Composio's failure response.", toolkit, "agent") : event3.op === "execute" && !reached ? issue9("ROUTE_NOT_REACHED", toolkit === "netsuite" ? "The SuiteQL call did not reach the NetSuite world: check q, limit and offset, then run again." : unreachedDetail(event3.status), toolkit) : void 0);
232968
+ record32({ ...event3, toolkit, relayHash: hash6(id15) }, event3.status, event3.op === "refused" ? issue9("ROUTE_REFUSED", refusedDetail(event3.reason, toolkit), toolkit, event3.reason === "NO_WORLD" ? "agent" : "harness") : event3.op === "execute" && !reached && event3.reason === "ARGUMENTS" ? issue9("ROUTE_ARGUMENTS", "The agent's NETSUITE_RUN_SUITEQL_QUERY arguments were invalid; it got Composio's failure response.", toolkit, "agent") : event3.op === "execute" && !reached && event3.status === 401 && toolkit === "quickbooks" && (event3.via ?? "direct") === "direct" ? issue9("ROUTE_KEY_REJECTED", KEY_REJECTED, toolkit) : event3.op === "execute" && !reached ? issue9("ROUTE_NOT_REACHED", toolkit === "netsuite" ? "The SuiteQL call did not reach the NetSuite world: check q, limit and offset, then run again." : unreachedDetail(event3.status), toolkit) : event3.op === "catalog" && event3.via !== "mcp" && event3.status === 401 ? issue9("ROUTE_KEY_REJECTED", KEY_REJECTED, toolkit) : void 0);
232883
232969
  },
232884
232970
  summary: () => {
232885
232971
  const result = {};
@@ -232916,7 +233002,7 @@ async function startIngressClient(options5) {
232916
233002
  }
232917
233003
  };
232918
233004
  }
232919
- var headersSchema, requestSchema, batchSchema, bindSchema, forwarded, methods2, hash6, REFUSAL_FIX, unreachedDetail;
233005
+ var headersSchema, requestSchema, batchSchema, bindSchema, forwarded, methods2, hash6, REFUSAL_FIX, unreachedDetail, KEY_REJECTED;
232920
233006
  var init_ingress_client = __esm({
232921
233007
  "backend/src/execution/ingress-client.ts"() {
232922
233008
  "use strict";
@@ -232924,6 +233010,7 @@ var init_ingress_client = __esm({
232924
233010
  init_src();
232925
233011
  init_composio();
232926
233012
  init_composio_connection();
233013
+ init_connection_route();
232927
233014
  headersSchema = external_exports.record(external_exports.string(), external_exports.string());
232928
233015
  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) });
232929
233016
  batchSchema = external_exports.strictObject({ requests: external_exports.array(requestSchema).max(8) });
@@ -232954,6 +233041,7 @@ var init_ingress_client = __esm({
232954
233041
  MCP_BATCH: "send one JSON-RPC object per MCP request"
232955
233042
  };
232956
233043
  unreachedDetail = (status6) => status6 === 401 || status6 === 403 ? `Composio answered ${status6} without calling the world: check the workspace secret COMPOSIO_API_KEY.` : status6 >= 500 ? `Composio answered ${status6} without calling the world; run again.` : `Composio answered ${status6} without calling the world: check the QuickBooks tool arguments and use the connection supplied by the route.`;
233044
+ KEY_REJECTED = "Composio answered 401 to the agent's call through the route: it does not accept the workspace secret COMPOSIO_API_KEY, which the route sends for the agent. Export the Composio project's API key as COMPOSIO_API_KEY, run ancha secrets set COMPOSIO_API_KEY, then run again.";
232957
233045
  }
232958
233046
  });
232959
233047
 
@@ -232983,6 +233071,12 @@ async function runRoutedTrial(spec, run7) {
232983
233071
  if (!spec.agent.routes?.quickbooks && !spec.agent.routes?.netsuite) return run7(spec);
232984
233072
  const descriptor3 = attemptDescriptor();
232985
233073
  const startedAt = performance.now();
233074
+ const unusable = unusableRouteKey(descriptor3.secretValues.COMPOSIO_API_KEY);
233075
+ if (unusable) {
233076
+ const { message: message8, fix } = unusableKeyReason(unusable, "run again");
233077
+ 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}` } });
233078
+ return { ...result, harnessIssues: result.harnessIssues.map((issue9) => ({ ...issue9, code: "ROUTE_KEY_REJECTED" })) };
233079
+ }
232986
233080
  let sessionId, captured;
232987
233081
  const route15 = await startIngressClient({
232988
233082
  routes: spec.agent.routes,
@@ -233021,13 +233115,15 @@ async function runRoutedTrial(spec, run7) {
233021
233115
  return { ...result, routes: route15.summary(), ...result.harnessIssues.some((issue9) => issue9.owner === "harness" && issue9.code?.startsWith("ROUTE_")) && { valid: false, passed: false } };
233022
233116
  } catch (error65) {
233023
233117
  await route15.close();
233024
- const connectionIssue = route15.entries().find((entry3) => entry3.issue?.code === "ROUTE_CONNECTION_FAILED")?.issue;
233118
+ const stopped = error65 instanceof AnchaError && error65.code === "AGENT_UNREACHABLE" ? error65 : void 0;
233119
+ const connectionIssue = route15.entries().find((entry3) => entry3.issue?.code === "ROUTE_CONNECTION_FAILED")?.issue ?? (stopped ? route15.entries().find((entry3) => entry3.issue?.code === "ROUTE_KEY_REJECTED")?.issue : void 0);
233025
233120
  if (!route15.failed && !connectionIssue || spec.signal?.aborted) throw error65;
233026
- const result = await invalidTrial({ scene: spec.scene, trial: spec.trial, dir: spec.dir, startedAt, envId: spec.env.id, ...sessionId && { sessionId }, ...captured && { capture: captured }, service: spec.agent.routes.quickbooks ? "quickbooks" : "netsuite", error: connectionIssue ? { code: "ROUTE_CONNECTION_FAILED", message: connectionIssue.message } : { code: "ROUTE_INGRESS_FAILED", message: "The Composio route could not be kept open." } });
233121
+ const result = await invalidTrial({ scene: spec.scene, trial: spec.trial, dir: spec.dir, startedAt, envId: spec.env.id, ...sessionId && { sessionId }, ...captured && { capture: captured }, service: spec.agent.routes.quickbooks ? "quickbooks" : "netsuite", error: connectionIssue ? { code: connectionIssue.code ?? "ROUTE_CONNECTION_FAILED", message: connectionIssue.message } : { code: "ROUTE_INGRESS_FAILED", message: "The Composio route could not be kept open." } });
233027
233122
  if (!captured) {
233028
233123
  result.trace = route15.entries().map((entry3, i) => ({ ...entry3, seq: i + 1 }));
233029
233124
  result.harnessIssues = collectHarnessIssues(result.trace, []);
233030
233125
  }
233126
+ if (stopped && connectionIssue?.code === "ROUTE_KEY_REJECTED") result.harnessIssues.push({ kind: "pipeline", owner: "agent", service: "agent", code: stopped.code, message: `${stopped.code}: ${stopped.message}`.slice(0, 500) });
233031
233127
  await mkdir4(spec.dir, { recursive: true });
233032
233128
  await writeFile3(join7(spec.dir, "trace.jsonl"), result.trace.map((entry3) => JSON.stringify(entry3) + "\n").join(""));
233033
233129
  return { ...result, routes: route15.summary() };
@@ -233045,6 +233141,7 @@ var init_routed_trial = __esm({
233045
233141
  init_invalid_trial();
233046
233142
  init_runtime3();
233047
233143
  init_ingress_client();
233144
+ init_connection_route();
233048
233145
  connections3 = /* @__PURE__ */ new WeakMap();
233049
233146
  captures = /* @__PURE__ */ new WeakMap();
233050
233147
  trialIngress = (env2) => connections3.get(env2);
@@ -243394,56 +243491,6 @@ var init_dependency_plan = __esm({
243394
243491
  }
243395
243492
  });
243396
243493
 
243397
- // backend/src/execution/connection-route.ts
243398
- function routedTools(routes2) {
243399
- return ["quickbooks", "netsuite"].filter((tool) => routes2?.[tool] === "composio");
243400
- }
243401
- function routedProbeTask(routes2) {
243402
- const systems = routedTools(routes2).map((tool) => tool === "netsuite" ? "NetSuite (NETSUITE_RUN_SUITEQL_QUERY)" : "QuickBooks (QUICKBOOKS_QUERY_ENTITIES)");
243403
- return `Ancha connection check: read one customer in each of these systems and reply with their names: ${systems.join(", ")}. Change nothing.`;
243404
- }
243405
- function connectionRouteEvidence(routes2, summary, trace2, log3) {
243406
- const tools2 = routedTools(routes2);
243407
- if (!tools2.length) return { details: [] };
243408
- const counts2 = tools2.map((tool) => ({ tool, route: summary?.[tool] }));
243409
- const details = counts2.map(({ tool, route: route15 }) => `${tool === "netsuite" ? "NetSuite" : "QuickBooks"} via Composio: ${route15?.executions ?? 0} execution${route15?.executions === 1 ? "" : "s"}, ${route15?.reached ?? 0} reached the world, ${route15?.refused ?? 0} refused${route15?.via ? ` \xB7 via direct ${route15.via.direct} / session ${route15.via.session} / MCP ${route15.via.mcp}` : ""}`);
243410
- const refused2 = trace2.filter((entry3) => entry3.routeEvent?.leg === "platform" && entry3.routeEvent.op === "refused");
243411
- for (const entry3 of refused2.slice(0, 5)) {
243412
- const event3 = entry3.routeEvent;
243413
- if (event3.leg !== "platform") continue;
243414
- details.push(`refused: ${event3.method} ${event3.slug ?? "Composio call"}${event3.via ? ` via ${event3.via}` : ""} (${event3.reason ?? "REFUSED"})`);
243415
- }
243416
- const first2 = refused2[0];
243417
- if (first2 || counts2.some(({ route: route15 }) => (route15?.refused ?? 0) > 0)) return { details, reason: {
243418
- code: "refused",
243419
- level: "fail",
243420
- message: "The Composio route refused a call.",
243421
- fix: first2?.issue?.message ?? "Use the tools declared in agent.routes through COMPOSIO_BASE_URL."
243422
- } };
243423
- const platformCalled = trace2.some((entry3) => entry3.routeEvent?.leg === "platform") || counts2.some(({ route: route15 }) => (route15?.executions ?? 0) > 0 || (route15?.sessions ?? 0) > 0);
243424
- if (!platformCalled && /\b(?:backend|api)\.composio\.(?:dev|ai)\b/i.test(log3)) return { details, reason: {
243425
- code: "outside_host",
243426
- level: "fail",
243427
- message: "The agent called Composio\u2019s own API host without reaching the Ancha gateway.",
243428
- fix: "The Composio client pins its API URL. Configure the client to take its API URL from COMPOSIO_BASE_URL, then run ancha agent upload again."
243429
- } };
243430
- const missed = counts2.filter(({ route: route15 }) => (route15?.executions ?? 0) > (route15?.reached ?? 0));
243431
- const issue9 = trace2.find((entry3) => entry3.issue?.code === "ROUTE_NOT_REACHED" || entry3.issue?.code === "ROUTE_ARGUMENTS")?.issue;
243432
- if (missed.length) return { details, reason: {
243433
- code: "unserved",
243434
- level: "warning",
243435
- message: `The check\u2019s Composio executions did not reach ${missed.map(({ tool }) => tool === "netsuite" ? "NetSuite" : "QuickBooks").join(" or ")}.`,
243436
- fix: issue9?.code === "ROUTE_ARGUMENTS" ? "Send NETSUITE_RUN_SUITEQL_QUERY its SuiteQL query in q, with integer limit and offset when paging." : issue9?.message ?? "Run ancha agent upload again."
243437
- } };
243438
- if (counts2.some(({ route: route15 }) => !route15?.reached)) return { details };
243439
- return { details, reason: { code: "answered", level: "pass", message: "The agent\u2019s Composio executions reached each routed world." } };
243440
- }
243441
- var init_connection_route = __esm({
243442
- "backend/src/execution/connection-route.ts"() {
243443
- "use strict";
243444
- }
243445
- });
243446
-
243447
243494
  // backend/src/execution/vm-connection.ts
243448
243495
  var vm_connection_exports = {};
243449
243496
  __export(vm_connection_exports, {
@@ -243518,6 +243565,11 @@ async function probeVmConnection(descriptor3, deps = {}) {
243518
243565
  const config12 = deps.agent ? void 0 : await loadConfig(descriptor3.projectDir, descriptor3.configPath);
243519
243566
  const agent = deps.agent ?? withLocalEnvironment(resolveRunAgent(config12, descriptor3.projectDir, { ...descriptor3.options.agentCommand !== null && { agent: descriptor3.options.agentCommand }, parallel: 1 }).agent, config12);
243520
243567
  if (agent.mode === "endpoint") assertVmEndpoint(agent);
243568
+ const unusable = routedTools(agent.routes).length ? unusableRouteKey(descriptor3.secretValues.COMPOSIO_API_KEY) : void 0;
243569
+ if (unusable) {
243570
+ probe.reason = unusableKeyReason(unusable);
243571
+ return { state: "failed", probe, message: probe.reason.message };
243572
+ }
243521
243573
  if (agent.slackTransport === "socket" || agent.mode === "endpoint" && agent.slackTransport === "http" && (!agent.readyUrl || config12?.agent?.slackTransport === "http" || deps.agent?.slackTransport === "http")) {
243522
243574
  return await probeSlackApp(descriptor3, agent, probe, deps);
243523
243575
  }
@@ -243676,7 +243728,11 @@ async function runWithTask(descriptor3, agent, run7) {
243676
243728
  const text31 = log3?.toString("utf8") ?? tail.join("\n");
243677
243729
  const route15 = connectionRouteEvidence(agent.routes, trial.routes, trial.trace, text31);
243678
243730
  if (route15.details.length) probe.routeDetails = route15.details;
243679
- const diagnosed = (code5) => code5 === "MODEL_KEY_REFUSED" || routed && (code5 === "ROUTE_REFUSED" || code5 === "ROUTE_NOT_REACHED");
243731
+ if (route15.reason?.code === "route_key") {
243732
+ Object.assign(probe, { reason: route15.reason, logTail: tail.length > 0 ? tail : text31.trimEnd().split("\n").filter(Boolean).slice(-10) });
243733
+ return { state: "failed", probe, message: route15.reason.message };
243734
+ }
243735
+ const diagnosed = (code5) => code5 === "MODEL_KEY_REFUSED" || routed && (code5 === "ROUTE_REFUSED" || code5 === "ROUTE_NOT_REACHED" || code5 === "ROUTE_KEY_REJECTED");
243680
243736
  const harnessIssue = trial.harnessIssues.some((issue9) => issue9.owner === "harness" && !diagnosed(issue9.code));
243681
243737
  if (harnessIssue || !trial.valid && !trial.harnessIssues.some((issue9) => diagnosed(issue9.code))) {
243682
243738
  Object.assign(probe, { logTail: tail, ...fix !== void 0 && { fix } });
@@ -243760,6 +243816,10 @@ async function probeSlackApp(descriptor3, agent, probe, deps) {
243760
243816
  child3 = void 0;
243761
243817
  const log3 = await readFile25(join44(descriptor3.outDir, "agent.log"), "utf8").catch(() => "");
243762
243818
  probe.logTail = log3.trimEnd().split("\n").filter(Boolean).slice(-10);
243819
+ if (ingress && routeKeyRejected(ingress.entries())) {
243820
+ probe.reason = { ...ROUTE_KEY_REASON };
243821
+ return { state: "failed", probe, message: ROUTE_KEY_REASON.message };
243822
+ }
243763
243823
  const fix = socket ? slackSocketFix : slackHttpFix;
243764
243824
  return { state: "failed", probe, message: error65 instanceof AnchaError ? `${error65.message}${error65.hint ? ` ${error65.hint}` : ""}` : `The Slack app did not connect. ${fix}` };
243765
243825
  } finally {