@foldrun/core 24.8.0 → 24.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/engine-common.d.ts +91 -0
- package/dist/src/engine-common.js +160 -0
- package/dist/src/engine-compact.d.ts +61 -0
- package/dist/src/engine-compact.js +293 -0
- package/dist/src/engine-loop.d.ts +2 -42
- package/dist/src/engine-loop.js +219 -156
- package/dist/src/engine-mcp.d.ts +63 -0
- package/dist/src/engine-mcp.js +275 -0
- package/dist/src/engine-tools.d.ts +11 -0
- package/dist/src/runner.js +3 -2
- package/dist/src/script-tools.d.ts +3 -1
- package/dist/src/script-tools.js +34 -6
- package/dist/src/step-exec.d.ts +6 -0
- package/dist/src/step-exec.js +43 -2
- package/package.json +2 -1
- package/src/engine-common.ts +202 -0
- package/src/engine-compact.ts +288 -0
- package/src/engine-loop.ts +194 -188
- package/src/engine-mcp.ts +281 -0
- package/src/engine-tools.ts +4 -0
- package/src/runner.ts +3 -2
- package/src/script-tools.ts +27 -4
- package/src/step-exec.ts +49 -2
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// MCP servers on foldrun's own loop (FOL-213): every tool beyond the six
|
|
2
|
+
// file and shell tools reaches a step as an MCP server — foldrun's own, made
|
|
3
|
+
// in this process (createSdkMcpServer: `foldrun_scripts` with `web` search,
|
|
4
|
+
// fetch and browse; agents, apis, a2a, install, ask, peers, history), and an
|
|
5
|
+
// agent's own `mcpServers:` (stdio, http, sse). The SDK connected them inside
|
|
6
|
+
// the Claude Code binary; this connects them here, so the loop offers the
|
|
7
|
+
// same tools under the same names.
|
|
8
|
+
//
|
|
9
|
+
// What stays where it was:
|
|
10
|
+
// - the tools run where they always ran — the browser pod, the egress
|
|
11
|
+
// proxy and its search door, the vault's site-bound secrets are behind
|
|
12
|
+
// the server, not in this file;
|
|
13
|
+
// - each tool is offered as `mcp__<server>__<tool>`, the SDK's name, so
|
|
14
|
+
// step-exec's grant (`mcpNames`), limits, hooks and the run record read
|
|
15
|
+
// it as before, and every call goes through the loop's permission order
|
|
16
|
+
// (engine-common.ts decide/after);
|
|
17
|
+
// - a server that does not connect refuses the step by name. The SDK went
|
|
18
|
+
// on without its tools; a step that runs without a tool it was given is
|
|
19
|
+
// the failure this engine refuses to have.
|
|
20
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
21
|
+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
22
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
23
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
24
|
+
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
25
|
+
/** The server a granted name belongs to: `mcp__<server>`, `mcp__<server>__*`
|
|
26
|
+
* (the runner grants a whole server so) or `mcp__<server>__<tool>`. Matched
|
|
27
|
+
* against the step's own server names, the longest first, so a server named
|
|
28
|
+
* `sales__eu` is not read as `sales`. */
|
|
29
|
+
export function grantedServer(name, servers) {
|
|
30
|
+
for (const s of [...servers].sort((a, b) => b.length - a.length)) {
|
|
31
|
+
const head = `mcp__${s}`;
|
|
32
|
+
if (name === head || name === `${head}__*`)
|
|
33
|
+
return { server: s, tool: null };
|
|
34
|
+
if (name.startsWith(`${head}__`) && name.length > head.length + 2)
|
|
35
|
+
return { server: s, tool: name };
|
|
36
|
+
}
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
/** Longest a call may run when its server names no timeout: the step's own
|
|
40
|
+
* timeout ends it sooner (the loop's signal). */
|
|
41
|
+
const DEFAULT_CALL_MS = 24 * 60 * 60 * 1000;
|
|
42
|
+
/** The longest a timer holds (2^31 − 1 ms, ~24.8 days); past it Node fires at once. */
|
|
43
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
44
|
+
const CONNECT_MS = 60_000;
|
|
45
|
+
/** The most text one call hands the model; the rest is said to be cut. */
|
|
46
|
+
const MAX_TEXT = 100_000;
|
|
47
|
+
const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
48
|
+
/** Refused before a model call is paid for: a server this loop cannot connect. */
|
|
49
|
+
export function checkMcpSpecs(servers, engine) {
|
|
50
|
+
// No prototype: a server named __proto__ is a server, not a prototype.
|
|
51
|
+
const out = Object.create(null);
|
|
52
|
+
for (const [name, raw] of Object.entries(servers)) {
|
|
53
|
+
const s = (raw ?? {});
|
|
54
|
+
const type = s.type ?? "stdio";
|
|
55
|
+
const ok = (type === "sdk" && typeof s.instance?.connect === "function") ||
|
|
56
|
+
(type === "stdio" && typeof s.command === "string" && !!s.command) ||
|
|
57
|
+
((type === "http" || type === "sse") && typeof s.url === "string" && !!s.url);
|
|
58
|
+
if (!ok)
|
|
59
|
+
throw new Error(`the ${engine} engine cannot connect the MCP server ${name} (type ${type}) — run this agent on the default engine.`);
|
|
60
|
+
if (!/^[A-Za-z0-9_-]+$/.test(name))
|
|
61
|
+
throw new Error(`the MCP server name ${name} has characters a tool name cannot hold (letters, digits, _ and -)`);
|
|
62
|
+
// The SDK honours a per-tool always_deny / always_ask; this loop would
|
|
63
|
+
// offer such a tool like any other, so it refuses the spec instead.
|
|
64
|
+
if (Array.isArray(s.tools) && s.tools.length)
|
|
65
|
+
throw new Error(`the ${engine} engine does not apply per-tool permission policies (MCP server ${name}) — run this agent on the default engine.`);
|
|
66
|
+
out[name] = { ...s, type };
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
function transportFor(s, env, cwd) {
|
|
71
|
+
if (s.type === "sdk") {
|
|
72
|
+
const [client, server] = InMemoryTransport.createLinkedPair();
|
|
73
|
+
return { client, server };
|
|
74
|
+
}
|
|
75
|
+
if (s.type === "stdio") {
|
|
76
|
+
// The step's environment, as the SDK gave it: already the allowlisted
|
|
77
|
+
// one (host-env.ts: the clock, the proxy that is the way out, declared
|
|
78
|
+
// secrets), never this process's. Then what the spec names. The MCP
|
|
79
|
+
// library adds PATH, HOME, SHELL, TERM, USER and LOGNAME from this
|
|
80
|
+
// process where the step has none: names a program needs, no secrets.
|
|
81
|
+
const base = {};
|
|
82
|
+
for (const [k, v] of Object.entries(env))
|
|
83
|
+
if (typeof v === "string")
|
|
84
|
+
base[k] = v;
|
|
85
|
+
return { client: new StdioClientTransport({ command: s.command, args: s.args ?? [], env: { ...base, ...(s.env ?? {}) }, cwd, stderr: "ignore" }) };
|
|
86
|
+
}
|
|
87
|
+
const url = new URL(s.url);
|
|
88
|
+
const requestInit = { headers: s.headers ?? {} };
|
|
89
|
+
// SSE is the older MCP transport (deprecated in the SDK); still accepted,
|
|
90
|
+
// because an agent may name a server that has nothing newer.
|
|
91
|
+
return { client: s.type === "sse" ? new SSEClientTransport(url, { requestInit }) : new StreamableHTTPClientTransport(url, { requestInit }) };
|
|
92
|
+
}
|
|
93
|
+
/** A call's result as the loop hands it on: its text and images in the
|
|
94
|
+
* order the server gave them (a caption stays beside its picture), the text
|
|
95
|
+
* cut to a size, marked an error when the server says it is one. */
|
|
96
|
+
export function outcomeOf(result) {
|
|
97
|
+
const parts = [];
|
|
98
|
+
const add = (text) => parts.push({ type: "text", text });
|
|
99
|
+
for (const c of (Array.isArray(result.content) ? result.content : [])) {
|
|
100
|
+
if (c.type === "text" && typeof c.text === "string")
|
|
101
|
+
add(c.text);
|
|
102
|
+
else if (c.type === "image" && typeof c.data === "string" && typeof c.mimeType === "string")
|
|
103
|
+
parts.push({ type: "image", data: c.data, mediaType: c.mimeType });
|
|
104
|
+
else if (c.type === "resource") {
|
|
105
|
+
const r = (c.resource ?? {});
|
|
106
|
+
add(typeof r.text === "string" ? r.text : `[resource ${String(r.uri ?? "")}${r.mimeType ? ` (${String(r.mimeType)})` : ""}]`);
|
|
107
|
+
}
|
|
108
|
+
else if (c.type === "resource_link")
|
|
109
|
+
add(`[resource ${String(c.uri ?? "")}]`);
|
|
110
|
+
else if (c.type === "audio")
|
|
111
|
+
add("[audio — not shown]");
|
|
112
|
+
}
|
|
113
|
+
if (!parts.some((p) => p.type === "text") && result.structuredContent !== undefined)
|
|
114
|
+
add(JSON.stringify(result.structuredContent));
|
|
115
|
+
if (!parts.length && "toolResult" in result)
|
|
116
|
+
add(typeof result.toolResult === "string" ? result.toolResult : JSON.stringify(result.toolResult));
|
|
117
|
+
// One budget across every text part, in order, the newline between two
|
|
118
|
+
// counted; a part past it is dropped, not kept empty.
|
|
119
|
+
let left = MAX_TEXT;
|
|
120
|
+
let cut = 0;
|
|
121
|
+
const kept = [];
|
|
122
|
+
let any = false;
|
|
123
|
+
for (const p of parts) {
|
|
124
|
+
if (p.type !== "text") {
|
|
125
|
+
kept.push(p);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const sep = any ? 1 : 0;
|
|
129
|
+
const room = left - sep;
|
|
130
|
+
// An empty part still fits when only its newline does.
|
|
131
|
+
if (room < 0 || (room === 0 && p.text.length > 0)) {
|
|
132
|
+
cut += p.text.length;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (p.text.length > room) {
|
|
136
|
+
let end = room;
|
|
137
|
+
// Never half a character: a cut between a surrogate pair drops both.
|
|
138
|
+
if (/[\uD800-\uDBFF]/.test(p.text[end - 1] ?? ""))
|
|
139
|
+
end--;
|
|
140
|
+
cut += p.text.length - end;
|
|
141
|
+
p.text = p.text.slice(0, end);
|
|
142
|
+
}
|
|
143
|
+
left -= p.text.length + sep;
|
|
144
|
+
any = true;
|
|
145
|
+
kept.push(p);
|
|
146
|
+
}
|
|
147
|
+
parts.length = 0;
|
|
148
|
+
parts.push(...kept);
|
|
149
|
+
if (cut)
|
|
150
|
+
add(`[cut: ${cut} more characters]`);
|
|
151
|
+
const texts = parts.filter((p) => p.type === "text");
|
|
152
|
+
const text = texts.map((p) => p.text).join("\n");
|
|
153
|
+
const hasImage = parts.some((p) => p.type === "image");
|
|
154
|
+
return { text, isError: result.isError === true, ...(hasImage ? { parts } : {}) };
|
|
155
|
+
}
|
|
156
|
+
/** A promise held to a time and a signal — the MCP client waits for a
|
|
157
|
+
* transport to start before its own timeout begins (an SSE server that
|
|
158
|
+
* never sends its endpoint would hold the step open forever). */
|
|
159
|
+
function bounded(work, ms, signal, what) {
|
|
160
|
+
return new Promise((resolve, reject) => {
|
|
161
|
+
const done = () => { clearTimeout(timer); signal.removeEventListener("abort", onAbort); };
|
|
162
|
+
const onAbort = () => { done(); reject(new Error(`${what}: stopped`)); };
|
|
163
|
+
const timer = setTimeout(() => { done(); reject(new Error(`${what}: no answer in ${Math.round(ms / 1000)} s`)); }, ms);
|
|
164
|
+
// Handled first, so the work failing after a stop is never unhandled.
|
|
165
|
+
work.then((v) => { done(); resolve(v); }, (e) => { done(); reject(e); });
|
|
166
|
+
if (signal.aborted)
|
|
167
|
+
return onAbort();
|
|
168
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
/** Connect every server and list its tools. All or none: one that fails
|
|
172
|
+
* closes the rest and refuses the step, naming it. */
|
|
173
|
+
/** `env` is the step's options' environment (where MCP_TOOL_TIMEOUT is
|
|
174
|
+
* read, as the SDK read it); `toolEnv` is what a tool's process starts
|
|
175
|
+
* from — the loop's shellEnv, which a caller keeps apart from the model's
|
|
176
|
+
* credentials. */
|
|
177
|
+
export async function connectMcp(servers, ctx) {
|
|
178
|
+
const open = [];
|
|
179
|
+
const close = async () => {
|
|
180
|
+
await Promise.all(open.map(async (o) => {
|
|
181
|
+
// A streamable HTTP server that gave a session is told it is over
|
|
182
|
+
// (DELETE), so it is not left holding one; then the local side closes.
|
|
183
|
+
if (o.transport instanceof StreamableHTTPClientTransport && o.transport.sessionId) {
|
|
184
|
+
await bounded(o.transport.terminateSession(), 5_000, new AbortController().signal, "end session").catch(() => undefined);
|
|
185
|
+
}
|
|
186
|
+
await o.client.close().catch(() => undefined);
|
|
187
|
+
await o.server?.close().catch(() => undefined);
|
|
188
|
+
}));
|
|
189
|
+
};
|
|
190
|
+
const tools = [];
|
|
191
|
+
const owner = new Map();
|
|
192
|
+
const instructions = [];
|
|
193
|
+
const envTimeout = Number(ctx.env.MCP_TOOL_TIMEOUT);
|
|
194
|
+
try {
|
|
195
|
+
for (const [name, s] of Object.entries(servers)) {
|
|
196
|
+
const t = transportFor(s, ctx.toolEnv, ctx.cwd);
|
|
197
|
+
const client = new Client({ name: "foldrun-engine", version: "1.0.0" });
|
|
198
|
+
open.push({ client, transport: t.client, server: t.server });
|
|
199
|
+
let listed;
|
|
200
|
+
if (ctx.signal.aborted)
|
|
201
|
+
throw new Error(`the MCP server ${name} did not start: connect: stopped`);
|
|
202
|
+
try {
|
|
203
|
+
const started = (async () => {
|
|
204
|
+
if (t.server)
|
|
205
|
+
await s.instance.connect(t.server);
|
|
206
|
+
await client.connect(t.client, { timeout: CONNECT_MS, signal: ctx.signal });
|
|
207
|
+
const found = [];
|
|
208
|
+
// A server that offers no tools says so in its capabilities.
|
|
209
|
+
if (!client.getServerCapabilities()?.tools)
|
|
210
|
+
return found;
|
|
211
|
+
let cursor;
|
|
212
|
+
do {
|
|
213
|
+
let page;
|
|
214
|
+
try {
|
|
215
|
+
page = await client.listTools(cursor ? { cursor } : undefined, { timeout: CONNECT_MS, signal: ctx.signal });
|
|
216
|
+
}
|
|
217
|
+
catch (err) {
|
|
218
|
+
// Some say they have tools and answer tools/list with "method
|
|
219
|
+
// not found" when they have none (the Agent SDK's in-process
|
|
220
|
+
// server with an empty list): no tools, not a failed start.
|
|
221
|
+
if (err.code === -32601 && !cursor)
|
|
222
|
+
return found;
|
|
223
|
+
throw err;
|
|
224
|
+
}
|
|
225
|
+
found.push(...page.tools);
|
|
226
|
+
cursor = page.nextCursor;
|
|
227
|
+
} while (cursor);
|
|
228
|
+
// Each page replaced the client's output-schema checks with its
|
|
229
|
+
// own: give it every page's, so a tool on page one is still checked.
|
|
230
|
+
client.cacheToolMetadata?.(found);
|
|
231
|
+
return found;
|
|
232
|
+
})();
|
|
233
|
+
listed = await bounded(started, CONNECT_MS, ctx.signal, "connect");
|
|
234
|
+
}
|
|
235
|
+
catch (err) {
|
|
236
|
+
throw new Error(`the MCP server ${name} did not start: ${err.message}`);
|
|
237
|
+
}
|
|
238
|
+
// The server's own timeout, else MCP_TOOL_TIMEOUT, as the SDK read them.
|
|
239
|
+
const told = client.getInstructions();
|
|
240
|
+
if (typeof told === "string" && told.trim())
|
|
241
|
+
instructions.push({ server: name, text: told.trim() });
|
|
242
|
+
const timeout = Math.min(MAX_TIMER_MS, typeof s.timeout === "number" && s.timeout >= 1000 ? s.timeout : envTimeout >= 1000 ? envTimeout : DEFAULT_CALL_MS);
|
|
243
|
+
for (const tool of listed) {
|
|
244
|
+
const full = `mcp__${name}__${tool.name}`;
|
|
245
|
+
if (!TOOL_NAME.test(full))
|
|
246
|
+
throw new Error(`the MCP server ${name} offers a tool whose full name ${full} is not one a model accepts (at most 64 letters, digits, _ and -)`);
|
|
247
|
+
if (owner.has(full))
|
|
248
|
+
throw new Error(`two MCP servers offer a tool named ${full} (${owner.get(full)} and ${name})`);
|
|
249
|
+
// A name that reads as another server's (sales offering eu__find
|
|
250
|
+
// beside a server sales__eu) would be granted by the wrong server:
|
|
251
|
+
// the step is refused rather than guess.
|
|
252
|
+
const readAs = grantedServer(full, Object.keys(servers));
|
|
253
|
+
if (readAs?.server !== name)
|
|
254
|
+
throw new Error(`the MCP tool ${full} from ${name} reads as server ${readAs?.server ?? "none"}'s — rename the server or the tool`);
|
|
255
|
+
owner.set(full, name);
|
|
256
|
+
tools.push({
|
|
257
|
+
name: full,
|
|
258
|
+
description: tool.description ?? "",
|
|
259
|
+
input_schema: tool.inputSchema ?? { type: "object" },
|
|
260
|
+
// Run beside other reads only when the server says it changes nothing.
|
|
261
|
+
readOnly: tool.annotations?.readOnlyHint === true,
|
|
262
|
+
run: async (input, toolCtx) => {
|
|
263
|
+
const result = await client.callTool({ name: tool.name, arguments: input }, undefined, { signal: toolCtx.signal, timeout, maxTotalTimeout: timeout });
|
|
264
|
+
return outcomeOf(result);
|
|
265
|
+
},
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
catch (err) {
|
|
271
|
+
await close();
|
|
272
|
+
throw err;
|
|
273
|
+
}
|
|
274
|
+
return { tools, owner, instructions, servers: Object.keys(servers).map((name) => ({ name, status: "connected" })), close };
|
|
275
|
+
}
|
|
@@ -17,6 +17,17 @@ export declare function killGroups(ctx: ToolContext): void;
|
|
|
17
17
|
export interface ToolOutcome {
|
|
18
18
|
text: string;
|
|
19
19
|
isError?: boolean;
|
|
20
|
+
/** When the tool returned images (an MCP server's screenshot): its text and
|
|
21
|
+
* images in their order, sent to the model so. `text` is still the whole
|
|
22
|
+
* text, for the record and the hooks. */
|
|
23
|
+
parts?: ({
|
|
24
|
+
type: "text";
|
|
25
|
+
text: string;
|
|
26
|
+
} | {
|
|
27
|
+
type: "image";
|
|
28
|
+
data: string;
|
|
29
|
+
mediaType: string;
|
|
30
|
+
})[];
|
|
20
31
|
}
|
|
21
32
|
export interface EngineTool {
|
|
22
33
|
name: string;
|
package/dist/src/runner.js
CHANGED
|
@@ -90,7 +90,7 @@ export { localDate } from "./clock.js";
|
|
|
90
90
|
* name and the proxy fills it, as for an http tool. */
|
|
91
91
|
export function unbindMcpHeaders(servers, bound, values, grant) {
|
|
92
92
|
const known = Object.fromEntries(bound.filter((n) => n in values).map((n) => [n, values[n]]));
|
|
93
|
-
const out =
|
|
93
|
+
const out = Object.create(null);
|
|
94
94
|
for (const [name, server] of Object.entries(servers)) {
|
|
95
95
|
if (server.type !== "http") {
|
|
96
96
|
out[name] = server;
|
|
@@ -1086,7 +1086,8 @@ grantsOnly = false) {
|
|
|
1086
1086
|
// MCP servers an agent connects to. `mcpServers:` is Claude Code's spelling
|
|
1087
1087
|
// for the inline form; a `type: mcp` tool file is the shared form. Both end
|
|
1088
1088
|
// up here, and both reach the model as ordinary MCP tools.
|
|
1089
|
-
|
|
1089
|
+
// No prototype: a server an agent names __proto__ is a server.
|
|
1090
|
+
const mcpServers = Object.create(null);
|
|
1090
1091
|
const mcpNames = [];
|
|
1091
1092
|
// What the granted tools' programs need — merged into this step's runtime
|
|
1092
1093
|
// below. The tool is the unit of code, so its dependencies live in tool.md
|
|
@@ -47,7 +47,9 @@ export declare function commandFor(spec: ScriptSpec, abs: string, overrides?: Re
|
|
|
47
47
|
cmd: string;
|
|
48
48
|
args: string[];
|
|
49
49
|
};
|
|
50
|
-
export declare function runScript(cwd: string, spec: ScriptSpec, values: Record<string, string>, env: Record<string, string>, libraryScripts: string, interpreters: Record<string, string>, exec: ExecutionContext | null
|
|
50
|
+
export declare function runScript(cwd: string, spec: ScriptSpec, values: Record<string, string>, env: Record<string, string>, libraryScripts: string, interpreters: Record<string, string>, exec: ExecutionContext | null,
|
|
51
|
+
/** A stop for the call (the MCP request's): the script ends with it. */
|
|
52
|
+
signal?: AbortSignal): Promise<{
|
|
51
53
|
code: number | null;
|
|
52
54
|
out: string;
|
|
53
55
|
}>;
|
package/dist/src/script-tools.js
CHANGED
|
@@ -126,7 +126,9 @@ function containerInterpreter(abs) {
|
|
|
126
126
|
};
|
|
127
127
|
return byExt[path.extname(abs).toLowerCase()] ?? abs;
|
|
128
128
|
}
|
|
129
|
-
export function runScript(cwd, spec, values, env, libraryScripts, interpreters, exec
|
|
129
|
+
export function runScript(cwd, spec, values, env, libraryScripts, interpreters, exec,
|
|
130
|
+
/** A stop for the call (the MCP request's): the script ends with it. */
|
|
131
|
+
signal) {
|
|
130
132
|
// An inline-code tool has no file yet: write it inside the agent's own
|
|
131
133
|
// directory — already an allowed root — and run it like any other script.
|
|
132
134
|
// Materialised per call rather than per build, so an edit to the tool's
|
|
@@ -228,11 +230,36 @@ export function runScript(cwd, spec, values, env, libraryScripts, interpreters,
|
|
|
228
230
|
// base and gets what the agent declared, by name — see host-env.ts.
|
|
229
231
|
// In a run container `env` already carries the container's whole
|
|
230
232
|
// environment, which is the boundary, so nothing is lost there.
|
|
233
|
+
const ownGroup = process.platform !== "win32" && !process.stdout.isTTY && !process.stdin.isTTY;
|
|
231
234
|
const child = spawn(cmd, args, {
|
|
232
235
|
cwd,
|
|
233
236
|
env: workspaceLinkEnv({ ...hostSafeEnv(), ...env }, cwd),
|
|
234
237
|
timeout: timeoutFor(spec),
|
|
238
|
+
// Unattended (no terminal: the platform, a schedule), a script leads
|
|
239
|
+
// its own process group, so a stop ends what it started too — a
|
|
240
|
+
// leftover child could otherwise write over a retry's output. At a
|
|
241
|
+
// terminal it stays in this process's group, so Ctrl-C reaches it.
|
|
242
|
+
detached: ownGroup,
|
|
235
243
|
});
|
|
244
|
+
// A stopped step stops its script: the call's stop kills it (its group
|
|
245
|
+
// when it has one). A container run's script is not followed — as on
|
|
246
|
+
// the SDK path before.
|
|
247
|
+
const stop = () => {
|
|
248
|
+
stopped = true;
|
|
249
|
+
try {
|
|
250
|
+
if (ownGroup && child.pid)
|
|
251
|
+
process.kill(-child.pid, "SIGKILL");
|
|
252
|
+
else
|
|
253
|
+
child.kill("SIGKILL");
|
|
254
|
+
}
|
|
255
|
+
catch { /* already gone */ }
|
|
256
|
+
};
|
|
257
|
+
let stopped = false;
|
|
258
|
+
if (signal?.aborted)
|
|
259
|
+
stop();
|
|
260
|
+
else
|
|
261
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
262
|
+
child.on("close", () => signal?.removeEventListener("abort", stop));
|
|
236
263
|
let out = "";
|
|
237
264
|
const append = (chunk) => {
|
|
238
265
|
if (out.length < MAX_OUTPUT)
|
|
@@ -243,9 +270,10 @@ export function runScript(cwd, spec, values, env, libraryScripts, interpreters,
|
|
|
243
270
|
child.on("error", (err) => resolve({ code: null, out: `failed to start: ${err.message}` }));
|
|
244
271
|
child.on("close", (code) => resolve({
|
|
245
272
|
code,
|
|
246
|
-
out:
|
|
247
|
-
|
|
248
|
-
|
|
273
|
+
out: (stopped ? "stopped: the step was stopped\n" : "") +
|
|
274
|
+
(out.length > MAX_OUTPUT
|
|
275
|
+
? `${out.slice(0, MAX_OUTPUT)}\n…[truncated]`
|
|
276
|
+
: out || "(no output)"),
|
|
249
277
|
}));
|
|
250
278
|
});
|
|
251
279
|
}
|
|
@@ -356,10 +384,10 @@ readable = () => false) {
|
|
|
356
384
|
const shape = scriptArgShape(spec.args);
|
|
357
385
|
return tool(spec.name, `${spec.description || `Run ${spec.run}.`} Runs the workspace script ${spec.run}; returns its output. ` +
|
|
358
386
|
`Credentials it needs are already in its environment.` +
|
|
359
|
-
(spec.guide ? `\n\nHow to use it (from its tool.md):\n${spec.guide}` : ""), shape, async (args) => {
|
|
387
|
+
(spec.guide ? `\n\nHow to use it (from its tool.md):\n${spec.guide}` : ""), shape, async (args, extra) => {
|
|
360
388
|
const started = Date.now();
|
|
361
389
|
const values = Object.fromEntries(Object.entries(args ?? {}).map(([k, v]) => [k, v === undefined ? "" : String(v)]));
|
|
362
|
-
const { code, out } = await runScript(agentDir, spec, values, env, libraryScripts, interpreters, exec);
|
|
390
|
+
const { code, out } = await runScript(agentDir, spec, values, env, libraryScripts, interpreters, exec, extra?.signal);
|
|
363
391
|
// The arguments, on the record. Without them a run says a script was
|
|
364
392
|
// called and not what it was asked to do — and for a script that
|
|
365
393
|
// writes to someone else's system, "it ran" is not an account of what
|
package/dist/src/step-exec.d.ts
CHANGED
|
@@ -82,6 +82,12 @@ export interface ExecOptions {
|
|
|
82
82
|
* Only for a person's own machine, on their word; a run container is
|
|
83
83
|
* its own boundary and needs nothing said (`sandboxBash: false`). */
|
|
84
84
|
engineHostShell?: boolean;
|
|
85
|
+
/** foldrun's loop: the model's context window in tokens, when it is not
|
|
86
|
+
* the 200k the loop assumes — compaction starts 16k short of it. */
|
|
87
|
+
contextWindow?: number;
|
|
88
|
+
/** foldrun's loop: false turns compaction off (a step that must see its
|
|
89
|
+
* whole conversation, or fail). */
|
|
90
|
+
compaction?: false;
|
|
85
91
|
agentDir: string;
|
|
86
92
|
workspaceRoot: string;
|
|
87
93
|
libraryRoot: string;
|
package/dist/src/step-exec.js
CHANGED
|
@@ -24,6 +24,7 @@ import { hostSafeEnv } from "./host-env.js";
|
|
|
24
24
|
import { validateSchema, describeSchemaErrors, looksLikeSchema } from "./json-schema.js";
|
|
25
25
|
import { CallCounter, callKeysFor, REFUSALS_BEFORE_STOP } from "./limits.js";
|
|
26
26
|
import { classifyCall, podAt, readPodEvents } from "./browser-pod.js";
|
|
27
|
+
import { grantedServer } from "./engine-mcp.js";
|
|
27
28
|
/** The four counts from one SDK usage object (snake_case, as the API
|
|
28
29
|
* reports it). The API counts fresh input apart from the cache's; here
|
|
29
30
|
* `inputTokens` is all of it, as it always was on the record, and the
|
|
@@ -186,6 +187,16 @@ async function executeStepInner(opts, runQuery) {
|
|
|
186
187
|
// its own list, a path outside the workspace, a shell command — names the
|
|
187
188
|
// agent that tried, not just the step.
|
|
188
189
|
const subagentNames = new Map();
|
|
190
|
+
// An MCP tool is granted when the server it belongs to is. Its server is
|
|
191
|
+
// read against the step's own server names, the longest first: with
|
|
192
|
+
// servers `sales` and `sales__eu`, `mcp__sales__eu__find` is sales__eu's,
|
|
193
|
+
// and granting `sales` does not grant it. A name no server of the step's
|
|
194
|
+
// claims falls back to the prefix it always matched on.
|
|
195
|
+
const serverNames = Object.keys(opts.mcpServers ?? {});
|
|
196
|
+
const fromGrantedMcp = (toolName) => {
|
|
197
|
+
const g = grantedServer(toolName, serverNames);
|
|
198
|
+
return g ? g.tool !== null && opts.mcpNames.includes(g.server) : opts.mcpNames.some((n) => toolName.startsWith(`mcp__${n}__`));
|
|
199
|
+
};
|
|
189
200
|
// `limits:` — this step's counts. A new step, a retry of one, or a
|
|
190
201
|
// fan-out instance each start from zero.
|
|
191
202
|
const counter = new CallCounter(opts.limits);
|
|
@@ -274,6 +285,10 @@ async function executeStepInner(opts, runQuery) {
|
|
|
274
285
|
// path (the CLI on someone's laptop, and the host executor) keeps it,
|
|
275
286
|
// because there a shell escape reaches the real machine.
|
|
276
287
|
...(opts.engineHostShell ? { engineHostShell: true } : {}),
|
|
288
|
+
// foldrun's loop only: the model's context window for compaction, or
|
|
289
|
+
// compaction off (engine-compact.ts). The SDK compacts by its own rules.
|
|
290
|
+
...(opts.contextWindow ? { contextWindow: opts.contextWindow } : {}),
|
|
291
|
+
...(opts.compaction === false ? { compaction: false } : {}),
|
|
277
292
|
sandbox: {
|
|
278
293
|
enabled: opts.sandboxBash !== false,
|
|
279
294
|
// Must stay false. Auto-allowing bash because it's sandboxed skips
|
|
@@ -368,7 +383,7 @@ async function executeStepInner(opts, runQuery) {
|
|
|
368
383
|
: isFilesystemTool(hookInput.tool_name)
|
|
369
384
|
? checkPaths(hookInput.tool_name, v.input, { agentDir, workspaceRoot, libraryRoot, configWrites: opts.configWrites })
|
|
370
385
|
: { ok: true };
|
|
371
|
-
const granted = opts.allowed.includes(hookInput.tool_name) ||
|
|
386
|
+
const granted = opts.allowed.includes(hookInput.tool_name) || fromGrantedMcp(hookInput.tool_name);
|
|
372
387
|
// The sub-agent guard read the ORIGINAL input: a rewrite of a
|
|
373
388
|
// delegation could otherwise swap subagent_type for one this
|
|
374
389
|
// step never declared (or the SDK's general-purpose).
|
|
@@ -427,7 +442,7 @@ async function executeStepInner(opts, runQuery) {
|
|
|
427
442
|
const via = options?.agentID ? (subagentNames.get(options.agentID) ?? "subagent") : undefined;
|
|
428
443
|
// The toolset was already narrowed to what the agent declared, so
|
|
429
444
|
// anything outside it is a denial with a reason the model can act on.
|
|
430
|
-
const fromGrantedServer =
|
|
445
|
+
const fromGrantedServer = fromGrantedMcp(toolName);
|
|
431
446
|
// A call the hook counted and this refuses never ran: give it back.
|
|
432
447
|
const refund = () => { if (counter.active)
|
|
433
448
|
counter.refund(callKeysFor(toolName, input, opts.toolOwners)); };
|
|
@@ -610,6 +625,32 @@ async function executeStepInner(opts, runQuery) {
|
|
|
610
625
|
// before the SDK and its MCP servers started.
|
|
611
626
|
if (message.type === "system" && message.subtype === "init")
|
|
612
627
|
loopStartedAt = Date.now();
|
|
628
|
+
if (message.type === "system" && message.subtype === "compact_boundary") {
|
|
629
|
+
// The conversation neared the model's context window; its older part
|
|
630
|
+
// was summarised (foldrun's loop: engine-compact.ts; the SDK: its own).
|
|
631
|
+
const meta = message.compact_metadata;
|
|
632
|
+
emit("info", `compacted the conversation${meta?.pre_tokens ? ` from about ${meta.pre_tokens.toLocaleString("en")} tokens` : ""}${meta?.post_tokens ? ` to about ${meta.post_tokens.toLocaleString("en")}` : ""}${meta?.trigger === "overflow" ? " (the model said it was too long)" : ""}`);
|
|
633
|
+
}
|
|
634
|
+
if (message.type === "system" && message.subtype === "compact_failed") {
|
|
635
|
+
emit("info", `could not compact the conversation: ${String(message.error ?? "no reason given")}`);
|
|
636
|
+
}
|
|
637
|
+
// A summary request (foldrun's loop) is a model call like any turn: its
|
|
638
|
+
// tokens are in the step's cost, and its budget, whether or not the
|
|
639
|
+
// summary was used.
|
|
640
|
+
const compactUsage = message.type === "system" && /^compact_(boundary|failed)$/.test(String(message.subtype))
|
|
641
|
+
? message.usage
|
|
642
|
+
: undefined;
|
|
643
|
+
if (compactUsage) {
|
|
644
|
+
turns.set(`compaction-${anonymousTurns++}`, { u: compactUsage, price: priceOf(message) });
|
|
645
|
+
if (ceiling) {
|
|
646
|
+
spentUsd = turnsTotal();
|
|
647
|
+
if (spentUsd >= ceiling) {
|
|
648
|
+
emit("error", `over budget — this step reached $${spentUsd.toFixed(4)} of its $${ceiling.toFixed(4)} ceiling mid-turn and was stopped (${opts.budgetNote ?? "budget: in the flow file"})`);
|
|
649
|
+
status = "failed";
|
|
650
|
+
break;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
613
654
|
if (message.type === "stream_event") {
|
|
614
655
|
const ev = message.event;
|
|
615
656
|
const agentKey = message.parent_tool_use_id ?? "";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foldrun/core",
|
|
3
|
-
"version": "24.
|
|
3
|
+
"version": "24.9.0",
|
|
4
4
|
"description": "Agents are just folders. The format, the runner, the checks.",
|
|
5
5
|
"license": "FSL-1.1-ALv2",
|
|
6
6
|
"type": "module",
|
|
@@ -61,6 +61,7 @@
|
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
63
|
"@anthropic-ai/claude-agent-sdk": "^0.3.296",
|
|
64
|
+
"@modelcontextprotocol/sdk": "1.32.1",
|
|
64
65
|
"gray-matter": "^4.0.3",
|
|
65
66
|
"zod": "4.6.7"
|
|
66
67
|
},
|