@parcha/agentrun-serve 0.1.0-beta.61 → 0.1.0-beta.62

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.
Files changed (131) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +102 -13
  3. package/dist/api-only.d.ts +4 -0
  4. package/dist/api-only.js +5 -1
  5. package/dist/archil-settings.d.ts +9 -0
  6. package/dist/archil-settings.js +8 -1
  7. package/dist/bash-read-only.d.ts +3 -0
  8. package/dist/bash-read-only.js +6 -3
  9. package/dist/chatgpt-plan.d.ts +26 -8
  10. package/dist/chatgpt-plan.js +89 -21
  11. package/dist/claude-login.d.ts +12 -5
  12. package/dist/claude-login.js +28 -3
  13. package/dist/cli.js +19 -8
  14. package/dist/composio-triggers.d.ts +9 -3
  15. package/dist/computers.d.ts +3 -0
  16. package/dist/computers.js +2 -1
  17. package/dist/console/assets/{backend-C9ffXUR5.js → backend-DEgVn5lC.js} +1 -1
  18. package/dist/console/assets/index-CG5tELph.js +639 -0
  19. package/dist/console/assets/share-CIeFK2Oe.js +6 -0
  20. package/dist/console/assets/{styles-fjQBFfMv.css → styles-D0SufbzK.css} +1 -1
  21. package/dist/console/index.html +3 -3
  22. package/dist/console/share.html +3 -3
  23. package/dist/cut-pool.d.ts +14 -0
  24. package/dist/cut-pool.js +98 -0
  25. package/dist/cut-worker.d.ts +14 -0
  26. package/dist/cut-worker.js +16 -0
  27. package/dist/decisions.d.ts +4 -0
  28. package/dist/decisions.js +9 -1
  29. package/dist/env-switch.d.ts +3 -0
  30. package/dist/env-switch.js +3 -0
  31. package/dist/harness-table.d.ts +7 -0
  32. package/dist/harness-table.js +6 -3
  33. package/dist/import.d.ts +8 -1
  34. package/dist/import.js +36 -5
  35. package/dist/key-check.js +22 -8
  36. package/dist/learned-nodes.d.ts +2 -1
  37. package/dist/learned-nodes.js +2 -1
  38. package/dist/mcp-gateway.d.ts +24 -0
  39. package/dist/mcp-gateway.js +97 -8
  40. package/dist/mcp-servers-store.d.ts +7 -10
  41. package/dist/mcp-servers-store.js +15 -9
  42. package/dist/native/cli.js +5 -1
  43. package/dist/ollama-provider.d.ts +10 -3
  44. package/dist/ollama-provider.js +17 -7
  45. package/dist/openapi.js +29 -12
  46. package/dist/otel/tracer.d.ts +6 -3
  47. package/dist/otel/tracer.js +24 -6
  48. package/dist/page.d.ts +7 -0
  49. package/dist/page.js +17 -4
  50. package/dist/place.d.ts +25 -9
  51. package/dist/place.js +37 -11
  52. package/dist/print.d.ts +3 -2
  53. package/dist/print.js +8 -6
  54. package/dist/run-launch.js +16 -3
  55. package/dist/run-model-key.d.ts +2 -1
  56. package/dist/run-model-key.js +2 -1
  57. package/dist/run-reads-over-store.d.ts +7 -0
  58. package/dist/run-reads-over-store.js +32 -4
  59. package/dist/runnable.d.ts +6 -3
  60. package/dist/runnable.js +16 -6
  61. package/dist/runner/adapter-loop.js +64 -25
  62. package/dist/runner/adapter-run-spec.d.ts +6 -1
  63. package/dist/runner/adapter-run-spec.js +14 -11
  64. package/dist/runner/adapters/index.d.ts +4 -0
  65. package/dist/runner/adapters/index.js +2 -1
  66. package/dist/runner/claim-secrets.d.ts +3 -1
  67. package/dist/runner/claim-secrets.js +18 -7
  68. package/dist/runner/cli-run-spec.js +12 -8
  69. package/dist/runner/dispatch.js +2 -0
  70. package/dist/runner/harness-loops.d.ts +5 -0
  71. package/dist/runner/harness-loops.js +4 -1
  72. package/dist/runner/live-ticker.js +3 -1
  73. package/dist/runner/loop-contract.d.ts +4 -1
  74. package/dist/runner/mcp-run.d.ts +5 -0
  75. package/dist/runner/mcp-run.js +18 -0
  76. package/dist/runner/meta-tools.js +4 -4
  77. package/dist/runner/metrics.d.ts +4 -2
  78. package/dist/runner/metrics.js +5 -3
  79. package/dist/runner/native-loop.js +2 -2
  80. package/dist/runner/run-child-host.d.ts +10 -6
  81. package/dist/runner/run-child-host.js +44 -29
  82. package/dist/runner/run-child.js +1 -0
  83. package/dist/runner/runner.js +2 -0
  84. package/dist/runner/workflow-calls.d.ts +4 -3
  85. package/dist/runner/workflow-calls.js +41 -12
  86. package/dist/runner/workflow-spec.js +1 -1
  87. package/dist/secret-rules.d.ts +0 -1
  88. package/dist/secret-rules.js +25 -5
  89. package/dist/server.d.ts +10 -1
  90. package/dist/server.js +114 -38
  91. package/dist/share-host.d.ts +111 -0
  92. package/dist/share-host.js +666 -0
  93. package/dist/store-reads/analytics.d.ts +15 -0
  94. package/dist/store-reads/analytics.js +17 -0
  95. package/dist/suggestions.js +32 -3
  96. package/dist/templates.d.ts +3 -1
  97. package/dist/templates.js +7 -3
  98. package/dist/tool-gate.d.ts +25 -9
  99. package/dist/tool-gate.js +58 -19
  100. package/dist/tool-plane.d.ts +1 -0
  101. package/dist/tool-plane.js +6 -2
  102. package/dist/trigger-composio.js +1 -1
  103. package/dist/webhooks.d.ts +3 -0
  104. package/dist/webhooks.js +5 -0
  105. package/dist/workspace/archil-claim.d.ts +7 -3
  106. package/dist/workspace/archil-claim.js +13 -5
  107. package/dist/workspace/archil-mount-credential.d.ts +6 -0
  108. package/dist/workspace/archil-mount-credential.js +11 -0
  109. package/dist/workspace/computer-deps.d.ts +5 -3
  110. package/dist/workspace/computer-deps.js +11 -9
  111. package/dist/workspace/computer-for-claim.d.ts +6 -2
  112. package/dist/workspace/computer-for-claim.js +43 -12
  113. package/dist/workspace/computer-janitor.d.ts +7 -4
  114. package/dist/workspace/computer-janitor.js +7 -4
  115. package/dist/workspace/computer-kept.d.ts +7 -1
  116. package/dist/workspace/computer-kept.js +7 -1
  117. package/dist/workspace/kind-skills/desktop/SKILL.md +12 -3
  118. package/dist/workspace/mount-revoke-left.d.ts +16 -4
  119. package/dist/workspace/mount-revoke-left.js +42 -22
  120. package/dist/workspace/resolve-computer.d.ts +11 -5
  121. package/dist/workspace/resolve-computer.js +22 -13
  122. package/dist/workspace/run-end-computers.js +1 -1
  123. package/dist/workspace/run-tools.d.ts +10 -3
  124. package/dist/workspace/run-tools.js +5 -4
  125. package/dist/wrapped.d.ts +29 -2
  126. package/dist/wrapped.js +20 -3
  127. package/launcher/agentrun-serve +1 -1
  128. package/package.json +12 -12
  129. package/dist/console/assets/index-BnZV3lvW.js +0 -639
  130. package/dist/console/assets/share-B1o5mJ56.js +0 -6
  131. /package/dist/console/assets/{styles-D_znYrHR.js → styles-BGZxYkky.js} +0 -0
