@minhtri2710/pi-durable-shared 0.0.0-stage → 2.0.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/README.md +47 -2
- package/bin/lint-state.sh +15 -0
- package/dist/durable-runtime.d.ts +25 -0
- package/dist/durable-runtime.js +266 -0
- package/dist/mcp-oauth.d.ts +19 -0
- package/dist/mcp-oauth.js +120 -0
- package/dist/mcp-tools.d.ts +42 -0
- package/dist/mcp-tools.js +335 -0
- package/dist/process-state.d.ts +8 -0
- package/dist/process-state.js +13 -0
- package/dist/project-rules.d.ts +6 -0
- package/dist/project-rules.js +84 -0
- package/dist/retention.d.ts +16 -0
- package/dist/retention.js +39 -0
- package/dist/search-tools.d.ts +25 -0
- package/dist/search-tools.js +83 -0
- package/dist/semaphore.d.ts +8 -0
- package/dist/semaphore.js +26 -0
- package/dist/session-lock.d.ts +4 -0
- package/dist/session-lock.js +97 -0
- package/dist/session-store.d.ts +20 -0
- package/dist/session-store.js +42 -0
- package/dist/testing.d.ts +7 -0
- package/dist/testing.js +19 -0
- package/dist/worker-codemode.d.ts +65 -0
- package/dist/worker-codemode.js +98 -0
- package/package.json +61 -4
- package/src/mcp-fixture-server.mjs +13 -0
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir, tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { defineExtension, defineTool } from "@earendil-works/pi-durable";
|
|
7
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { createMcpResultSchema, createMcpToolName, limitMcpContent, McpAuthRequiredError, McpClient, McpInitializeRejectedError, mcpNamespace, McpSessionExpiredError, McpTimeoutError, normalizeMcpInputSchema, STATELESS_PROTOCOL_VERSION, StdioTransport, StreamableHttpTransport, toMcpModelContent, validateMcpServerConfig, } from "@earendil-works/pi-mcp";
|
|
9
|
+
import { McpOAuthAuthorizationRequiredError } from "@earendil-works/pi-mcp/oauth";
|
|
10
|
+
import { processState } from "./process-state.js";
|
|
11
|
+
import { sweepTempFilesOnce } from "./retention.js";
|
|
12
|
+
import { checkMetadataDocumentCallback, usesOAuth, workerAuthProvider } from "./mcp-oauth.js";
|
|
13
|
+
const CONNECT_MS = 20_000;
|
|
14
|
+
/** A set with an unusable server is opened again by a call this long after it, keeping the servers that connected. */
|
|
15
|
+
const RETRY_MS = 30_000;
|
|
16
|
+
// On globalThis, not module-local: a /reload loads this module again, and its own variable would open the servers a second
|
|
17
|
+
// time while the first set stays open. `holders`: the sessions of pi-swarm and pi-teamwork using the set; the last to let go closes it.
|
|
18
|
+
// `readOnly`: the tools of the open set whose server marks them `readOnlyHint`; pi-guards runs those without asking.
|
|
19
|
+
const shared = processState("pi-worker-mcp", () => ({}));
|
|
20
|
+
export function setWorkerMcpAuthResolver(resolver) {
|
|
21
|
+
shared.authResolver = resolver;
|
|
22
|
+
}
|
|
23
|
+
const readJson = (file) => { try {
|
|
24
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (error.code === "ENOENT")
|
|
28
|
+
return undefined;
|
|
29
|
+
throw error;
|
|
30
|
+
} };
|
|
31
|
+
const expandHome = (value) => value === "~" ? homedir() : value.startsWith("~/") || value.startsWith("~\\") ? join(homedir(), value.slice(2)) : value;
|
|
32
|
+
// Mirrors Pi's core/resolve-config-value.js: `$NAME` / `${NAME}` from the environment, `$$` / `$!` escapes, an empty variable is unset; an unset one fails the server instead of sending an empty secret.
|
|
33
|
+
const envValue = (name) => {
|
|
34
|
+
const value = process.env[name] || undefined;
|
|
35
|
+
if (value === undefined)
|
|
36
|
+
throw new Error(`environment variable ${name} is not set`);
|
|
37
|
+
return value;
|
|
38
|
+
};
|
|
39
|
+
export const expand = (text) => {
|
|
40
|
+
let out = "";
|
|
41
|
+
for (let i = 0; i < text.length; i++) {
|
|
42
|
+
if (text[i] !== "$") {
|
|
43
|
+
out += text[i];
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const next = text[i + 1];
|
|
47
|
+
if (next === "$" || next === "!") {
|
|
48
|
+
out += next;
|
|
49
|
+
i++;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (next === "{") {
|
|
53
|
+
const end = text.indexOf("}", i + 2);
|
|
54
|
+
if (end >= 0) {
|
|
55
|
+
const name = text.slice(i + 2, end);
|
|
56
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
57
|
+
out += envValue(name);
|
|
58
|
+
i = end;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(text.slice(i + 1));
|
|
65
|
+
if (match) {
|
|
66
|
+
const name = match[0];
|
|
67
|
+
out += envValue(name);
|
|
68
|
+
i += name.length;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
out += "$";
|
|
73
|
+
}
|
|
74
|
+
return out;
|
|
75
|
+
};
|
|
76
|
+
const expandAll = (record) => record && Object.fromEntries(Object.entries(record).map(([key, value]) => [key, expand(value)]));
|
|
77
|
+
async function saveToTempFile(data, extension) {
|
|
78
|
+
const safeExt = extension.startsWith(".") ? extension : `.${extension}`;
|
|
79
|
+
const file = join(tmpdir(), `pi-mcp-${randomUUID()}${safeExt}`);
|
|
80
|
+
await writeFile(file, data, { flag: "wx", mode: 0o600 });
|
|
81
|
+
return file;
|
|
82
|
+
}
|
|
83
|
+
/** The servers workers use: every server the user-level `<agent dir>/mcp.json` defines that is not `enabled: false`. An invalid one is reported in `errors`. */
|
|
84
|
+
function selectedServers(errors) {
|
|
85
|
+
const defined = readJson(join(getAgentDir(), "mcp.json"))?.mcpServers ?? {};
|
|
86
|
+
const chosen = [];
|
|
87
|
+
const namespaces = new Map();
|
|
88
|
+
for (const name of Object.keys(defined)) {
|
|
89
|
+
const checked = validateMcpServerConfig(name, defined[name], { checkMetadataDocumentCallback });
|
|
90
|
+
if (checked.kind === "invalid") {
|
|
91
|
+
errors.push(checked.error);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (checked.config.enabled === false)
|
|
95
|
+
continue;
|
|
96
|
+
const ns = mcpNamespace(name);
|
|
97
|
+
const existing = namespaces.get(ns);
|
|
98
|
+
if (existing && existing !== name) {
|
|
99
|
+
errors.push(`${name}: server name conflicts with "${existing}"`);
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
namespaces.set(ns, name);
|
|
103
|
+
chosen.push({ name, kind: checked.kind, config: checked.config, fingerprint: JSON.stringify({ kind: checked.kind, config: checked.config }) });
|
|
104
|
+
}
|
|
105
|
+
return chosen;
|
|
106
|
+
}
|
|
107
|
+
function buildTransport(server) {
|
|
108
|
+
const { config } = server;
|
|
109
|
+
if (server.kind === "stdio") {
|
|
110
|
+
return new StdioTransport({
|
|
111
|
+
command: expandHome(config.command),
|
|
112
|
+
args: config.args?.map(expandHome),
|
|
113
|
+
cwd: config.cwd ? expandHome(config.cwd) : undefined,
|
|
114
|
+
env: expandAll(config.env),
|
|
115
|
+
inheritEnv: true,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
const provider = config.auth?.provider;
|
|
119
|
+
const authProvider = usesOAuth(config)
|
|
120
|
+
? workerAuthProvider(server.name, config, expand)
|
|
121
|
+
: provider
|
|
122
|
+
? { token: async () => await shared.authResolver?.(provider), settled: async () => { } }
|
|
123
|
+
: undefined;
|
|
124
|
+
return new StreamableHttpTransport({
|
|
125
|
+
url: config.url,
|
|
126
|
+
headers: expandAll(config.headers),
|
|
127
|
+
...(authProvider ? { authProvider } : {}),
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
async function connectOnce(server, protocolOverride) {
|
|
131
|
+
const { config } = server;
|
|
132
|
+
const transport = buildTransport(server);
|
|
133
|
+
const client = new McpClient({
|
|
134
|
+
name: "pi-workers",
|
|
135
|
+
version: "1.0.0",
|
|
136
|
+
protocol: protocolOverride ?? config.protocol ?? "auto",
|
|
137
|
+
connectTimeoutMs: CONNECT_MS,
|
|
138
|
+
...(config.timeout ? { requestTimeoutMs: config.timeout * 1000 } : {}),
|
|
139
|
+
});
|
|
140
|
+
let timer;
|
|
141
|
+
try {
|
|
142
|
+
// The listing is part of connecting: a server that initializes and then stalls on tools/list would otherwise hold every caller.
|
|
143
|
+
const tools = await Promise.race([
|
|
144
|
+
client.connect(transport).then(() => client.serverCapabilities?.tools ? client.listTools() : []),
|
|
145
|
+
new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error(`no answer in ${CONNECT_MS / 1000}s`)), CONNECT_MS); }),
|
|
146
|
+
]);
|
|
147
|
+
return { client, tools };
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
await client.close().catch(() => { });
|
|
151
|
+
await transport.close().catch(() => { });
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
clearTimeout(timer);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async function connect(server) {
|
|
159
|
+
const { config } = server;
|
|
160
|
+
try {
|
|
161
|
+
return await connectOnce(server);
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
if (server.kind === "stdio" &&
|
|
165
|
+
config.protocol === undefined &&
|
|
166
|
+
error instanceof McpInitializeRejectedError &&
|
|
167
|
+
!(error.discoverError instanceof McpTimeoutError)) {
|
|
168
|
+
try {
|
|
169
|
+
return await connectOnce(server, STATELESS_PROTOCOL_VERSION);
|
|
170
|
+
}
|
|
171
|
+
catch (retryError) {
|
|
172
|
+
error = retryError;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
// Pi's own sign-in serves workers: a server not signed in there is signed in with Pi's command, never by a worker.
|
|
176
|
+
if (error instanceof McpOAuthAuthorizationRequiredError || error instanceof McpAuthRequiredError) {
|
|
177
|
+
const provider = server.kind === "http" ? config.auth?.provider : undefined;
|
|
178
|
+
throw new Error(provider ? `needs sign-in; run: /login ${provider}` : `needs sign-in; run: pi mcp login ${server.name}`);
|
|
179
|
+
}
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/** Connects the selected servers; those `previous` holds connected with unchanged config are kept, and removed or changed ones close. */
|
|
184
|
+
async function open(previous) {
|
|
185
|
+
const errors = [];
|
|
186
|
+
let servers = [];
|
|
187
|
+
try {
|
|
188
|
+
servers = selectedServers(errors);
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
errors.push(`MCP configuration: ${error instanceof Error ? error.message : String(error)}`);
|
|
192
|
+
}
|
|
193
|
+
const byName = new Map(servers.map((server) => [server.name, server]));
|
|
194
|
+
const kept = (previous?.served ?? []).filter((item) => byName.get(item.name)?.fingerprint === item.fingerprint);
|
|
195
|
+
for (const item of previous?.served ?? [])
|
|
196
|
+
if (!kept.includes(item)) {
|
|
197
|
+
item.link.shutdown = true;
|
|
198
|
+
void item.link.client.close().catch(() => { });
|
|
199
|
+
}
|
|
200
|
+
// Connected in parallel, named one by one in name order after: the same servers give the same tool names after a restart.
|
|
201
|
+
const fresh = await Promise.all(servers.filter((server) => !kept.some((item) => item.name === server.name)).map(async (server) => {
|
|
202
|
+
try {
|
|
203
|
+
return { server, ...(await connect(server)) };
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
errors.push(`${server.name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
207
|
+
return undefined;
|
|
208
|
+
}
|
|
209
|
+
}));
|
|
210
|
+
const taken = new Set(kept.flatMap((item) => (item.extension.tools ?? []).map((tool) => tool.name)));
|
|
211
|
+
const served = [...kept];
|
|
212
|
+
for (const { server, client, tools: listed } of fresh.filter((item) => item !== undefined).sort((a, b) => a.server.name.localeCompare(b.server.name))) {
|
|
213
|
+
// A server that drops is connected again by the next call, not before: nothing runs against it while no worker asks. The call it dropped on fails, since it may have run.
|
|
214
|
+
const link = { client, dead: false, shutdown: false };
|
|
215
|
+
const watch = (target) => { target.onClose(() => { if (!link.shutdown && link.client === target)
|
|
216
|
+
link.dead = true; }); };
|
|
217
|
+
watch(client);
|
|
218
|
+
const usable = async () => {
|
|
219
|
+
if (link.shutdown)
|
|
220
|
+
throw new Error(`MCP server ${server.name} is closed`);
|
|
221
|
+
if (!link.dead)
|
|
222
|
+
return link.client;
|
|
223
|
+
link.reconnecting ??= connect(server).then(({ client: fresh }) => {
|
|
224
|
+
// Closed while connecting: the new client is closed too, not left running for no one.
|
|
225
|
+
if (link.shutdown) {
|
|
226
|
+
void fresh.close().catch(() => { });
|
|
227
|
+
throw new Error(`MCP server ${server.name} is closed`);
|
|
228
|
+
}
|
|
229
|
+
link.client = fresh;
|
|
230
|
+
link.dead = false;
|
|
231
|
+
watch(fresh);
|
|
232
|
+
return fresh;
|
|
233
|
+
}).finally(() => { link.reconnecting = undefined; });
|
|
234
|
+
return link.reconnecting;
|
|
235
|
+
};
|
|
236
|
+
const tools = [], readOnly = [];
|
|
237
|
+
for (const tool of listed) {
|
|
238
|
+
const exposure = (server.config.toolExposure?.[tool.name] ?? server.config.exposure);
|
|
239
|
+
if (exposure === "hidden")
|
|
240
|
+
continue;
|
|
241
|
+
const deferred = exposure === "deferred" || exposure === "codemode" || exposure === "codemode-deferred";
|
|
242
|
+
const name = createMcpToolName(server.name, tool.name, (candidate) => taken.has(candidate));
|
|
243
|
+
taken.add(name);
|
|
244
|
+
// The server's own account, trusted as the user chose: a server that marks a writing tool read-only runs it unasked.
|
|
245
|
+
const reads = tool.annotations?.readOnlyHint === true;
|
|
246
|
+
if (reads)
|
|
247
|
+
readOnly.push(name);
|
|
248
|
+
tools.push(defineTool({
|
|
249
|
+
name,
|
|
250
|
+
description: `${tool.description ?? tool.title ?? tool.name} (MCP server ${server.name}; ${reads ? "read-only by the server's account, so it runs without approval" : "every call needs a person's approval"})`,
|
|
251
|
+
parameters: normalizeMcpInputSchema(tool.inputSchema),
|
|
252
|
+
structuredOutputSchema: createMcpResultSchema(tool.outputSchema),
|
|
253
|
+
...(deferred ? { deferred: true } : {}),
|
|
254
|
+
async execute(args, _api, context) {
|
|
255
|
+
let result;
|
|
256
|
+
for (let attempt = 1;; attempt++) {
|
|
257
|
+
const active = await usable();
|
|
258
|
+
try {
|
|
259
|
+
result = await active.callTool(tool.name, args, { signal: context?.abortSignal });
|
|
260
|
+
break;
|
|
261
|
+
}
|
|
262
|
+
catch (error) {
|
|
263
|
+
if (error instanceof McpSessionExpiredError && attempt === 1) {
|
|
264
|
+
if (link.client === active)
|
|
265
|
+
link.dead = true;
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
throw error;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const converted = await toMcpModelContent(server.name, result, { saveOutput: saveToTempFile });
|
|
272
|
+
if (result.isError && !converted.some((block) => block.type === "text" && block.text.trim() !== "")) {
|
|
273
|
+
converted.push({ type: "text", text: `MCP tool ${server.name}/${tool.name} returned an error` });
|
|
274
|
+
}
|
|
275
|
+
const limited = await limitMcpContent(converted, saveToTempFile);
|
|
276
|
+
// What a script sees is what the model would: the limited content, not the server's raw blocks (which skip the limit), and no `_meta`.
|
|
277
|
+
const scriptResult = { content: limited.content, ...(result.structuredContent !== undefined ? { structuredContent: result.structuredContent } : {}), ...(result.isError ? { isError: true } : {}) };
|
|
278
|
+
return {
|
|
279
|
+
output: limited.content,
|
|
280
|
+
structuredOutput: scriptResult,
|
|
281
|
+
...(result.isError ? { isError: true } : {}),
|
|
282
|
+
};
|
|
283
|
+
},
|
|
284
|
+
}));
|
|
285
|
+
}
|
|
286
|
+
served.push({ name: server.name, fingerprint: server.fingerprint, link, readOnly, extension: defineExtension({ name: `workers.mcp.${server.name}`, namespace: { name: server.name, description: server.config.description ?? `MCP server ${server.name}` }, tools }) });
|
|
287
|
+
}
|
|
288
|
+
// Ordered by name, so the same worker selects the same extensions after a restart.
|
|
289
|
+
served.sort((a, b) => a.name.localeCompare(b.name));
|
|
290
|
+
const extensions = served.map((item) => item.extension);
|
|
291
|
+
return { served, links: served.map((item) => item.link), errors, extensions, tools: extensions.flatMap((extension) => [...(extension.tools ?? [])]), at: Date.now() };
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* The MCP tools workers may call, connected once per process; `errors` names servers of `mcp.json` that were unusable.
|
|
295
|
+
* A set with errors is opened again once `RETRY_MS` have passed, so a server that was down, or a fixed configuration, is
|
|
296
|
+
* picked up without a restart.
|
|
297
|
+
*/
|
|
298
|
+
export function workerMcp() {
|
|
299
|
+
const settled = shared.settled;
|
|
300
|
+
if (shared.connecting && !(settled?.errors.length && Date.now() - settled.at >= RETRY_MS) && !shared.stale)
|
|
301
|
+
return shared.connecting;
|
|
302
|
+
shared.stale = false;
|
|
303
|
+
shared.settled = undefined;
|
|
304
|
+
sweepTempFilesOnce();
|
|
305
|
+
const connecting = shared.connecting = open(settled).then((value) => { if (shared.connecting === connecting) {
|
|
306
|
+
shared.settled = value;
|
|
307
|
+
shared.readOnly = new Set(value.served.flatMap((item) => item.readOnly));
|
|
308
|
+
} return value; }, (error) => { if (shared.connecting === connecting)
|
|
309
|
+
shared.connecting = undefined; throw error; });
|
|
310
|
+
return connecting;
|
|
311
|
+
}
|
|
312
|
+
/** Marks the cached MCP set stale so the next `workerMcp()` call reconciles the user-level `mcp.json`. */
|
|
313
|
+
export function invalidateWorkerMcp() {
|
|
314
|
+
if (shared.settled)
|
|
315
|
+
shared.stale = true;
|
|
316
|
+
}
|
|
317
|
+
/** Closes the connections; the next `workerMcp()` connects again. */
|
|
318
|
+
export async function closeWorkerMcp() {
|
|
319
|
+
const current = shared.connecting;
|
|
320
|
+
shared.connecting = undefined;
|
|
321
|
+
shared.settled = undefined;
|
|
322
|
+
shared.readOnly = undefined;
|
|
323
|
+
shared.stale = false;
|
|
324
|
+
// A reconnect in flight is awaited: it sees shutdown and closes the client it made, so none is left running.
|
|
325
|
+
if (current)
|
|
326
|
+
await Promise.all((await current.catch(() => undefined))?.links.map(async (link) => { link.shutdown = true; await link.reconnecting?.catch(() => { }); await link.client.close().catch(() => { }); }) ?? []);
|
|
327
|
+
}
|
|
328
|
+
/** Marks `holder` (a package's session) as using the connections; called before each use, as it costs nothing. */
|
|
329
|
+
export function holdWorkerMcp(holder) { (shared.holders ??= new Set()).add(holder); }
|
|
330
|
+
/** `holder` is done with the connections: the last holder closes them, so one session ending leaves the others theirs. */
|
|
331
|
+
export async function releaseWorkerMcp(holder) {
|
|
332
|
+
shared.holders?.delete(holder);
|
|
333
|
+
if (!shared.holders?.size)
|
|
334
|
+
await closeWorkerMcp();
|
|
335
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The state `key` names, kept on globalThis under `Symbol.for(key)`: made by `init` the first time any copy of this
|
|
3
|
+
* module asks, then the same object for every later ask. A /reload loads the extension's modules again, and a Pi process
|
|
4
|
+
* can carry two extensions that each installed their own copy of this package; module-level variables would split the
|
|
5
|
+
* state in two (two sets of MCP connections, two sandboxes), so every state that must outlive a module instance goes
|
|
6
|
+
* through here. The key is used as given, because some are read by other packages (pi-guards reads "pi-worker-mcp").
|
|
7
|
+
*/
|
|
8
|
+
export declare function processState<T>(key: string, init: () => T): T;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The state `key` names, kept on globalThis under `Symbol.for(key)`: made by `init` the first time any copy of this
|
|
3
|
+
* module asks, then the same object for every later ask. A /reload loads the extension's modules again, and a Pi process
|
|
4
|
+
* can carry two extensions that each installed their own copy of this package; module-level variables would split the
|
|
5
|
+
* state in two (two sets of MCP connections, two sandboxes), so every state that must outlive a module instance goes
|
|
6
|
+
* through here. The key is used as given, because some are read by other packages (pi-guards reads "pi-worker-mcp").
|
|
7
|
+
*/
|
|
8
|
+
export function processState(key, init) {
|
|
9
|
+
const symbol = Symbol.for(key), store = globalThis;
|
|
10
|
+
if (!(symbol in store))
|
|
11
|
+
store[symbol] = init();
|
|
12
|
+
return store[symbol];
|
|
13
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The user's and the project's AGENTS.md (or CLAUDE.md) text for a worker's instructions: the agent directory's, then each
|
|
3
|
+
* directory from the filesystem root down to `cwd`, nearest last, so the nearest wins when they disagree. Global rules
|
|
4
|
+
* keep a dedicated share of `max` so a large repository file never crowds them out; empty when there is none.
|
|
5
|
+
*/
|
|
6
|
+
export declare function projectRules(cwd: string, max?: number): string;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
const NAMES = ["AGENTS.md", "CLAUDE.md"];
|
|
5
|
+
// A regular file only: O_NOFOLLOW refuses a symlink that would point a worker's instructions at any file; a device or huge file would block or fill memory.
|
|
6
|
+
const MAX_BYTES = 256 * 1024;
|
|
7
|
+
const read = (file) => {
|
|
8
|
+
let fd;
|
|
9
|
+
try {
|
|
10
|
+
fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
11
|
+
const info = fstatSync(fd);
|
|
12
|
+
if (!info.isFile())
|
|
13
|
+
return "";
|
|
14
|
+
const target = Math.min(info.size > 0 ? info.size : MAX_BYTES, MAX_BYTES);
|
|
15
|
+
const buffer = Buffer.allocUnsafe(target);
|
|
16
|
+
let offset = 0;
|
|
17
|
+
while (offset < target) {
|
|
18
|
+
const n = readSync(fd, buffer, offset, target - offset, offset);
|
|
19
|
+
if (n <= 0)
|
|
20
|
+
break;
|
|
21
|
+
offset += n;
|
|
22
|
+
}
|
|
23
|
+
return buffer.subarray(0, offset).toString("utf8").trim();
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return "";
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
if (fd !== undefined)
|
|
30
|
+
closeSync(fd);
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
function sliceTailSafe(text, max) {
|
|
34
|
+
if (text.length <= max)
|
|
35
|
+
return text;
|
|
36
|
+
let start = text.length - max;
|
|
37
|
+
const code = text.charCodeAt(start);
|
|
38
|
+
if (code >= 0xdc00 && code <= 0xdfff)
|
|
39
|
+
start++;
|
|
40
|
+
return `...${text.slice(start)}`;
|
|
41
|
+
}
|
|
42
|
+
function sliceHeadSafe(text, max) {
|
|
43
|
+
if (text.length <= max)
|
|
44
|
+
return text;
|
|
45
|
+
let end = max;
|
|
46
|
+
const prev = text.charCodeAt(end - 1);
|
|
47
|
+
if (prev >= 0xd800 && prev <= 0xdbff)
|
|
48
|
+
end--;
|
|
49
|
+
return `${text.slice(0, end)}...`;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The user's and the project's AGENTS.md (or CLAUDE.md) text for a worker's instructions: the agent directory's, then each
|
|
53
|
+
* directory from the filesystem root down to `cwd`, nearest last, so the nearest wins when they disagree. Global rules
|
|
54
|
+
* keep a dedicated share of `max` so a large repository file never crowds them out; empty when there is none.
|
|
55
|
+
*/
|
|
56
|
+
export function projectRules(cwd, max = 6000) {
|
|
57
|
+
const agentDir = resolve(getAgentDir());
|
|
58
|
+
const dirs = [];
|
|
59
|
+
for (let dir = resolve(cwd); !dirs.includes(dir); dir = dirname(dir))
|
|
60
|
+
dirs.unshift(dir);
|
|
61
|
+
const globalText = read(join(agentDir, NAMES[0])) || read(join(agentDir, NAMES[1]));
|
|
62
|
+
const globalPart = globalText ? `# ${agentDir}\n${globalText}` : "";
|
|
63
|
+
const localParts = dirs
|
|
64
|
+
.filter((dir) => dir !== agentDir)
|
|
65
|
+
.flatMap((dir) => { const text = read(join(dir, NAMES[0])) || read(join(dir, NAMES[1])); return text ? [`# ${dir}\n${text}`] : []; });
|
|
66
|
+
const localText = localParts.join("\n\n");
|
|
67
|
+
if (!globalPart && !localText)
|
|
68
|
+
return "";
|
|
69
|
+
if (!globalPart)
|
|
70
|
+
return sliceTailSafe(localText, max);
|
|
71
|
+
if (!localText)
|
|
72
|
+
return sliceHeadSafe(globalPart, max);
|
|
73
|
+
const combined = `${globalPart}\n\n${localText}`;
|
|
74
|
+
if (combined.length <= max)
|
|
75
|
+
return combined;
|
|
76
|
+
if (max < 500)
|
|
77
|
+
return sliceTailSafe(combined, max);
|
|
78
|
+
const globalBudget = Math.min(globalPart.length, Math.max(Math.floor(max / 3), max - localText.length - 2));
|
|
79
|
+
const keptGlobal = sliceHeadSafe(globalPart, globalBudget);
|
|
80
|
+
const localBudget = Math.max(0, max - keptGlobal.length - 2);
|
|
81
|
+
if (localBudget === 0)
|
|
82
|
+
return keptGlobal;
|
|
83
|
+
return `${keptGlobal}\n\n${sliceTailSafe(localText, localBudget)}`;
|
|
84
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Temporary files that MCP results spill into; see `sweepTempFiles`. */
|
|
2
|
+
export declare const MCP_TEMP_PREFIX = "pi-mcp-";
|
|
3
|
+
export declare const TEMP_MAX_AGE_MS: number;
|
|
4
|
+
/**
|
|
5
|
+
* Removes the files this package left in the temp directory: named `prefix`*, regular (never a link), owned by the
|
|
6
|
+
* current user, mode 0600 as they were written, and last changed more than `maxAgeMs` ago. Anything else in a shared
|
|
7
|
+
* temp directory is not ours to remove. Returns the files removed.
|
|
8
|
+
*/
|
|
9
|
+
export declare function sweepTempFiles(options?: {
|
|
10
|
+
dir?: string;
|
|
11
|
+
prefix?: string;
|
|
12
|
+
maxAgeMs?: number;
|
|
13
|
+
now?: number;
|
|
14
|
+
}): Promise<string[]>;
|
|
15
|
+
/** One sweep per process, however many copies of this module ask: the first MCP connection starts it. */
|
|
16
|
+
export declare function sweepTempFilesOnce(): void;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { lstat, readdir, unlink } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { processState } from "./process-state.js";
|
|
5
|
+
/** Temporary files that MCP results spill into; see `sweepTempFiles`. */
|
|
6
|
+
export const MCP_TEMP_PREFIX = "pi-mcp-";
|
|
7
|
+
export const TEMP_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
8
|
+
/**
|
|
9
|
+
* Removes the files this package left in the temp directory: named `prefix`*, regular (never a link), owned by the
|
|
10
|
+
* current user, mode 0600 as they were written, and last changed more than `maxAgeMs` ago. Anything else in a shared
|
|
11
|
+
* temp directory is not ours to remove. Returns the files removed.
|
|
12
|
+
*/
|
|
13
|
+
export async function sweepTempFiles(options = {}) {
|
|
14
|
+
const { dir = tmpdir(), prefix = MCP_TEMP_PREFIX, maxAgeMs = TEMP_MAX_AGE_MS, now = Date.now() } = options;
|
|
15
|
+
const uid = process.getuid?.();
|
|
16
|
+
const removed = [];
|
|
17
|
+
for (const name of await readdir(dir).catch(() => [])) {
|
|
18
|
+
if (!name.startsWith(prefix))
|
|
19
|
+
continue;
|
|
20
|
+
const file = join(dir, name);
|
|
21
|
+
try {
|
|
22
|
+
const info = await lstat(file);
|
|
23
|
+
if (!info.isFile() || (uid !== undefined && info.uid !== uid) || (info.mode & 0o777) !== 0o600 || now - info.mtimeMs <= maxAgeMs)
|
|
24
|
+
continue;
|
|
25
|
+
await unlink(file);
|
|
26
|
+
removed.push(file);
|
|
27
|
+
}
|
|
28
|
+
catch { /* gone already, or not ours to remove */ }
|
|
29
|
+
}
|
|
30
|
+
return removed;
|
|
31
|
+
}
|
|
32
|
+
/** One sweep per process, however many copies of this module ask: the first MCP connection starts it. */
|
|
33
|
+
export function sweepTempFilesOnce() {
|
|
34
|
+
const state = processState("pi-durable-shared.temp-sweep", () => ({ started: false }));
|
|
35
|
+
if (state.started)
|
|
36
|
+
return;
|
|
37
|
+
state.started = true;
|
|
38
|
+
void sweepTempFiles().catch(() => { });
|
|
39
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
import { type Context } from "@earendil-works/chord/context";
|
|
3
|
+
import { type ToolExecutionApi } from "@earendil-works/pi-durable";
|
|
4
|
+
type Exec = NonNullable<ToolExecutionApi["env"]>["exec"];
|
|
5
|
+
/**
|
|
6
|
+
* `env.exec` counts its `timeout` in seconds; a caller here thinks in milliseconds, so this is the one place that
|
|
7
|
+
* converts (passing 30 000 ms as `timeout` would be 30 000 seconds, more than eight hours).
|
|
8
|
+
*/
|
|
9
|
+
export declare function execWithTimeout(env: {
|
|
10
|
+
exec: Exec;
|
|
11
|
+
}, argv: string[], options: {
|
|
12
|
+
timeoutMs: number;
|
|
13
|
+
onOutput?: (text: string) => void;
|
|
14
|
+
}, context: Context): Promise<import("@earendil-works/pi-durable/env").Result<import("@earendil-works/pi-durable/env").ShellExecResult, import("@earendil-works/pi-durable/env").ExecutionError>>;
|
|
15
|
+
/** Read-only search tools a role may list beside `read`: `grep` runs ripgrep, `find` runs fd. */
|
|
16
|
+
export declare const SearchTools: import("@earendil-works/pi-durable").Extension<import("@earendil-works/pi-durable").ToolRegistration<Type.TObject<{
|
|
17
|
+
pattern: Type.TString;
|
|
18
|
+
path: Type.TOptional<Type.TString>;
|
|
19
|
+
glob: Type.TOptional<Type.TString>;
|
|
20
|
+
fixed: Type.TOptional<Type.TBoolean>;
|
|
21
|
+
}>, import("@earendil-works/chord/json").JsonValue, import("@earendil-works/chord/json").JsonValue> | import("@earendil-works/pi-durable").ToolRegistration<Type.TObject<{
|
|
22
|
+
pattern: Type.TOptional<Type.TString>;
|
|
23
|
+
path: Type.TOptional<Type.TString>;
|
|
24
|
+
}>, import("@earendil-works/chord/json").JsonValue, import("@earendil-works/chord/json").JsonValue>>;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
import { withCancel } from "@earendil-works/chord/context";
|
|
3
|
+
import { defineExtension, defineTool } from "@earendil-works/pi-durable";
|
|
4
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { statSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
const MAX_OUTPUT = 50_000;
|
|
8
|
+
const SEARCH_TIMEOUT_MS = 30_000;
|
|
9
|
+
/**
|
|
10
|
+
* `env.exec` counts its `timeout` in seconds; a caller here thinks in milliseconds, so this is the one place that
|
|
11
|
+
* converts (passing 30 000 ms as `timeout` would be 30 000 seconds, more than eight hours).
|
|
12
|
+
*/
|
|
13
|
+
export function execWithTimeout(env, argv, options, context) {
|
|
14
|
+
const { timeoutMs, ...rest } = options;
|
|
15
|
+
return env.exec(argv, { ...rest, timeout: timeoutMs / 1000 }, context);
|
|
16
|
+
}
|
|
17
|
+
const isRegularFile = (file) => {
|
|
18
|
+
try {
|
|
19
|
+
return statSync(file).isFile();
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* The binary as Pi's own grep and find tools find it: the copy Pi downloads into `<agentDir>/bin` when PATH has none,
|
|
27
|
+
* else the PATH name, `fdfind` on Debian and Ubuntu. Not exported by Pi, so this mirrors its tools-manager.
|
|
28
|
+
*/
|
|
29
|
+
function binary(names) {
|
|
30
|
+
const windows = process.platform === "win32", exe = windows ? ".exe" : "";
|
|
31
|
+
const local = join(getAgentDir(), "bin", names[0] + exe);
|
|
32
|
+
if (isRegularFile(local))
|
|
33
|
+
return local;
|
|
34
|
+
const pathEnv = process.env.PATH ?? process.env.Path ?? "";
|
|
35
|
+
const onPath = (name) => pathEnv.split(windows ? ";" : ":").some((dir) => dir && isRegularFile(join(dir, name + exe)));
|
|
36
|
+
return names.find(onPath) ?? names[0];
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Runs `argv` without a shell in the worker's directory. An exit code above `nothing` is an error: rg exits 1 when
|
|
40
|
+
* nothing matched and 2 on an error, fd exits 0 either way and 1 on an error.
|
|
41
|
+
*/
|
|
42
|
+
async function search(argv, nothing, api, context) {
|
|
43
|
+
if (!api.env)
|
|
44
|
+
throw new Error("No execution environment");
|
|
45
|
+
let output = "";
|
|
46
|
+
// Stopped once past the limit, so a broad search does not read the rest of the tree for output nobody keeps.
|
|
47
|
+
const limited = withCancel(context);
|
|
48
|
+
let full = false;
|
|
49
|
+
try {
|
|
50
|
+
const result = await execWithTimeout(api.env, argv, { timeoutMs: SEARCH_TIMEOUT_MS, onOutput: (text) => { if (full)
|
|
51
|
+
return; output += text; if (output.length > MAX_OUTPUT) {
|
|
52
|
+
full = true;
|
|
53
|
+
limited.cancel();
|
|
54
|
+
} } }, limited.context);
|
|
55
|
+
if (!result.ok && !full)
|
|
56
|
+
throw result.error;
|
|
57
|
+
if (result.ok && result.value.exitCode > nothing) {
|
|
58
|
+
const body = full ? `${output.slice(0, MAX_OUTPUT)}\n(truncated)` : (output || `exit code ${result.value.exitCode}`);
|
|
59
|
+
return { output: [{ type: "text", text: body }], isError: true };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
limited.cancel();
|
|
64
|
+
}
|
|
65
|
+
const text = full ? `${output.slice(0, MAX_OUTPUT)}\n(truncated; narrow the pattern or path)` : output || "(no matches)";
|
|
66
|
+
return { output: [{ type: "text", text }] };
|
|
67
|
+
}
|
|
68
|
+
/** Read-only search tools a role may list beside `read`: `grep` runs ripgrep, `find` runs fd. */
|
|
69
|
+
export const SearchTools = defineExtension({
|
|
70
|
+
name: "teamwork.search",
|
|
71
|
+
tools: [
|
|
72
|
+
defineTool({
|
|
73
|
+
name: "grep", description: "Search file contents with ripgrep (smart case, git-aware). Returns path:line:text.", replay: "safe",
|
|
74
|
+
parameters: Type.Object({ pattern: Type.String({ description: "Regex, or literal text with fixed: true" }), path: Type.Optional(Type.String()), glob: Type.Optional(Type.String({ description: "Include glob, e.g. *.ts" })), fixed: Type.Optional(Type.Boolean()) }),
|
|
75
|
+
execute: (args, api, context) => search([binary(["rg"]), "-n", "--smart-case", ...(args.fixed ? ["-F"] : []), ...(args.glob ? ["-g", args.glob] : []), "-e", args.pattern, "--", args.path?.trim() || "."], 1, api, context),
|
|
76
|
+
}),
|
|
77
|
+
defineTool({
|
|
78
|
+
name: "find", description: "Find files by name with fd (regex on the file name, git-aware).", replay: "safe",
|
|
79
|
+
parameters: Type.Object({ pattern: Type.Optional(Type.String({ description: "Regex on the file name; omit to list all" })), path: Type.Optional(Type.String()) }),
|
|
80
|
+
execute: (args, api, context) => search([binary(["fd", "fdfind"]), "--color", "never", "--", args.pattern || ".", args.path?.trim() || "."], 0, api, context),
|
|
81
|
+
}),
|
|
82
|
+
],
|
|
83
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** A counting semaphore whose waiters queue in order and leave the queue when their signal aborts. */
|
|
2
|
+
export type Semaphore = {
|
|
3
|
+
acquire(signal?: AbortSignal): Promise<() => void>;
|
|
4
|
+
};
|
|
5
|
+
export declare function createSemaphore(limit: () => number): Semaphore & {
|
|
6
|
+
readonly active: number;
|
|
7
|
+
readonly waiting: number;
|
|
8
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export function createSemaphore(limit) {
|
|
2
|
+
const state = { active: 0 };
|
|
3
|
+
const queue = [];
|
|
4
|
+
const pump = () => { while (queue.length && state.active < limit()) {
|
|
5
|
+
state.active++;
|
|
6
|
+
queue.shift().grant();
|
|
7
|
+
} };
|
|
8
|
+
const releaser = () => { let released = false; return () => { if (released)
|
|
9
|
+
return; released = true; state.active--; pump(); }; };
|
|
10
|
+
return {
|
|
11
|
+
get active() { return state.active; },
|
|
12
|
+
get waiting() { return queue.length; },
|
|
13
|
+
acquire(signal) {
|
|
14
|
+
if (signal?.aborted)
|
|
15
|
+
return Promise.reject(signal.reason ?? new Error("aborted"));
|
|
16
|
+
return new Promise((resolve, reject) => {
|
|
17
|
+
const entry = { grant: () => { signal?.removeEventListener("abort", onAbort); resolve(releaser()); } };
|
|
18
|
+
const onAbort = () => { const at = queue.indexOf(entry); if (at >= 0)
|
|
19
|
+
queue.splice(at, 1); reject(signal.reason ?? new Error("aborted")); };
|
|
20
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
21
|
+
queue.push(entry);
|
|
22
|
+
pump();
|
|
23
|
+
});
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Creates `lockPath` atomically with this process's pid, first removing a lock whose process is gone. Returns its inode. */
|
|
2
|
+
export declare function acquireLock(lockPath: string): Promise<number | undefined>;
|
|
3
|
+
/** Acquires `lockPath` with this process's id; the release removes it only while it still names this process. */
|
|
4
|
+
export declare function acquireSessionLock(lockPath: string): Promise<() => Promise<void>>;
|