@buildanagent/harness 0.1.0-alpha.30 → 0.1.0-alpha.31
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/README.md +69 -3
- package/dist/credentials/addresses.d.ts +9 -0
- package/dist/credentials/addresses.js +52 -0
- package/dist/credentials/addresses.js.map +1 -1
- package/dist/credentials/egress-proxy.js +34 -4
- package/dist/credentials/egress-proxy.js.map +1 -1
- package/dist/extensions/load.js +5 -2
- package/dist/extensions/load.js.map +1 -1
- package/dist/extensions/lock.d.ts +16 -2
- package/dist/extensions/lock.js +155 -21
- package/dist/extensions/lock.js.map +1 -1
- package/dist/extensions/mcp-pins-node.d.ts +16 -0
- package/dist/extensions/mcp-pins-node.js +18 -0
- package/dist/extensions/mcp-pins-node.js.map +1 -0
- package/dist/extensions/node.d.ts +4 -2
- package/dist/extensions/node.js +4 -2
- package/dist/extensions/node.js.map +1 -1
- package/dist/harness.d.ts +7 -1
- package/dist/harness.js.map +1 -1
- package/dist/mcp/connection.d.ts +9 -3
- package/dist/mcp/connection.js +192 -25
- package/dist/mcp/connection.js.map +1 -1
- package/dist/mcp/errors.d.ts +5 -2
- package/dist/mcp/errors.js.map +1 -1
- package/dist/mcp/guarded-fetch.d.ts +33 -0
- package/dist/mcp/guarded-fetch.js +391 -0
- package/dist/mcp/guarded-fetch.js.map +1 -0
- package/dist/mcp/http-node.d.ts +15 -0
- package/dist/mcp/http-node.js +179 -0
- package/dist/mcp/http-node.js.map +1 -0
- package/dist/mcp/index.d.ts +6 -3
- package/dist/mcp/index.js +5 -2
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/manager.d.ts +4 -3
- package/dist/mcp/manager.js +432 -47
- package/dist/mcp/manager.js.map +1 -1
- package/dist/mcp/pins.d.ts +9 -0
- package/dist/mcp/pins.js +54 -0
- package/dist/mcp/pins.js.map +1 -0
- package/dist/mcp/record.js +6 -0
- package/dist/mcp/record.js.map +1 -1
- package/dist/mcp/remote-config.d.ts +20 -0
- package/dist/mcp/remote-config.js +208 -0
- package/dist/mcp/remote-config.js.map +1 -0
- package/dist/mcp/remote.d.ts +20 -0
- package/dist/mcp/remote.js +146 -0
- package/dist/mcp/remote.js.map +1 -0
- package/dist/mcp/types.d.ts +198 -8
- package/dist/mcp/types.js.map +1 -1
- package/dist/server/protocol.schema.json +6 -3
- package/dist/session/runner.js +39 -6
- package/dist/session/runner.js.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/types.d.ts +16 -0
- package/dist/tools/types.js.map +1 -1
- package/llms.txt +18 -2
- package/package.json +7 -6
package/dist/extensions/lock.js
CHANGED
|
@@ -1,13 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Content-hash pins for project extensions. An extension is a folder; its hash covers every file in it, in
|
|
3
|
-
* order, each by its path and its own SHA-256, so a changed, added, removed or renamed file changes the hash.
|
|
4
|
-
* file, `extensions.lock.json`, holds one hash per extension folder
|
|
2
|
+
* Content-hash pins for project extensions and MCP tools. An extension is a folder; its hash covers every file in it, in
|
|
3
|
+
* sorted order, each by its path and its own SHA-256, so a changed, added, removed or renamed file changes the hash.
|
|
4
|
+
* The lock file, `extensions.lock.json`, holds one hash per extension folder under `extensions`, and under `mcp` the
|
|
5
|
+
* approved definition hash of each tool of each MCP server:
|
|
6
|
+
*
|
|
7
|
+
* ```json
|
|
8
|
+
* { "version": 1, "extensions": { "audit": "sha256:…" }, "mcp": { "docs": { "tools": { "search": "sha256:…" } } } }
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* Each writer keeps the other's member, and every write to one path in this process runs after the one before it. A
|
|
12
|
+
* file with no `extensions` member pins no extension, so writing MCP pins alone leaves a project's extensions unpinned
|
|
13
|
+
* rather than refused. `writeLock()` replaces a file it can't read; `writeMcpPins()` refuses one. Node-only: it reads
|
|
14
|
+
* and writes files.
|
|
5
15
|
*/
|
|
6
16
|
import { createHash } from "node:crypto";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
17
|
+
import { constants } from "node:fs";
|
|
18
|
+
import { mkdir, open, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
19
|
+
import { dirname, join, resolve } from "node:path";
|
|
9
20
|
import { HarnessError } from "../errors.js";
|
|
10
21
|
const LOCK_VERSION = 1;
|
|
22
|
+
const MAX_LOCK_BYTES = 1024 * 1024;
|
|
11
23
|
/** Every file under `dir`, as paths relative to it with `/` separators, in sorted order. */
|
|
12
24
|
async function filesUnder(dir, prefix = "") {
|
|
13
25
|
const entries = await readdir(join(dir, prefix), { withFileTypes: true });
|
|
@@ -49,38 +61,160 @@ export function parseObject(text, file) {
|
|
|
49
61
|
}
|
|
50
62
|
return parsed;
|
|
51
63
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
64
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
65
|
+
/**
|
|
66
|
+
* The lock file's text, or `undefined` when there is none. It is checked and read through one handle, so a file
|
|
67
|
+
* swapped in between the two is never read: the open refuses a link and does not wait on a pipe, the handle must be a
|
|
68
|
+
* regular file within the cap, and no more than the cap and one byte is ever read.
|
|
69
|
+
*/
|
|
70
|
+
async function readCapped(file) {
|
|
71
|
+
let handle;
|
|
55
72
|
try {
|
|
56
|
-
|
|
57
|
-
if (!(await stat(file)).isFile())
|
|
58
|
-
throw new HarnessError("invalid_extension", `${file} is not a regular file`);
|
|
59
|
-
text = await readFile(file, "utf8");
|
|
73
|
+
handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
60
74
|
}
|
|
61
75
|
catch (error) {
|
|
62
|
-
|
|
76
|
+
const code = error.code;
|
|
77
|
+
if (code === "ENOENT")
|
|
63
78
|
return undefined;
|
|
79
|
+
if (code === "ELOOP")
|
|
80
|
+
throw new HarnessError("invalid_extension", `${file} is a link, which a lock file may not be`);
|
|
64
81
|
throw error;
|
|
65
82
|
}
|
|
83
|
+
try {
|
|
84
|
+
const found = await handle.stat();
|
|
85
|
+
// A pipe or a device would hang or never end, so only a regular file is read.
|
|
86
|
+
if (!found.isFile())
|
|
87
|
+
throw new HarnessError("invalid_extension", `${file} is not a regular file`);
|
|
88
|
+
const tooBig = () => new HarnessError("invalid_extension", `${file} is over ${MAX_LOCK_BYTES} bytes, which no lock file needs`);
|
|
89
|
+
if (found.size > MAX_LOCK_BYTES)
|
|
90
|
+
throw tooBig();
|
|
91
|
+
const buffer = new Uint8Array(MAX_LOCK_BYTES + 1);
|
|
92
|
+
let length = 0;
|
|
93
|
+
for (;;) {
|
|
94
|
+
const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);
|
|
95
|
+
if (bytesRead === 0)
|
|
96
|
+
break;
|
|
97
|
+
length += bytesRead;
|
|
98
|
+
if (length > MAX_LOCK_BYTES)
|
|
99
|
+
throw tooBig();
|
|
100
|
+
}
|
|
101
|
+
return new TextDecoder().decode(buffer.subarray(0, length));
|
|
102
|
+
}
|
|
103
|
+
finally {
|
|
104
|
+
await handle.close();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** The lock file's parsed body, checked for its version and the shape of both members, or `undefined` without one. */
|
|
108
|
+
async function readBody(file) {
|
|
109
|
+
const text = await readCapped(file);
|
|
110
|
+
if (text === undefined)
|
|
111
|
+
return undefined;
|
|
66
112
|
const parsed = parseObject(text, file);
|
|
67
|
-
|
|
113
|
+
const badMember = (value) => value !== undefined && !isObject(value);
|
|
114
|
+
if (parsed.version !== LOCK_VERSION || badMember(parsed.extensions) || badMember(parsed.mcp)) {
|
|
68
115
|
throw new HarnessError("invalid_extension", `the lock file ${file} is not an extensions.lock.json of version 1`);
|
|
69
116
|
}
|
|
117
|
+
return parsed;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* The pins in a lock file, by extension folder name, or `undefined` when there is no lock file or it pins no
|
|
121
|
+
* extension, because it holds MCP pins alone.
|
|
122
|
+
*/
|
|
123
|
+
export async function readLock(file) {
|
|
124
|
+
const body = await readBody(file);
|
|
125
|
+
if (body?.extensions === undefined)
|
|
126
|
+
return undefined;
|
|
70
127
|
const pins = new Map();
|
|
71
|
-
for (const [name, hash] of Object.entries(
|
|
128
|
+
for (const [name, hash] of Object.entries(body.extensions)) {
|
|
72
129
|
if (typeof hash !== "string")
|
|
73
130
|
throw new HarnessError("invalid_extension", `the lock file pins "${name}" to no hash`);
|
|
74
131
|
pins.set(name, hash);
|
|
75
132
|
}
|
|
76
133
|
return pins;
|
|
77
134
|
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
135
|
+
const sorted = (entries) => Object.fromEntries([...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
|
136
|
+
// The writes waiting on each lock file, by its resolved path, so every writer in this process, `writeLock()` and every
|
|
137
|
+
// `fileMcpPinStore()` alike, reads and replaces the file one after another and none loses another's change.
|
|
138
|
+
const queues = new Map();
|
|
139
|
+
/** Runs `work` after every earlier write to the same file in this process has settled. */
|
|
140
|
+
function serially(file, work) {
|
|
141
|
+
const key = resolve(file);
|
|
142
|
+
const run = (queues.get(key) ?? Promise.resolve()).then(work);
|
|
143
|
+
const settled = run.catch(() => { });
|
|
144
|
+
queues.set(key, settled);
|
|
145
|
+
void settled.then(() => {
|
|
146
|
+
if (queues.get(key) === settled)
|
|
147
|
+
queues.delete(key);
|
|
148
|
+
});
|
|
149
|
+
return run;
|
|
150
|
+
}
|
|
151
|
+
/** The lock file's body, or `undefined` when there is none or it can't be read as a lock file. */
|
|
152
|
+
async function readBodyOrNone(file) {
|
|
153
|
+
try {
|
|
154
|
+
return await readBody(file);
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
if (error instanceof HarnessError && error.code === "invalid_extension")
|
|
158
|
+
return undefined;
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Writes the lock file for these extension pins, keeping its MCP pins, and replaces the old file in one step. A lock
|
|
164
|
+
* file that can't be read as one, such as one left with merge-conflict markers, is replaced whole, so a person can
|
|
165
|
+
* repin a broken file; its MCP pins go with it, and their tools wait for approval again.
|
|
166
|
+
*/
|
|
167
|
+
export function writeLock(file, pins) {
|
|
168
|
+
return serially(file, async () => {
|
|
169
|
+
const before = await readBodyOrNone(file);
|
|
170
|
+
await writeBody(file, {
|
|
171
|
+
version: LOCK_VERSION,
|
|
172
|
+
extensions: sorted(pins),
|
|
173
|
+
...(before?.mcp === undefined ? {} : { mcp: before.mcp }),
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
/** The MCP pins of one server in a lock file, by tool name, or `undefined` when it holds none for the server. */
|
|
178
|
+
export async function readMcpPins(file, server) {
|
|
179
|
+
const body = await readBody(file);
|
|
180
|
+
const servers = (body?.mcp ?? {});
|
|
181
|
+
if (!Object.hasOwn(servers, server))
|
|
182
|
+
return undefined;
|
|
183
|
+
const entry = servers[server];
|
|
184
|
+
if (!isObject(entry) || !isObject(entry.tools)) {
|
|
185
|
+
throw new HarnessError("invalid_extension", `the lock file ${file} holds no tool pins for "${server}"`);
|
|
186
|
+
}
|
|
187
|
+
const pins = {};
|
|
188
|
+
for (const [name, hash] of Object.entries(entry.tools)) {
|
|
189
|
+
if (typeof hash !== "string")
|
|
190
|
+
throw new HarnessError("invalid_extension", `the lock file pins a tool to no hash`);
|
|
191
|
+
Object.defineProperty(pins, name, { value: hash, enumerable: true, writable: true, configurable: true });
|
|
192
|
+
}
|
|
193
|
+
return pins;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Replaces the MCP pins of one server in a lock file, keeping every other member. It throws `invalid_extension` for a
|
|
197
|
+
* lock file it can't read, rather than replace it: a file without its extension pins would let unpinned extensions load.
|
|
198
|
+
*/
|
|
199
|
+
export function writeMcpPins(file, server, pins) {
|
|
200
|
+
return serially(file, async () => {
|
|
201
|
+
const before = await readBody(file);
|
|
202
|
+
const servers = { ...(before?.mcp ?? {}) };
|
|
203
|
+
Object.defineProperty(servers, server, {
|
|
204
|
+
value: { tools: sorted(Object.entries(pins)) },
|
|
205
|
+
enumerable: true,
|
|
206
|
+
writable: true,
|
|
207
|
+
configurable: true,
|
|
208
|
+
});
|
|
209
|
+
await writeBody(file, {
|
|
210
|
+
version: LOCK_VERSION,
|
|
211
|
+
...(before?.extensions === undefined ? {} : { extensions: before.extensions }),
|
|
212
|
+
mcp: sorted(Object.entries(servers)),
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
/** Writes a lock file's body, replacing the old one in one step. */
|
|
217
|
+
async function writeBody(file, body) {
|
|
84
218
|
await mkdir(dirname(file), { recursive: true });
|
|
85
219
|
const temp = `${file}.${globalThis.crypto.randomUUID()}.tmp`;
|
|
86
220
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lock.js","sourceRoot":"","sources":["../../src/extensions/lock.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACzF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,MAAM,YAAY,GAAG,CAAC,CAAC;AAEvB,4FAA4F;AAC5F,KAAK,UAAU,UAAU,CAAC,GAAW,EAAE,MAAM,GAAG,EAAE;IAChD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1E,MAAM,KAAK,GAAa,EAAE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AAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;QAC5D,MAAM,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAChC,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["/**\n * Content-hash pins for project extensions. An extension is a folder; its hash covers every file in it, in sorted\n * order, each by its path and its own SHA-256, so a changed, added, removed or renamed file changes the hash. The lock\n * file, `extensions.lock.json`, holds one hash per extension folder. Node-only: it reads and writes files.\n */\nimport { createHash } from \"node:crypto\";\nimport { mkdir, readdir, readFile, rename, rm, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { HarnessError } from \"../errors.js\";\n\nconst LOCK_VERSION = 1;\n\n/** Every file under `dir`, as paths relative to it with `/` separators, in sorted order. */\nasync function filesUnder(dir: string, prefix = \"\"): Promise<string[]> {\n const entries = await readdir(join(dir, prefix), { withFileTypes: true });\n const found: string[] = [];\n for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {\n const relative = prefix === \"\" ? entry.name : `${prefix}/${entry.name}`;\n if (entry.isDirectory()) found.push(...(await filesUnder(dir, relative)));\n else if (entry.isFile()) found.push(relative);\n // A link or a device file is not hashed but would still be followed by an import, so it cannot be pinned.\n else\n throw new HarnessError(\n \"invalid_extension\",\n `${join(dir, relative)} is a link or a special file, which an extension may not contain`,\n );\n }\n return found;\n}\n\n/** The hash of an extension folder: `sha256:` and the digest over each file's path and content digest, in sorted order. */\nexport async function hashExtensionDir(dir: string): Promise<string> {\n const total = createHash(\"sha256\");\n for (const file of await filesUnder(dir)) {\n const content = createHash(\"sha256\")\n .update(await readFile(join(dir, file)))\n .digest(\"hex\");\n total.update(`${file}\\0${content}\\n`);\n }\n return `sha256:${total.digest(\"hex\")}`;\n}\n\n/** Parses JSON that must be an object, or throws `invalid_extension` naming the file. */\nexport function parseObject(text: string, file: string): Record<string, unknown> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new HarnessError(\"invalid_extension\", `${file} is not valid JSON`);\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new HarnessError(\"invalid_extension\", `${file} is not a JSON object`);\n }\n return parsed as Record<string, unknown>;\n}\n\n/** The pins in a lock file, by extension folder name, or `undefined` when there is no lock file. */\nexport async function readLock(file: string): Promise<ReadonlyMap<string, string> | undefined> {\n let text: string;\n try {\n // A pipe or a device would hang or never end, so only a regular file is read.\n if (!(await stat(file)).isFile()) throw new HarnessError(\"invalid_extension\", `${file} is not a regular file`);\n text = await readFile(file, \"utf8\");\n } catch (error) {\n if ((error as { code?: string }).code === \"ENOENT\") return undefined;\n throw error;\n }\n const parsed = parseObject(text, file) as { version?: unknown; extensions?: Record<string, unknown> };\n if (parsed.version !== LOCK_VERSION || typeof parsed.extensions !== \"object\" || parsed.extensions === null) {\n throw new HarnessError(\"invalid_extension\", `the lock file ${file} is not an extensions.lock.json of version 1`);\n }\n const pins = new Map<string, string>();\n for (const [name, hash] of Object.entries(parsed.extensions)) {\n if (typeof hash !== \"string\")\n throw new HarnessError(\"invalid_extension\", `the lock file pins \"${name}\" to no hash`);\n pins.set(name, hash);\n }\n return pins;\n}\n\n/** Writes the lock file for these pins, replacing the old one in one step. */\nexport async function writeLock(file: string, pins: ReadonlyMap<string, string>): Promise<void> {\n const body = {\n version: LOCK_VERSION,\n extensions: Object.fromEntries([...pins].sort(([a], [b]) => (a < b ? -1 : 1))),\n };\n await mkdir(dirname(file), { recursive: true });\n const temp = `${file}.${globalThis.crypto.randomUUID()}.tmp`;\n try {\n await writeFile(temp, `${JSON.stringify(body, null, 2)}\\n`);\n await rename(temp, file);\n } catch (error) {\n await rm(temp, { force: true });\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AAI,EAAE,CAAC,CAAC;QAChC,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["/**\n * Content-hash pins for project extensions and MCP tools. An extension is a folder; its hash covers every file in it, in\n * sorted order, each by its path and its own SHA-256, so a changed, added, removed or renamed file changes the hash.\n * The lock file, `extensions.lock.json`, holds one hash per extension folder under `extensions`, and under `mcp` the\n * approved definition hash of each tool of each MCP server:\n *\n * ```json\n * { \"version\": 1, \"extensions\": { \"audit\": \"sha256:…\" }, \"mcp\": { \"docs\": { \"tools\": { \"search\": \"sha256:…\" } } } }\n * ```\n *\n * Each writer keeps the other's member, and every write to one path in this process runs after the one before it. A\n * file with no `extensions` member pins no extension, so writing MCP pins alone leaves a project's extensions unpinned\n * rather than refused. `writeLock()` replaces a file it can't read; `writeMcpPins()` refuses one. Node-only: it reads\n * and writes files.\n */\nimport { createHash } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { mkdir, open, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { HarnessError } from \"../errors.js\";\n\nconst LOCK_VERSION = 1;\nconst MAX_LOCK_BYTES = 1024 * 1024;\n\n/** Every file under `dir`, as paths relative to it with `/` separators, in sorted order. */\nasync function filesUnder(dir: string, prefix = \"\"): Promise<string[]> {\n const entries = await readdir(join(dir, prefix), { withFileTypes: true });\n const found: string[] = [];\n for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {\n const relative = prefix === \"\" ? entry.name : `${prefix}/${entry.name}`;\n if (entry.isDirectory()) found.push(...(await filesUnder(dir, relative)));\n else if (entry.isFile()) found.push(relative);\n // A link or a device file is not hashed but would still be followed by an import, so it cannot be pinned.\n else\n throw new HarnessError(\n \"invalid_extension\",\n `${join(dir, relative)} is a link or a special file, which an extension may not contain`,\n );\n }\n return found;\n}\n\n/** The hash of an extension folder: `sha256:` and the digest over each file's path and content digest, in sorted order. */\nexport async function hashExtensionDir(dir: string): Promise<string> {\n const total = createHash(\"sha256\");\n for (const file of await filesUnder(dir)) {\n const content = createHash(\"sha256\")\n .update(await readFile(join(dir, file)))\n .digest(\"hex\");\n total.update(`${file}\\0${content}\\n`);\n }\n return `sha256:${total.digest(\"hex\")}`;\n}\n\n/** Parses JSON that must be an object, or throws `invalid_extension` naming the file. */\nexport function parseObject(text: string, file: string): Record<string, unknown> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new HarnessError(\"invalid_extension\", `${file} is not valid JSON`);\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new HarnessError(\"invalid_extension\", `${file} is not a JSON object`);\n }\n return parsed as Record<string, unknown>;\n}\n\ntype LockBody = { version?: unknown; extensions?: unknown; mcp?: unknown };\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * The lock file's text, or `undefined` when there is none. It is checked and read through one handle, so a file\n * swapped in between the two is never read: the open refuses a link and does not wait on a pipe, the handle must be a\n * regular file within the cap, and no more than the cap and one byte is ever read.\n */\nasync function readCapped(file: string): Promise<string | undefined> {\n let handle: import(\"node:fs/promises\").FileHandle;\n try {\n handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));\n } catch (error) {\n const code = (error as { code?: string }).code;\n if (code === \"ENOENT\") return undefined;\n if (code === \"ELOOP\")\n throw new HarnessError(\"invalid_extension\", `${file} is a link, which a lock file may not be`);\n throw error;\n }\n try {\n const found = await handle.stat();\n // A pipe or a device would hang or never end, so only a regular file is read.\n if (!found.isFile()) throw new HarnessError(\"invalid_extension\", `${file} is not a regular file`);\n const tooBig = () =>\n new HarnessError(\"invalid_extension\", `${file} is over ${MAX_LOCK_BYTES} bytes, which no lock file needs`);\n if (found.size > MAX_LOCK_BYTES) throw tooBig();\n const buffer = new Uint8Array(MAX_LOCK_BYTES + 1);\n let length = 0;\n for (;;) {\n const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);\n if (bytesRead === 0) break;\n length += bytesRead;\n if (length > MAX_LOCK_BYTES) throw tooBig();\n }\n return new TextDecoder().decode(buffer.subarray(0, length));\n } finally {\n await handle.close();\n }\n}\n\n/** The lock file's parsed body, checked for its version and the shape of both members, or `undefined` without one. */\nasync function readBody(file: string): Promise<LockBody | undefined> {\n const text = await readCapped(file);\n if (text === undefined) return undefined;\n const parsed = parseObject(text, file) as LockBody;\n const badMember = (value: unknown) => value !== undefined && !isObject(value);\n if (parsed.version !== LOCK_VERSION || badMember(parsed.extensions) || badMember(parsed.mcp)) {\n throw new HarnessError(\"invalid_extension\", `the lock file ${file} is not an extensions.lock.json of version 1`);\n }\n return parsed;\n}\n\n/**\n * The pins in a lock file, by extension folder name, or `undefined` when there is no lock file or it pins no\n * extension, because it holds MCP pins alone.\n */\nexport async function readLock(file: string): Promise<ReadonlyMap<string, string> | undefined> {\n const body = await readBody(file);\n if (body?.extensions === undefined) return undefined;\n const pins = new Map<string, string>();\n for (const [name, hash] of Object.entries(body.extensions as Record<string, unknown>)) {\n if (typeof hash !== \"string\")\n throw new HarnessError(\"invalid_extension\", `the lock file pins \"${name}\" to no hash`);\n pins.set(name, hash);\n }\n return pins;\n}\n\nconst sorted = (entries: Iterable<readonly [string, unknown]>) =>\n Object.fromEntries([...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));\n\n// The writes waiting on each lock file, by its resolved path, so every writer in this process, `writeLock()` and every\n// `fileMcpPinStore()` alike, reads and replaces the file one after another and none loses another's change.\nconst queues = new Map<string, Promise<unknown>>();\n\n/** Runs `work` after every earlier write to the same file in this process has settled. */\nfunction serially<T>(file: string, work: () => Promise<T>): Promise<T> {\n const key = resolve(file);\n const run = (queues.get(key) ?? Promise.resolve()).then(work);\n const settled = run.catch(() => {});\n queues.set(key, settled);\n void settled.then(() => {\n if (queues.get(key) === settled) queues.delete(key);\n });\n return run;\n}\n\n/** The lock file's body, or `undefined` when there is none or it can't be read as a lock file. */\nasync function readBodyOrNone(file: string): Promise<LockBody | undefined> {\n try {\n return await readBody(file);\n } catch (error) {\n if (error instanceof HarnessError && error.code === \"invalid_extension\") return undefined;\n throw error;\n }\n}\n\n/**\n * Writes the lock file for these extension pins, keeping its MCP pins, and replaces the old file in one step. A lock\n * file that can't be read as one, such as one left with merge-conflict markers, is replaced whole, so a person can\n * repin a broken file; its MCP pins go with it, and their tools wait for approval again.\n */\nexport function writeLock(file: string, pins: ReadonlyMap<string, string>): Promise<void> {\n return serially(file, async () => {\n const before = await readBodyOrNone(file);\n await writeBody(file, {\n version: LOCK_VERSION,\n extensions: sorted(pins),\n ...(before?.mcp === undefined ? {} : { mcp: before.mcp }),\n });\n });\n}\n\n/** The MCP pins of one server in a lock file, by tool name, or `undefined` when it holds none for the server. */\nexport async function readMcpPins(file: string, server: string): Promise<Readonly<Record<string, string>> | undefined> {\n const body = await readBody(file);\n const servers = (body?.mcp ?? {}) as Record<string, unknown>;\n if (!Object.hasOwn(servers, server)) return undefined;\n const entry = servers[server];\n if (!isObject(entry) || !isObject(entry.tools)) {\n throw new HarnessError(\"invalid_extension\", `the lock file ${file} holds no tool pins for \"${server}\"`);\n }\n const pins: Record<string, string> = {};\n for (const [name, hash] of Object.entries(entry.tools)) {\n if (typeof hash !== \"string\") throw new HarnessError(\"invalid_extension\", `the lock file pins a tool to no hash`);\n Object.defineProperty(pins, name, { value: hash, enumerable: true, writable: true, configurable: true });\n }\n return pins;\n}\n\n/**\n * Replaces the MCP pins of one server in a lock file, keeping every other member. It throws `invalid_extension` for a\n * lock file it can't read, rather than replace it: a file without its extension pins would let unpinned extensions load.\n */\nexport function writeMcpPins(file: string, server: string, pins: Readonly<Record<string, string>>): Promise<void> {\n return serially(file, async () => {\n const before = await readBody(file);\n const servers = { ...((before?.mcp ?? {}) as Record<string, unknown>) };\n Object.defineProperty(servers, server, {\n value: { tools: sorted(Object.entries(pins)) },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n await writeBody(file, {\n version: LOCK_VERSION,\n ...(before?.extensions === undefined ? {} : { extensions: before.extensions }),\n mcp: sorted(Object.entries(servers)),\n });\n });\n}\n\n/** Writes a lock file's body, replacing the old one in one step. */\nasync function writeBody(file: string, body: Record<string, unknown>): Promise<void> {\n await mkdir(dirname(file), { recursive: true });\n const temp = `${file}.${globalThis.crypto.randomUUID()}.tmp`;\n try {\n await writeFile(temp, `${JSON.stringify(body, null, 2)}\\n`);\n await rename(temp, file);\n } catch (error) {\n await rm(temp, { force: true });\n throw error;\n }\n}\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `fileMcpPinStore()`: MCP tool pins kept in a project's `extensions.lock.json`, beside the extension pins, so a
|
|
3
|
+
* person reviews and commits both in one file. Node-only: it reads and writes the file.
|
|
4
|
+
*/
|
|
5
|
+
import type { McpPinStore } from "../mcp/types.js";
|
|
6
|
+
/**
|
|
7
|
+
* A pin store over the lock file at `lockFile`, such as `.agents/extensions.lock.json`. Every write to one path in
|
|
8
|
+
* this process, through any store or `writeLock()`, runs after the ones before it, and each replaces the file in one
|
|
9
|
+
* step, keeping its extension pins. A missing file holds no pins, and a file that can't be read is refused, not
|
|
10
|
+
* replaced. Two paths that name one file through a link, or a write from another process, can still lose a change.
|
|
11
|
+
*
|
|
12
|
+
* The lock file sits in the project, so whoever can commit to the project can approve definitions for any server the
|
|
13
|
+
* host configures: give a project's pins to the manager only for a project the person trusts, as project extensions
|
|
14
|
+
* load only then. A lock file that is a link, or over 1 MiB, is refused.
|
|
15
|
+
*/
|
|
16
|
+
export declare function fileMcpPinStore(lockFile: string): McpPinStore;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { readMcpPins, writeMcpPins } from "./lock.js";
|
|
2
|
+
/**
|
|
3
|
+
* A pin store over the lock file at `lockFile`, such as `.agents/extensions.lock.json`. Every write to one path in
|
|
4
|
+
* this process, through any store or `writeLock()`, runs after the ones before it, and each replaces the file in one
|
|
5
|
+
* step, keeping its extension pins. A missing file holds no pins, and a file that can't be read is refused, not
|
|
6
|
+
* replaced. Two paths that name one file through a link, or a write from another process, can still lose a change.
|
|
7
|
+
*
|
|
8
|
+
* The lock file sits in the project, so whoever can commit to the project can approve definitions for any server the
|
|
9
|
+
* host configures: give a project's pins to the manager only for a project the person trusts, as project extensions
|
|
10
|
+
* load only then. A lock file that is a link, or over 1 MiB, is refused.
|
|
11
|
+
*/
|
|
12
|
+
export function fileMcpPinStore(lockFile) {
|
|
13
|
+
return {
|
|
14
|
+
read: (server) => readMcpPins(lockFile, server),
|
|
15
|
+
write: (server, pins) => writeMcpPins(lockFile, server, pins),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=mcp-pins-node.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-pins-node.js","sourceRoot":"","sources":["../../src/extensions/mcp-pins-node.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEtD;;;;;;;;;GASG;AACH,MAAM,UAAU,eAAe,CAAC,QAAgB;IAC9C,OAAO;QACL,IAAI,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,WAAW,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC/C,KAAK,EAAE,CAAC,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC;KAC9D,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `fileMcpPinStore()`: MCP tool pins kept in a project's `extensions.lock.json`, beside the extension pins, so a\n * person reviews and commits both in one file. Node-only: it reads and writes the file.\n */\nimport type { McpPinStore } from \"../mcp/types.js\";\nimport { readMcpPins, writeMcpPins } from \"./lock.js\";\n\n/**\n * A pin store over the lock file at `lockFile`, such as `.agents/extensions.lock.json`. Every write to one path in\n * this process, through any store or `writeLock()`, runs after the ones before it, and each replaces the file in one\n * step, keeping its extension pins. A missing file holds no pins, and a file that can't be read is refused, not\n * replaced. Two paths that name one file through a link, or a write from another process, can still lose a change.\n *\n * The lock file sits in the project, so whoever can commit to the project can approve definitions for any server the\n * host configures: give a project's pins to the manager only for a project the person trusts, as project extensions\n * load only then. A lock file that is a link, or over 1 MiB, is refused.\n */\nexport function fileMcpPinStore(lockFile: string): McpPinStore {\n return {\n read: (server) => readMcpPins(lockFile, server),\n write: (server, pins) => writeMcpPins(lockFile, server, pins),\n };\n}\n"]}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `@buildanagent/harness/extensions/node`: loading the extensions a project supplies, with the trust file and the lock
|
|
3
|
-
* file. It needs Node's file system; the portable parts are in
|
|
3
|
+
* file, and the lock file's MCP tool pins. It needs Node's file system; the portable parts are in
|
|
4
|
+
* `@buildanagent/harness/extensions`.
|
|
4
5
|
*/
|
|
5
6
|
export { contextFiles, type FoundContextFiles, planFileSource } from "./context-files-node.js";
|
|
6
7
|
export { type LoadOptions, loadProjectExtensions, type ProjectExtensions, pinProjectExtensions } from "./load.js";
|
|
7
|
-
export { hashExtensionDir, readLock, writeLock } from "./lock.js";
|
|
8
|
+
export { hashExtensionDir, readLock, readMcpPins, writeLock, writeMcpPins } from "./lock.js";
|
|
9
|
+
export { fileMcpPinStore } from "./mcp-pins-node.js";
|
|
8
10
|
export { type DiscoveredSkills, type DiscoverSkillsOptions, discoverSkills } from "./skills-node.js";
|
|
9
11
|
export { fileTrustStore } from "./trust-file.js";
|
|
10
12
|
export { realPathTrustStore } from "./trust-store-node.js";
|
package/dist/extensions/node.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `@buildanagent/harness/extensions/node`: loading the extensions a project supplies, with the trust file and the lock
|
|
3
|
-
* file. It needs Node's file system; the portable parts are in
|
|
3
|
+
* file, and the lock file's MCP tool pins. It needs Node's file system; the portable parts are in
|
|
4
|
+
* `@buildanagent/harness/extensions`.
|
|
4
5
|
*/
|
|
5
6
|
export { contextFiles, planFileSource } from "./context-files-node.js";
|
|
6
7
|
export { loadProjectExtensions, pinProjectExtensions } from "./load.js";
|
|
7
|
-
export { hashExtensionDir, readLock, writeLock } from "./lock.js";
|
|
8
|
+
export { hashExtensionDir, readLock, readMcpPins, writeLock, writeMcpPins } from "./lock.js";
|
|
9
|
+
export { fileMcpPinStore } from "./mcp-pins-node.js";
|
|
8
10
|
export { discoverSkills } from "./skills-node.js";
|
|
9
11
|
export { fileTrustStore } from "./trust-file.js";
|
|
10
12
|
export { realPathTrustStore } from "./trust-store-node.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.js","sourceRoot":"","sources":["../../src/extensions/node.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"node.js","sourceRoot":"","sources":["../../src/extensions/node.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,YAAY,EAA0B,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAC/F,OAAO,EAAoB,qBAAqB,EAA0B,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAClH,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAC7F,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAqD,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACrG,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/extensions/node`: loading the extensions a project supplies, with the trust file and the lock\n * file, and the lock file's MCP tool pins. It needs Node's file system; the portable parts are in\n * `@buildanagent/harness/extensions`.\n */\n\nexport { contextFiles, type FoundContextFiles, planFileSource } from \"./context-files-node.js\";\nexport { type LoadOptions, loadProjectExtensions, type ProjectExtensions, pinProjectExtensions } from \"./load.js\";\nexport { hashExtensionDir, readLock, readMcpPins, writeLock, writeMcpPins } from \"./lock.js\";\nexport { fileMcpPinStore } from \"./mcp-pins-node.js\";\nexport { type DiscoveredSkills, type DiscoverSkillsOptions, discoverSkills } from \"./skills-node.js\";\nexport { fileTrustStore } from \"./trust-file.js\";\nexport { realPathTrustStore } from \"./trust-store-node.js\";\n"]}
|
package/dist/harness.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ import type { Skill } from "./extensions/skills.js";
|
|
|
14
14
|
import type { ExtensionLoadedRecord } from "./extensions/types.js";
|
|
15
15
|
import type { PermissionPipeline } from "./permissions/types.js";
|
|
16
16
|
import type { Session } from "./session/session.js";
|
|
17
|
-
import type { ToolRegistry, ToolWrapper } from "./tools/types.js";
|
|
17
|
+
import type { ToolRegistry, ToolWrapper, TurnBoundary } from "./tools/types.js";
|
|
18
18
|
/** What the session's `env_stamp` records about where the turns run. */
|
|
19
19
|
export interface HarnessEnv {
|
|
20
20
|
readonly cwd: string;
|
|
@@ -60,6 +60,12 @@ export interface HarnessOptions<H = unknown> {
|
|
|
60
60
|
* resolve against `env.cwd`.
|
|
61
61
|
*/
|
|
62
62
|
readonly skills?: readonly Skill[];
|
|
63
|
+
/**
|
|
64
|
+
* Components that change tools between turns, such as an MCP manager. Each turn calls their `beginTurn()` in order
|
|
65
|
+
* before it builds its tools, and writes the notices they return in front of its input, so the model reads what
|
|
66
|
+
* changed and the tools a request sends stay as they are. A resumed turn and a code call run no boundary.
|
|
67
|
+
*/
|
|
68
|
+
readonly turnBoundaries?: readonly TurnBoundary[];
|
|
63
69
|
/** Observers that see every event of every turn, after the runner's own. A code call emits no events. */
|
|
64
70
|
readonly observers?: readonly Observer[];
|
|
65
71
|
/** Binds a tool to the turn's host context, such as a write cap. A tool can also read it as `ctx.app`. */
|
package/dist/harness.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"harness.js","sourceRoot":"","sources":["../src/harness.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The harness's types: the settings every turn of a harness shares, and the code calls it runs. A turn can override the\n * model, the system prompt and the tools; what it can't override, such as the registry and the permission pipeline, is\n * fixed here. `H` is the type of the per-turn host context, which reaches a tool's `execute` as `ctx.app` and is in no\n * request, event or saved entry. `createHarness()` lives in its own module, because it binds the code-call runner,\n * which imports these types.\n */\nimport type { Model } from \"@buildanagent/gateway\";\nimport type { ApprovalPolicy, PermissionMode, SandboxTier } from \"@buildanagent/protocol\";\nimport type { ApprovalSigner, Interceptors, Observer, SignedPendingRequest, ToolResult } from \"@buildanagent/sdk\";\nimport type { Clock } from \"@buildanagent/sdk/testing\";\nimport type { ContextPolicy } from \"./context/types.js\";\nimport type { Skill } from \"./extensions/skills.js\";\nimport type { ExtensionLoadedRecord } from \"./extensions/types.js\";\nimport type { PermissionPipeline } from \"./permissions/types.js\";\nimport type { Session } from \"./session/session.js\";\nimport type { ToolRegistry, ToolWrapper } from \"./tools/types.js\";\n\n/** What the session's `env_stamp` records about where the turns run. */\nexport interface HarnessEnv {\n readonly cwd: string;\n readonly permissionMode: PermissionMode;\n readonly approvalPolicy: ApprovalPolicy;\n readonly sandbox: SandboxTier;\n}\n\n/** The options of `createHarness()`. */\nexport interface HarnessOptions<H = unknown> {\n readonly registry: ToolRegistry;\n /** The model a turn uses unless it names another. */\n readonly model: Model;\n /** The system prompt a turn uses unless it names another. */\n readonly system: string;\n /** What `env_stamp` records. A field left out takes `/`, `default`, `on-request` or `none`. */\n readonly env?: Partial<HarnessEnv>;\n /**\n * The tenant a write acts for: one tenant is one user, so a business key never spans two users. Default `local`,\n * for a host that has one user. `effectScope()` puts it in the scope a guarded write takes.\n */\n readonly tenant?: string;\n /** The harness's version, stamped into each session header. */\n readonly harnessVersion?: string;\n /** A hash of the ablation switches, stamped into each session header. Default `none`. */\n readonly ablationHash?: string;\n /** When set, its gate decides every tool call, and each decision is written to the log. */\n readonly pipeline?: PermissionPipeline;\n /**\n * Hooks that run with the pipeline's gate in every turn, before it for a gate, as `composeInterceptors()` orders\n * them. A code call from `invokeTool()` runs no turn, so they don't see it.\n */\n readonly interceptors?: Interceptors;\n /** The context layers every turn runs through, from `createContextPolicy()`. Without one a turn sends its whole transcript. */\n readonly context?: ContextPolicy;\n /**\n * The extensions this harness runs, as `recordsOf()` or `loadProjectExtensions()` gives them. A turn writes an\n * `extension_loaded` entry for each the session's log does not hold yet, so a session shows which code ran.\n */\n readonly extensionRecords?: readonly ExtensionLoadedRecord[];\n /**\n * The skills the system prompt lists, as `discoverSkills()` gives them. When a successful `read` call opens the whole\n * of one's `SKILL.md`, with no `offset` or `limit`, the turn writes a `skill_loaded` entry. Relative paths in the call\n * resolve against `env.cwd`.\n */\n readonly skills?: readonly Skill[];\n /** Observers that see every event of every turn, after the runner's own. A code call emits no events. */\n readonly observers?: readonly Observer[];\n /** Binds a tool to the turn's host context, such as a write cap. A tool can also read it as `ctx.app`. */\n readonly wrap?: ToolWrapper<H>;\n /** Signs the pauses a turn ends in. */\n readonly signer?: ApprovalSigner;\n}\n\n/** A tool call that the host's own code makes with `Harness.invokeTool()`, with no model step. */\nexport interface CodeCall<H = unknown> {\n /** The tool's name or alias in the registry. */\n readonly tool: string;\n /** The input the tool runs with. It is recorded and hashed as given, so it must have a canonical JSON form. */\n readonly input: unknown;\n /**\n * The host context the tool runs with, as `ctx.app`. A call that asks for a person binds a MAC of it into the signed\n * request, so `Approvals.resolve()` runs the call only when it is given the same host context.\n */\n readonly hostContext?: H;\n /**\n * The call id of an earlier code call that this one undoes. The earlier call must have run, and this call must reach\n * an effect key of its own. The `code_call` entry records the link.\n */\n readonly compensates?: string;\n /** Aborts the call. An aborted signal before the call starts writes nothing; the tool receives it as `ctx.signal`. */\n readonly signal?: AbortSignal;\n /** The clock of the entries, the signed request and the tool's `ctx.clock`. Default the system clock. */\n readonly clock?: Clock;\n /** Makes the ids of the entries, the call and the signed request. Default `crypto.randomUUID()`. */\n readonly newId?: () => string;\n}\n\n/**\n * What a code call ended in.\n *\n * - `done`: the tool ran. `result` is the whole of what it returned, with a write outcome's sentence in front of its\n * content, even when the call's `tool_result` entry holds it capped.\n * - `denied`: the permission pipeline or a person refused the call. The tool never ran.\n * - `awaiting_approval`: a person must answer `pending` through `Approvals.resolve()`. It has no `entryId`.\n *\n * `entryId` is the id of the call's `tool_result` entry. `effectKey` is the call's effect identity: from the tool's\n * business key when it declares one, and otherwise from the call id, which is the id of the call's `code_call` entry.\n */\nexport type CodeCallResult =\n | {\n readonly status: \"done\";\n readonly callId: string;\n readonly result: ToolResult<unknown>;\n readonly entryId: string;\n readonly effectKey: string;\n }\n | { readonly status: \"denied\"; readonly callId: string; readonly reason: string; readonly entryId: string }\n | {\n readonly status: \"awaiting_approval\";\n readonly callId: string;\n readonly pending: SignedPendingRequest;\n readonly effectKey: string;\n };\n\n/** A harness: its options with the defaults filled in. */\nexport interface Harness<H = unknown> extends HarnessOptions<H> {\n readonly env: HarnessEnv;\n readonly tenant: string;\n readonly harnessVersion: string;\n readonly ablationHash: string;\n /**\n * Runs a tool call that the host's own code chose, through the same permission pipeline, signed pause and log as a\n * call the model makes, with no model call. The session must be open with its lock.\n *\n * The call's own entries start with a `code_call` entry, then the pipeline's `permission_decision`. Before them it\n * writes what the session lacks: a new session's header and environment stamp, and a result for each earlier code\n * call a crash left open.\n *\n * The call ends one of three ways:\n *\n * - An allow runs the tool through the harness's `wrap` with `call.hostContext`, writes its `tool_result` and returns\n * `done`. The harness's `context` policy caps the stored result, and the store's entry bound cuts it to fit, with\n * its outcome kept.\n * - A deny writes an error `tool_result` and returns `denied`.\n * - An ask that no sticky allowance covers writes an `approval_requested` entry, signed as `createPendingRequest()`\n * signs it, and returns `awaiting_approval`. `Approvals.resolve()` answers it.\n *\n * A code call runs no turn, so the harness's `interceptors` and `observers` don't see it. Put a guard that must cover\n * code calls in the pipeline's hooks, which see `initiator: \"code\"`, or in `wrap`.\n *\n * It throws before it writes anything:\n *\n * - `invalid_code_call` for a tool the registry lacks or that runs on the client, an input or host context with no\n * canonical JSON form, a business key that fails, a harness with no permission pipeline, or a compensation that\n * names no code call that ran or would share that call's effect key.\n * - `approval_unavailable` for a harness with no signer.\n * - The signal's reason for a signal aborted before the call starts.\n */\n invokeTool(this: Harness<H>, session: Session, call: CodeCall<H>): Promise<CodeCallResult>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"harness.js","sourceRoot":"","sources":["../src/harness.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The harness's types: the settings every turn of a harness shares, and the code calls it runs. A turn can override the\n * model, the system prompt and the tools; what it can't override, such as the registry and the permission pipeline, is\n * fixed here. `H` is the type of the per-turn host context, which reaches a tool's `execute` as `ctx.app` and is in no\n * request, event or saved entry. `createHarness()` lives in its own module, because it binds the code-call runner,\n * which imports these types.\n */\nimport type { Model } from \"@buildanagent/gateway\";\nimport type { ApprovalPolicy, PermissionMode, SandboxTier } from \"@buildanagent/protocol\";\nimport type { ApprovalSigner, Interceptors, Observer, SignedPendingRequest, ToolResult } from \"@buildanagent/sdk\";\nimport type { Clock } from \"@buildanagent/sdk/testing\";\nimport type { ContextPolicy } from \"./context/types.js\";\nimport type { Skill } from \"./extensions/skills.js\";\nimport type { ExtensionLoadedRecord } from \"./extensions/types.js\";\nimport type { PermissionPipeline } from \"./permissions/types.js\";\nimport type { Session } from \"./session/session.js\";\nimport type { ToolRegistry, ToolWrapper, TurnBoundary } from \"./tools/types.js\";\n\n/** What the session's `env_stamp` records about where the turns run. */\nexport interface HarnessEnv {\n readonly cwd: string;\n readonly permissionMode: PermissionMode;\n readonly approvalPolicy: ApprovalPolicy;\n readonly sandbox: SandboxTier;\n}\n\n/** The options of `createHarness()`. */\nexport interface HarnessOptions<H = unknown> {\n readonly registry: ToolRegistry;\n /** The model a turn uses unless it names another. */\n readonly model: Model;\n /** The system prompt a turn uses unless it names another. */\n readonly system: string;\n /** What `env_stamp` records. A field left out takes `/`, `default`, `on-request` or `none`. */\n readonly env?: Partial<HarnessEnv>;\n /**\n * The tenant a write acts for: one tenant is one user, so a business key never spans two users. Default `local`,\n * for a host that has one user. `effectScope()` puts it in the scope a guarded write takes.\n */\n readonly tenant?: string;\n /** The harness's version, stamped into each session header. */\n readonly harnessVersion?: string;\n /** A hash of the ablation switches, stamped into each session header. Default `none`. */\n readonly ablationHash?: string;\n /** When set, its gate decides every tool call, and each decision is written to the log. */\n readonly pipeline?: PermissionPipeline;\n /**\n * Hooks that run with the pipeline's gate in every turn, before it for a gate, as `composeInterceptors()` orders\n * them. A code call from `invokeTool()` runs no turn, so they don't see it.\n */\n readonly interceptors?: Interceptors;\n /** The context layers every turn runs through, from `createContextPolicy()`. Without one a turn sends its whole transcript. */\n readonly context?: ContextPolicy;\n /**\n * The extensions this harness runs, as `recordsOf()` or `loadProjectExtensions()` gives them. A turn writes an\n * `extension_loaded` entry for each the session's log does not hold yet, so a session shows which code ran.\n */\n readonly extensionRecords?: readonly ExtensionLoadedRecord[];\n /**\n * The skills the system prompt lists, as `discoverSkills()` gives them. When a successful `read` call opens the whole\n * of one's `SKILL.md`, with no `offset` or `limit`, the turn writes a `skill_loaded` entry. Relative paths in the call\n * resolve against `env.cwd`.\n */\n readonly skills?: readonly Skill[];\n /**\n * Components that change tools between turns, such as an MCP manager. Each turn calls their `beginTurn()` in order\n * before it builds its tools, and writes the notices they return in front of its input, so the model reads what\n * changed and the tools a request sends stay as they are. A resumed turn and a code call run no boundary.\n */\n readonly turnBoundaries?: readonly TurnBoundary[];\n /** Observers that see every event of every turn, after the runner's own. A code call emits no events. */\n readonly observers?: readonly Observer[];\n /** Binds a tool to the turn's host context, such as a write cap. A tool can also read it as `ctx.app`. */\n readonly wrap?: ToolWrapper<H>;\n /** Signs the pauses a turn ends in. */\n readonly signer?: ApprovalSigner;\n}\n\n/** A tool call that the host's own code makes with `Harness.invokeTool()`, with no model step. */\nexport interface CodeCall<H = unknown> {\n /** The tool's name or alias in the registry. */\n readonly tool: string;\n /** The input the tool runs with. It is recorded and hashed as given, so it must have a canonical JSON form. */\n readonly input: unknown;\n /**\n * The host context the tool runs with, as `ctx.app`. A call that asks for a person binds a MAC of it into the signed\n * request, so `Approvals.resolve()` runs the call only when it is given the same host context.\n */\n readonly hostContext?: H;\n /**\n * The call id of an earlier code call that this one undoes. The earlier call must have run, and this call must reach\n * an effect key of its own. The `code_call` entry records the link.\n */\n readonly compensates?: string;\n /** Aborts the call. An aborted signal before the call starts writes nothing; the tool receives it as `ctx.signal`. */\n readonly signal?: AbortSignal;\n /** The clock of the entries, the signed request and the tool's `ctx.clock`. Default the system clock. */\n readonly clock?: Clock;\n /** Makes the ids of the entries, the call and the signed request. Default `crypto.randomUUID()`. */\n readonly newId?: () => string;\n}\n\n/**\n * What a code call ended in.\n *\n * - `done`: the tool ran. `result` is the whole of what it returned, with a write outcome's sentence in front of its\n * content, even when the call's `tool_result` entry holds it capped.\n * - `denied`: the permission pipeline or a person refused the call. The tool never ran.\n * - `awaiting_approval`: a person must answer `pending` through `Approvals.resolve()`. It has no `entryId`.\n *\n * `entryId` is the id of the call's `tool_result` entry. `effectKey` is the call's effect identity: from the tool's\n * business key when it declares one, and otherwise from the call id, which is the id of the call's `code_call` entry.\n */\nexport type CodeCallResult =\n | {\n readonly status: \"done\";\n readonly callId: string;\n readonly result: ToolResult<unknown>;\n readonly entryId: string;\n readonly effectKey: string;\n }\n | { readonly status: \"denied\"; readonly callId: string; readonly reason: string; readonly entryId: string }\n | {\n readonly status: \"awaiting_approval\";\n readonly callId: string;\n readonly pending: SignedPendingRequest;\n readonly effectKey: string;\n };\n\n/** A harness: its options with the defaults filled in. */\nexport interface Harness<H = unknown> extends HarnessOptions<H> {\n readonly env: HarnessEnv;\n readonly tenant: string;\n readonly harnessVersion: string;\n readonly ablationHash: string;\n /**\n * Runs a tool call that the host's own code chose, through the same permission pipeline, signed pause and log as a\n * call the model makes, with no model call. The session must be open with its lock.\n *\n * The call's own entries start with a `code_call` entry, then the pipeline's `permission_decision`. Before them it\n * writes what the session lacks: a new session's header and environment stamp, and a result for each earlier code\n * call a crash left open.\n *\n * The call ends one of three ways:\n *\n * - An allow runs the tool through the harness's `wrap` with `call.hostContext`, writes its `tool_result` and returns\n * `done`. The harness's `context` policy caps the stored result, and the store's entry bound cuts it to fit, with\n * its outcome kept.\n * - A deny writes an error `tool_result` and returns `denied`.\n * - An ask that no sticky allowance covers writes an `approval_requested` entry, signed as `createPendingRequest()`\n * signs it, and returns `awaiting_approval`. `Approvals.resolve()` answers it.\n *\n * A code call runs no turn, so the harness's `interceptors` and `observers` don't see it. Put a guard that must cover\n * code calls in the pipeline's hooks, which see `initiator: \"code\"`, or in `wrap`.\n *\n * It throws before it writes anything:\n *\n * - `invalid_code_call` for a tool the registry lacks or that runs on the client, an input or host context with no\n * canonical JSON form, a business key that fails, a harness with no permission pipeline, or a compensation that\n * names no code call that ran or would share that call's effect key.\n * - `approval_unavailable` for a harness with no signer.\n * - The signal's reason for a signal aborted before the call starts.\n */\n invokeTool(this: Harness<H>, session: Session, call: CodeCall<H>): Promise<CodeCallResult>;\n}\n"]}
|
package/dist/mcp/connection.d.ts
CHANGED
|
@@ -1,16 +1,21 @@
|
|
|
1
|
-
import type { McpConnection, McpServerConfig } from "./types.js";
|
|
1
|
+
import type { McpConnection, McpServerConfig, McpTimers } from "./types.js";
|
|
2
|
+
/** The platform's timers, which never hold a Node process open on their own. */
|
|
3
|
+
export declare const systemTimers: McpTimers;
|
|
2
4
|
/** A server's settings with their defaults, checked. Throws a `HarnessError`, code `invalid_mcp_config`. */
|
|
3
5
|
export declare function checkServerConfig(config: McpServerConfig): {
|
|
4
6
|
connectMs: number;
|
|
5
7
|
probeMs: number;
|
|
6
8
|
requestMs: number;
|
|
7
9
|
maxTools: number;
|
|
10
|
+
secrets: readonly string[];
|
|
8
11
|
};
|
|
9
12
|
/**
|
|
10
13
|
* Connects one server and negotiates its era. A stdio server that exits cleanly after the `server/discover` probe, as
|
|
11
14
|
* servers on some older SDKs do on any request before `initialize`, is started once more and spoken to as a legacy
|
|
12
|
-
* server; a server that crashes runs once.
|
|
13
|
-
* `signal` aborts it, and the server is closed.
|
|
15
|
+
* server; a server that crashes runs once. An `sse` server is spoken to as a legacy server, with no probe. The whole
|
|
16
|
+
* connect, a restart included, takes at most `connectTimeoutMs`. `signal` aborts it, and the server is closed. On a
|
|
17
|
+
* 2026-07-28 server that advertises tool-list changes, the connection opens a `subscriptions/listen` stream for them.
|
|
18
|
+
* `timers` runs the stream's reopen delays; the default is the platform's.
|
|
14
19
|
*
|
|
15
20
|
* Throws a `HarnessError`, code `invalid_mcp_config`, for a config that can't be used, and an `McpError`, code
|
|
16
21
|
* `mcp_connect_failed`, when the server does not start, does not finish the handshake within `connectTimeoutMs`, is
|
|
@@ -19,4 +24,5 @@ export declare function checkServerConfig(config: McpServerConfig): {
|
|
|
19
24
|
export declare function connectMcpServer(config: McpServerConfig, options?: {
|
|
20
25
|
readonly log?: (line: string) => void;
|
|
21
26
|
readonly signal?: AbortSignal;
|
|
27
|
+
readonly timers?: McpTimers;
|
|
22
28
|
}): Promise<McpConnection>;
|