@parcha/agentrun-serve 0.1.0-beta.60 → 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 (179) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/README.md +139 -22
  3. package/dist/acp-package.d.ts +4 -0
  4. package/dist/api-only.d.ts +23 -1
  5. package/dist/api-only.js +43 -4
  6. package/dist/archil-settings.d.ts +9 -0
  7. package/dist/archil-settings.js +8 -1
  8. package/dist/bash-read-only.d.ts +3 -0
  9. package/dist/bash-read-only.js +6 -3
  10. package/dist/browser-person.d.ts +1 -1
  11. package/dist/browser-person.js +1 -1
  12. package/dist/calendar/tools.js +1 -1
  13. package/dist/chatgpt-plan.d.ts +26 -8
  14. package/dist/chatgpt-plan.js +89 -21
  15. package/dist/claude-login.d.ts +12 -5
  16. package/dist/claude-login.js +28 -3
  17. package/dist/cli.js +61 -18
  18. package/dist/composio-triggers.d.ts +9 -3
  19. package/dist/computers.d.ts +3 -0
  20. package/dist/computers.js +2 -1
  21. package/dist/console/assets/{backend-QnwGVBeU.js → backend-DEgVn5lC.js} +1 -1
  22. package/dist/console/assets/index-CG5tELph.js +639 -0
  23. package/dist/console/assets/share-CIeFK2Oe.js +6 -0
  24. package/dist/console/assets/{styles-CcceGcu2.js → styles-BGZxYkky.js} +2 -2
  25. package/dist/console/assets/{styles-fjQBFfMv.css → styles-D0SufbzK.css} +1 -1
  26. package/dist/console/index.html +3 -3
  27. package/dist/console/share.html +3 -3
  28. package/dist/cut-pool.d.ts +14 -0
  29. package/dist/cut-pool.js +98 -0
  30. package/dist/cut-worker.d.ts +14 -0
  31. package/dist/cut-worker.js +16 -0
  32. package/dist/decisions.d.ts +4 -0
  33. package/dist/decisions.js +9 -1
  34. package/dist/env-switch.d.ts +3 -0
  35. package/dist/env-switch.js +3 -0
  36. package/dist/errors.d.ts +1 -0
  37. package/dist/errors.js +2 -0
  38. package/dist/harness-check.js +2 -1
  39. package/dist/harness-recipe.d.ts +13 -2
  40. package/dist/harness-recipe.js +30 -7
  41. package/dist/harness-sign-in.js +2 -1
  42. package/dist/harness-table.d.ts +12 -3
  43. package/dist/harness-table.js +13 -8
  44. package/dist/import.d.ts +8 -1
  45. package/dist/import.js +36 -5
  46. package/dist/key-check.js +22 -8
  47. package/dist/key-refusal.js +6 -4
  48. package/dist/learn/secrets.d.ts +2 -1
  49. package/dist/learn/secrets.js +2 -2
  50. package/dist/learned-nodes.d.ts +37 -0
  51. package/dist/learned-nodes.js +24 -0
  52. package/dist/local-model.d.ts +144 -0
  53. package/dist/local-model.js +214 -0
  54. package/dist/mcp-gateway.d.ts +24 -0
  55. package/dist/mcp-gateway.js +97 -8
  56. package/dist/mcp-probe.d.ts +7 -0
  57. package/dist/mcp-probe.js +7 -0
  58. package/dist/mcp-servers-store.d.ts +7 -10
  59. package/dist/mcp-servers-store.js +15 -9
  60. package/dist/native/cli.js +5 -1
  61. package/dist/ollama-provider.d.ts +42 -0
  62. package/dist/ollama-provider.js +118 -2
  63. package/dist/openapi.js +85 -16
  64. package/dist/otel/tracer.d.ts +6 -3
  65. package/dist/otel/tracer.js +24 -6
  66. package/dist/page.d.ts +7 -0
  67. package/dist/page.js +17 -4
  68. package/dist/place.d.ts +28 -11
  69. package/dist/place.js +43 -14
  70. package/dist/print.d.ts +3 -2
  71. package/dist/print.js +8 -6
  72. package/dist/redact/match.d.ts +17 -4
  73. package/dist/redact/match.js +57 -15
  74. package/dist/run-export.js +4 -2
  75. package/dist/run-launch.js +16 -3
  76. package/dist/run-model-key.d.ts +2 -1
  77. package/dist/run-model-key.js +2 -1
  78. package/dist/run-reads-over-store.d.ts +7 -0
  79. package/dist/run-reads-over-store.js +32 -4
  80. package/dist/run-usage.js +3 -2
  81. package/dist/runnable.d.ts +6 -3
  82. package/dist/runnable.js +16 -6
  83. package/dist/runner/adapter-loop.d.ts +8 -1
  84. package/dist/runner/adapter-loop.js +148 -29
  85. package/dist/runner/adapter-run-spec.d.ts +9 -6
  86. package/dist/runner/adapter-run-spec.js +38 -52
  87. package/dist/runner/adapters/index.d.ts +4 -0
  88. package/dist/runner/adapters/index.js +2 -1
  89. package/dist/runner/adapters/pi.d.ts +3 -2
  90. package/dist/runner/adapters/pi.js +3 -1
  91. package/dist/runner/audit.d.ts +1 -1
  92. package/dist/runner/claim-secrets.d.ts +3 -1
  93. package/dist/runner/claim-secrets.js +18 -7
  94. package/dist/runner/cli-run-spec.js +24 -17
  95. package/dist/runner/compare-end.d.ts +1 -1
  96. package/dist/runner/dispatch.js +4 -2
  97. package/dist/runner/harness-loops.d.ts +14 -0
  98. package/dist/runner/harness-loops.js +51 -5
  99. package/dist/runner/held.d.ts +4 -1
  100. package/dist/runner/live-ticker.js +5 -4
  101. package/dist/runner/loop-contract.d.ts +4 -1
  102. package/dist/runner/mcp-claim.js +3 -2
  103. package/dist/runner/mcp-run.d.ts +24 -4
  104. package/dist/runner/mcp-run.js +47 -2
  105. package/dist/runner/meta-tools.js +4 -4
  106. package/dist/runner/metrics.d.ts +6 -0
  107. package/dist/runner/metrics.js +12 -4
  108. package/dist/runner/monid-run.js +3 -1
  109. package/dist/runner/native-loop.js +3 -3
  110. package/dist/runner/redact.d.ts +3 -0
  111. package/dist/runner/redact.js +7 -0
  112. package/dist/runner/run-child-host.d.ts +10 -6
  113. package/dist/runner/run-child-host.js +44 -29
  114. package/dist/runner/run-child.js +1 -0
  115. package/dist/runner/runner.js +2 -0
  116. package/dist/runner/sdk-loop.js +5 -3
  117. package/dist/runner/workflow-calls.d.ts +5 -1
  118. package/dist/runner/workflow-calls.js +65 -19
  119. package/dist/runner/workflow-loop.d.ts +1 -1
  120. package/dist/runner/workflow-loop.js +3 -1
  121. package/dist/runner/workflow-spec.d.ts +4 -0
  122. package/dist/runner/workflow-spec.js +18 -13
  123. package/dist/runs-over-store.d.ts +2 -2
  124. package/dist/runs-over-store.js +1 -1
  125. package/dist/secret-cut.js +7 -4
  126. package/dist/secret-rules.d.ts +0 -1
  127. package/dist/secret-rules.js +122 -88
  128. package/dist/server.d.ts +17 -1
  129. package/dist/server.js +208 -69
  130. package/dist/share-host.d.ts +111 -0
  131. package/dist/share-host.js +666 -0
  132. package/dist/slack.js +2 -1
  133. package/dist/store/postgres/migrate.js +3 -1
  134. package/dist/store-reads/analytics.d.ts +15 -0
  135. package/dist/store-reads/analytics.js +17 -0
  136. package/dist/store-reads/learning.d.ts +5 -4
  137. package/dist/store-reads/learning.js +7 -4
  138. package/dist/suggestions.js +32 -3
  139. package/dist/templates.d.ts +3 -1
  140. package/dist/templates.js +7 -3
  141. package/dist/tool-gate.d.ts +25 -9
  142. package/dist/tool-gate.js +58 -19
  143. package/dist/tool-plane.d.ts +24 -1
  144. package/dist/tool-plane.js +75 -3
  145. package/dist/tools.d.ts +12 -2
  146. package/dist/tools.js +42 -7
  147. package/dist/trigger-composio.js +1 -1
  148. package/dist/trigger-launch-hook.d.ts +2 -2
  149. package/dist/trigger-launch-hook.js +1 -1
  150. package/dist/triggers.d.ts +7 -4
  151. package/dist/triggers.js +4 -4
  152. package/dist/webhooks.d.ts +3 -0
  153. package/dist/webhooks.js +5 -0
  154. package/dist/workspace/archil-claim.d.ts +7 -3
  155. package/dist/workspace/archil-claim.js +13 -5
  156. package/dist/workspace/archil-mount-credential.d.ts +6 -0
  157. package/dist/workspace/archil-mount-credential.js +11 -0
  158. package/dist/workspace/computer-deps.d.ts +5 -3
  159. package/dist/workspace/computer-deps.js +11 -9
  160. package/dist/workspace/computer-for-claim.d.ts +6 -2
  161. package/dist/workspace/computer-for-claim.js +43 -12
  162. package/dist/workspace/computer-janitor.d.ts +7 -4
  163. package/dist/workspace/computer-janitor.js +7 -4
  164. package/dist/workspace/computer-kept.d.ts +7 -1
  165. package/dist/workspace/computer-kept.js +7 -1
  166. package/dist/workspace/kind-skills/desktop/SKILL.md +12 -3
  167. package/dist/workspace/mount-revoke-left.d.ts +16 -4
  168. package/dist/workspace/mount-revoke-left.js +42 -22
  169. package/dist/workspace/resolve-computer.d.ts +11 -5
  170. package/dist/workspace/resolve-computer.js +22 -13
  171. package/dist/workspace/run-end-computers.js +1 -1
  172. package/dist/workspace/run-tools.d.ts +10 -3
  173. package/dist/workspace/run-tools.js +5 -4
  174. package/dist/wrapped.d.ts +29 -2
  175. package/dist/wrapped.js +20 -3
  176. package/launcher/agentrun-serve +1 -1
  177. package/package.json +12 -12
  178. package/dist/console/assets/index-DZi-muIj.js +0 -629
  179. package/dist/console/assets/share-pz61zIn9.js +0 -6
