@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 CHANGED
@@ -1,3 +1,48 @@
1
- # Temporary Holding Version
1
+ # pi-durable-shared
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The durable runtime, MCP, search and code mode helpers that pi-orchestrator, pi-swarm, pi-teamwork and pi-schedule used to carry as byte-identical copies. One package, one copy.
4
+
5
+ ## Modules
6
+
7
+ Install with `npm install @minhtri2710/pi-durable-shared`. Import each as `@minhtri2710/pi-durable-shared/<module>` (built to `dist/<module>.js` with `.d.ts`).
8
+
9
+ - `process-state`: `processState(key, init)`, the one way to keep state on `globalThis` so it outlives a `/reload` and is shared by every copy of this package in the process. The key is used as given (`pi-guards` reads `pi-worker-mcp`).
10
+ - `durable-runtime`, `session-store`, `session-lock`: the per-session durable harness, its SQLite store and its lock (a stale reclaim claim ages by `ctime`).
11
+ - `mcp-tools`, `mcp-oauth`: MCP servers for workers: every server of the user-level `<agent dir>/mcp.json` that is not `enabled: false`, connected separately from Pi's own. An invalid or failing server is reported in `errors`, not thrown. `$NAME`, `${NAME}` and `$$` expand in `env` and `headers`. A script sees the limited content, not the server's raw blocks or `_meta`.
12
+ - `worker-codemode`: the code mode sandbox and tool. Scripts run at most `max(4, availableParallelism)` at a time (`PI_CODEMODE_MAX_WORKERS` overrides); one over the limit waits, and leaves the queue when its signal aborts. `configureWorkerCodemode({ inlineBudget })` sets the budget the sandbox is created with.
13
+ - `search-tools`: `grep` and `find` for workers. `execWithTimeout` takes milliseconds and passes seconds to `exec`.
14
+ - `retention`: removes `pi-mcp-*` temp files that are regular, owned by the current user, mode 0600 and older than 7 days; runs once per process.
15
+ - `project-rules`: the AGENTS.md / CLAUDE.md text for a worker's instructions.
16
+ - `testing`: `loadTwice(specifier)`, which loads a module twice as a reload does.
17
+
18
+ `pi-lint-state` (a `bin`) fails when a file that defines tools or tasks has module-level `let`, `new Map/Set` or a raw `??=` slot instead of `processState`. The consumers run it as `npm run lint:state`, first in `npm test`. It needs ripgrep.
19
+
20
+ ## Develop with npm link
21
+
22
+ ```sh
23
+ cd pi-durable-shared && npm install && npm run build
24
+ cd ../pi-swarm && npm link ../pi-durable-shared # likewise pi-teamwork, pi-orchestrator, pi-schedule
25
+ ```
26
+
27
+ `npm link` makes `node_modules/@minhtri2710/pi-durable-shared` a symlink to this directory, so a consumer runs the built `dist`: run `npm run build` (or `npx tsc -p tsconfig.build.json --watch`) after each change here. A consumer's `npm install` removes the link; run `npm link ../pi-durable-shared` again.
28
+
29
+ ```sh
30
+ npm test # node --test src/*.test.ts
31
+ npm run typecheck # tsc -p .
32
+ ```
33
+
34
+ ## Publish to npm
35
+
36
+ Consumers depend on `"@minhtri2710/pi-durable-shared": "^2.0.0"`. The package ships a prebuilt `dist`, so installing it runs no scripts. `prepublishOnly` builds and tests before each publish.
37
+
38
+ ```sh
39
+ npm login # once, in your terminal
40
+ cd pi-durable-shared
41
+ npm publish # publishConfig sets public access
42
+ ```
43
+
44
+ To release a change, bump the version (`npm version patch`), run `npm publish`, push the commit and tag, then run `npm update @minhtri2710/pi-durable-shared` in the consumers.
45
+
46
+ ## Two copies in one process
47
+
48
+ Two extensions can each install their own copy of this package. Everything that must be one per process (the runtimes, the MCP connections, the sandbox and its queue) is kept through `processState`, so the copies share it. Keep new process-wide state there too.
@@ -0,0 +1,15 @@
1
+ #!/bin/sh
2
+ # Fails when a file that defines durable tools or tasks keeps module-level state outside processState.
3
+ #
4
+ # A /reload loads a file again, and a runtime kept open across it keeps the tools of the copy that made them. State in a
5
+ # module-level variable is then two states: the old copy's tools see one, the live extension the other. State that must
6
+ # survive goes through processState(key, init) from pi-durable-shared/process-state.
7
+ # Needs ripgrep. Run it in a package directory: `pi-lint-state`.
8
+ files=$(rg -l -e 'defineTool' -e 'defineTask' -g '*.ts' -g '!*.test.ts' -g '!node_modules' -g '!dist' .) || exit 0
9
+ status=0
10
+ # At column 0 only: a let or var, a new Map/Set kept in a const, or a raw globalThis `??=` slot.
11
+ if rg -n -e '^(export )?(let|var) ' -e '^(export )?const [^=]*= new (Map|Set|WeakMap|WeakSet)\b' -e '^[^ /*].*\?\?= ' $files; then
12
+ echo "lint:state: module-level state in a file that defines tools or tasks; use processState(key, init) from pi-durable-shared/process-state" >&2
13
+ status=1
14
+ fi
15
+ exit $status
@@ -0,0 +1,25 @@
1
+ import { type MutableModels } from "@earendil-works/pi-ai";
2
+ import { type Extension, type Harness as DurableHarness, type Registry, type Report, type ToolRegistration } from "@earendil-works/pi-durable";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ export type DurableRuntime = {
5
+ harness: DurableHarness;
6
+ registry: Registry;
7
+ models: MutableModels;
8
+ settling: Set<string | number>;
9
+ };
10
+ /** Built-in coding tools (`read`, `write`, `edit`, `bash`) with Pi 1.8.0's lightweight WASM image processor. */
11
+ export declare function workerCodingTools(): Promise<Extension<ToolRegistration>>;
12
+ /**
13
+ * Forwards any unreported durable worker model usage from `Harness.usage()` to the parent Pi session via
14
+ * `pi.appendUsage()`, using a durable watermark doc so restarts and `/reload` never double-count.
15
+ */
16
+ export declare function flushDurableUsage(runtime: DurableRuntime, pi: Pick<ExtensionAPI, "appendUsage">, kind: string, note?: string): Promise<void>;
17
+ export declare function hasDurableRuntime(ctx: ExtensionContext, namespace: string): Promise<boolean>;
18
+ /** `options` apply when the runtime is created; a runtime already open keeps the settings it was opened with. */
19
+ export declare function getDurableRuntime(ctx: ExtensionContext, namespace: string, extensions?: readonly Extension<ToolRegistration>[], options?: {
20
+ afterFailedRun?: "continue";
21
+ onReport?: (report: Report) => void;
22
+ }): Promise<DurableRuntime>;
23
+ /** Whether `runtime` is still the open one for this session, so a caller racing a shutdown does not keep a closed one. */
24
+ export declare function isOpen(ctx: ExtensionContext, namespace: string, runtime: DurableRuntime): boolean;
25
+ export declare function closeDurableRuntime(ctx: ExtensionContext, namespace: string): Promise<void>;
@@ -0,0 +1,266 @@
1
+ import { access } from "node:fs/promises";
2
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
3
+ import { createModels, createProvider } from "@earendil-works/pi-ai";
4
+ import { defineDoc, Harness, createRegistry } from "@earendil-works/pi-durable";
5
+ import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
6
+ import { createNodePiImages } from "@earendil-works/pi-durable/images/pi-images/node";
7
+ import { createCodingTools } from "@earendil-works/pi-durable/tools";
8
+ import { setWorkerMcpAuthResolver } from "./mcp-tools.js";
9
+ import { processState } from "./process-state.js";
10
+ import { databasePath, openSessionStore } from "./session-store.js";
11
+ // Opens and closes in flight, process-wide like the runtimes, so an instance started by /reload sees them too.
12
+ const pending = processState("pi-durable-extension.opening", () => new Map());
13
+ const closing = processState("pi-durable-extension.closing", () => new Map());
14
+ const codingTools = processState("pi-durable-extension.coding-tools", () => ({ built: undefined }));
15
+ const UsageWatermarkDoc = defineDoc({
16
+ kind: "pi.ext.usage-watermark",
17
+ version: 1,
18
+ scope: "session",
19
+ initial: () => ({ reported: {} }),
20
+ checkpointWhen: (_value, _ops, info) => info.deltasSinceBase > 32,
21
+ });
22
+ const runtimes = () => processState("pi-durable-extension.runtimes", () => new Map());
23
+ /** Built-in coding tools (`read`, `write`, `edit`, `bash`) with Pi 1.8.0's lightweight WASM image processor. */
24
+ export async function workerCodingTools() {
25
+ // A failed build is not kept: the next call tries again.
26
+ return codingTools.built ??= createNodePiImages()
27
+ .then((images) => createCodingTools({ images }))
28
+ .catch((error) => { codingTools.built = undefined; throw error; });
29
+ }
30
+ function diffUsage(latest, prev) {
31
+ const input = Math.max(0, latest.input - (prev?.input ?? 0));
32
+ const output = Math.max(0, latest.output - (prev?.output ?? 0));
33
+ const cacheRead = Math.max(0, latest.cacheRead - (prev?.cacheRead ?? 0));
34
+ const cacheWrite = Math.max(0, latest.cacheWrite - (prev?.cacheWrite ?? 0));
35
+ const totalTokens = Math.max(0, latest.totalTokens - (prev?.totalTokens ?? 0));
36
+ const costInput = Math.max(0, latest.cost.input - (prev?.cost.input ?? 0));
37
+ const costOutput = Math.max(0, latest.cost.output - (prev?.cost.output ?? 0));
38
+ const costCacheRead = Math.max(0, latest.cost.cacheRead - (prev?.cost.cacheRead ?? 0));
39
+ const costCacheWrite = Math.max(0, latest.cost.cacheWrite - (prev?.cost.cacheWrite ?? 0));
40
+ const costTotal = Math.max(0, latest.cost.total - (prev?.cost.total ?? 0));
41
+ const cacheWrite1h = latest.cacheWrite1h !== undefined ? Math.max(0, latest.cacheWrite1h - (prev?.cacheWrite1h ?? 0)) : undefined;
42
+ const reasoning = latest.reasoning !== undefined ? Math.max(0, latest.reasoning - (prev?.reasoning ?? 0)) : undefined;
43
+ const imageOutput = latest.imageOutput !== undefined ? Math.max(0, latest.imageOutput - (prev?.imageOutput ?? 0)) : undefined;
44
+ if (input === 0 && output === 0 && cacheRead === 0 && cacheWrite === 0 && totalTokens === 0 && costTotal === 0)
45
+ return undefined;
46
+ return {
47
+ input,
48
+ output,
49
+ cacheRead,
50
+ cacheWrite,
51
+ totalTokens,
52
+ ...(cacheWrite1h !== undefined ? { cacheWrite1h } : {}),
53
+ ...(reasoning !== undefined ? { reasoning } : {}),
54
+ ...(imageOutput !== undefined ? { imageOutput } : {}),
55
+ cost: {
56
+ input: costInput,
57
+ output: costOutput,
58
+ cacheRead: costCacheRead,
59
+ cacheWrite: costCacheWrite,
60
+ total: costTotal,
61
+ ...(latest.cost.totalFromProvider !== undefined ? { totalFromProvider: latest.cost.totalFromProvider } : {}),
62
+ },
63
+ };
64
+ }
65
+ /**
66
+ * Forwards any unreported durable worker model usage from `Harness.usage()` to the parent Pi session via
67
+ * `pi.appendUsage()`, using a durable watermark doc so restarts and `/reload` never double-count.
68
+ */
69
+ export async function flushDurableUsage(runtime, pi, kind, note) {
70
+ let total;
71
+ try {
72
+ total = await runtime.harness.usage(BACKGROUND_CONTEXT);
73
+ }
74
+ catch {
75
+ return;
76
+ }
77
+ const entries = Object.entries(total.models);
78
+ if (!entries.length)
79
+ return;
80
+ const updates = [];
81
+ try {
82
+ await runtime.harness.commit(async (tx) => {
83
+ const doc = await tx.doc(UsageWatermarkDoc);
84
+ for (const [key, latest] of entries) {
85
+ const prev = Object.hasOwn(doc.reported, key) ? doc.reported[key] : undefined;
86
+ const delta = diffUsage(latest, prev);
87
+ if (!delta)
88
+ continue;
89
+ const slash = key.indexOf("/");
90
+ if (slash < 1)
91
+ continue;
92
+ updates.push({ provider: key.slice(0, slash), model: key.slice(slash + 1), usage: delta });
93
+ doc.reported[key] = structuredClone(latest);
94
+ }
95
+ }, BACKGROUND_CONTEXT);
96
+ }
97
+ catch {
98
+ return;
99
+ }
100
+ for (const item of updates) {
101
+ try {
102
+ pi.appendUsage({ kind, provider: item.provider, model: item.model, usage: item.usage, ...(note ? { note } : {}) });
103
+ }
104
+ catch { }
105
+ }
106
+ }
107
+ function syncModels(target, source) {
108
+ const groups = new Map();
109
+ for (const model of source.getAll()) {
110
+ const models = groups.get(model.provider) ?? [];
111
+ models.push(model);
112
+ groups.set(model.provider, models);
113
+ }
114
+ for (const provider of target.getProviders())
115
+ if (!groups.has(provider.id))
116
+ target.deleteProvider(provider.id);
117
+ for (const [id, models] of groups) {
118
+ const sourceProvider = source.getProvider(id);
119
+ const api = {
120
+ stream: (model, context, options) => source.stream(model, context, options),
121
+ streamSimple: (model, context, options) => source.streamSimple(model, context, options),
122
+ };
123
+ target.setProvider(createProvider({
124
+ id,
125
+ name: sourceProvider?.name ?? id,
126
+ baseUrl: sourceProvider?.baseUrl,
127
+ headers: sourceProvider?.headers,
128
+ auth: {
129
+ apiKey: {
130
+ name: `Pi session auth (${id})`,
131
+ async check() {
132
+ return models.some((model) => source.hasConfiguredAuth(model)) ? { type: "api_key", source: "Pi session" } : undefined;
133
+ },
134
+ async resolve() {
135
+ const model = models.find((candidate) => source.hasConfiguredAuth(candidate));
136
+ if (!model)
137
+ return undefined;
138
+ const result = await source.getApiKeyAndHeaders(model);
139
+ return result.ok
140
+ ? { auth: { apiKey: result.apiKey, headers: result.headers, baseUrl: result.baseUrl }, env: result.env, source: "Pi session" }
141
+ : undefined;
142
+ },
143
+ },
144
+ },
145
+ models,
146
+ api,
147
+ }));
148
+ }
149
+ }
150
+ export async function hasDurableRuntime(ctx, namespace) {
151
+ const { path, persistent } = databasePath(ctx, namespace);
152
+ if (runtimes().has(path) || pending.has(path))
153
+ return true;
154
+ if (!persistent)
155
+ return false;
156
+ try {
157
+ await access(path);
158
+ return true;
159
+ }
160
+ catch (error) {
161
+ if (error.code === "ENOENT")
162
+ return false;
163
+ throw error;
164
+ }
165
+ }
166
+ function defaultReport(report) {
167
+ if (report.kind === "storage_failed" || report.kind === "task_faulted") {
168
+ const detail = report.error instanceof Error ? report.error.message : String(report.error);
169
+ console.error(`[pi-durable] ${report.kind}: ${detail}`);
170
+ }
171
+ }
172
+ /** `options` apply when the runtime is created; a runtime already open keeps the settings it was opened with. */
173
+ export async function getDurableRuntime(ctx, namespace, extensions = [], options = {}) {
174
+ if (typeof ctx.modelRegistry?.getApiKeyForProvider === "function") {
175
+ setWorkerMcpAuthResolver((provider) => ctx.modelRegistry.getApiKeyForProvider(provider));
176
+ }
177
+ const { sessionId, path } = databasePath(ctx, namespace);
178
+ let cached;
179
+ const closingRuntime = closing.get(path);
180
+ if (closingRuntime)
181
+ await closingRuntime;
182
+ cached = runtimes().get(path);
183
+ if (!cached) {
184
+ let opening = pending.get(path);
185
+ if (!opening) {
186
+ opening = createDurableRuntime(ctx, namespace, sessionId, path, extensions, options);
187
+ pending.set(path, opening);
188
+ }
189
+ try {
190
+ cached = await opening;
191
+ }
192
+ finally {
193
+ if (pending.get(path) === opening)
194
+ pending.delete(path);
195
+ }
196
+ }
197
+ // A close that began while this open ran is a shutdown: its closer takes this runtime, so it is not reopened.
198
+ const closingAgain = closing.get(path);
199
+ if (closingAgain) {
200
+ await closingAgain;
201
+ throw new Error("Durable runtime closed while opening");
202
+ }
203
+ if (runtimes().get(path) !== cached)
204
+ throw new Error("Durable runtime closed while opening");
205
+ if (cached.sessionId !== sessionId)
206
+ throw new Error("Durable session identity mismatch");
207
+ // An install publishes a new registry, which wakes every call parked at a gate, so only a missing extension is
208
+ // installed. One already there by name stays, also the copy an instance before /reload installed: the guards and the
209
+ // board keep their per-instance state on globalThis, so an earlier copy reaches the live instance.
210
+ for (const extension of extensions)
211
+ if (!cached.registry.snapshot().extension(extension.name))
212
+ cached.registry.install(extension);
213
+ syncModels(cached.models, ctx.modelRegistry);
214
+ cached.harness.resume();
215
+ return cached;
216
+ }
217
+ async function createDurableRuntime(ctx, namespace, sessionId, path, extensions, options) {
218
+ let store;
219
+ let harness;
220
+ try {
221
+ store = await openSessionStore(ctx, namespace);
222
+ const registry = createRegistry();
223
+ for (const extension of extensions)
224
+ registry.install(extension);
225
+ const models = createModels();
226
+ syncModels(models, ctx.modelRegistry);
227
+ const { onReport, ...settings } = options;
228
+ harness = await Harness.open(store.storage, { models: () => models, registry, env: ({ cwd }) => new NodeExecutionEnv({ cwd: cwd ?? ctx.cwd }), onReport: onReport ?? defaultReport, settings: { restartLimit: 3, ...settings } }, BACKGROUND_CONTEXT);
229
+ const runtime = { harness, registry, models, sessionId, releaseLock: store.releaseLock, persistent: store.persistent, settling: new Set() };
230
+ runtimes().set(path, runtime);
231
+ harness.resume();
232
+ return runtime;
233
+ }
234
+ catch (error) {
235
+ await (harness ? harness.close(BACKGROUND_CONTEXT) : store?.storage.close(BACKGROUND_CONTEXT))?.catch(() => { });
236
+ await store?.releaseLock();
237
+ throw error;
238
+ }
239
+ }
240
+ /** Whether `runtime` is still the open one for this session, so a caller racing a shutdown does not keep a closed one. */
241
+ export function isOpen(ctx, namespace, runtime) { const { path } = databasePath(ctx, namespace); return runtimes().get(path) === runtime && !closing.has(path); }
242
+ export async function closeDurableRuntime(ctx, namespace) {
243
+ const { path } = databasePath(ctx, namespace);
244
+ const alreadyClosing = closing.get(path);
245
+ if (alreadyClosing)
246
+ return alreadyClosing;
247
+ const found = runtimes().get(path), opening = pending.get(path);
248
+ if (!found && !opening)
249
+ return;
250
+ // Registered before any await, so an open that finishes meanwhile sees the close and waits for it.
251
+ const closingRuntime = (async () => {
252
+ const runtime = found ?? await opening.catch(() => undefined);
253
+ if (!runtime)
254
+ return;
255
+ if (runtimes().get(path) === runtime)
256
+ runtimes().delete(path);
257
+ try {
258
+ await runtime.harness.close(BACKGROUND_CONTEXT);
259
+ }
260
+ finally {
261
+ await runtime.releaseLock();
262
+ }
263
+ })().finally(() => closing.delete(path));
264
+ closing.set(path, closingRuntime);
265
+ await closingRuntime;
266
+ }
@@ -0,0 +1,19 @@
1
+ import { type McpAuthProvider, type McpOAuthState } from "@earendil-works/pi-mcp/oauth";
2
+ export declare const checkMetadataDocumentCallback: (callbackUrl: string | undefined) => "oauth.clientRegistration \"cimd\" requires oauth.callbackUrl on localhost or 127.0.0.1 with path /callback" | undefined;
3
+ type States = Record<string, McpOAuthState>;
4
+ /** Reads the file under its lock, applies `change` to the states and writes them back when it returns a result with `write`. */
5
+ export declare function withFile<T>(change: (states: States) => {
6
+ result: T;
7
+ write?: boolean;
8
+ }): T;
9
+ /** Whether Pi would sign this server in with OAuth: an HTTP server with no `Authorization` header of its own. */
10
+ export declare const usesOAuth: (config: {
11
+ headers?: Record<string, string>;
12
+ auth?: unknown;
13
+ }) => boolean;
14
+ /** An auth provider reading Pi's stored sign-in for `name`; its requests fail with an authorization error until `pi mcp login`. */
15
+ export declare function workerAuthProvider(name: string, config: {
16
+ url: string;
17
+ oauth?: Record<string, unknown>;
18
+ }, env: (text: string) => string): McpAuthProvider;
19
+ export {};
@@ -0,0 +1,120 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
5
+ import { mcpNamespace } from "@earendil-works/pi-mcp";
6
+ import { createMcpAuthProvider, McpRefreshLockBusyError } from "@earendil-works/pi-mcp/oauth";
7
+ import lockfile from "proper-lockfile";
8
+ /**
9
+ * Pi's OAuth sign-in for remote MCP servers, read and refreshed from a worker's own connection. Pi keeps it in
10
+ * `<agent dir>/mcp-auth.json` keyed `<namespace>|<url>`, with a refresh lock per server beside it; this uses both the
11
+ * same way, so a sign-in done with `pi mcp login` serves workers, and a token either side refreshes serves the other.
12
+ * Pi does not export its store, so this mirrors it (as search-tools.ts mirrors Pi's tool-manager). A worker never opens
13
+ * a browser: a server that is not signed in fails with `pi mcp login <name>` as the way out.
14
+ */
15
+ const REFRESH_LOCK_STALE_MS = 20_000, REFRESH_LOCK_WAIT_MS = 25_000, REFRESH_LOCK_RETRY_MS = 100;
16
+ // As Pi's own store: a short synchronous wait for the file lock another process holds.
17
+ const FILE_LOCK_ATTEMPTS = 10, FILE_LOCK_DELAY_MS = 20;
18
+ const CLIENT_NAME = "pi";
19
+ // Pi's Client ID Metadata Documents list `/callback` on localhost and 127.0.0.1; a client signed in through one needs it to refresh.
20
+ const DOCUMENTS = { baseUrl: "https://pi.dev/oauth", listsRedirectUrl: (callbackUrl) => { const url = new URL(callbackUrl); return url.hostname !== "[::1]" && url.pathname === "/callback"; } };
21
+ export const checkMetadataDocumentCallback = (callbackUrl) => callbackUrl === undefined || DOCUMENTS.listsRedirectUrl(callbackUrl) ? undefined : 'oauth.clientRegistration "cimd" requires oauth.callbackUrl on localhost or 127.0.0.1 with path /callback';
22
+ const parse = (text) => { if (!text?.trim())
23
+ return {}; const value = JSON.parse(text); return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {}; };
24
+ const authFile = () => join(getAgentDir(), "mcp-auth.json");
25
+ /** Reads the file under its lock, applies `change` to the states and writes them back when it returns a result with `write`. */
26
+ export function withFile(change) {
27
+ const file = authFile();
28
+ mkdirSync(getAgentDir(), { recursive: true, mode: 0o700 });
29
+ // `wx`: created only when absent, so a racing writer's tokens are never replaced by an empty file.
30
+ try {
31
+ writeFileSync(file, "{}", { encoding: "utf-8", mode: 0o600, flag: "wx" });
32
+ }
33
+ catch (error) {
34
+ if (error.code !== "EEXIST")
35
+ throw error;
36
+ }
37
+ const release = lockSync(file);
38
+ try {
39
+ const states = parse(readFileSync(file, "utf-8"));
40
+ const { result, write } = change(states);
41
+ if (write) {
42
+ // Written beside and renamed over, so a crash mid-write leaves the old file, not a cut one.
43
+ // Beside the real file, so a symlinked store keeps its link; wx, so a file or link planted at the temp name is never followed.
44
+ const target = realpathSync(file), temp = `${target}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
45
+ try {
46
+ writeFileSync(temp, `${JSON.stringify(states, null, 2)}\n`, { encoding: "utf-8", mode: 0o600, flag: "wx" });
47
+ renameSync(temp, target);
48
+ }
49
+ catch (error) {
50
+ rmSync(temp, { force: true });
51
+ throw error;
52
+ }
53
+ }
54
+ return result;
55
+ }
56
+ finally {
57
+ release();
58
+ }
59
+ }
60
+ function lockSync(file) {
61
+ for (let attempt = 1;; attempt++) {
62
+ try {
63
+ return lockfile.lockSync(file);
64
+ }
65
+ catch (error) {
66
+ if (error.code !== "ELOCKED" || attempt === FILE_LOCK_ATTEMPTS)
67
+ throw error;
68
+ // Synchronous, as the store's callers are.
69
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, FILE_LOCK_DELAY_MS);
70
+ }
71
+ }
72
+ }
73
+ /** One server's state, keyed as Pi keys it, with Pi's refresh lock file so Pi and workers never refresh one grant twice. */
74
+ function storeFor(name, serverUrl) {
75
+ const legacy = String(new URL(serverUrl)), key = `${mcpNamespace(name)}|${legacy}`;
76
+ return {
77
+ load: () => withFile((states) => ({ result: states[key] ?? states[legacy] })),
78
+ save: (state) => withFile((states) => { states[key] = state; return { result: undefined, write: true }; }),
79
+ async withRefreshLock(fn) {
80
+ const dir = getAgentDir();
81
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
82
+ const hash = createHash("sha256").update(key).digest("hex").slice(0, 16);
83
+ const release = await lockfile.lock(join(dir, `mcp-auth-refresh-${hash}`), {
84
+ realpath: false, stale: REFRESH_LOCK_STALE_MS,
85
+ retries: { retries: REFRESH_LOCK_WAIT_MS / REFRESH_LOCK_RETRY_MS, factor: 1, minTimeout: REFRESH_LOCK_RETRY_MS, maxTimeout: REFRESH_LOCK_RETRY_MS },
86
+ onCompromised: () => { },
87
+ }).catch((error) => { throw error?.code === "ELOCKED" ? new McpRefreshLockBusyError() : error; });
88
+ try {
89
+ return await fn();
90
+ }
91
+ finally {
92
+ await release().catch(() => { });
93
+ }
94
+ },
95
+ };
96
+ }
97
+ /** The `oauth` entry of an `mcp.json` server as sign-in settings; `${NAME}` in the secret reads the environment. */
98
+ function settingsOf(oauth, env) {
99
+ if (!oauth)
100
+ return {};
101
+ const text = (value) => typeof value === "string" ? value : undefined;
102
+ const secret = text(oauth.clientSecret), metadata = text(oauth.authServerMetadataUrl);
103
+ return {
104
+ clientId: text(oauth.clientId), clientSecret: secret === undefined ? undefined : env(secret),
105
+ callbackPort: typeof oauth.callbackPort === "number" ? oauth.callbackPort : undefined, callbackUrl: text(oauth.callbackUrl),
106
+ scope: text(oauth.scope), clientName: text(oauth.clientName),
107
+ clientRegistration: oauth.clientRegistration === "dcr" || oauth.clientRegistration === "cimd" || oauth.clientRegistration === "auto" ? oauth.clientRegistration : undefined,
108
+ ...(metadata ? { authServerMetadataUrl: new URL(metadata) } : {}),
109
+ };
110
+ }
111
+ /** Whether Pi would sign this server in with OAuth: an HTTP server with no `Authorization` header of its own. */
112
+ export const usesOAuth = (config) => !config.auth && !Object.keys(config.headers ?? {}).some((header) => header.toLowerCase() === "authorization");
113
+ /** An auth provider reading Pi's stored sign-in for `name`; its requests fail with an authorization error until `pi mcp login`. */
114
+ export function workerAuthProvider(name, config, env) {
115
+ const { oauth } = config;
116
+ return createMcpAuthProvider({
117
+ serverUrl: config.url, store: storeFor(name, config.url), settings: () => settingsOf(oauth, env), onChallenge: () => { },
118
+ clientName: CLIENT_NAME, clientMetadataDocuments: DOCUMENTS,
119
+ });
120
+ }
@@ -0,0 +1,42 @@
1
+ import { type Extension, type ToolRegistration } from "@earendil-works/pi-durable";
2
+ import { McpClient } from "@earendil-works/pi-mcp";
3
+ /** `extensions`: one per connected server, each a code mode namespace. `tools`: all their tools. */
4
+ type Link = {
5
+ client: McpClient;
6
+ dead: boolean;
7
+ shutdown: boolean;
8
+ reconnecting?: Promise<McpClient>;
9
+ };
10
+ type Served = {
11
+ name: string;
12
+ fingerprint: string;
13
+ link: Link;
14
+ extension: Extension<ToolRegistration>;
15
+ readOnly: string[];
16
+ };
17
+ type Connected = {
18
+ served: Served[];
19
+ links: Link[];
20
+ extensions: Extension<ToolRegistration>[];
21
+ tools: ToolRegistration[];
22
+ errors: string[];
23
+ at: number;
24
+ };
25
+ type AuthResolver = (provider: string) => Promise<string | undefined>;
26
+ export declare function setWorkerMcpAuthResolver(resolver: AuthResolver | undefined): void;
27
+ export declare const expand: (text: string) => string;
28
+ /**
29
+ * The MCP tools workers may call, connected once per process; `errors` names servers of `mcp.json` that were unusable.
30
+ * A set with errors is opened again once `RETRY_MS` have passed, so a server that was down, or a fixed configuration, is
31
+ * picked up without a restart.
32
+ */
33
+ export declare function workerMcp(): Promise<Connected>;
34
+ /** Marks the cached MCP set stale so the next `workerMcp()` call reconciles the user-level `mcp.json`. */
35
+ export declare function invalidateWorkerMcp(): void;
36
+ /** Closes the connections; the next `workerMcp()` connects again. */
37
+ export declare function closeWorkerMcp(): Promise<void>;
38
+ /** Marks `holder` (a package's session) as using the connections; called before each use, as it costs nothing. */
39
+ export declare function holdWorkerMcp(holder: string): void;
40
+ /** `holder` is done with the connections: the last holder closes them, so one session ending leaves the others theirs. */
41
+ export declare function releaseWorkerMcp(holder: string): Promise<void>;
42
+ export {};