@@ -0,0 +1,14 @@
1
+ export type CutJob = {
2
+ readonly id: number;
3
+ readonly text: string;
4
+ readonly values: readonly string[];
5
+ readonly max: number;
6
+ readonly held: readonly (readonly [number, number])[];
7
+ };
8
+ export type CutReply = {
9
+ readonly id: number;
10
+ readonly text: string;
11
+ } | {
12
+ readonly id: number;
13
+ readonly failed: string;
14
+ };
@@ -0,0 +1,16 @@
1
+ // The cut of a run file's text (cutFileText, the step a share's export takes too), in a worker thread: a text and a set
2
+ // of values whose cut runs long block this thread, never the server's, and cut-pool.ts terminates it at the read's
3
+ // deadline. One job at a time, each answered by its id: the cut text, or the name of what it threw (never its message,
4
+ // which may quote the text). The job's `max` is the text's byte length, which cutFileText measures itself.
5
+ import { parentPort } from "node:worker_threads";
6
+ import { cutFileText } from "./run-file-cut.js";
7
+ parentPort?.on("message", (job) => {
8
+ let reply;
9
+ try {
10
+ reply = { id: job.id, text: cutFileText(job.text, job.values, job.held) };
11
+ }
12
+ catch (error) {
13
+ reply = { id: job.id, failed: error instanceof Error ? error.name : "unknown" };
14
+ }
15
+ parentPort.postMessage(reply);
16
+ });
@@ -1,5 +1,9 @@
1
1
  import type { DecisionProvider } from "@parcha/agentrun-dsl";
2
2
  export declare const JEV_KEY_ENV = "TYPESAFE_API_KEY";
3
+ /** TypeSafe's base in `env`: TYPESAFE_BASE_URL, else TypeSafe's own, held to the rule for a URL a key goes to
4
+ * (httpsBase), which throws in words naming the variable and the URL's origin alone. A run's Jev provider and the key's
5
+ * check (key-check.ts) both send TYPESAFE_API_KEY to it, so the key goes where it was checked. */
6
+ export declare const typesafeBase: (env: NodeJS.ProcessEnv) => string;
3
7
  export declare const JEV_OPENROUTER_KEY_ENV = "OPENROUTER_API_KEY";
4
8
  export declare const PARALLEL_KEY_ENV = "PARALLEL_API_KEY";
5
9
  /** The provider a decision node that names none is answered by. */
package/dist/decisions.js CHANGED
@@ -17,12 +17,17 @@
17
17
  // set it since #2244 removed that engine. Only tests set it; its deletion is its own change.
18
18
  import { closeSync, readFileSync } from "node:fs";
19
19
  import { pathToFileURL } from "node:url";
20
+ import { httpsBase } from "@parcha/agentrun-computer";
20
21
  import { openRouterApp } from "@parcha/agentrun-kernel/host";
21
22
  import { JEV_MODEL } from "@parcha/agentrun-web";
22
23
  import { WEB_JEV_OFF_ENV, webJevOff } from "./env-switch.js";
23
24
  import { FAUX_ENV } from "./model.js";
24
25
  import { keyNeeded } from "./key-words.js";
25
26
  export const JEV_KEY_ENV = "TYPESAFE_API_KEY";
27
+ /** TypeSafe's base in `env`: TYPESAFE_BASE_URL, else TypeSafe's own, held to the rule for a URL a key goes to
28
+ * (httpsBase), which throws in words naming the variable and the URL's origin alone. A run's Jev provider and the key's
29
+ * check (key-check.ts) both send TYPESAFE_API_KEY to it, so the key goes where it was checked. */
30
+ export const typesafeBase = (env) => httpsBase(env.TYPESAFE_BASE_URL?.trim() || "https://api.typesafe.ai", "TYPESAFE_BASE_URL");
26
31
  export const JEV_OPENROUTER_KEY_ENV = "OPENROUTER_API_KEY";
27
32
  export const PARALLEL_KEY_ENV = "PARALLEL_API_KEY";
28
33
  /** The provider a decision node that names none is answered by. */
