@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,97 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { link, readFile, stat, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
const errorCode = (error) => typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
|
|
4
|
+
const STALE_CLAIM_MS = 60_000;
|
|
5
|
+
/** Creates `lockPath` atomically with this process's pid, first removing a lock whose process is gone. Returns its inode. */
|
|
6
|
+
export async function acquireLock(lockPath) {
|
|
7
|
+
const staged = `${lockPath}.tmp.${process.pid}.${randomUUID().slice(0, 8)}`;
|
|
8
|
+
await writeFile(staged, String(process.pid), { mode: 0o600, flag: "wx" });
|
|
9
|
+
const ino = (await stat(staged).catch(() => undefined))?.ino;
|
|
10
|
+
try {
|
|
11
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
12
|
+
try {
|
|
13
|
+
await link(staged, lockPath);
|
|
14
|
+
return ino;
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
if (errorCode(error) !== "EEXIST")
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
const contents = await readFile(lockPath, "utf8").catch((error) => { if (errorCode(error) === "ENOENT")
|
|
21
|
+
return undefined; throw error; });
|
|
22
|
+
if (contents === undefined)
|
|
23
|
+
continue;
|
|
24
|
+
if (!/^\d+$/.test(contents))
|
|
25
|
+
throw new Error("Durable runtime lock is incomplete; refusing to remove it");
|
|
26
|
+
const pid = Number(contents);
|
|
27
|
+
if (!Number.isSafeInteger(pid) || pid < 1)
|
|
28
|
+
throw new Error("Durable runtime lock has an invalid process ID");
|
|
29
|
+
let alive = true;
|
|
30
|
+
try {
|
|
31
|
+
process.kill(pid, 0);
|
|
32
|
+
}
|
|
33
|
+
catch (check) {
|
|
34
|
+
if (errorCode(check) === "ESRCH")
|
|
35
|
+
alive = false;
|
|
36
|
+
else if (errorCode(check) !== "EPERM")
|
|
37
|
+
throw check;
|
|
38
|
+
}
|
|
39
|
+
if (alive)
|
|
40
|
+
throw new Error(`Durable runtime already open for this Pi session (pid ${pid}); if that process is not Pi, remove ${lockPath}`);
|
|
41
|
+
// Its process is gone. Removing the lock by path could remove one another reclaimer wrote since it was read, so one
|
|
42
|
+
// reclaimer claims it first: a hard link named after the dead pid, which exists once. The claim holds the lock file
|
|
43
|
+
// it linked, so reading it confirms that file is the dead one; the lock goes before the claim, so a late reclaimer's
|
|
44
|
+
// link finds no lock or a live one.
|
|
45
|
+
const claim = `${lockPath}.${pid}`;
|
|
46
|
+
try {
|
|
47
|
+
await link(lockPath, claim);
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (errorCode(error) === "ENOENT")
|
|
51
|
+
continue;
|
|
52
|
+
if (errorCode(error) === "EEXIST") {
|
|
53
|
+
const claimInfo = await stat(claim).catch(() => undefined);
|
|
54
|
+
// ctime, not mtime: a hard link is made without touching the file's mtime, which is when the lock was written, so only ctime says when this claim was made.
|
|
55
|
+
if (claimInfo && Date.now() - claimInfo.ctimeMs >= STALE_CLAIM_MS) {
|
|
56
|
+
await unlink(claim).catch((unlinkErr) => { if (errorCode(unlinkErr) !== "ENOENT")
|
|
57
|
+
throw unlinkErr; });
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
throw new Error(`Durable runtime lock of exited pid ${pid} is being reclaimed; if no Pi opens this session, remove ${claim}`);
|
|
61
|
+
}
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
if (await readFile(claim, "utf8") === contents)
|
|
66
|
+
await unlink(lockPath).catch((error) => { if (errorCode(error) !== "ENOENT")
|
|
67
|
+
throw error; });
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
await unlink(claim).catch((error) => { if (errorCode(error) !== "ENOENT")
|
|
71
|
+
throw error; });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
throw new Error("Durable runtime lock keeps changing; try again");
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
await unlink(staged).catch((error) => { if (errorCode(error) !== "ENOENT")
|
|
78
|
+
throw error; });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** Acquires `lockPath` with this process's id; the release removes it only while it still names this process. */
|
|
82
|
+
export async function acquireSessionLock(lockPath) {
|
|
83
|
+
const ino = await acquireLock(lockPath);
|
|
84
|
+
let released = false;
|
|
85
|
+
return async () => {
|
|
86
|
+
if (released)
|
|
87
|
+
return;
|
|
88
|
+
released = true;
|
|
89
|
+
// Only the file this acquisition created: after a release the same pid may own a newer lock.
|
|
90
|
+
if (ino === undefined || (await stat(lockPath).catch(() => undefined))?.ino !== ino)
|
|
91
|
+
return;
|
|
92
|
+
const owner = Number(await readFile(lockPath, "utf8").catch(() => ""));
|
|
93
|
+
if (owner === process.pid)
|
|
94
|
+
await unlink(lockPath).catch((error) => { if (errorCode(error) !== "ENOENT")
|
|
95
|
+
throw error; });
|
|
96
|
+
};
|
|
97
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type Storage } from "@earendil-works/pi-durable";
|
|
2
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
export type SessionStore = {
|
|
4
|
+
storage: Storage;
|
|
5
|
+
releaseLock: () => Promise<void>;
|
|
6
|
+
path: string;
|
|
7
|
+
persistent: boolean;
|
|
8
|
+
};
|
|
9
|
+
/** The session-scoped store path: SQLite beside the session directory, or a memory key when the session has none. */
|
|
10
|
+
export declare function databasePath(ctx: ExtensionContext, namespace: string): {
|
|
11
|
+
sessionId: string;
|
|
12
|
+
path: string;
|
|
13
|
+
persistent: boolean;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Opens the session's durable store: an owner-only SQLite file one process at a time may hold (the lock is reclaimed
|
|
17
|
+
* when its process dies), or memory storage when the session has no directory. A failure closes what opened and
|
|
18
|
+
* releases the lock.
|
|
19
|
+
*/
|
|
20
|
+
export declare function openSessionStore(ctx: ExtensionContext, namespace: string): Promise<SessionStore>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { constants as fsConstants } from "node:fs";
|
|
3
|
+
import { chmod, mkdir, open } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
6
|
+
import { MemoryStorage } from "@earendil-works/pi-durable";
|
|
7
|
+
import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
|
|
8
|
+
import { acquireSessionLock } from "./session-lock.js";
|
|
9
|
+
/** The session-scoped store path: SQLite beside the session directory, or a memory key when the session has none. */
|
|
10
|
+
export function databasePath(ctx, namespace) {
|
|
11
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
12
|
+
const dir = ctx.sessionManager.getSessionDir();
|
|
13
|
+
const hash = createHash("sha256").update(sessionId).digest("hex").slice(0, 24);
|
|
14
|
+
return { sessionId, path: dir ? join(dir, `${namespace}-${hash}.sqlite`) : `memory:${namespace}:${sessionId}`, persistent: Boolean(dir) };
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Opens the session's durable store: an owner-only SQLite file one process at a time may hold (the lock is reclaimed
|
|
18
|
+
* when its process dies), or memory storage when the session has no directory. A failure closes what opened and
|
|
19
|
+
* releases the lock.
|
|
20
|
+
*/
|
|
21
|
+
export async function openSessionStore(ctx, namespace) {
|
|
22
|
+
const { path, persistent } = databasePath(ctx, namespace);
|
|
23
|
+
if (!persistent)
|
|
24
|
+
return { storage: new MemoryStorage(), releaseLock: async () => { }, path, persistent };
|
|
25
|
+
await mkdir(ctx.sessionManager.getSessionDir(), { recursive: true, mode: 0o700 });
|
|
26
|
+
const releaseLock = await acquireSessionLock(`${path}.lock`);
|
|
27
|
+
let storage;
|
|
28
|
+
try {
|
|
29
|
+
const file = await open(path, fsConstants.O_CREAT | fsConstants.O_APPEND | fsConstants.O_WRONLY | (fsConstants.O_NOFOLLOW ?? 0), 0o600);
|
|
30
|
+
await file.close();
|
|
31
|
+
await chmod(path, 0o600);
|
|
32
|
+
storage = await openNodeSqliteStorage(path, { busyTimeoutMs: 5000 });
|
|
33
|
+
await chmod(`${path}-wal`, 0o600).catch(() => { });
|
|
34
|
+
await chmod(`${path}-shm`, 0o600).catch(() => { });
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
await storage?.close(BACKGROUND_CONTEXT).catch(() => { });
|
|
38
|
+
await releaseLock();
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
return { storage, releaseLock, path, persistent };
|
|
42
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loads the module at `specifier` twice, as a /reload does: two instances with their own module-level variables, the
|
|
3
|
+
* older first. A state that must survive the reload has to live on globalThis (see `processState`), and a test that
|
|
4
|
+
* drives the older instance's tools through the newer one's state fails when it does not.
|
|
5
|
+
* `specifier` is resolved from this file: pass an absolute URL, `new URL("./index.ts", import.meta.url).href`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function loadTwice<T = Record<string, any>>(specifier: string | URL): Promise<[older: T, newer: T]>;
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Loads the module at `specifier` twice, as a /reload does: two instances with their own module-level variables, the
|
|
11
|
+
* older first. A state that must survive the reload has to live on globalThis (see `processState`), and a test that
|
|
12
|
+
* drives the older instance's tools through the newer one's state fails when it does not.
|
|
13
|
+
* `specifier` is resolved from this file: pass an absolute URL, `new URL("./index.ts", import.meta.url).href`.
|
|
14
|
+
*/
|
|
15
|
+
export async function loadTwice(specifier) {
|
|
16
|
+
const base = String(specifier), tag = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
17
|
+
const older = await import(__rewriteRelativeImportExtension(`${base}?older-${tag}`)), newer = await import(__rewriteRelativeImportExtension(`${base}?newer-${tag}`));
|
|
18
|
+
return [older, newer];
|
|
19
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { Extension, ToolRegistration } from "@earendil-works/pi-durable";
|
|
2
|
+
import { type Semaphore } from "./semaphore.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Whether workers get code mode, and whether it is the only tool the model is offered, as Pi's settings say for the
|
|
5
|
+
* session itself: `defaultTools` names `codemode` (a plain entry, or `+codemode` / `-codemode` applied in order), and
|
|
6
|
+
* `codemode.mode: "only"` hides every other tool from the model, which then reaches them through scripts. Read when a
|
|
7
|
+
* worker is created and stored with it, so a later change of the settings leaves running workers as they were.
|
|
8
|
+
*/
|
|
9
|
+
export type WorkerCodemode = {
|
|
10
|
+
enabled: boolean;
|
|
11
|
+
only: boolean;
|
|
12
|
+
};
|
|
13
|
+
/** `inlineBudget` is not part of a worker's record: it belongs to the one sandbox, so pass it to `workerCodemode` when that is created. */
|
|
14
|
+
export declare function codemodeOf(settings: {
|
|
15
|
+
defaultTools?: readonly string[];
|
|
16
|
+
codemode?: {
|
|
17
|
+
mode?: string;
|
|
18
|
+
inlineBudget?: number;
|
|
19
|
+
};
|
|
20
|
+
}): WorkerCodemode & {
|
|
21
|
+
inlineBudget?: number;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Records the `codemode.inlineBudget` the sandbox is created with: the one setting of Pi's that belongs to the shared
|
|
25
|
+
* sandbox, not to a worker. A sandbox already open keeps the budget it was created with; the next one takes this.
|
|
26
|
+
*/
|
|
27
|
+
export declare function configureWorkerCodemode(settings: {
|
|
28
|
+
inlineBudget?: number;
|
|
29
|
+
}): void;
|
|
30
|
+
/**
|
|
31
|
+
* The code mode extension with its tool's `execute` held by the semaphore: a call over the limit waits for a free slot
|
|
32
|
+
* (and leaves the queue when its signal aborts) instead of failing.
|
|
33
|
+
*/
|
|
34
|
+
export declare function queued(extension: Extension<ToolRegistration>, semaphore?: Semaphore): Extension<ToolRegistration>;
|
|
35
|
+
/** The code mode extension every runtime installs, over one sandbox per process, created with the budget `configureWorkerCodemode` recorded. */
|
|
36
|
+
export declare function workerCodemode(): Extension<ToolRegistration>;
|
|
37
|
+
/**
|
|
38
|
+
* What a new worker's agent takes from `config`. Without code mode the extension is removed, its tool and its prompt
|
|
39
|
+
* section both. With it, `tools` is the code mode tool for a host that names the enabled tools (a role's list), and in
|
|
40
|
+
* `only` mode the model is offered nothing else. Scripts call the worker's enabled tools through the same hooks as a
|
|
41
|
+
* direct call, so a role's tool list and the guards' approvals still bound what a script can do.
|
|
42
|
+
*/
|
|
43
|
+
export declare function codemodeAgent(config: WorkerCodemode | undefined): {
|
|
44
|
+
tools: ToolRegistration[];
|
|
45
|
+
agent: {
|
|
46
|
+
extensions: {
|
|
47
|
+
remove: Extension<ToolRegistration>[];
|
|
48
|
+
};
|
|
49
|
+
modelTools?: undefined;
|
|
50
|
+
};
|
|
51
|
+
} | {
|
|
52
|
+
tools: ToolRegistration[];
|
|
53
|
+
agent: {
|
|
54
|
+
extensions?: undefined;
|
|
55
|
+
modelTools: ToolRegistration[];
|
|
56
|
+
} | {
|
|
57
|
+
extensions?: undefined;
|
|
58
|
+
modelTools?: undefined;
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
export declare function closeWorkerCodemode(): Promise<void>;
|
|
62
|
+
/** As `holdWorkerMcp`: `holder` uses the sandbox. */
|
|
63
|
+
export declare function holdWorkerCodemode(holder: string): void;
|
|
64
|
+
/** As `releaseWorkerMcp`: the last holder closes the sandbox. */
|
|
65
|
+
export declare function releaseWorkerCodemode(holder: string): Promise<void>;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { availableParallelism } from "node:os";
|
|
2
|
+
import { CodemodeSandbox } from "@earendil-works/pi-codemode";
|
|
3
|
+
import { createCodemodeExtension } from "@earendil-works/pi-durable/codemode";
|
|
4
|
+
import { processState } from "./process-state.js";
|
|
5
|
+
import { createSemaphore } from "./semaphore.js";
|
|
6
|
+
/** `inlineBudget` is not part of a worker's record: it belongs to the one sandbox, so pass it to `workerCodemode` when that is created. */
|
|
7
|
+
export function codemodeOf(settings) {
|
|
8
|
+
const entries = settings.defaultTools ?? [];
|
|
9
|
+
let enabled = false;
|
|
10
|
+
for (const entry of entries) {
|
|
11
|
+
if (entry === "codemode" || entry === "+codemode")
|
|
12
|
+
enabled = true;
|
|
13
|
+
else if (entry === "-codemode")
|
|
14
|
+
enabled = false;
|
|
15
|
+
}
|
|
16
|
+
const budget = settings.codemode?.inlineBudget;
|
|
17
|
+
return {
|
|
18
|
+
enabled,
|
|
19
|
+
only: enabled && settings.codemode?.mode === "only",
|
|
20
|
+
...(typeof budget === "number" && Number.isFinite(budget) && budget > 0 ? { inlineBudget: Math.floor(budget) } : {}),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
const DEFAULT_HEAP_BYTES = 256 * 1024 * 1024;
|
|
24
|
+
/** How many scripts run at once: `PI_CODEMODE_MAX_WORKERS`, else the larger of 4 and the cores. A script past it waits its turn. */
|
|
25
|
+
function maxWorkers() {
|
|
26
|
+
const raw = Number(process.env.PI_CODEMODE_MAX_WORKERS);
|
|
27
|
+
return Number.isInteger(raw) && raw > 0 ? raw : Math.max(4, availableParallelism());
|
|
28
|
+
}
|
|
29
|
+
const slots = processState("pi-worker-codemode.queue", () => createSemaphore(maxWorkers));
|
|
30
|
+
// On globalThis, not module-local: a reloaded module must find the sandbox, not make a second.
|
|
31
|
+
const shared = processState("pi-worker-codemode", () => ({}));
|
|
32
|
+
/**
|
|
33
|
+
* Records the `codemode.inlineBudget` the sandbox is created with: the one setting of Pi's that belongs to the shared
|
|
34
|
+
* sandbox, not to a worker. A sandbox already open keeps the budget it was created with; the next one takes this.
|
|
35
|
+
*/
|
|
36
|
+
export function configureWorkerCodemode(settings) {
|
|
37
|
+
shared.inlineBudget = settings.inlineBudget;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The code mode extension with its tool's `execute` held by the semaphore: a call over the limit waits for a free slot
|
|
41
|
+
* (and leaves the queue when its signal aborts) instead of failing.
|
|
42
|
+
*/
|
|
43
|
+
// shortcut: pi-codemode's `acquireWorker` is synchronous and can only throw to deny, so the wait is placed around the tool's execute instead.
|
|
44
|
+
// It bounds scripts, which is what holds a worker each. Remove this wrapper and pass an async `acquireWorker` to the sandbox once pi-codemode supports one.
|
|
45
|
+
export function queued(extension, semaphore = slots) {
|
|
46
|
+
const [tool, ...rest] = extension.tools;
|
|
47
|
+
const held = { ...tool, async execute(args, api, context) {
|
|
48
|
+
const release = await semaphore.acquire(context?.abortSignal);
|
|
49
|
+
try {
|
|
50
|
+
return await tool.execute(args, api, context);
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
release();
|
|
54
|
+
}
|
|
55
|
+
} };
|
|
56
|
+
return { ...extension, tools: [held, ...rest] };
|
|
57
|
+
}
|
|
58
|
+
/** The code mode extension every runtime installs, over one sandbox per process, created with the budget `configureWorkerCodemode` recorded. */
|
|
59
|
+
export function workerCodemode() {
|
|
60
|
+
const inlineBudget = shared.inlineBudget;
|
|
61
|
+
shared.current ??= (() => {
|
|
62
|
+
const sandbox = new CodemodeSandbox({ memoryLimitBytes: DEFAULT_HEAP_BYTES });
|
|
63
|
+
return {
|
|
64
|
+
sandbox,
|
|
65
|
+
extension: queued(createCodemodeExtension({
|
|
66
|
+
sandbox,
|
|
67
|
+
models: false,
|
|
68
|
+
...(typeof inlineBudget === "number" && Number.isFinite(inlineBudget) && inlineBudget > 0 ? { inlineBudget: Math.floor(inlineBudget) } : {}),
|
|
69
|
+
})),
|
|
70
|
+
};
|
|
71
|
+
})();
|
|
72
|
+
return shared.current.extension;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* What a new worker's agent takes from `config`. Without code mode the extension is removed, its tool and its prompt
|
|
76
|
+
* section both. With it, `tools` is the code mode tool for a host that names the enabled tools (a role's list), and in
|
|
77
|
+
* `only` mode the model is offered nothing else. Scripts call the worker's enabled tools through the same hooks as a
|
|
78
|
+
* direct call, so a role's tool list and the guards' approvals still bound what a script can do.
|
|
79
|
+
*/
|
|
80
|
+
export function codemodeAgent(config) {
|
|
81
|
+
const extension = workerCodemode(), tool = extension.tools[0];
|
|
82
|
+
if (!config?.enabled)
|
|
83
|
+
return { tools: [], agent: { extensions: { remove: [extension] } } };
|
|
84
|
+
return { tools: [tool], agent: config.only ? { modelTools: [tool] } : {} };
|
|
85
|
+
}
|
|
86
|
+
export async function closeWorkerCodemode() {
|
|
87
|
+
const closing = shared.current;
|
|
88
|
+
shared.current = undefined;
|
|
89
|
+
await closing?.sandbox.close();
|
|
90
|
+
}
|
|
91
|
+
/** As `holdWorkerMcp`: `holder` uses the sandbox. */
|
|
92
|
+
export function holdWorkerCodemode(holder) { (shared.holders ??= new Set()).add(holder); }
|
|
93
|
+
/** As `releaseWorkerMcp`: the last holder closes the sandbox. */
|
|
94
|
+
export async function releaseWorkerCodemode(holder) {
|
|
95
|
+
shared.holders?.delete(holder);
|
|
96
|
+
if (!shared.holders?.size)
|
|
97
|
+
await closeWorkerCodemode();
|
|
98
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@minhtri2710/pi-durable-shared",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Durable runtime, MCP, search and code mode helpers shared by the pi-orchestrator, pi-swarm, pi-teamwork and pi-schedule extensions.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"pi",
|
|
9
|
+
"pi-extension",
|
|
10
|
+
"durable",
|
|
11
|
+
"mcp",
|
|
12
|
+
"codemode"
|
|
13
|
+
],
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/minhtri2710/pi-durable-shared.git"
|
|
17
|
+
},
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"bin",
|
|
24
|
+
"src/mcp-fixture-server.mjs"
|
|
25
|
+
],
|
|
26
|
+
"exports": {
|
|
27
|
+
"./*": {
|
|
28
|
+
"types": "./dist/*.d.ts",
|
|
29
|
+
"default": "./dist/*.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
34
|
+
"test": "node --test src/*.test.ts",
|
|
35
|
+
"typecheck": "tsc -p .",
|
|
36
|
+
"prepublishOnly": "npm run build && npm test"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@earendil-works/chord": "1.8.0",
|
|
40
|
+
"@earendil-works/pi-codemode": "1.8.0",
|
|
41
|
+
"@earendil-works/pi-durable": "1.8.0",
|
|
42
|
+
"@earendil-works/pi-mcp": "1.8.0",
|
|
43
|
+
"proper-lockfile": "4.1.2"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"@earendil-works/pi-ai": "*",
|
|
47
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
48
|
+
"@earendil-works/pi-tui": "*",
|
|
49
|
+
"typebox": "*"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@earendil-works/pi-ai": "1.8.0",
|
|
53
|
+
"@earendil-works/pi-coding-agent": "1.8.0",
|
|
54
|
+
"@earendil-works/pi-tui": "1.8.0",
|
|
55
|
+
"@types/node": "^22.20.7",
|
|
56
|
+
"@types/proper-lockfile": "4.1.4",
|
|
57
|
+
"typebox": "1.4.7",
|
|
58
|
+
"typescript": "^7.0.2"
|
|
59
|
+
},
|
|
60
|
+
"bin": {
|
|
61
|
+
"pi-lint-state": "bin/lint-state.sh"
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// A minimal stdio MCP server for mcp-tools.test.ts: one tool, `echo`, answering line-delimited JSON-RPC.
|
|
2
|
+
import { createInterface } from "node:readline";
|
|
3
|
+
|
|
4
|
+
const send = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
|
|
5
|
+
createInterface({ input: process.stdin }).on("line", (line) => {
|
|
6
|
+
const message = JSON.parse(line);
|
|
7
|
+
if (message.id === undefined) return;
|
|
8
|
+
if (message.method === "initialize") send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "fixture", version: "1" } } });
|
|
9
|
+
else if (message.method === "tools/list") send({ jsonrpc: "2.0", id: message.id, result: { tools: [{ name: "echo", description: "Echoes text", ...(process.env.FIXTURE_READ_ONLY ? { annotations: { readOnlyHint: true } } : {}), inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"] } }] } });
|
|
10
|
+
else if (message.method === "tools/call" && message.params.arguments.text === "die") process.exit(1);
|
|
11
|
+
else if (message.method === "tools/call") send({ jsonrpc: "2.0", id: message.id, result: { content: [{ type: "text", text: `echo: ${message.params.arguments.text}` }] } });
|
|
12
|
+
else send({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "unknown method" } });
|
|
13
|
+
});
|