@@ -7,6 +7,30 @@
7
7
  * `refused: true` on one refused before any node ran (it ran nothing). A run's `workflow_calls` read these
8
8
  * (runner/workflow-calls.ts). */
9
9
  export const LEARNED_NODES = "agentrun.learned_nodes";
10
+ /** The record of a learned_workflow call that ended `failed` with no node kept, where the tool kept none: an agent's call
11
+ * a crash cut mid-call, refused when it was issued again (adapter-loop.ts learnedEntry, learnedCallRan). An earlier
12
+ * attempt may have run nodes and spent, so it is no refusal: its $ is what its call id booked. */
13
+ export const failedRecord = (call, workflow, digest, caller) => ({ call, workflow, digest, caller, nodes: [], ended: "failed" });
14
+ /** The record of a learned_workflow call refused before the tool saw it (`refused`: it ran nothing), which the loop keeps
15
+ * where the tool never ran: the platform's call its gate refused (runner/adapter-loop.ts serveFirst), and an agent's its
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, or while an attempt of it its gate let go was closed by no
18
+ * refusal (runner/workflow-calls.ts workflowCallsOf). */
19
+ export const refusedRecord = (call, workflow, digest, caller) => ({ ...failedRecord(call, workflow, digest, caller), refused: true });
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:
21
+ * `{ call }`, its call's id (adapter-loop.ts sessionGate). An attempt a crash cuts before its record is kept leaves
22
+ * this, so a later refusal of the call issued again knows an attempt after any earlier refusal may have run. */
23
+ export const LEARNED_ALLOWED = "agentrun.learned_allowed";
24
+ /** Whether an attempt of learned_workflow call `call` may have run, from its root's `entries`: the newest of its allow
25
+ * marks (LEARNED_ALLOWED) and its records (LEARNED_NODES) is a mark, or a record not `refused`. Neither: `replayed`, the
26
+ * bridge's word that the call is issued again (a run begun before the marks existed has none), else no attempt was let
27
+ * go, so none ran. */
28
+ export function learnedCallRan(entries, call, replayed = false) {
29
+ const newest = entries.findLast((entry) => (entry.kind === LEARNED_ALLOWED || entry.kind === LEARNED_NODES) && entry.data?.call === call);
30
+ if (newest === undefined)
31
+ return replayed;
32
+ return newest.kind === LEARNED_ALLOWED || newest.data.refused !== true;
33
+ }
10
34
  /** The most nodes a call keeps: a map over a long list runs its body once per item. */