@@ -253,7 +258,10 @@ export async function decisionProvidersIn(env) {
253
258
  * (the runner's store), so both routes build the same providers. */
254
259
  async function decisionProvidersFrom(handed, env) {
255
260
  const providers = {};
256
- const jev = handed[JEV_KEY_ENV] !== undefined ? { apiKey: handed[JEV_KEY_ENV] } : handed[JEV_OPENROUTER_KEY_ENV] !== undefined ? { provider: "openrouter", apiKey: handed[JEV_OPENROUTER_KEY_ENV] } : undefined;
261
+ // TypeSafe's SDK reads TYPESAFE_BASE_URL from the process's environment when given no base, and sends the key there:
262
+ // on TypeSafe's route the base is always given, read from `env` by the rule a saved key's check takes it by
263
+ // (typesafeBase), so the key goes where it was checked.
264
+ const jev = handed[JEV_KEY_ENV] !== undefined ? { apiKey: handed[JEV_KEY_ENV], baseURL: typesafeBase(env) } : handed[JEV_OPENROUTER_KEY_ENV] !== undefined ? { provider: "openrouter", apiKey: handed[JEV_OPENROUTER_KEY_ENV] } : undefined;
257
265
  if (jev) {
258
266
  const [{ jevProvider }, faux] = await Promise.all([import("@parcha/agentrun-jev"), fauxFetch(env, FAUX_JEV_ENV)]);
259
267
  providers.jev = jevProvider({ ...jev, ...(faux ? { fetch: faux } : {}) });
@@ -2,12 +2,15 @@
2
2
  export declare const API_ONLY_ENV = "AGENTRUN_API_ONLY";
3
3
  /** The run-keys setting (run-keys.ts). */
4
4
  export declare const RUN_KEYS_ENV = "AGENTRUN_RUN_KEYS";
5
+ /** The share host (share-host.ts), as --share-host. */
6
+ export declare const SHARE_HOST_ENV = "AGENTRUN_SHARE_HOST";
5
7
  /** Jev off for the web tools (web-run.ts jevWebOf): web_search's results go unranked, whatever key the server holds. */
6
8
  export declare const WEB_JEV_OFF_ENV = "AGENTRUN_WEB_JEV_OFF";
7
9
  /** What each setting means on, and off where off needs saying: the words a refused value answers. */
8
10
  declare const MEANS: {
9
11
  readonly AGENTRUN_API_ONLY: readonly ["serve the run API only", "the whole server"];
10
12
  readonly AGENTRUN_RUN_KEYS: readonly ["each run brings the tool keys this server does not hold"];
13
+ readonly AGENTRUN_SHARE_HOST: readonly ["serve shares under /r/ alone", "the whole server"];
11
14
  readonly AGENTRUN_WEB_JEV_OFF: readonly ["the web tools run without Jev", "Jev ranks web_search's results where the server holds a TypeSafe key"];
12
15
  };
13
16
  /** Whether `env` turns setting `name` on: `1` or `true` on; unset, empty, `0` or `false` off. Any other value is refused
@@ -4,12 +4,15 @@
4
4
  export const API_ONLY_ENV = "AGENTRUN_API_ONLY";
5
5
  /** The run-keys setting (run-keys.ts). */
6
6
  export const RUN_KEYS_ENV = "AGENTRUN_RUN_KEYS";
7
+ /** The share host (share-host.ts), as --share-host. */
8
+ export const SHARE_HOST_ENV = "AGENTRUN_SHARE_HOST";
7
9
  /** Jev off for the web tools (web-run.ts jevWebOf): web_search's results go unranked, whatever key the server holds. */
8
10
  export const WEB_JEV_OFF_ENV = "AGENTRUN_WEB_JEV_OFF";
9
11
  /** What each setting means on, and off where off needs saying: the words a refused value answers. */
10
12
  const MEANS = {
11
13
  [API_ONLY_ENV]: ["serve the run API only", "the whole server"],
12
14
  [RUN_KEYS_ENV]: ["each run brings the tool keys this server does not hold"],
15
+ [SHARE_HOST_ENV]: ["serve shares under /r/ alone", "the whole server"],
13
16
  [WEB_JEV_OFF_ENV]: ["the web tools run without Jev", "Jev ranks web_search's results where the server holds a TypeSafe key"],
14
17
  };
15
18
  /** Whether `env` turns setting `name` on: `1` or `true` on; unset, empty, `0` or `false` off. Any other value is refused
@@ -201,6 +201,13 @@ export interface AcpPlanEntryOptions extends ModuleChecks, Pick<HarnessEntry, "o
201
201
  * built-in Goose starts. A module's acpEntry is the proxy-billed one alone. */
202
202
  export declare function acpEntryOf(options: AcpEntryOptions, host?: AcpEntryHost): HarnessEntry;
203
203
  export declare function acpEntryOf(options: AcpPlanEntryOptions, host?: AcpEntryHost): HarnessEntry;
204
+ /** What Cursor gives acpEntryOf for its plan-billed entry: billed to its owner's Cursor plan on the owner's Cursor API key
205
+ * (`ownKeys`), its model one Cursor lists for that key (`cursor/<model-id>`, `cursor/default` for Cursor's own). Listed
206
+ * only once its owner has installed it (`agentrun harness install cursor`): `missing` is its release, looked up and
207
+ * verified (harness-cursor.ts cursorMissing), and `beforeStart` checks its launcher and every file beside it again
208
+ * before each process starts. Stopped by its owner's turn and tool-call limits (cursorLimitsOf), which its card says.
209
+ * Exported for its tests, which read its recipe on a host with no Cursor release installed. */
210
+ export declare function cursorOptions(facts: AdapterFacts): AcpPlanEntryOptions;
204
211
  /** The secrets the built-in harnesses own (each entry's ownKeys), whether or not its package is beside serve here: a
205
212
  * server without Cursor's adapter still never hands CURSOR_API_KEY to another harness's run (run-secrets.ts keysFor). */
206
213
  export declare const BUILTIN_OWN_KEYS: readonly string[];
@@ -334,8 +334,9 @@ async function gooseLaunch(launch) {
334
334
  * (`ownKeys`), its model one Cursor lists for that key (`cursor/<model-id>`, `cursor/default` for Cursor's own). Listed
335
335
  * only once its owner has installed it (`agentrun harness install cursor`): `missing` is its release, looked up and
336
336
  * verified (harness-cursor.ts cursorMissing), and `beforeStart` checks its launcher and every file beside it again
337
- * before each process starts. Stopped by its owner's turn and tool-call limits (cursorLimitsOf), which its card says. */
338
- function cursorOptions(facts) {
337
+ * before each process starts. Stopped by its owner's turn and tool-call limits (cursorLimitsOf), which its card says.
338
+ * Exported for its tests, which read its recipe on a host with no Cursor release installed. */
339
+ export function cursorOptions(facts) {
339
340
  /** Cursor's launcher, or the HarnessUnavailable that says why it is not here, with the fix (install, pins) it names. */
340
341
  const launcher = async (env) => {
341
342
  const found = await cursorMissing(env);
@@ -351,7 +352,9 @@ function cursorOptions(facts) {
351
352
  card: cursorCardOf,
352
353
  missing: async (env) => void (await launcher(env)),
353
354
  recipe: async (launch) => {
354
- if (!launch.env[CURSOR_KEY])
355
+ // A held run its model kept from running is laid no key (claim-secrets.ts) and never starts Cursor (acpPlanEntryOf),
356
+ // so it is never refused for the key: its claim holds its computer.
357
+ if (!launch.held && !launch.env[CURSOR_KEY])
355
358
  throw new HarnessUnavailable(`${facts.label} runs on your Cursor API key, and ${CURSOR_KEY} is not set where AgentRun starts: set it there (it is handed to Cursor's runs alone), then restart AgentRun.`);
356
359
  const acp = acpPackage();
357
360
  let limits;
package/dist/import.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type StorageWrite } from "@earendil-works/pi-durable";
2
2
  import { type EntryLike } from "./timeline/index.js";
3
- import { type Locator, type Session, type Source } from "@parcha/agentrun-import";
3
+ import { cacheTotals, type Locator, type Session, type Source } from "@parcha/agentrun-import";
4
4
  import { type Found } from "./import-summary.js";
5
5
  import { type Store } from "./store/index.js";
6
6
  /** What `runImport`, `planImport` and the CLI reach of the server's open store: the agents it reads and writes, the runs it
@@ -197,6 +197,13 @@ export declare function transcriptOf(session: Session, cut: (value: unknown) =>
197
197
  batches: StorageWrite[][];
198
198
  entries: EntryLike[];
199
199
  };
200
+ /** A run's cache as its metrics keep it (GET /v2/wrapped sums them): the cache read and the whole prompt (input, cache
201
+ * read and write) of its requests and its subagents', its hit rate's parts; its breaks by cause, their extra cost
202
+ * (USD) and how many are unpriced. Numbers alone. */
203
+ export type RunCache = {
204
+ read: number;
205
+ prompt: number;
206
+ } & Omit<ReturnType<typeof cacheTotals>, "sessions">;
200
207
  /** What an imported agent is told when its project has no CLAUDE.md or AGENTS.md (or the harness's own file): an agentic
201
208
  * revision with no instructions is refused every run (runnable.ts), so an import never writes one. */
202
209
  export declare const importedInstructions: (project: string, source: Source) => string;
package/dist/import.js CHANGED
@@ -14,7 +14,7 @@ import { BACKGROUND_CONTEXT as ctx } from "@earendil-works/chord/context";
14
14
  import { AssistantEntry, ROOT_CONVERSATION_ID, ToolResultEntry, UserEntry } from "@earendil-works/pi-durable";
15
15
  import { REQUEST_COST, runMetricsOf } from "./timeline/index.js";
16
16
  import { defaultData } from "./files.js";
17
- import { childrenOf, HARNESS_OF, inOrder, locatorKey, locatorOf, locatorParent, locatorSize, mirroredIn, mostEffortOf, ownRequests, priceRequests, READERS, readSession, SOURCE_NAMES, SOURCES, sessionKey, sessionLocators, withSubagentCosts } from "@parcha/agentrun-import";
17
+ import { CACHE_SOURCES, cacheTotals, childrenOf, conversationOf, fileCache, HARNESS_OF, inOrder, locatorKey, locatorOf, locatorParent, locatorSize, mirroredIn, mostEffortOf, ownRequests, priceRequests, READERS, readSession, SOURCE_NAMES, SOURCES, sessionKey, sessionLocators, sessionBreaks, withSubagentCosts } from "@parcha/agentrun-import";
18
18
  import { hoursOf, summaryLines } from "./import-summary.js";
19
19
  import { stopOnce } from "./stop-signals.js";
20
20
  import { catalogPrices, providerModels } from "./model.js";
@@ -942,7 +942,7 @@ async function holdBack(children, parts, childIds, now) {
942
942
  * files (Claude Code's), and those naming its thread (Codex's, whichever of its files they ran under). One gone or
943
943
  * unreadable is passed over. All of them are held at once, so their sizes are taken from `budget` (what the run's own
944
944
  * files left of MAX_RUN_BYTES) before each is read: RunTooLarge once it is spent, as one file over the cap alone spends it. */
945
- async function readChildren(plan, session, parts, seen, budget) {
945
+ async function readChildren(plan, session, parts, seen, budget, chain = false) {
946
946
  const out = [];
947
947
  const visited = new Set();
948
948
  const under = async (owner) => {
@@ -958,7 +958,7 @@ async function readChildren(plan, session, parts, seen, budget) {
958
958
  // No subagent is passed over for its size: the run would be kept without its usage.
959
959
  if (!fits(budget, stats.bytes))
960
960
  throw new RunTooLarge();
961
- const child = await readSession(locator, session.source, { seen, lookups: lookupsOf(plan) }).catch(() => undefined);
961
+ const child = await readSession(locator, session.source, { seen, lookups: lookupsOf(plan), ...(chain ? { chain } : {}) }).catch(() => undefined);
962
962
  if (!child)
963
963
  continue;
964
964
  out.push(child);
@@ -1260,6 +1260,34 @@ export function transcriptOf(session, cut, children = []) {
1260
1260
  /** What a run's requests cost at the catalog's list prices, each at its own provider's entry for its model: undefined when
1261
1261
  * one request's tokens are unknown or its provider does not list its model (the request was served at a price no one
1262
1262
  * lists here). A provider's $0 entry is $0. A request of no tokens costs nothing at any price. */
1263
+ /** Whether a source's runs are analyzed for their cache as they are imported: the sources that write a chain
1264
+ * (CACHE_SOURCES), read with it. */
1265
+ const cached = (source) => CACHE_SOURCES.includes(source);
1266
+ /** `parts` (every file of a run read, in order, each with its chain) and its subagents analyzed as cacheHome analyzes a
1267
+ * session: each file alone, then joined into one conversation (sessionBreaks), at the catalog's prices. */
1268
+ async function runCacheOf(parts, subagents, catalog) {
1269
+ const options = { catalog };
1270
+ let read = 0;
1271
+ let prompt = 0;
1272
+ for (const turn of [...parts, ...subagents].flatMap((session) => session.turns)) {
1273
+ if (turn.role !== "assistant" || !turn.usage)
1274
+ continue;
1275
+ read += turn.usage.cacheRead;
1276
+ prompt += turn.usage.input + turn.usage.cacheRead + turn.usage.cacheWrite;
1277
+ }
1278
+ const fileOf = async (session) => ({ file: await fileCache(session, options), requests: session.turns.filter((turn) => turn.role === "assistant").length });
1279
+ const files = [];
1280
+ for (const part of parts)
1281
+ files.push(await fileOf(part));
1282
+ // Each subagent a conversation of its own, in the order read: a thread that goes on in another rollout is one.
1283
+ const conversations = new Map();
1284
+ for (const child of subagents) {
1285
+ const key = conversationOf(locatorOf(child), child);
1286
+ (conversations.get(key) ?? conversations.set(key, []).get(key)).push(await fileOf(child));
1287
+ }
1288
+ const { sessions: _sessions, ...totals } = cacheTotals([{ breaks: await sessionBreaks(files, [...conversations.values()], options) }]);
1289
+ return { read, prompt, ...totals };
1290
+ }
1263
1291
  async function estimateOf(entries, catalog) {
1264
1292
  // Unknown when one answer priced here has unknown tokens (a failed one's counts are its own, as runMetricsOf reads them).
1265
1293
  if (runMetricsOf(entries.filter((entry) => entry.kind === "pi.assistant")).unmetered > 0)
@@ -1400,7 +1428,7 @@ export async function runImport(store, plan, options) {
1400
1428
  over = true;
1401
1429
  break;
1402
1430
  }
1403
- const part = stats ? await readSession(locatorOf(entry), listed.source, { seen: seen(listed.source), lookups: lookupsOf(plan) }).catch((error) => void report.skipped.push(unread(file, error))) : void report.skipped.push({ what: file, why: "gone since it was listed", kind: "vanished" });
1431
+ const part = stats ? await readSession(locatorOf(entry), listed.source, { seen: seen(listed.source), lookups: lookupsOf(plan), ...(cached(listed.source) ? { chain: true } : {}) }).catch((error) => void report.skipped.push(unread(file, error))) : void report.skipped.push({ what: file, why: "gone since it was listed", kind: "vanished" });
1404
1432
  if (!part || !stats)
1405
1433
  continue;
1406
1434
  searched.push(part);
@@ -1433,7 +1461,7 @@ export async function runImport(store, plan, options) {
1433
1461
  // holding a key counts among the keys removed.
1434
1462
  const keptAs = text(session.id) === session.id ? session.id : redactedId(session.id);
1435
1463
  session.id = keptAs;
1436
- const subagents = await readChildren(plan, session, searched, seen(listed.source), budget).catch((error) => {
1464
+ const subagents = await readChildren(plan, session, searched, seen(listed.source), budget, cached(listed.source)).catch((error) => {
1437
1465
  if (!(error instanceof RunTooLarge))
1438
1466
  throw error;
1439
1467
  report.skipped.push(tooLarge(listed));
@@ -1455,6 +1483,9 @@ export async function runImport(store, plan, options) {
1455
1483
  const estimate = costUsd === undefined ? await estimateOf([...entries, ...subagents.flatMap(entriesOf)], catalog) : undefined;
1456
1484
  if (estimate !== undefined)
1457
1485
  Object.assign(metrics, { costUsdEst: estimate, costBasis: "catalog" });
1486
+ // Its cache, for GET /v2/wrapped: numbers alone, from every file of it read (copies too, as cacheHome joins them).
1487
+ if (cached(session.source))
1488
+ Object.assign(metrics, { cache: await runCacheOf(searched, subagents, await catalog()) });
1458
1489
  const answer = session.turns.findLast((t) => t.role === "assistant" && t.text)?.text;
1459
1490
  // Cut, then put on one line and clipped: a key the clip cut short, or a passphrase whose spaces were changed, would
1460
1491
  // match no cut.
package/dist/key-check.js CHANGED
@@ -2,12 +2,15 @@
2
2
  // costs nothing, given CHECK_MS to answer. A 401 is the provider refusing the key, and the save is refused with nothing
3
3
  // kept; a 2xx is the key accepted. A 403 is the provider knowing the key and not answering this call: a key scoped away
4
4
  // from it (an OpenAI restricted key without the Models permission) may still do its tools' work, so it is never refused.
5
- // That, no such call for the provider, no answer in time, the network, a redirect (never followed: Node's fetch carries
5
+ // That, no such call for the provider, a base URL the key may not go to (never sent one), no answer in time, the network, a redirect (never followed: Node's fetch carries
6
6
  // a key's own header, x-api-key or x-bb-api-key, to wherever one points), or any other status keeps the key as not
7
7
  // checked, saying why: an answer that does not say whether a key works never stops a save.
8
8
  // Never a paid request: each call below cites the provider's pages that show it is not billed. No outcome holds the
9
9
  // key: the provider's first sentence is quoted only when it holds no KEY_PIECE characters of the key in a row.
10
+ import { httpsBase } from "@parcha/agentrun-computer";
11
+ import { typesafeBase } from "./decisions.js";
10
12
  import { MONID_API } from "./monid.js";
13
+ import { ANTHROPIC_ORIGIN, gatewayBase } from "./provider.js";
11
14
  import { isObject } from "./validate.js";
12
15
  /** How long a provider has to answer a check. */
13
16
  export const CHECK_MS = 5_000;
@@ -15,7 +18,9 @@ export const CHECK_MS = 5_000;
15
18
  const KEY_PIECE = 6;
16
19
  /** The most characters of a provider's words quoted. */
17
20
  const QUOTE = 200;
18
- const base = (set, fallback) => (set?.trim() || fallback).replace(/\/+$/, "");
21
+ /** The base a vendor's calls go to: `set`, the server's variable `name`, else the vendor's own, held to the rule for a URL a
22
+ * key goes to (httpsBase), which throws in words naming the variable and the URL's origin alone. */
23
+ const base = (set, fallback, name) => httpsBase(set?.trim() || fallback, name);
19
24
  /** Each provider's check, by key id (tool-keys.ts' TOOL_KEYS, and a model provider's key where the server keeps one),
20
25
  * made with the key and the server's environment, at the base this server sends that provider's calls to. */
21
26
  export const KEY_CHECKS = {
@@ -27,17 +32,18 @@ export const KEY_CHECKS = {
27
32
  parallel: (key) => ({ url: "https://api.parallel.ai/v1/monitors?limit=1", headers: { "x-api-key": key } }),
28
33
  // A list of the key's projects: Browserbase bills a session's browser time and proxy bandwidth, and this opens no
29
34
  // session (https://docs.browserbase.com/reference/api/list-projects, https://docs.browserbase.com/account/billing/plans).
30
- browserbase: (key, env) => ({ url: `${base(env.BROWSERBASE_BASE_URL, "https://api.browserbase.com")}/v1/projects`, headers: { "x-bb-api-key": key } }),
35
+ browserbase: (key, env) => ({ url: `${base(env.BROWSERBASE_BASE_URL, "https://api.browserbase.com", "BROWSERBASE_BASE_URL")}/v1/projects`, headers: { "x-bb-api-key": key } }),
31
36
  // A list of the key's browser sessions, one at most: Kernel bills a browser's running time, and this starts none
32
37
  // (https://www.kernel.sh/docs/api-reference/browsers/list-browser-sessions, https://www.kernel.sh/docs/info/pricing).
33
- kernel: (key, env) => ({ url: `${base(env.KERNEL_BASE_URL, "https://api.onkernel.com")}/browsers?limit=1`, headers: { authorization: `Bearer ${key}` } }),
38
+ kernel: (key, env) => ({ url: `${base(env.KERNEL_BASE_URL, "https://api.onkernel.com", "KERNEL_BASE_URL")}/browsers?limit=1`, headers: { authorization: `Bearer ${key}` } }),
34
39
  // A list of the account's models: TypeSafe prices a System One request's input tokens
35
40
  // (https://docs.typesafe.ai/api/list-models, https://docs.typesafe.ai/models).
36
- typesafe: (key, env) => ({ url: `${base(env.TYPESAFE_BASE_URL, "https://api.typesafe.ai")}/v1/models`, headers: { authorization: `Bearer ${key}` } }),
41
+ typesafe: (key, env) => ({ url: `${typesafeBase(env)}/v1/models`, headers: { authorization: `Bearer ${key}` } }),
37
42
  // A model provider's key: its list of models, or OpenRouter's record of the key; each prices tokens, and these use none
38
43
  // (https://platform.claude.com/docs/en/api/models/list, https://openrouter.ai/docs/api-reference/limits). OpenAI's is
39
- // in NOT_CHECKED.
40
- anthropic: (key, env) => ({ url: `${base(env.ANTHROPIC_BASE_URL, "https://api.anthropic.com")}/v1/models?limit=1`, headers: { "x-api-key": key, "anthropic-version": "2023-06-01" } }),
44
+ // in NOT_CHECKED. ANTHROPIC_BASE_URL is the gateway the model path sends Anthropic's key to, under that path's rule
45
+ // (gatewayBase: plain http to this machine alone, one trailing /v1 off), so the check goes where the runs go.
46
+ anthropic: (key, env) => ({ url: `${env.ANTHROPIC_BASE_URL ? gatewayBase("ANTHROPIC_BASE_URL", env.ANTHROPIC_BASE_URL) : ANTHROPIC_ORIGIN}/v1/models?limit=1`, headers: { "x-api-key": key, "anthropic-version": "2023-06-01" } }),
41
47
  openrouter: (key) => ({ url: "https://openrouter.ai/api/v1/key", headers: { authorization: `Bearer ${key}` } }),
42
48
  // Particle bills inference tokens; its authenticated model listing performs no generation
43
49
  // (https://docs.particle.ai/models, https://docs.particle.ai/pricing).
@@ -82,7 +88,15 @@ export async function checkKey(row, key, env, fetcher, ms = CHECK_MS, stop, name
82
88
  return notChecked(`${row.label} has no call that costs nothing to check a key with`);
83
89
  if (!fetcher)
84
90
  return notChecked(`This server runs on faux providers and has no fake ${row.label} to check the key with`);
85
- const { url, ...init } = check(key, env);
91
+ let call;
92
+ try {
93
+ call = check(key, env);
94
+ }
95
+ catch (error) {
96
+ // A base URL the key may not go to, refused by the variable's name in words that give its origin at most: nothing is sent.
97
+ return notChecked(`${row.label} was not checked: ${error.message}`);
98
+ }
99
+ const { url, ...init } = call;
86
100
  let res;
87
101
  try {
88
102
  res = await fetcher(url, { ...init, redirect: "manual", signal: stop ? AbortSignal.any([AbortSignal.timeout(ms), stop]) : AbortSignal.timeout(ms) });
@@ -26,7 +26,8 @@ export declare const failedRecord: (call: string, workflow: string, digest: stri
26
26
  /** The record of a learned_workflow call refused before the tool saw it (`refused`: it ran nothing), which the loop keeps
27
27
  * where the tool never ran: the platform's call its gate refused (runner/adapter-loop.ts serveFirst), and an agent's its
28
28
  * gate refused with no attempt of it let go since its last refusal (adapter-loop.ts learnedEntry). Either reads
29
- * `failed` once anything was booked under its call id (runner/workflow-calls.ts workflowCallsOf). */
29
+ * `failed` once anything was booked under its call id, or while an attempt of it its gate let go was closed by no
30
+ * refusal (runner/workflow-calls.ts workflowCallsOf). */
30
31
  export declare const refusedRecord: (call: string, workflow: string, digest: string, caller: "platform" | "agent") => {
31
32
  refused: true;
32
33
  call: string;
@@ -14,7 +14,8 @@ export const failedRecord = (call, workflow, digest, caller) => ({ call, workflo
14
14
  /** The record of a learned_workflow call refused before the tool saw it (`refused`: it ran nothing), which the loop keeps
15
15
  * where the tool never ran: the platform's call its gate refused (runner/adapter-loop.ts serveFirst), and an agent's its
16
16
  * gate refused with no attempt of it let go since its last refusal (adapter-loop.ts learnedEntry). Either reads
17
- * `failed` once anything was booked under its call id (runner/workflow-calls.ts workflowCallsOf). */
17
+ * `failed` once anything was booked under its call id, or while an attempt of it its gate let go was closed by no
18
+ * refusal (runner/workflow-calls.ts workflowCallsOf). */
18
19
  export const refusedRecord = (call, workflow, digest, caller) => ({ ...failedRecord(call, workflow, digest, caller), refused: true });
19
20
  /** The mark an agent's learned_workflow call on a CLI gets in the run's journal when its gate lets it go, before it runs:
20
21
  * `{ call }`, its call's id (adapter-loop.ts sessionGate). An attempt a crash cuts before its record is kept leaves
@@ -134,9 +134,33 @@ export interface McpGatewayOptions {
134
134
  * summary. UNREADABLE for a tool: a stored setting that does not read, and every call of the tool is refused unsent.
135
135
  * None, or undefined for a tool: its answers are the model's, as always. */
136
136
  filed?: (server: string, tool: string) => FileSetting | typeof UNREADABLE | undefined;
137
+ /** The run's redactor (the runner's one, holding every key the run opened: its own model and tool keys, the other
138
+ * servers' credentials), after each call's own scrub on every text the gateway answers or files: the model's answer,
139
+ * a filed answer, a long answer's filed rest, a server's results and an error's words; its values (heldValues) read
140
+ * in a binary payload filed whole (filedJson). Every claim's MCP gives it (mcp-run.ts); a gateway given none does not
141
+ * start. */
142
+ redact: ((text: string) => string) & {
143
+ readonly heldValues?: () => readonly string[];
144
+ };
137
145
  }
138
146
  /** A run's journal commit. */
139
147
  export type McpCommit = <T>(change: (tx: unknown) => Promise<T>) => Promise<T>;
148
+ /** A binary payload of an answer filed whole (an image's or an audio's data, a resource's blob), as it is filed: scrubbed
149
+ * of the call's own credentials (`own`) and kept whole, unless it holds one of `values` (what the run's redactor holds),
150
+ * as written, in any form the matcher finds, or in the text of the bytes it decodes to, or that text holds a secret's shape (a JWT,
151
+ * a private key: SECRET_SHAPES, which the run's redactor cuts in text). Then it is "[redacted]" whole: a cut inside it
152
+ * would leave no payload a reader could open either. Its base64 text is not read for a shape: the MCP client takes no
153
+ * payload that is not base64, and in base64 a shape stands only by chance (a Google API key's run, about once in 50 MiB)
154
+ * or as a server's deliberate encoding, which no redactor stops. `values` undefined (a redactor that names none): the
155
+ * payload is cut as the rest is, by `clean`. */
156
+ export declare function binaryKept(payload: string, clean: (text: string) => string, own: (text: string) => string, values: readonly string[] | undefined): string;
157
+ /** The text in a payload's bytes, one run to a line. A run is the bytes between two that are neither text nor what the
158
+ * matcher reads past in a Latin-1 decode: printable ASCII and whitespace (a no-break space among it), and the bytes it
159
+ * reads as nothing (a NUL, a control character, a soft hyphen, a spacing accent: IGNORED_BYTES, which go). A held value
160
+ * cut into short pieces by one of them, or written as UTF-16 or UTF-32 in either byte order, still reads whole. A run is
161
+ * kept when MIN_SECRET or more printable characters are left. Both steps are linear in the bytes. Only these runs are
162
+ * read: a value or a shape the bytes carry is text, and every view read over binary bytes cost about 25 s a MiB. */
163
+ export declare function textRuns(bytes: string): string;
140
164
  /** The gateway: a session's servers, and their calls. `credentials` is read at every call and every request, never
141
165
  * copied: a change the claim step makes after (a token refreshed behind the claim, a server removed) reaches it, even
142
166
  * through a client already connected. */
@@ -30,6 +30,7 @@ import { saveOnce } from "./save-once.js";
30
30
  import { paidLedger, paidStep } from "./paid-calls.js";
31
31
  import { metaToolOf } from "./mcp-meta.js";
32
32
  import { SIGN_IN_AGAIN } from "./mcp-oauth.js";
33
+ import { MIN_SECRET, secretShapes, valueLeft } from "./learn/secrets.js";
33
34
  import { capped, mcpClient, scrub } from "./mcp-wire.js";
34
35
  import { resourceResult, resourceToolOperation, resourceToolProblem } from "./mcp-resources.js";
35
36
  import { mcpNameOf, mcpToolName } from "./tool-names.js";
@@ -190,7 +191,50 @@ function unreachable(error) {
190
191
  const said = (text, isError = false) => ({ content: [{ type: "text", text }], ...(isError ? { isError: true } : {}) });
191
192
  /** The refusal of a call of a tool whose stored file setting does not read (filed-tool.ts UNREADABLE). */
192
193
  const unreadableFile = (server, tool) => `${mcpToolName(server, tool)} can't be called: its file setting in the agent's tool settings does not read, so no call is let through until the owner sets it again or removes it (Settings → Tools). Nothing was sent.`;
194
+ /** A binary payload of an answer filed whole (an image's or an audio's data, a resource's blob), as it is filed: scrubbed
195
+ * of the call's own credentials (`own`) and kept whole, unless it holds one of `values` (what the run's redactor holds),
196
+ * as written, in any form the matcher finds, or in the text of the bytes it decodes to, or that text holds a secret's shape (a JWT,
197
+ * a private key: SECRET_SHAPES, which the run's redactor cuts in text). Then it is "[redacted]" whole: a cut inside it
198
+ * would leave no payload a reader could open either. Its base64 text is not read for a shape: the MCP client takes no
199
+ * payload that is not base64, and in base64 a shape stands only by chance (a Google API key's run, about once in 50 MiB)
200
+ * or as a server's deliberate encoding, which no redactor stops. `values` undefined (a redactor that names none): the
201
+ * payload is cut as the rest is, by `clean`. */
202
+ export function binaryKept(payload, clean, own, values) {
203
+ if (!values)
204
+ return clean(payload);
205
+ const scrubbed = own(payload);
206
+ const text = textRuns(Buffer.from(scrubbed, "base64").toString("latin1"));
207
+ if (secretShapes(text).length > 0)
208
+ return "[redacted]";
209
+ if (!values.length)
210
+ return scrubbed;
211
+ return valueLeft(scrubbed, values, []) || valueLeft(text, values, []) ? "[redacted]" : scrubbed;
212
+ }
213
+ /** The text in a payload's bytes, one run to a line. A run is the bytes between two that are neither text nor what the
214
+ * matcher reads past in a Latin-1 decode: printable ASCII and whitespace (a no-break space among it), and the bytes it
215
+ * reads as nothing (a NUL, a control character, a soft hyphen, a spacing accent: IGNORED_BYTES, which go). A held value
216
+ * cut into short pieces by one of them, or written as UTF-16 or UTF-32 in either byte order, still reads whole. A run is
217
+ * kept when MIN_SECRET or more printable characters are left. Both steps are linear in the bytes. Only these runs are
218
+ * read: a value or a shape the bytes carry is text, and every view read over binary bytes cost about 25 s a MiB. */
219
+ export function textRuns(bytes) {
220
+ const runs = [];
221
+ for (const [found] of bytes.matchAll(RUN)) {
222
+ const text = found.replace(IGNORED_BYTES, "");
223
+ let printable = 0;
224
+ for (let at = 0; at < text.length && printable < MIN_SECRET; at++)
225
+ if (text.charCodeAt(at) > 0x20 && text.charCodeAt(at) < 0x7f)
226
+ printable++;
227
+ if (printable >= MIN_SECRET)
228
+ runs.push(text);
229
+ }
230
+ return runs.join("\n");
231
+ }
232
+ const RUN = /[\x00-\xa0\xa8\xad\xaf\xb4\xb8]+/g;
233
+ const IGNORED_BYTES = /[\x00-\x08\x0e-\x1f\x7f-\x9f\xa8\xad\xaf\xb4\xb8]+/g;
193
234
  export function mcpGateway(options) {
235
+ if (typeof options.redact !== "function")
236
+ throw new TypeError("An MCP gateway was given no redactor (the run's), so it does not start: an answer would reach the model and the run's files cut of its own server's credentials alone");
237
+ const runCut = options.redact;
194
238
  /** Each server's client, with the account query it was connected with (`query`, JSON): a message that binds the run to
195
239
  * another account connects again, so no session made as one account carries another's calls. */
196
240
  const clients = new Map();
@@ -300,13 +344,54 @@ export function mcpGateway(options) {
300
344
  text = clean(JSON.stringify(result.structuredContent));
301
345
  return { text, other: blocks.length - texts.length };
302
346
  };
347
+ /** `result` as the JSON filed for an answer with blocks that are not text, every text in it cut by `clean`. An image's
348
+ * or an audio's data and a resource's blob are base64, one run with no whitespace, which the run's redactor would show
349
+ * as "[redacted]" past a piece (key-refusal.ts redactedAnswer), and a screenshot is far longer than one: each is
350
+ * filed as binaryKept keeps it, at its own block. */
351
+ const filedJson = (result, clean, own, values) => {
352
+ const blocks = Array.isArray(result.content) ? result.content : [];
353
+ const payloads = [];
354
+ const bare = blocks.map((block, at) => {
355
+ if (!block || typeof block !== "object")
356
+ return block;
357
+ const one = block;
358
+ if ((one.type === "image" || one.type === "audio") && typeof one.data === "string") {
359
+ payloads.push({ at, key: "data", text: one.data });
360
+ return { ...one, data: "" };
361
+ }
362
+ const resource = one.type === "resource" && one.resource && typeof one.resource === "object" ? one.resource : undefined;
363
+ if (resource && typeof resource.blob === "string") {
364
+ payloads.push({ at, key: "blob", text: resource.blob });
365
+ return { ...one, resource: { ...resource, blob: "" } };
366
+ }
367
+ return block;
368
+ });
369
+ const filed = clean(JSON.stringify(payloads.length ? { ...result, content: bare } : result));
370
+ if (!payloads.length)
371
+ return filed;
372
+ let doc;
373
+ try {
374
+ doc = JSON.parse(filed);
375
+ }
376
+ catch {
377
+ return filed;
378
+ }
379
+ const content = Array.isArray(doc.content) ? doc.content : [];
380
+ for (const { at, key, text } of payloads) {
381
+ const block = content[at];
382
+ const into = key === "data" ? block : block?.resource;
383
+ if (into && typeof into === "object" && into[key] === "")
384
+ into[key] = binaryKept(text, clean, own, values);
385
+ }
386
+ return JSON.stringify(doc);
387
+ };
303
388
  /** The model's text of `result`: its text blocks and its embedded text resources (GitHub's get_file_contents answers a
304
389
  * file as one) joined, its structured content when it has neither. Past MCP_CLIP, its start and the rest filed in the
305
390
  * run's evidence/mcp/<server>/ as readable lines, through its Workspace (never through a link), the text saying where
306
391
  * and the read offset that goes on (filed-answer.ts), so read pages through it with no shell. With blocks that are
307
392
  * neither (an image, a blob), the whole result is filed there as JSON, and the text says where. `clean` scrubs every
308
393
  * credential the call's server took or sent. */
309
- const textOf = async (server, tool, result, clean) => {
394
+ const textOf = async (server, tool, result, clean, filedAs) => {
310
395
  const { text, other } = answerOf(result, clean);
311
396
  if (text.length <= MCP_CLIP && other === 0)
312
397
  return text;
@@ -315,7 +400,7 @@ export function mcpGateway(options) {
315
400
  return filedAnswer(async () => workspaceAt(await options.work()), `evidence/mcp/${server}`, name, text, MCP_CLIP);
316
401
  const head = text.length > MCP_CLIP ? `${text.slice(0, MCP_CLIP)}\n[cut at ${MCP_CLIP} of ${text.length} characters; ` : `${text}\n[${other} block${other > 1 ? "s" : ""} that ${other > 1 ? "are" : "is"} not text; `;
317
402
  try {
318
- await workspaceAt(await options.work()).write(`evidence/mcp/${server}/${name}.json`, clean(JSON.stringify(result)));
403
+ await workspaceAt(await options.work()).write(`evidence/mcp/${server}/${name}.json`, filedAs(result));
319
404
  }
320
405
  catch (error) {
321
406
  // The Workspace's code and the port's line for it, never the error's message, which names paths.
@@ -329,9 +414,9 @@ export function mcpGateway(options) {
329
414
  * error, so the model can still react through a shown field. An answer with blocks that are not text is filed as the
330
415
  * whole result's JSON. A write that fails (or a Workspace that cannot open) answers an error in the Workspace's words,
331
416
  * none of the answer shown. */
332
- const filedOf = async (setting, tool, result, clean) => {
417
+ const filedOf = async (setting, tool, result, clean, filedAs) => {
333
418
  const { text: answer, other } = answerOf(result, clean);
334
- const text = other === 0 ? answer : clean(JSON.stringify(result));
419
+ const text = other === 0 ? answer : filedAs(result);
335
420
  const path = `${setting.folder}/${tool.replace(/[^A-Za-z0-9_.-]/g, "_")}-${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID().slice(0, 8)}.json`;
336
421
  try {
337
422
  await workspaceAt(await options.work()).write(path, text);
@@ -387,8 +472,12 @@ export function mcpGateway(options) {
387
472
  // Read at each use: a token refreshed while the call is out, and sent, is scrubbed with the one it took.
388
473
  const held = callSet(server);
389
474
  const scrubbed = scrubberOf(server, hold(server, headers), held.values);
390
- // Every text the model reads of the call (its answer, a filed one, an error), its keys read as the agent's own.
391
- const clean = back ? (text) => back(scrubbed(text)) : scrubbed;
475
+ // Every text the model reads of the call or the run's files keep of it (its answer, a filed one, an error), its keys
476
+ // read as the agent's own, then cut by the run's redactor: a value the run holds that the server echoed reaches
477
+ // neither. The one place each of those texts passes.
478
+ const own = back ? (text) => back(scrubbed(text)) : scrubbed;
479
+ const clean = (text) => runCut(own(text));
480
+ const filedAs = (whole) => filedJson(whole, clean, own, runCut.heldValues?.());
392
481
  hold(server, queryOf(server));
393
482
  try {
394
483
  const upstream = await until(connect(server, url, headers), boundedSignal);
@@ -414,8 +503,8 @@ export function mcpGateway(options) {
414
503
  if (filing === UNREADABLE)
415
504
  return said(unreadableFile(server, tool.name), true);
416
505
  if (filing)
417
- return await filedOf(filing, tool.name, result, clean);
418
- return said(await textOf(server, tool.name, result, clean), result.isError === true);
506
+ return await filedOf(filing, tool.name, result, clean, filedAs);
507
+ return said(await textOf(server, tool.name, result, clean, filedAs), result.isError === true);
419
508
  }
420
509
  catch (error) {
421
510
  if (signal.aborted)
@@ -1,5 +1,6 @@
1
1
  import { type InputIssue } from "./errors.js";
2
2
  import { type Listed, type McpPrices, type McpTool } from "./mcp-probe.js";
3
+ import type { ComposioCredentialOf } from "./composio-triggers.js";
3
4
  import { type SecretMeta } from "./secret-writes.js";
4
5
  import { type ClientKind, type OAuthNetwork } from "./mcp-oauth.js";
5
6
  import { type Cleanup, COMPOSIO_KEY_ENV, type ComposioMade } from "./composio-made.js";
@@ -439,17 +440,13 @@ export declare class McpServersOverStore {
439
440
  /** The saved OAuth token set of `row` (the row read and checked, as opened), for a sign-in again that reuses the kept
440
441
  * client. */
441
442
  private openedSet;
442
- /** A saved Composio preset server's key (its sealed x-api-key), the Composio user its address names (`user_id`, the
443
- * preset's default when none), its toolkit and the auth config its save recorded (composio-made.ts; none for a server
444
- * saved before that was recorded): what its Composio triggers are made with (composio-triggers.ts). Refused
445
- * when `name` is no such server: on the trigger's `source.server` at its create (`field`), as a 404 on the server's own
443
+ /** A saved Composio preset server's key (its sealed x-api-key), its toolkit and the auth config its save recorded
444
+ * (composio-made.ts; none for a server saved before that was recorded), and for a trigger's own steps (`field`) the
445
+ * Composio user its address names (`user_id`, the preset's default when none): what its Composio triggers are made with
446
+ * (composio-triggers.ts). The server's own routes (`route`) are answered no user: none of them sends one. Refused when
447
+ * `name` is no such server: on the trigger's `source.server` at its create (`field`), as a 404 on the server's own
446
448
  * routes (`route`). The key goes only to Composio. */
447
- composioOf(name: string, refusal: "field" | "route"): Promise<{
448
- key: string;
449
- user: string;
450
- toolkit: string;
451
- auth_config?: string;
452
- }>;
449
+ composioOf<R extends "field" | "route">(name: string, refusal: R): Promise<ComposioCredentialOf<R>>;
453
450
  /** What the saved server `row` is, for a template's apply to match (mcp-sources.ts sourceOf): github on the GitHub App's
454
451
  * tokens, else its record, else url with none. */
455
452
  sourceOf(row: RecordedRow & {