@minhtri2710/pi-durable-shared 2.0.0 → 2.2.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 +13 -5
- package/bin/lint-state.sh +15 -3
- package/dist/durable-runtime.d.ts +13 -1
- package/dist/durable-runtime.js +41 -9
- package/dist/mcp-oauth.js +2 -1
- package/dist/mcp-tools.d.ts +11 -0
- package/dist/mcp-tools.js +74 -7
- package/dist/tool-arguments.d.ts +2 -0
- package/dist/tool-arguments.js +27 -0
- package/dist/worker-extensions.d.ts +11 -0
- package/dist/worker-extensions.js +21 -0
- package/package.json +5 -3
package/README.md
CHANGED
|
@@ -8,23 +8,31 @@ Install with `npm install @minhtri2710/pi-durable-shared`. Import each as `@minh
|
|
|
8
8
|
|
|
9
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
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
|
-
- `
|
|
11
|
+
- `worker-extensions`: the worker-extension registry. `registerWorkerExtension(extension)` offers an extension named `workers.ext.<name>` to every durable worker: swarm workers, teamwork tasks and the orchestrator executor. It returns the function that unregisters it. `workerExtensions()` lists the registered ones. The registry is process-wide, so it survives `/reload` and is shared by every copy of this package. Each `getDurableRuntime` installs the registered extensions (a re-registered one replaces the old object) and uninstalls one that was unregistered; only `workers.ext.*` and `workers.mcp.*` names are touched. A runtime open before a registration picks it up at its next `getDurableRuntime`. pi-background is the first user. `workerCodingTools()` gives `bash` a default timeout of 600 seconds; a call's own `timeout` wins.
|
|
12
|
+
- `mcp-tools`, `mcp-oauth`: MCP servers for workers: every server of the user-level `<agent dir>/mcp.json` except those with `enabled: false` (off everywhere) or `workers: false` (off for workers only), connected separately from Pi's own. A switched-off entry is skipped before validation, so it never yields an error. An invalid or failing active 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
13
|
- `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
14
|
- `search-tools`: `grep` and `find` for workers. `execWithTimeout` takes milliseconds and passes seconds to `exec`.
|
|
14
15
|
- `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
16
|
- `project-rules`: the AGENTS.md / CLAUDE.md text for a worker's instructions.
|
|
17
|
+
- `tool-arguments`: `parseJsonStringArguments(schema)`, for a tool's `prepareArguments`: it parses arguments that arrive as a JSON string into the object the schema describes.
|
|
16
18
|
- `testing`: `loadTwice(specifier)`, which loads a module twice as a reload does.
|
|
17
19
|
|
|
18
20
|
`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
21
|
|
|
20
|
-
## Develop
|
|
22
|
+
## Develop against a local build
|
|
23
|
+
|
|
24
|
+
`@earendil-works/pi-durable` and `@earendil-works/chord` are peer dependencies, along with pi-ai, pi-coding-agent, pi-tui and typebox. The host supplies them, so the host and this package run one copy of each. Per-copy state, such as the signal tokens made by `defineSignal`, only works within a single copy.
|
|
25
|
+
|
|
26
|
+
Do not use `npm link`. It symlinks the consumer to this directory, so Node resolves `@earendil-works/pi-durable` from here as a second copy. A token from the host's `defineSignal` is then unknown to the harness opened here, and `harness.signal` throws `Signal ... was not built by defineSignal()`.
|
|
27
|
+
|
|
28
|
+
Install a real copy of the local build instead:
|
|
21
29
|
|
|
22
30
|
```sh
|
|
23
31
|
cd pi-durable-shared && npm install && npm run build
|
|
24
|
-
cd ../pi-swarm && npm
|
|
32
|
+
cd ../pi-swarm && npm install --no-save --install-links ../pi-durable-shared # likewise pi-teamwork, pi-orchestrator, pi-schedule
|
|
25
33
|
```
|
|
26
34
|
|
|
27
|
-
`npm
|
|
35
|
+
Run `npm run build` here and repeat the install in the consumer after each change. `--no-save` leaves the consumer's `package.json` alone, and a plain `npm install` in the consumer replaces the copy with the published version.
|
|
28
36
|
|
|
29
37
|
```sh
|
|
30
38
|
npm test # node --test src/*.test.ts
|
|
@@ -33,7 +41,7 @@ npm run typecheck # tsc -p .
|
|
|
33
41
|
|
|
34
42
|
## Publish to npm
|
|
35
43
|
|
|
36
|
-
Consumers depend on `"@minhtri2710/pi-durable-shared": "^2.
|
|
44
|
+
Consumers depend on `"@minhtri2710/pi-durable-shared": "^2.2.0"`. The package ships a prebuilt `dist`, so installing it runs no scripts. `prepublishOnly` builds and tests before each publish.
|
|
37
45
|
|
|
38
46
|
```sh
|
|
39
47
|
npm login # once, in your terminal
|
package/bin/lint-state.sh
CHANGED
|
@@ -5,11 +5,23 @@
|
|
|
5
5
|
# module-level variable is then two states: the old copy's tools see one, the live extension the other. State that must
|
|
6
6
|
# survive goes through processState(key, init) from pi-durable-shared/process-state.
|
|
7
7
|
# Needs ripgrep. Run it in a package directory: `pi-lint-state`.
|
|
8
|
-
|
|
8
|
+
if ! command -v rg >/dev/null 2>&1; then
|
|
9
|
+
echo "lint:state: ripgrep (rg) is required" >&2
|
|
10
|
+
exit 2
|
|
11
|
+
fi
|
|
12
|
+
list=$(mktemp) || exit 2
|
|
13
|
+
trap 'rm -f "$list"' EXIT
|
|
14
|
+
rg -l -e 'defineTool' -e 'defineTask' -g '*.ts' -g '!*.test.ts' -g '!node_modules' -g '!dist' . >"$list"
|
|
15
|
+
# rg exits 1 when nothing matches, 2 or more when it failed.
|
|
16
|
+
case $? in 0) ;; 1) exit 0 ;; *) echo "lint:state: rg failed" >&2; exit 2 ;; esac
|
|
9
17
|
status=0
|
|
10
18
|
# At column 0 only: a let or var, a new Map/Set kept in a const, or a raw globalThis `??=` slot.
|
|
11
|
-
|
|
19
|
+
# One file per call, read a line at a time, so a path with spaces stays one argument.
|
|
20
|
+
while IFS= read -r file; do
|
|
21
|
+
rg -n --with-filename -e '^(export )?(let|var) ' -e '^(export )?const [^=]*= new (Map|Set|WeakMap|WeakSet)\b' -e '^[^ /*].*\?\?= ' -- "$file"
|
|
22
|
+
case $? in 0) status=1 ;; 1) ;; *) echo "lint:state: rg failed" >&2; exit 2 ;; esac
|
|
23
|
+
done <"$list"
|
|
24
|
+
if [ "$status" -ne 0 ]; then
|
|
12
25
|
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
26
|
fi
|
|
15
27
|
exit $status
|
|
@@ -7,7 +7,11 @@ export type DurableRuntime = {
|
|
|
7
7
|
models: MutableModels;
|
|
8
8
|
settling: Set<string | number>;
|
|
9
9
|
};
|
|
10
|
-
/**
|
|
10
|
+
/** What a worker's `bash` call with no `timeout` gets, in seconds. */
|
|
11
|
+
export declare const WORKER_BASH_TIMEOUT_SECONDS = 600;
|
|
12
|
+
/** The coding tools with `bash` defaulting to `WORKER_BASH_TIMEOUT_SECONDS`; an explicit `timeout` is validated and used as given. */
|
|
13
|
+
export declare function withBashTimeout(extension: Extension<ToolRegistration>): Extension<ToolRegistration>;
|
|
14
|
+
/** Built-in coding tools (`read`, `write`, `edit`, `bash`) with Pi 1.8.0's lightweight WASM image processor; `bash` times out after 10 minutes unless the call passes a `timeout`. */
|
|
11
15
|
export declare function workerCodingTools(): Promise<Extension<ToolRegistration>>;
|
|
12
16
|
/**
|
|
13
17
|
* Forwards any unreported durable worker model usage from `Harness.usage()` to the parent Pi session via
|
|
@@ -15,6 +19,14 @@ export declare function workerCodingTools(): Promise<Extension<ToolRegistration>
|
|
|
15
19
|
*/
|
|
16
20
|
export declare function flushDurableUsage(runtime: DurableRuntime, pi: Pick<ExtensionAPI, "appendUsage">, kind: string, note?: string): Promise<void>;
|
|
17
21
|
export declare function hasDurableRuntime(ctx: ExtensionContext, namespace: string): Promise<boolean>;
|
|
22
|
+
/**
|
|
23
|
+
* Makes the registry's `workers.mcp.*` and `workers.ext.*` extensions exactly `extensions`' ones: a changed one (another object under the
|
|
24
|
+
* same name) is replaced, one no longer listed is uninstalled. Each install publishes a registry and wakes every parked
|
|
25
|
+
* call, so an unchanged extension is left alone. Other extensions are installed only when missing: one already there by
|
|
26
|
+
* name stays, also the copy an instance before /reload installed (the guards and the board keep their per-instance state
|
|
27
|
+
* on globalThis, so an earlier copy reaches the live instance).
|
|
28
|
+
*/
|
|
29
|
+
export declare function syncWorkerMcpExtensions(registry: Registry, extensions: readonly Extension<ToolRegistration>[]): void;
|
|
18
30
|
/** `options` apply when the runtime is created; a runtime already open keeps the settings it was opened with. */
|
|
19
31
|
export declare function getDurableRuntime(ctx: ExtensionContext, namespace: string, extensions?: readonly Extension<ToolRegistration>[], options?: {
|
|
20
32
|
afterFailedRun?: "continue";
|
package/dist/durable-runtime.js
CHANGED
|
@@ -8,6 +8,7 @@ import { createCodingTools } from "@earendil-works/pi-durable/tools";
|
|
|
8
8
|
import { setWorkerMcpAuthResolver } from "./mcp-tools.js";
|
|
9
9
|
import { processState } from "./process-state.js";
|
|
10
10
|
import { databasePath, openSessionStore } from "./session-store.js";
|
|
11
|
+
import { WORKER_EXTENSION_PREFIX, workerExtensions } from "./worker-extensions.js";
|
|
11
12
|
// Opens and closes in flight, process-wide like the runtimes, so an instance started by /reload sees them too.
|
|
12
13
|
const pending = processState("pi-durable-extension.opening", () => new Map());
|
|
13
14
|
const closing = processState("pi-durable-extension.closing", () => new Map());
|
|
@@ -20,11 +21,25 @@ const UsageWatermarkDoc = defineDoc({
|
|
|
20
21
|
checkpointWhen: (_value, _ops, info) => info.deltasSinceBase > 32,
|
|
21
22
|
});
|
|
22
23
|
const runtimes = () => processState("pi-durable-extension.runtimes", () => new Map());
|
|
23
|
-
/**
|
|
24
|
+
/** What a worker's `bash` call with no `timeout` gets, in seconds. */
|
|
25
|
+
export const WORKER_BASH_TIMEOUT_SECONDS = 600;
|
|
26
|
+
const BASH_TIMEOUT_NOTE = ` With no timeout a command is stopped after ${WORKER_BASH_TIMEOUT_SECONDS} seconds; pass a larger timeout for a longer one, or run it with pi-background when that tool is available.`;
|
|
27
|
+
/** The coding tools with `bash` defaulting to `WORKER_BASH_TIMEOUT_SECONDS`; an explicit `timeout` is validated and used as given. */
|
|
28
|
+
export function withBashTimeout(extension) {
|
|
29
|
+
return {
|
|
30
|
+
...extension,
|
|
31
|
+
tools: extension.tools?.map((tool) => tool.name !== "bash" ? tool : {
|
|
32
|
+
...tool,
|
|
33
|
+
description: tool.description + BASH_TIMEOUT_NOTE,
|
|
34
|
+
execute: (args, api, context) => tool.execute({ ...args, timeout: args.timeout ?? WORKER_BASH_TIMEOUT_SECONDS }, api, context),
|
|
35
|
+
}),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** Built-in coding tools (`read`, `write`, `edit`, `bash`) with Pi 1.8.0's lightweight WASM image processor; `bash` times out after 10 minutes unless the call passes a `timeout`. */
|
|
24
39
|
export async function workerCodingTools() {
|
|
25
40
|
// A failed build is not kept: the next call tries again.
|
|
26
41
|
return codingTools.built ??= createNodePiImages()
|
|
27
|
-
.then((images) => createCodingTools({ images }))
|
|
42
|
+
.then((images) => withBashTimeout(createCodingTools({ images })))
|
|
28
43
|
.catch((error) => { codingTools.built = undefined; throw error; });
|
|
29
44
|
}
|
|
30
45
|
function diffUsage(latest, prev) {
|
|
@@ -169,6 +184,28 @@ function defaultReport(report) {
|
|
|
169
184
|
console.error(`[pi-durable] ${report.kind}: ${detail}`);
|
|
170
185
|
}
|
|
171
186
|
}
|
|
187
|
+
const MCP_PREFIX = "workers.mcp.";
|
|
188
|
+
const isManaged = (name) => name.startsWith(MCP_PREFIX) || name.startsWith(WORKER_EXTENSION_PREFIX);
|
|
189
|
+
/**
|
|
190
|
+
* Makes the registry's `workers.mcp.*` and `workers.ext.*` extensions exactly `extensions`' ones: a changed one (another object under the
|
|
191
|
+
* same name) is replaced, one no longer listed is uninstalled. Each install publishes a registry and wakes every parked
|
|
192
|
+
* call, so an unchanged extension is left alone. Other extensions are installed only when missing: one already there by
|
|
193
|
+
* name stays, also the copy an instance before /reload installed (the guards and the board keep their per-instance state
|
|
194
|
+
* on globalThis, so an earlier copy reaches the live instance).
|
|
195
|
+
*/
|
|
196
|
+
export function syncWorkerMcpExtensions(registry, extensions) {
|
|
197
|
+
const wanted = new Set(extensions.map((extension) => extension.name));
|
|
198
|
+
for (const installed of registry.snapshot().installed())
|
|
199
|
+
if (isManaged(installed.name) && !wanted.has(installed.name))
|
|
200
|
+
registry.uninstall(installed);
|
|
201
|
+
for (const extension of extensions) {
|
|
202
|
+
const current = registry.snapshot().extension(extension.name);
|
|
203
|
+
if (current === extension)
|
|
204
|
+
continue;
|
|
205
|
+
if (!current || isManaged(extension.name))
|
|
206
|
+
registry.install(extension);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
172
209
|
/** `options` apply when the runtime is created; a runtime already open keeps the settings it was opened with. */
|
|
173
210
|
export async function getDurableRuntime(ctx, namespace, extensions = [], options = {}) {
|
|
174
211
|
if (typeof ctx.modelRegistry?.getApiKeyForProvider === "function") {
|
|
@@ -204,12 +241,7 @@ export async function getDurableRuntime(ctx, namespace, extensions = [], options
|
|
|
204
241
|
throw new Error("Durable runtime closed while opening");
|
|
205
242
|
if (cached.sessionId !== sessionId)
|
|
206
243
|
throw new Error("Durable session identity mismatch");
|
|
207
|
-
|
|
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);
|
|
244
|
+
syncWorkerMcpExtensions(cached.registry, [...extensions, ...workerExtensions()]);
|
|
213
245
|
syncModels(cached.models, ctx.modelRegistry);
|
|
214
246
|
cached.harness.resume();
|
|
215
247
|
return cached;
|
|
@@ -220,7 +252,7 @@ async function createDurableRuntime(ctx, namespace, sessionId, path, extensions,
|
|
|
220
252
|
try {
|
|
221
253
|
store = await openSessionStore(ctx, namespace);
|
|
222
254
|
const registry = createRegistry();
|
|
223
|
-
for (const extension of extensions)
|
|
255
|
+
for (const extension of [...extensions, ...workerExtensions()])
|
|
224
256
|
registry.install(extension);
|
|
225
257
|
const models = createModels();
|
|
226
258
|
syncModels(models, ctx.modelRegistry);
|
package/dist/mcp-oauth.js
CHANGED
|
@@ -75,7 +75,8 @@ function storeFor(name, serverUrl) {
|
|
|
75
75
|
const legacy = String(new URL(serverUrl)), key = `${mcpNamespace(name)}|${legacy}`;
|
|
76
76
|
return {
|
|
77
77
|
load: () => withFile((states) => ({ result: states[key] ?? states[legacy] })),
|
|
78
|
-
|
|
78
|
+
// The legacy URL-only key is taken over by the namespaced one, as Pi does, so a stale copy never shadows it.
|
|
79
|
+
save: (state) => withFile((states) => { states[key] = state; delete states[legacy]; return { result: undefined, write: true }; }),
|
|
79
80
|
async withRefreshLock(fn) {
|
|
80
81
|
const dir = getAgentDir();
|
|
81
82
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
package/dist/mcp-tools.d.ts
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
import { type Extension, type ToolRegistration } from "@earendil-works/pi-durable";
|
|
2
2
|
import { McpClient } from "@earendil-works/pi-mcp";
|
|
3
|
+
declare const EXPOSURES: readonly ["codemode", "deferred", "direct", "hidden"];
|
|
4
|
+
type Exposure = (typeof EXPOSURES)[number];
|
|
5
|
+
/**
|
|
6
|
+
* Exposure of one tool, as Pi's getMcpToolExposure: an exact `toolExposure` entry, then a wildcard one, then the server's
|
|
7
|
+
* `exposure`. Undefined when none is set: Pi then means `codemode`, but a worker without code mode would then not be
|
|
8
|
+
* offered the tool at all, so an unset exposure keeps the tool callable directly.
|
|
9
|
+
*/
|
|
10
|
+
export declare function toolExposure(config: {
|
|
11
|
+
exposure?: unknown;
|
|
12
|
+
toolExposure?: Record<string, unknown>;
|
|
13
|
+
}, toolName: string): Exposure | undefined;
|
|
3
14
|
/** `extensions`: one per connected server, each a code mode namespace. `tools`: all their tools. */
|
|
4
15
|
type Link = {
|
|
5
16
|
client: McpClient;
|
package/dist/mcp-tools.js
CHANGED
|
@@ -11,6 +11,58 @@ import { processState } from "./process-state.js";
|
|
|
11
11
|
import { sweepTempFilesOnce } from "./retention.js";
|
|
12
12
|
import { checkMetadataDocumentCallback, usesOAuth, workerAuthProvider } from "./mcp-oauth.js";
|
|
13
13
|
const CONNECT_MS = 20_000;
|
|
14
|
+
// Pi's core/mcp-servers.js is not exported by pi-coding-agent, so its checks beyond pi-mcp's are mirrored here.
|
|
15
|
+
const EXPOSURES = ["codemode", "deferred", "direct", "hidden"];
|
|
16
|
+
const EXPOSURE_ALIASES = { "codemode-deferred": "codemode" };
|
|
17
|
+
const LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
|
|
18
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
19
|
+
const isExposure = (value) => typeof value === "string" && EXPOSURES.includes(value);
|
|
20
|
+
const resolveAlias = (value) => typeof value === "string" ? EXPOSURE_ALIASES[value] ?? value : value;
|
|
21
|
+
/** The entry with exposure aliases resolved, as Pi validates it. */
|
|
22
|
+
function resolveExposureAliases(entry) {
|
|
23
|
+
const resolved = { ...entry };
|
|
24
|
+
if (entry.exposure !== undefined)
|
|
25
|
+
resolved.exposure = resolveAlias(entry.exposure);
|
|
26
|
+
if (isRecord(entry.toolExposure))
|
|
27
|
+
resolved.toolExposure = Object.fromEntries(Object.entries(entry.toolExposure).map(([tool, value]) => [tool, resolveAlias(value)]));
|
|
28
|
+
return resolved;
|
|
29
|
+
}
|
|
30
|
+
/** Pi's checks on a validated entry: exposure values, and `auth` only over https or loopback http. An error message, or undefined. */
|
|
31
|
+
function checkPiFields(kind, config) {
|
|
32
|
+
const allowed = EXPOSURES.map((value) => `"${value}"`).join(", ");
|
|
33
|
+
if (config.exposure !== undefined && !isExposure(config.exposure))
|
|
34
|
+
return `exposure must be one of ${allowed}`;
|
|
35
|
+
if (config.toolExposure !== undefined) {
|
|
36
|
+
if (!isRecord(config.toolExposure))
|
|
37
|
+
return "toolExposure must map tool names to exposures";
|
|
38
|
+
for (const [tool, value] of Object.entries(config.toolExposure))
|
|
39
|
+
if (!isExposure(value))
|
|
40
|
+
return `toolExposure "${tool}" must be one of ${allowed}`;
|
|
41
|
+
}
|
|
42
|
+
if (kind === "http" && config.auth !== undefined) {
|
|
43
|
+
if (!isRecord(config.auth) || typeof config.auth.provider !== "string" || !config.auth.provider)
|
|
44
|
+
return "auth.provider must be a provider name";
|
|
45
|
+
const parsed = new URL(config.url);
|
|
46
|
+
if (parsed.protocol !== "https:" && !LOOPBACK_HOSTS.includes(parsed.hostname))
|
|
47
|
+
return "auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]";
|
|
48
|
+
}
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
const patternOf = (pattern) => new RegExp(`^${pattern.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`);
|
|
52
|
+
/**
|
|
53
|
+
* Exposure of one tool, as Pi's getMcpToolExposure: an exact `toolExposure` entry, then a wildcard one, then the server's
|
|
54
|
+
* `exposure`. Undefined when none is set: Pi then means `codemode`, but a worker without code mode would then not be
|
|
55
|
+
* offered the tool at all, so an unset exposure keeps the tool callable directly.
|
|
56
|
+
*/
|
|
57
|
+
export function toolExposure(config, toolName) {
|
|
58
|
+
const overrides = config.toolExposure ?? {};
|
|
59
|
+
if (Object.hasOwn(overrides, toolName))
|
|
60
|
+
return overrides[toolName];
|
|
61
|
+
for (const [pattern, exposure] of Object.entries(overrides))
|
|
62
|
+
if (pattern.includes("*") && patternOf(pattern).test(toolName))
|
|
63
|
+
return exposure;
|
|
64
|
+
return config.exposure;
|
|
65
|
+
}
|
|
14
66
|
/** A set with an unusable server is opened again by a call this long after it, keeping the servers that connected. */
|
|
15
67
|
const RETRY_MS = 30_000;
|
|
16
68
|
// On globalThis, not module-local: a /reload loads this module again, and its own variable would open the servers a second
|
|
@@ -80,19 +132,32 @@ async function saveToTempFile(data, extension) {
|
|
|
80
132
|
await writeFile(file, data, { flag: "wx", mode: 0o600 });
|
|
81
133
|
return file;
|
|
82
134
|
}
|
|
83
|
-
/** The servers workers use: every server the user-level `<agent dir>/mcp.json` defines
|
|
135
|
+
/** The servers workers use: every server the user-level `<agent dir>/mcp.json` defines, except those with `enabled: false` (off everywhere) or `workers: false` (off for workers only). Those are skipped before validation, so a switched-off entry never yields an error. An invalid active one is reported in `errors`. */
|
|
84
136
|
function selectedServers(errors) {
|
|
85
137
|
const defined = readJson(join(getAgentDir(), "mcp.json"))?.mcpServers ?? {};
|
|
86
138
|
const chosen = [];
|
|
87
139
|
const namespaces = new Map();
|
|
88
140
|
for (const name of Object.keys(defined)) {
|
|
89
|
-
const
|
|
141
|
+
const entry = defined[name];
|
|
142
|
+
if (entry && typeof entry === "object") {
|
|
143
|
+
const { enabled, workers } = entry;
|
|
144
|
+
if (workers !== undefined && typeof workers !== "boolean") {
|
|
145
|
+
errors.push(`${name}: workers must be true or false`);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (enabled === false || workers === false)
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
const checked = validateMcpServerConfig(name, isRecord(entry) ? resolveExposureAliases(entry) : entry, { checkMetadataDocumentCallback });
|
|
90
152
|
if (checked.kind === "invalid") {
|
|
91
153
|
errors.push(checked.error);
|
|
92
154
|
continue;
|
|
93
155
|
}
|
|
94
|
-
|
|
156
|
+
const fieldError = checkPiFields(checked.kind, checked.config);
|
|
157
|
+
if (fieldError) {
|
|
158
|
+
errors.push(`server "${name}": ${fieldError}`);
|
|
95
159
|
continue;
|
|
160
|
+
}
|
|
96
161
|
const ns = mcpNamespace(name);
|
|
97
162
|
const existing = namespaces.get(ns);
|
|
98
163
|
if (existing && existing !== name) {
|
|
@@ -235,10 +300,10 @@ async function open(previous) {
|
|
|
235
300
|
};
|
|
236
301
|
const tools = [], readOnly = [];
|
|
237
302
|
for (const tool of listed) {
|
|
238
|
-
const exposure = (server.config
|
|
303
|
+
const exposure = toolExposure(server.config, tool.name);
|
|
239
304
|
if (exposure === "hidden")
|
|
240
305
|
continue;
|
|
241
|
-
const deferred = exposure === "deferred" || exposure === "codemode"
|
|
306
|
+
const deferred = exposure === "deferred" || exposure === "codemode";
|
|
242
307
|
const name = createMcpToolName(server.name, tool.name, (candidate) => taken.has(candidate));
|
|
243
308
|
taken.add(name);
|
|
244
309
|
// The server's own account, trusted as the user chose: a server that marks a writing tool read-only runs it unasked.
|
|
@@ -299,10 +364,12 @@ export function workerMcp() {
|
|
|
299
364
|
const settled = shared.settled;
|
|
300
365
|
if (shared.connecting && !(settled?.errors.length && Date.now() - settled.at >= RETRY_MS) && !shared.stale)
|
|
301
366
|
return shared.connecting;
|
|
367
|
+
// An open still in flight is waited for, so its connections are the ones reconciled, not left running beside a second set.
|
|
368
|
+
const previous = settled ? Promise.resolve(settled) : shared.connecting?.catch(() => undefined) ?? Promise.resolve(undefined);
|
|
302
369
|
shared.stale = false;
|
|
303
370
|
shared.settled = undefined;
|
|
304
371
|
sweepTempFilesOnce();
|
|
305
|
-
const connecting = shared.connecting = open(
|
|
372
|
+
const connecting = shared.connecting = previous.then((last) => open(last)).then((value) => { if (shared.connecting === connecting) {
|
|
306
373
|
shared.settled = value;
|
|
307
374
|
shared.readOnly = new Set(value.served.flatMap((item) => item.readOnly));
|
|
308
375
|
} return value; }, (error) => { if (shared.connecting === connecting)
|
|
@@ -311,7 +378,7 @@ export function workerMcp() {
|
|
|
311
378
|
}
|
|
312
379
|
/** Marks the cached MCP set stale so the next `workerMcp()` call reconciles the user-level `mcp.json`. */
|
|
313
380
|
export function invalidateWorkerMcp() {
|
|
314
|
-
if (shared.settled)
|
|
381
|
+
if (shared.connecting || shared.settled)
|
|
315
382
|
shared.stale = true;
|
|
316
383
|
}
|
|
317
384
|
/** Closes the connections; the next `workerMcp()` connects again. */
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2
|
+
// Models sometimes send nested array/object parameters as JSON strings; parse those so schema validation sees the real type.
|
|
3
|
+
export function parseJsonStringArguments(schema) {
|
|
4
|
+
const properties = schema.properties ?? {};
|
|
5
|
+
const structured = Object.entries(properties).flatMap(([key, property]) => property.type === "array" || property.type === "object" ? [[key, property.type]] : []);
|
|
6
|
+
return (args) => {
|
|
7
|
+
if (!isPlainObject(args))
|
|
8
|
+
return args;
|
|
9
|
+
let result = args;
|
|
10
|
+
for (const [key, type] of structured) {
|
|
11
|
+
const value = args[key];
|
|
12
|
+
if (typeof value !== "string")
|
|
13
|
+
continue;
|
|
14
|
+
let parsed;
|
|
15
|
+
try {
|
|
16
|
+
parsed = JSON.parse(value);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
if (type === "array" ? Array.isArray(parsed) : isPlainObject(parsed)) {
|
|
22
|
+
result = { ...result, [key]: parsed };
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return result;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Extension, ToolRegistration } from "@earendil-works/pi-durable";
|
|
2
|
+
/** Every registered worker extension is named `workers.ext.<name>`; `getDurableRuntime` installs and uninstalls only names with this prefix. */
|
|
3
|
+
export declare const WORKER_EXTENSION_PREFIX = "workers.ext.";
|
|
4
|
+
/**
|
|
5
|
+
* Offers `extension` to every durable worker: swarm workers, teamwork tasks and the orchestrator executor. A runtime
|
|
6
|
+
* picks it up at its next `getDurableRuntime`. Registering a name again replaces the earlier extension. Returns the
|
|
7
|
+
* function that unregisters it; the next `getDurableRuntime` uninstalls it. Unregistering after a replacement leaves
|
|
8
|
+
* the replacement in place.
|
|
9
|
+
*/
|
|
10
|
+
export declare function registerWorkerExtension(extension: Extension<ToolRegistration>): () => void;
|
|
11
|
+
export declare function workerExtensions(): readonly Extension<ToolRegistration>[];
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { processState } from "./process-state.js";
|
|
2
|
+
/** Every registered worker extension is named `workers.ext.<name>`; `getDurableRuntime` installs and uninstalls only names with this prefix. */
|
|
3
|
+
export const WORKER_EXTENSION_PREFIX = "workers.ext.";
|
|
4
|
+
// Process-wide, so a /reload and every copy of this package see the same list.
|
|
5
|
+
const registered = () => processState("pi-durable-shared.worker-extensions", () => new Map());
|
|
6
|
+
/**
|
|
7
|
+
* Offers `extension` to every durable worker: swarm workers, teamwork tasks and the orchestrator executor. A runtime
|
|
8
|
+
* picks it up at its next `getDurableRuntime`. Registering a name again replaces the earlier extension. Returns the
|
|
9
|
+
* function that unregisters it; the next `getDurableRuntime` uninstalls it. Unregistering after a replacement leaves
|
|
10
|
+
* the replacement in place.
|
|
11
|
+
*/
|
|
12
|
+
export function registerWorkerExtension(extension) {
|
|
13
|
+
if (!extension.name.startsWith(WORKER_EXTENSION_PREFIX))
|
|
14
|
+
throw new Error(`A worker extension is named "${WORKER_EXTENSION_PREFIX}<name>", got "${extension.name}"`);
|
|
15
|
+
registered().set(extension.name, extension);
|
|
16
|
+
return () => { if (registered().get(extension.name) === extension)
|
|
17
|
+
registered().delete(extension.name); };
|
|
18
|
+
}
|
|
19
|
+
export function workerExtensions() {
|
|
20
|
+
return [...registered().values()];
|
|
21
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@minhtri2710/pi-durable-shared",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "Durable runtime, MCP, search and code mode helpers shared by the pi-orchestrator, pi-swarm, pi-teamwork and pi-schedule extensions.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -36,21 +36,23 @@
|
|
|
36
36
|
"prepublishOnly": "npm run build && npm test"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
|
-
"@earendil-works/chord": "1.8.0",
|
|
40
39
|
"@earendil-works/pi-codemode": "1.8.0",
|
|
41
|
-
"@earendil-works/pi-durable": "1.8.0",
|
|
42
40
|
"@earendil-works/pi-mcp": "1.8.0",
|
|
43
41
|
"proper-lockfile": "4.1.2"
|
|
44
42
|
},
|
|
45
43
|
"peerDependencies": {
|
|
44
|
+
"@earendil-works/chord": "1.8.0",
|
|
46
45
|
"@earendil-works/pi-ai": "*",
|
|
47
46
|
"@earendil-works/pi-coding-agent": "*",
|
|
47
|
+
"@earendil-works/pi-durable": "1.8.0",
|
|
48
48
|
"@earendil-works/pi-tui": "*",
|
|
49
49
|
"typebox": "*"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
|
+
"@earendil-works/chord": "1.8.0",
|
|
52
53
|
"@earendil-works/pi-ai": "1.8.0",
|
|
53
54
|
"@earendil-works/pi-coding-agent": "1.8.0",
|
|
55
|
+
"@earendil-works/pi-durable": "1.8.0",
|
|
54
56
|
"@earendil-works/pi-tui": "1.8.0",
|
|
55
57
|
"@types/node": "^22.20.7",
|
|
56
58
|
"@types/proper-lockfile": "4.1.4",
|