11
35
  export const LEARNED_NODES_MAX = 64;
12
36
  /** The LEARNED_NODES entry that counts for each learned_workflow call in `entries`, by the call's id, as its index in
@@ -0,0 +1,144 @@
1
+ import { type OllamaPullLine } from "./ollama-provider.js";
2
+ /** The GPU where it is cheap to read: Apple silicon's unified memory (darwin on arm64), an NVIDIA card as nvidia-smi names
3
+ * it, else unknown. */
4
+ export type Gpu = {
5
+ readonly kind: "apple";
6
+ readonly unified: true;
7
+ } | {
8
+ readonly kind: "nvidia";
9
+ readonly name: string;
10
+ readonly memory_bytes: number;
11
+ } | {
12
+ readonly kind: "unknown";
13
+ };
14
+ /** What this machine is. */
15
+ export type Machine = {
16
+ readonly platform: string;
17
+ readonly arch: string;
18
+ readonly ram_bytes: number;
19
+ readonly gpu: Gpu;
20
+ };
21
+ /** The Ollama here: whether this server asks one at all (never under the faux model or a model gateway, model.ts
22
+ * asksOllama), whether it answered, and the version it says. */
23
+ export type OllamaFacts = {
24
+ readonly asked: false;
25
+ readonly reachable: false;
26
+ readonly version: null;
27
+ } | {
28
+ readonly asked: true;
29
+ readonly reachable: false;
30
+ readonly version: null;
31
+ } | {
32
+ readonly asked: true;
33
+ readonly reachable: true;
34
+ readonly version: string;
35
+ };
36
+ /** Everything the recommendation reads: the machine, its Ollama, and the tags that Ollama has pulled. */
37
+ export type LocalFacts = {
38
+ readonly machine: Machine;
39
+ readonly ollama: OllamaFacts;
40
+ readonly pulled: readonly string[];
41
+ };
42
+ /** The model recommended here, and why in words; `tag` null where none fits, and the words say what to do instead. */
43
+ export type Recommendation = {
44
+ readonly tag: string;
45
+ readonly why: string;
46
+ readonly pulled: boolean;
47
+ } | {
48
+ readonly tag: null;
49
+ readonly why: string;
50
+ readonly pulled: false;
51
+ };
52
+ /** The non-Apple pick, and Apple's where Inkling does not run: one line. A measurement (qwen3:8b against qwen3:30b-a3b,
53
+ * through this server's own runs) sets it. */
54
+ export declare const QWEN3_DEFAULT = "qwen3:8b";
55
+ /** Apple silicon's pick, where its Ollama runs it (MLX, on Apple silicon alone). */
56
+ export declare const INKLING = "inkling-2-mini";
57
+ /** The first Ollama that runs INKLING. */
58
+ export declare const INKLING_OLLAMA = "0.40.17";
59
+ /** Where Ollama is installed from. */
60
+ export declare const OLLAMA_DOWNLOAD = "https://ollama.com/download";
61
+ /** The least memory (total RAM; Apple silicon's unified memory) each tag is offered on, in GiB: its weights at Ollama's
62
+ * default quantization, the KV cache of the context this server asks (ollama-provider.ts contextOf), and room for the
63
+ * system. A machine sold as 16 GB reads about 15.5 GiB, so each floor sits under the size it is meant for. */
64
+ export declare const RAM_FLOOR_GIB: Readonly<Record<string, number>>;
65
+ /** Every tag the recommendation can name, and so the only tags a pull here takes. */
66
+ export declare const LOCAL_MODEL_TAGS: readonly string[];
67
+ /** A tag as Ollama lists it: with no `:`, `:latest`. */
68
+ export declare const fullTag: (tag: string) => string;
69
+ /** `version` at or past `floor`, both dotted numbers (a suffix such as `-rc1` ignored); an unreadable version is not. */
70
+ export declare function versionAtLeast(version: string, floor: string): boolean;
71
+ /**
72
+ * The model this server recommends for `facts`, and why. No Ollama: none, and where to install it. Apple silicon with an
73
+ * Ollama at INKLING_OLLAMA or later and the memory for it: INKLING. Everyone else: QWEN3_DEFAULT, or the next smaller qwen3
74
+ * that fits in memory, or none, saying what each needs; Apple silicon on an older Ollama is told to update for INKLING. A
75
+ * tag already pulled says so: no pull needed.
76
+ */
77
+ export declare function recommendLocalModel(facts: LocalFacts): Recommendation;
78
+ /** How long nvidia-smi is waited for. */
79
+ export declare const NVIDIA_SMI_TIMEOUT_MS = 2000;
80
+ /** nvidia-smi's first line, `<name>, <MiB>`, as a GPU; unknown for anything else. */
81
+ export declare function nvidiaOf(out: string | undefined): Gpu;
82
+ /** This machine, read once: what a server serves for its life. A test hands its own (ServeOptions.machine). */
83
+ export declare function readMachine(): Promise<Machine>;
84
+ /** The pull here, as the read surface shows it. */
85
+ export type PullView = {
86
+ tag: string;
87
+ state: "pulling" | "done" | "failed";
88
+ status: string;
89
+ completed_bytes: number;
90
+ total_bytes: number;
91
+ error?: string;
92
+ };
93
+ /** One pull at a time, through `pull`; `finished` once it succeeds (the listing dropped and read again), before it reads
94
+ * done. A log line at its start, its end and its failure: the tag, the bytes and the milliseconds, nothing else. */
95
+ export declare function localPulls({ pull, finished, log, signal }: {
96
+ pull: (tag: string, onLine: (line: OllamaPullLine) => void, signal: AbortSignal) => Promise<void>;
97
+ finished: (tag: string) => Promise<void>;
98
+ log?: (line: string) => void;
99
+ signal: AbortSignal;
100
+ }): {
101
+ view: () => PullView | null;
102
+ pulling: () => boolean;
103
+ /** Starts pulling `tag` (checked by the caller), behind the answer. */
104
+ start(tag: string): PullView;
105
+ };
106
+ export type LocalPulls = ReturnType<typeof localPulls>;
107
+ /** Whether the Ollama `env` names is on another machine: OLLAMA_HOST names an address that is not this machine's own
108
+ * (a loopback name). This server reads only its own memory and GPU, so it recommends and pulls nothing for that one. An
109
+ * address the base rule refuses is no Ollama asked at all, and not said to be elsewhere. */
110
+ export declare function ollamaElsewhere(env: NodeJS.ProcessEnv): boolean;
111
+ /** The words for an Ollama on another machine (ollamaElsewhere), which never name its address. */
112
+ export declare const OLLAMA_ELSEWHERE = "The Ollama OLLAMA_HOST names is on another machine, and this server reads only its own memory and GPU, so it recommends and pulls no model for that one. Pull one where that Ollama runs: ollama pull <tag>.";
113
+ /** Why no pull is made through the Ollama `env` names, in words, or undefined where one may: the faux model or a model
114
+ * gateway takes every model here (asksOllama); a server that is not one owner's own on their own machine (`notOwn`,
115
+ * server.ts whyNotOwnMachine's reasons) pulls nothing into an Ollama that is not theirs. */
116
+ export declare function pullRefusal(env: NodeJS.ProcessEnv, notOwn: readonly string[]): string | undefined;
117
+ /** What GET /settings/local-model and POST /settings/local-model/pull read. */
118
+ export type LocalModelDeps = {
119
+ env: NodeJS.ProcessEnv;
120
+ notOwn: readonly string[];
121
+ machine: () => Promise<Machine>;
122
+ pulls: LocalPulls;
123
+ };
124
+ /** The read surface: the machine, its Ollama, the recommendation, the pull here, and whether a pull may be made. */
125
+ export declare function localModelView({ env, notOwn, machine, pulls }: LocalModelDeps): Promise<{
126
+ machine: Machine;
127
+ ollama: OllamaFacts;
128
+ recommended: Recommendation;
129
+ pull: PullView | null;
130
+ can_pull: boolean;
131
+ refused: string | null;
132
+ }>;
133
+ /** POST /settings/local-model/pull: `{ tag }`, one of LOCAL_MODEL_TAGS (422 otherwise), where a pull may be made (403 in
134
+ * words otherwise), none under way (409 local_model_pulling). Answers the read surface with the pull started. */
135
+ export declare function pullLocalModel(deps: LocalModelDeps, body: unknown): Promise<{
136
+ machine: Machine;
137
+ ollama: OllamaFacts;
138
+ recommended: Recommendation;
139
+ pull: PullView | null;
140
+ can_pull: boolean;
141
+ refused: string | null;
142
+ }>;
143
+ /** The real pull: through the Ollama `env` names (ollama-provider.ts ollamaPull). */
144
+ export declare const pullThrough: (env: () => NodeJS.ProcessEnv, stallMs?: number) => (tag: string, onLine: (line: OllamaPullLine) => void, signal: AbortSignal) => Promise<void>;
@@ -0,0 +1,214 @@
1
+ // A free local model on the owner's own machine: what the machine is (platform, arch, memory, GPU) and its Ollama, the
2
+ // model this server recommends for it (recommendLocalModel, a pure function of those facts), and one pull of it at a time
3
+ // through that Ollama, its progress on the read surface (GET /settings/local-model). A pull is only ever of a tag the
4
+ // recommendation can name (LOCAL_MODEL_TAGS), and only where the Ollama here is the owner's own: one owner's own server on
5
+ // their own machine (server.ts whyNotOwnMachine, the rule ollama-provider.ts ollamaHostOf names the default address by),
6
+ // never under the faux model or a model gateway (model.ts asksOllama). Once a pull ends, the kept listing is dropped
7
+ // (ollamaForget), so the model is in the picker at once.
8
+ import { execFile } from "node:child_process";
9
+ import { arch, platform, totalmem } from "node:os";
10
+ import { ApiError } from "./errors.js";
11
+ import { isLoopbackName } from "./host-check.js";
12
+ import { asksOllama, FAUX_ENV } from "./model.js";
13
+ import { ollamaBase, ollamaModels, ollamaPull, ollamaVersion } from "./ollama-provider.js";
14
+ import { logLine } from "./print.js";
15
+ import { registerSecretPage, registerSecretWrite } from "./secret-writes.js";
16
+ import { isObject, unknownFields } from "./validate.js";
17
+ // Owner-only: the machine's facts are the owner's, and a pull spends their disk and bandwidth.
18
+ for (const operation of ["getLocalModel", "pullLocalModel"])
19
+ registerSecretWrite(operation, () => true);
20
+ registerSecretPage(["getLocalModel", "pullLocalModel"], "/#/");
21
+ /** The non-Apple pick, and Apple's where Inkling does not run: one line. A measurement (qwen3:8b against qwen3:30b-a3b,
22
+ * through this server's own runs) sets it. */
23
+ export const QWEN3_DEFAULT = "qwen3:8b";
24
+ /** Apple silicon's pick, where its Ollama runs it (MLX, on Apple silicon alone). */
25
+ export const INKLING = "inkling-2-mini";
26
+ /** The first Ollama that runs INKLING. */
27
+ export const INKLING_OLLAMA = "0.40.17";
28
+ /** Where Ollama is installed from. */
29
+ export const OLLAMA_DOWNLOAD = "https://ollama.com/download";
30
+ const GIB = 1024 ** 3;
31
+ /** The least memory (total RAM; Apple silicon's unified memory) each tag is offered on, in GiB: its weights at Ollama's
32
+ * default quantization, the KV cache of the context this server asks (ollama-provider.ts contextOf), and room for the
33
+ * system. A machine sold as 16 GB reads about 15.5 GiB, so each floor sits under the size it is meant for. */
34
+ export const RAM_FLOOR_GIB = {
35
+ [INKLING]: 15,
36
+ "qwen3:30b-a3b": 30,
37
+ "qwen3:8b": 15,
38
+ "qwen3:4b": 11,
39
+ };
40
+ /** The qwen3 tags, largest first: the pick is QWEN3_DEFAULT, else the next smaller that fits. */
41
+ const QWEN3_LADDER = ["qwen3:30b-a3b", "qwen3:8b", "qwen3:4b"];
42
+ const QWEN3_FITS = QWEN3_LADDER.slice(Math.max(0, QWEN3_LADDER.indexOf(QWEN3_DEFAULT)));
43
+ /** Every tag the recommendation can name, and so the only tags a pull here takes. */
44
+ export const LOCAL_MODEL_TAGS = Object.freeze([INKLING, ...QWEN3_FITS]);
45
+ /** A tag as Ollama lists it: with no `:`, `:latest`. */
46
+ export const fullTag = (tag) => (tag.includes(":") ? tag : `${tag}:latest`);
47
+ const gib = (bytes) => `${(bytes / GIB).toFixed(1)} GiB`;
48
+ const fits = (machine, tag) => machine.ram_bytes >= (RAM_FLOOR_GIB[tag] ?? Infinity) * GIB;
49
+ const needs = (tag) => `${tag} needs ${RAM_FLOOR_GIB[tag]} GiB of memory`;
50
+ /** `version` at or past `floor`, both dotted numbers (a suffix such as `-rc1` ignored); an unreadable version is not. */
51
+ export function versionAtLeast(version, floor) {
52
+ const parts = (text) => /^v?(\d+)\.(\d+)\.(\d+)/.exec(text.trim())?.slice(1).map(Number);
53
+ const [have, want] = [parts(version), parts(floor)];
54
+ if (!have || !want)
55
+ return false;
56
+ for (let i = 0; i < 3; i++)
57
+ if (have[i] !== want[i])
58
+ return have[i] > want[i];
59
+ return true;
60
+ }
61
+ /** Whether this machine is Apple silicon. */
62
+ const appleSilicon = (machine) => machine.gpu.kind === "apple";
63
+ /**
64
+ * The model this server recommends for `facts`, and why. No Ollama: none, and where to install it. Apple silicon with an
65
+ * Ollama at INKLING_OLLAMA or later and the memory for it: INKLING. Everyone else: QWEN3_DEFAULT, or the next smaller qwen3
66
+ * that fits in memory, or none, saying what each needs; Apple silicon on an older Ollama is told to update for INKLING. A
67
+ * tag already pulled says so: no pull needed.
68
+ */
69
+ export function recommendLocalModel(facts) {
70
+ const { machine, ollama } = facts;
71
+ if (!ollama.asked)
72
+ return { tag: null, why: "This server asks no Ollama.", pulled: false };
73
+ if (!ollama.reachable)
74
+ return { tag: null, why: `Ollama isn't running on this machine. Install it from ${OLLAMA_DOWNLOAD}, start it, then come back here.`, pulled: false };
75
+ const has = new Set(facts.pulled.map(fullTag));
76
+ const done = (tag, why) => (has.has(fullTag(tag)) ? { tag, why: `${why} Already pulled: no pull needed.`, pulled: true } : { tag, why, pulled: false });
77
+ const apple = appleSilicon(machine);
78
+ const inklingRuns = apple && versionAtLeast(ollama.version, INKLING_OLLAMA);
79
+ if (inklingRuns && fits(machine, INKLING))
80
+ return done(INKLING, `Apple silicon with Ollama ${ollama.version} runs ${INKLING}; ${needs(INKLING)}, and this Mac has ${gib(machine.ram_bytes)}.`);
81
+ const notes = [
82
+ ...(apple && !inklingRuns ? [`Update Ollama to ${INKLING_OLLAMA} for ${INKLING}.`] : []),
83
+ ...(inklingRuns ? [`${needs(INKLING)}, and this Mac has ${gib(machine.ram_bytes)}.`] : []),
84
+ ];
85
+ const tag = QWEN3_FITS.find((candidate) => fits(machine, candidate));
86
+ if (!tag) {
87
+ const least = QWEN3_FITS[QWEN3_FITS.length - 1];
88
+ return { tag: null, why: [`This machine has ${gib(machine.ram_bytes)} of memory, and the smallest local model offered here, ${needs(least)}. Add a model key instead.`, ...notes].join(" "), pulled: false };
89
+ }
90
+ const smaller = tag === QWEN3_DEFAULT ? "" : ` ${needs(QWEN3_DEFAULT)}, so the smaller ${tag}.`;
91
+ return done(tag, [`${tag} fits this machine's ${gib(machine.ram_bytes)} of memory (it needs ${RAM_FLOOR_GIB[tag]} GiB).${smaller}`, ...notes].join(" "));
92
+ }
93
+ // ---- the machine ------------------------------------------------------------------------------------------------------
94
+ /** How long nvidia-smi is waited for. */
95
+ export const NVIDIA_SMI_TIMEOUT_MS = 2_000;
96
+ /** The first GPU nvidia-smi names (`name, memory.total` in MiB), or unknown where it is not there, fails or is slow. */
97
+ async function nvidiaGpu() {
98
+ const out = await new Promise((resolve) => {
99
+ execFile("nvidia-smi", ["--query-gpu=name,memory.total", "--format=csv,noheader,nounits"], { timeout: NVIDIA_SMI_TIMEOUT_MS, windowsHide: true }, (error, stdout) => resolve(error ? undefined : stdout));
100
+ });
101
+ return nvidiaOf(out);
102
+ }
103
+ /** nvidia-smi's first line, `<name>, <MiB>`, as a GPU; unknown for anything else. */
104
+ export function nvidiaOf(out) {
105
+ const line = out?.split("\n").map((text) => text.trim()).find(Boolean);
106
+ const match = line ? /^(.+?),\s*(\d+)(?:\s*MiB)?$/.exec(line) : null;
107
+ return match ? { kind: "nvidia", name: match[1].trim().slice(0, 200), memory_bytes: Number(match[2]) * 1024 ** 2 } : { kind: "unknown" };
108
+ }
109
+ /** This machine, read once: what a server serves for its life. A test hands its own (ServeOptions.machine). */
110
+ export async function readMachine() {
111
+ const [os, cpu] = [platform(), arch()];
112
+ const gpu = os === "darwin" && cpu === "arm64" ? { kind: "apple", unified: true } : await nvidiaGpu();
113
+ return { platform: os, arch: cpu, ram_bytes: totalmem(), gpu };
114
+ }
115
+ /** One pull at a time, through `pull`; `finished` once it succeeds (the listing dropped and read again), before it reads
116
+ * done. A log line at its start, its end and its failure: the tag, the bytes and the milliseconds, nothing else. */
117
+ export function localPulls({ pull, finished, log, signal }) {
118
+ let current;
119
+ return {
120
+ view: () => (current ? { ...current } : null),
121
+ pulling: () => current?.state === "pulling",
122
+ /** Starts pulling `tag` (checked by the caller), behind the answer. */
123
+ start(tag) {
124
+ const layers = new Map();
125
+ const mine = { tag, state: "pulling", status: "starting", completed_bytes: 0, total_bytes: 0 };
126
+ current = mine;
127
+ const started = performance.now();
128
+ log?.(logLine("local_model_pull_start", { tag }));
129
+ const onLine = (line) => {
130
+ mine.status = line.status.slice(0, 200);
131
+ if (line.digest && line.total !== undefined) {
132
+ layers.set(line.digest, { total: line.total, completed: Math.min(line.completed ?? 0, line.total) });
133
+ mine.total_bytes = [...layers.values()].reduce((sum, layer) => sum + layer.total, 0);
134
+ mine.completed_bytes = [...layers.values()].reduce((sum, layer) => sum + layer.completed, 0);
135
+ }
136
+ };
137
+ void pull(tag, onLine, signal)
138
+ .then(() => finished(tag))
139
+ .then(() => {
140
+ Object.assign(mine, { state: "done", status: "success", completed_bytes: mine.total_bytes });
141
+ log?.(logLine("local_model_pull_end", { tag, bytes: mine.total_bytes, ms: Math.round(performance.now() - started) }));
142
+ })
143
+ .catch((error) => {
144
+ Object.assign(mine, { state: "failed", error: (error instanceof Error ? error.message : String(error)).slice(0, 500) });
145
+ log?.(logLine("local_model_pull_failed", { tag, bytes: mine.completed_bytes, ms: Math.round(performance.now() - started) }));
146
+ });
147
+ return { ...mine };
148
+ },
149
+ };
150
+ }
151
+ // ---- the route --------------------------------------------------------------------------------------------------------
152
+ /** Whether the Ollama `env` names is on another machine: OLLAMA_HOST names an address that is not this machine's own
153
+ * (a loopback name). This server reads only its own memory and GPU, so it recommends and pulls nothing for that one. An
154
+ * address the base rule refuses is no Ollama asked at all, and not said to be elsewhere. */
155
+ export function ollamaElsewhere(env) {
156
+ if (!env.OLLAMA_HOST?.trim())
157
+ return false;
158
+ try {
159
+ return !isLoopbackName(new URL(ollamaBase(env)).hostname);
160
+ }
161
+ catch {
162
+ return false;
163
+ }
164
+ }
165
+ /** The words for an Ollama on another machine (ollamaElsewhere), which never name its address. */
166
+ export const OLLAMA_ELSEWHERE = "The Ollama OLLAMA_HOST names is on another machine, and this server reads only its own memory and GPU, so it recommends and pulls no model for that one. Pull one where that Ollama runs: ollama pull <tag>.";
167
+ /** Why no pull is made through the Ollama `env` names, in words, or undefined where one may: the faux model or a model
168
+ * gateway takes every model here (asksOllama); a server that is not one owner's own on their own machine (`notOwn`,
169
+ * server.ts whyNotOwnMachine's reasons) pulls nothing into an Ollama that is not theirs. */
170
+ export function pullRefusal(env, notOwn) {
171
+ if (env[FAUX_ENV])
172
+ return "This server runs the faux model, so no local model is pulled here.";
173
+ if (!asksOllama(env))
174
+ return "This server sends every model to its model gateway (AGENT_MODEL_BASE_URL), so a local model would not run here.";
175
+ if (notOwn.length)
176
+ return `A local model is pulled from here only on one owner's own server on their own machine, and this server ${notOwn.join("; ")}. Pull it where Ollama runs: ollama pull <tag>.`;
177
+ if (!env.OLLAMA_HOST?.trim())
178
+ return "No Ollama is asked here.";
179
+ if (ollamaElsewhere(env))
180
+ return OLLAMA_ELSEWHERE;
181
+ return undefined;
182
+ }
183
+ /** The read surface: the machine, its Ollama, the recommendation, the pull here, and whether a pull may be made. */
184
+ export async function localModelView({ env, notOwn, machine, pulls }) {
185
+ const refused = pullRefusal(env, notOwn);
186
+ const asked = asksOllama(env);
187
+ const [facts, version, listed] = await Promise.all([machine(), asked ? ollamaVersion(env) : undefined, asked ? ollamaModels(env) : []]);
188
+ const ollama = !asked ? { asked: false, reachable: false, version: null } : version === undefined ? { asked: true, reachable: false, version: null } : { asked: true, reachable: true, version };
189
+ // An Ollama on another machine is not this machine's: no recommendation from this machine's memory and GPU for it.
190
+ const recommended = asked && ollamaElsewhere(env) ? { tag: null, why: OLLAMA_ELSEWHERE, pulled: false }
191
+ : recommendLocalModel({ machine: facts, ollama, pulled: listed.map((model) => model.name) });
192
+ // Not asked, the refusal is the only word on it: never that Ollama isn't running.
193
+ return { machine: facts, ollama, recommended: asked || !refused ? recommended : { ...recommended, why: refused }, pull: pulls.view(), can_pull: refused === undefined, refused: refused ?? null };
194
+ }
195
+ /** POST /settings/local-model/pull: `{ tag }`, one of LOCAL_MODEL_TAGS (422 otherwise), where a pull may be made (403 in
196
+ * words otherwise), none under way (409 local_model_pulling). Answers the read surface with the pull started. */
197
+ export async function pullLocalModel(deps, body) {
198
+ if (!isObject(body) || typeof body.tag !== "string")
199
+ throw new ApiError("input_invalid", "Name the tag to pull: { \"tag\": \"<tag>\" }.", { fields: [{ field: "tag", reason: "missing", message: "required, a string" }] });
200
+ const extra = unknownFields(body, ["tag"]);
201
+ if (extra.length)
202
+ throw new ApiError("input_invalid", extra.map((issue) => issue.message).join(" "), { fields: extra });
203
+ if (!LOCAL_MODEL_TAGS.includes(body.tag))
204
+ throw new ApiError("input_invalid", `Only the tags this server recommends are pulled from here: ${LOCAL_MODEL_TAGS.join(", ")}.`, { fields: [{ field: "tag", reason: "not_an_option", message: `one of ${LOCAL_MODEL_TAGS.join(", ")}` }] });
205
+ const refused = pullRefusal(deps.env, deps.notOwn);
206
+ if (refused)
207
+ throw new ApiError("forbidden", refused);
208
+ if (deps.pulls.pulling())
209
+ throw new ApiError("local_model_pulling", `A pull of ${deps.pulls.view()?.tag} is under way here: one at a time. Its progress is on GET /settings/local-model.`);
210
+ deps.pulls.start(body.tag);
211
+ return localModelView(deps);
212
+ }
213
+ /** The real pull: through the Ollama `env` names (ollama-provider.ts ollamaPull). */
214
+ export const pullThrough = (env, stallMs) => (tag, onLine, signal) => ollamaPull(env(), tag, onLine, { signal, ...(stallMs !== undefined ? { stallMs } : {}) });
@@ -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)
@@ -20,6 +20,13 @@ export declare const UNUSABLE: {
20
20
  * token handed, or which was sealed before the seal marked who handed it. */
21
21
  readonly composioOwnersUser: "the Composio user this run is bound to is one the owner connects on this install, and nothing marks the binding as the owner's: hand mcp_auth again on a message, or start a new run";
22
22
  };
