@minhtri2710/pi-durable-shared 2.1.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 +2 -1
- 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 +64 -5
- package/dist/worker-extensions.d.ts +11 -0
- package/dist/worker-extensions.js +21 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,6 +8,7 @@ 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
|
+
- `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.
|
|
11
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`.
|
|
@@ -40,7 +41,7 @@ npm run typecheck # tsc -p .
|
|
|
40
41
|
|
|
41
42
|
## Publish to npm
|
|
42
43
|
|
|
43
|
-
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.
|
|
44
45
|
|
|
45
46
|
```sh
|
|
46
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
|
|
@@ -96,11 +148,16 @@ function selectedServers(errors) {
|
|
|
96
148
|
if (enabled === false || workers === false)
|
|
97
149
|
continue;
|
|
98
150
|
}
|
|
99
|
-
const checked = validateMcpServerConfig(name, entry, { checkMetadataDocumentCallback });
|
|
151
|
+
const checked = validateMcpServerConfig(name, isRecord(entry) ? resolveExposureAliases(entry) : entry, { checkMetadataDocumentCallback });
|
|
100
152
|
if (checked.kind === "invalid") {
|
|
101
153
|
errors.push(checked.error);
|
|
102
154
|
continue;
|
|
103
155
|
}
|
|
156
|
+
const fieldError = checkPiFields(checked.kind, checked.config);
|
|
157
|
+
if (fieldError) {
|
|
158
|
+
errors.push(`server "${name}": ${fieldError}`);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
104
161
|
const ns = mcpNamespace(name);
|
|
105
162
|
const existing = namespaces.get(ns);
|
|
106
163
|
if (existing && existing !== name) {
|
|
@@ -243,10 +300,10 @@ async function open(previous) {
|
|
|
243
300
|
};
|
|
244
301
|
const tools = [], readOnly = [];
|
|
245
302
|
for (const tool of listed) {
|
|
246
|
-
const exposure = (server.config
|
|
303
|
+
const exposure = toolExposure(server.config, tool.name);
|
|
247
304
|
if (exposure === "hidden")
|
|
248
305
|
continue;
|
|
249
|
-
const deferred = exposure === "deferred" || exposure === "codemode"
|
|
306
|
+
const deferred = exposure === "deferred" || exposure === "codemode";
|
|
250
307
|
const name = createMcpToolName(server.name, tool.name, (candidate) => taken.has(candidate));
|
|
251
308
|
taken.add(name);
|
|
252
309
|
// The server's own account, trusted as the user chose: a server that marks a writing tool read-only runs it unasked.
|
|
@@ -307,10 +364,12 @@ export function workerMcp() {
|
|
|
307
364
|
const settled = shared.settled;
|
|
308
365
|
if (shared.connecting && !(settled?.errors.length && Date.now() - settled.at >= RETRY_MS) && !shared.stale)
|
|
309
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);
|
|
310
369
|
shared.stale = false;
|
|
311
370
|
shared.settled = undefined;
|
|
312
371
|
sweepTempFilesOnce();
|
|
313
|
-
const connecting = shared.connecting = open(
|
|
372
|
+
const connecting = shared.connecting = previous.then((last) => open(last)).then((value) => { if (shared.connecting === connecting) {
|
|
314
373
|
shared.settled = value;
|
|
315
374
|
shared.readOnly = new Set(value.served.flatMap((item) => item.readOnly));
|
|
316
375
|
} return value; }, (error) => { if (shared.connecting === connecting)
|
|
@@ -319,7 +378,7 @@ export function workerMcp() {
|
|
|
319
378
|
}
|
|
320
379
|
/** Marks the cached MCP set stale so the next `workerMcp()` call reconciles the user-level `mcp.json`. */
|
|
321
380
|
export function invalidateWorkerMcp() {
|
|
322
|
-
if (shared.settled)
|
|
381
|
+
if (shared.connecting || shared.settled)
|
|
323
382
|
shared.stale = true;
|
|
324
383
|
}
|
|
325
384
|
/** Closes the connections; the next `workerMcp()` connects again. */
|
|
@@ -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",
|