23
+ /** What a run's timeline says of a server whose credential comes from each run when the run was handed none: its tools
24
+ * were left out of the run's (mcp-run.ts mcpForClaim), so the model is never offered a tool every call of which is
25
+ * refused. */
26
+ export declare const unconnectedWords: (server: string) => string;
27
+ /** The run's timeline note when a message hands the credential of servers whose tools its claim left out
28
+ * (unconnectedWords) while a turn is going: that turn's tools stay as they are, so the message waits for the next. */
29
+ export declare const connectedLaterWords: (servers: readonly string[]) => string;
23
30
  export declare const REFRESH_MARGIN_MS: number;
24
31
  /** How long an access token given with no expiry is taken to last: it is refreshed within the margin of then. */
25
32
  export declare const UNKNOWN_EXPIRY_MS: number;
package/dist/mcp-probe.js CHANGED
@@ -37,6 +37,13 @@ export const UNUSABLE = {
37
37
  * token handed, or which was sealed before the seal marked who handed it. */
38
38
  composioOwnersUser: "the Composio user this run is bound to is one the owner connects on this install, and nothing marks the binding as the owner's: hand mcp_auth again on a message, or start a new run",
39
39
  };
40
+ /** What a run's timeline says of a server whose credential comes from each run when the run was handed none: its tools
41
+ * were left out of the run's (mcp-run.ts mcpForClaim), so the model is never offered a tool every call of which is
42
+ * refused. */
43
+ export const unconnectedWords = (server) => `The MCP server ${server}'s tools were left out of this run: ${UNUSABLE.perRunMissing}.`;
44
+ /** The run's timeline note when a message hands the credential of servers whose tools its claim left out
45
+ * (unconnectedWords) while a turn is going: that turn's tools stay as they are, so the message waits for the next. */
46
+ export const connectedLaterWords = (servers) => `The MCP server${servers.length > 1 ? "s" : ""} ${servers.join(", ")} ${servers.length > 1 ? "were" : "was"} handed ${servers.length > 1 ? "their credentials" : "its credential"} by a message while this turn was going without ${servers.length > 1 ? "their" : "its"} tools: the message runs as the run's next turn, which has them.`;
40
47
  export const REFRESH_MARGIN_MS = 5 * 60_000;
41
48
  /** How long an access token given with no expiry is taken to last: it is refreshed within the margin of then. */
42
49
  export const UNKNOWN_EXPIRY_MS = 60 * 60_000;