pi-better-subagents 0.32.7 → 0.34.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 -0
- package/agent-catalog.mjs +24 -0
- package/agent-commands.ts +71 -4
- package/agent-inspection.ts +2 -1
- package/agents-catalog-tool.ts +8 -1
- package/assignment-outcomes.ts +14 -3
- package/assignment-projection.mjs +12 -4
- package/assignment-report.ts +92 -0
- package/catalog-host-admission.ts +69 -0
- package/catalog-overlay.ts +10 -0
- package/catalog-runtime.ts +10 -2
- package/catalog-store.ts +23 -0
- package/catalog-ui.ts +26 -10
- package/child-operations.ts +2 -0
- package/child-ownership.ts +1 -1
- package/docs/agent-catalog-operations.md +38 -0
- package/health-observation.ts +9 -4
- package/index.ts +154 -84
- package/launch-abort.ts +21 -0
- package/list.mjs +1 -1
- package/navigator.mjs +2 -1
- package/operation-bridge-types.ts +18 -1
- package/output-payload.ts +2 -0
- package/package.json +4 -2
- package/parse.ts +7 -6
- package/registry.ts +4 -2
- package/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/runtime-client/artifacts/darwin-arm64.json +1 -0
- package/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/runtime-client/artifacts/darwin-x64.json +1 -0
- package/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/runtime-client/artifacts/linux-arm64.json +1 -0
- package/runtime-client/artifacts/linux-x64.gz +0 -0
- package/runtime-client/artifacts/linux-x64.json +1 -0
- package/runtime-client/scripts/private-runtime/format.mjs +90 -0
- package/runtime-client/src/daemon-owner.mjs +218 -0
- package/runtime-client/src/runtime/client.mjs +130 -0
- package/runtime-client/src/runtime/root.mjs +41 -0
- package/runtime-client/src/runtime/socket.mjs +9 -0
- package/runtime-client/src/runtime/status-cli.mjs +14 -0
- package/runtime-client/src/runtime/work-client.mjs +102 -0
- package/runtime-client/src/startup/artifact.mjs +76 -0
- package/runtime-client/src/startup/install.mjs +184 -0
- package/runtime-client/src/startup/managed-types.mjs +1 -0
- package/runtime-client/src/startup/runtime.mjs +120 -0
- package/session-store.ts +85 -30
- package/shared-catalog.ts +69 -0
- package/shared-harness-settings.ts +4 -2
- package/shared-log-utils.ts +18 -7
- package/shared-navigator.ts +16 -4
- package/shared-operation-coordinator/assignment-observation.mjs +80 -3
- package/shared-operation-coordinator/index.ts +2 -0
- package/shared-operation-coordinator/src/discovery.ts +9 -0
- package/shared-operation-coordinator/src/errors.ts +2 -0
- package/shared-operation-coordinator/src/operations.ts +6 -4
- package/shared-operation-coordinator/src/result-supervision.ts +128 -0
- package/shared-operation-coordinator/src/schema.ts +39 -1
- package/shared-operation-coordinator/src/store.ts +55 -0
- package/shared-operation-coordinator/src/task-cancellation.ts +224 -0
- package/shared-operation-coordinator/src/types.ts +6 -0
- package/shared-work-client.d.mts +12 -0
- package/shared-work-client.mjs +102 -0
- package/skill-picker.ts +6 -2
- package/tools.ts +39 -2
- package/work-observation.ts +177 -0
- package/worker-operations-host.ts +3 -0
- package/worker-waits.ts +50 -13
package/package.json
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-subagents",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.34.0",
|
|
4
4
|
"description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"bin": {
|
|
8
|
+
"pi-subagents-runtime-status": "./runtime-client/src/runtime/status-cli.mjs",
|
|
8
9
|
"pi-agent-catalog": "./agent-catalog.mjs"
|
|
9
10
|
},
|
|
10
11
|
"exports": {
|
|
@@ -41,7 +42,7 @@
|
|
|
41
42
|
},
|
|
42
43
|
"scripts": {
|
|
43
44
|
"pretest": "node ../../scripts/sync-shared-log-utils.mjs && node ../../scripts/sync-shared-sandbox-core.mjs && node ../../scripts/sync-task-sandbox.mjs",
|
|
44
|
-
"prepack": "node ../../scripts/sync-shared-log-utils.mjs && node ../../scripts/sync-shared-sandbox-core.mjs && node ../../scripts/sync-task-sandbox.mjs",
|
|
45
|
+
"prepack": "node ../../scripts/sync-shared-log-utils.mjs && node ../../scripts/sync-shared-sandbox-core.mjs && node ../../scripts/sync-task-sandbox.mjs && node ../../scripts/sync-runtime-client.mjs",
|
|
45
46
|
"typecheck": "tsc -p tsconfig.task-runtime.json",
|
|
46
47
|
"test": "node --import tsx --import ./tests/isolate-registry.mjs --test tests/*.test.mjs",
|
|
47
48
|
"test:cross-session": "node --import tsx --import ./tests/isolate-registry.mjs --test --test-name-pattern \"callback session isolation\" tests/extension_health_lifecycle.test.mjs",
|
|
@@ -52,6 +53,7 @@
|
|
|
52
53
|
"verify": "npm run typecheck && npm test"
|
|
53
54
|
},
|
|
54
55
|
"files": [
|
|
56
|
+
"runtime-client/**",
|
|
55
57
|
"*.ts",
|
|
56
58
|
"*.mjs",
|
|
57
59
|
"*.d.mts",
|
package/parse.ts
CHANGED
|
@@ -183,11 +183,11 @@ function transcriptContent(msg: Msg | undefined): ContentBlock[] {
|
|
|
183
183
|
/** Bounded, display-oriented transcript fold for the subagent detail view. */
|
|
184
184
|
export function readRunTranscript(
|
|
185
185
|
id: string,
|
|
186
|
-
options: { maxBytes?: number; maxEntries?: number } = {},
|
|
186
|
+
options: { maxBytes?: number; maxEntries?: number; logPath?: string } = {},
|
|
187
187
|
): RunTranscript {
|
|
188
188
|
const maxBytes = Math.max(1024, options.maxBytes ?? DEFAULT_TRANSCRIPT_TAIL_BYTES);
|
|
189
189
|
const maxEntries = Math.max(1, options.maxEntries ?? DEFAULT_TRANSCRIPT_ENTRIES);
|
|
190
|
-
const tail = readTail(logPathFor(id), maxBytes);
|
|
190
|
+
const tail = readTail(options.logPath ?? logPathFor(id), maxBytes);
|
|
191
191
|
if (tail.error) return { entries: [], truncated: false, diagnostic: `Log unreadable: ${tail.error}` };
|
|
192
192
|
|
|
193
193
|
const lines = tail.text.split(/\r?\n/);
|
|
@@ -1312,15 +1312,16 @@ function foldParseEvent(state: ParseState, e: Record<string, unknown>): void {
|
|
|
1312
1312
|
* rotated, truncated, or rewritten log is detected and re-read from a bounded
|
|
1313
1313
|
* tail (see log-cursor.ts).
|
|
1314
1314
|
*/
|
|
1315
|
-
export function parseRun(id: string): ParsedRun {
|
|
1316
|
-
const
|
|
1317
|
-
const
|
|
1315
|
+
export function parseRun(id: string, options: { logPath?: string } = {}): ParsedRun {
|
|
1316
|
+
const key = options.logPath ?? id;
|
|
1317
|
+
const previous = parseStates.get(key);
|
|
1318
|
+
const read = readAppendedLines(options.logPath ?? logPathFor(id), previous?.cursor, maxParseBytes());
|
|
1318
1319
|
const state = read.restarted || !previous ? freshState(read.cursor) : previous;
|
|
1319
1320
|
state.cursor = read.cursor;
|
|
1320
1321
|
if (read.totalBytes > 0) state.totalBytes = read.totalBytes;
|
|
1321
1322
|
if (read.truncated) state.windowTruncated = true;
|
|
1322
1323
|
state.error = read.error;
|
|
1323
|
-
rememberParseState(
|
|
1324
|
+
rememberParseState(key, state);
|
|
1324
1325
|
|
|
1325
1326
|
if (read.error !== undefined) {
|
|
1326
1327
|
return {
|
package/registry.ts
CHANGED
|
@@ -240,6 +240,8 @@ export interface RunMeta {
|
|
|
240
240
|
completionCallbackSentAt?: number;
|
|
241
241
|
completionCallbackSuppressedAt?: number;
|
|
242
242
|
completionCallbackSuppressedReason?: string;
|
|
243
|
+
outcomeDeliveryDeferredReason?: string;
|
|
244
|
+
assignmentReport?: { version: 1; assignmentId: string; attemptId: string; digest: string; path: string };
|
|
243
245
|
orphanedCallbackSuppressedAt?: number;
|
|
244
246
|
orphanedCallbackSuppressedReason?: string;
|
|
245
247
|
lostCallbackSuppressedAt?: number;
|
|
@@ -1350,7 +1352,7 @@ export function removeMetaArtifacts(meta: RunMeta, options: RemoveMetaArtifactsO
|
|
|
1350
1352
|
* whose raw log/run directory was already reclaimed. The volatile record wins
|
|
1351
1353
|
* whenever both exist, so a reclaimed log never hides the live one.
|
|
1352
1354
|
*/
|
|
1353
|
-
export function listMetas(): RunMeta[] {
|
|
1355
|
+
export function listMetas(options: { includeArchived?: boolean } = {}): RunMeta[] {
|
|
1354
1356
|
let ids: string[] = [];
|
|
1355
1357
|
try {
|
|
1356
1358
|
registryIo.fullDirectoryReads += 1;
|
|
@@ -1366,7 +1368,7 @@ export function listMetas(): RunMeta[] {
|
|
|
1366
1368
|
if (!meta) continue;
|
|
1367
1369
|
metas.push(meta);
|
|
1368
1370
|
}
|
|
1369
|
-
for (const meta of listArchivedAttempts()) {
|
|
1371
|
+
for (const meta of options.includeArchived === false ? [] : listArchivedAttempts()) {
|
|
1370
1372
|
if (seen.has(meta.id)) continue;
|
|
1371
1373
|
seen.add(meta.id);
|
|
1372
1374
|
metas.push(meta);
|
|
Binary file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"d8babdaa88ccdf11463b69738823e4175a88cb25e1f6b51bd1cde1dc5ebbd6b3"},"sha256":"40cbb55c9f6bcba62ac2fde5d00521d44c627177baede403fdfa9ee53ccec6ce"}
|
|
Binary file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"0c892582dfd3e78b9f5fc25821dfd6b7c233f7f8b6d31677196dc3aaeda0a909"},"sha256":"61e469f213ae5ef7e379897f03f069b4a8c668a3a338f7fee7cafffeb7c648f3"}
|
|
Binary file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"d71fc0b69c23b6808726d5a971c3ddd1da00985dfb655c79190b83c3997fcb1f"},"sha256":"057130e7109c592068e375f31a5f39297163326bb88f6461d59ae4e7742d7a80"}
|
|
Binary file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"5e132e98f011fb0eee44a2184ef8d17787a7ac0f1b792b676b08582d248ba19f"},"sha256":"a007cde2962d0b0eb4fe378a3e9d08fd2f20ada6fce2c96b76f849cb6dd62c96"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { isAbsolute, posix } from "node:path";
|
|
3
|
+
export const NODE_CHECKSUMS = {
|
|
4
|
+
"linux-x64": "ace9fa104992ed0829642629c46ca7bd7fd6e76278cb96c958c4b387d29658ea",
|
|
5
|
+
"linux-arm64": "734ff04fa7f8ed2e8a78d40cacf5ac3fc4515dac2858757cbab313eb483ba8a2",
|
|
6
|
+
"darwin-x64": "2526230ad7d922be82d4fdb1e7ee1e84303e133e3b4b0ec4c2897ab31de0253d",
|
|
7
|
+
"darwin-arm64": "25495ff85bd89e2d8a24d88566d7e2f827c6b0d3d872b2cebf75371f93fcb1fe",
|
|
8
|
+
};
|
|
9
|
+
// Extracted bin/node hashes from the archives authenticated by NODE_CHECKSUMS.
|
|
10
|
+
// Source: https://nodejs.org/dist/v24.14.1/SHASUMS256.txt
|
|
11
|
+
export const NODE_EXECUTABLE_CHECKSUMS = {
|
|
12
|
+
"linux-x64": "bf9112eb83a827dc9f9c8d19bb7bddcbf00f7b2fedae18fdcaee05406981f20a",
|
|
13
|
+
"linux-arm64": "7fac13c04c19207c3e904a7721f8c045e6b99493471e2df85444f764cdd21934",
|
|
14
|
+
"darwin-x64": "9ab4f6249a8de4671c3205ef58621dfb19d120a9c59fd96ed206571bafb0319c",
|
|
15
|
+
"darwin-arm64": "35d4bc736bbe4161f0c074aa140ddb74586e46969bc2ad63d32c838bec4463ff",
|
|
16
|
+
};
|
|
17
|
+
export function digest(value) { return createHash("sha256").update(value).digest("hex"); }
|
|
18
|
+
export function stable(value) {
|
|
19
|
+
if (Array.isArray(value))
|
|
20
|
+
return `[${value.map(stable).join(",")}]`;
|
|
21
|
+
if (value && typeof value === "object")
|
|
22
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable(value[key])}`).join(",")}}`;
|
|
23
|
+
return JSON.stringify(value);
|
|
24
|
+
}
|
|
25
|
+
export function validateBuild(value) {
|
|
26
|
+
if (!value || value.format !== 1 || !Object.hasOwn(NODE_CHECKSUMS, value.platform) || value.nodeVersion !== "24.14.1"
|
|
27
|
+
|| !/^\d+\.\d+\.\d+$/.test(value.piSdkVersion) || !/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(value.serverVersion)
|
|
28
|
+
|| !Number.isSafeInteger(value.protocolVersion) || value.protocolVersion < 1
|
|
29
|
+
|| ![value.contentId, value.sourceDigest, value.dependencyLockDigest].every((v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v)))
|
|
30
|
+
throw new Error("Artifact: invalid build metadata or unsupported platform");
|
|
31
|
+
const { contentId, ...identity } = value;
|
|
32
|
+
if (digest(stable(identity)) !== contentId)
|
|
33
|
+
throw new Error("Artifact: content identity mismatch");
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
export function safeSourcePath(path) {
|
|
37
|
+
return typeof path === "string" && path.length <= 512 && !path.includes("\\") && !/[\0-\x1f\x7f]/.test(path)
|
|
38
|
+
&& !isAbsolute(path) && path === posix.normalize(path) && !path.split("/").some((p) => !p || p === ".." || p === "." || p === "node_modules" || p === ".git" || p === "test-support" || p.startsWith(".env") || p === "auth.json" || p === "settings.json")
|
|
39
|
+
&& (path.startsWith("src/") || ["package.json", "scripts/private-runtime/format.ts", "scripts/private-runtime/installer.ts", "scripts/private-runtime/package.json", "scripts/private-runtime/package-lock.json"].includes(path));
|
|
40
|
+
}
|
|
41
|
+
export function validatePayload(value) {
|
|
42
|
+
if (!value || value.format !== 1 || !Array.isArray(value.files) || value.files.length > 10000)
|
|
43
|
+
throw new Error("Artifact: invalid file table");
|
|
44
|
+
validateBuild(value.build);
|
|
45
|
+
const paths = new Set();
|
|
46
|
+
let size = 0;
|
|
47
|
+
for (const file of value.files) {
|
|
48
|
+
if (!file || Object.keys(file).sort().join(",") !== "data,path" || !safeSourcePath(file.path) || paths.has(file.path))
|
|
49
|
+
throw new Error("Artifact: unsafe or duplicate path");
|
|
50
|
+
if (typeof file.data !== "string" || file.data.length > 16 * 1024 * 1024 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(file.data))
|
|
51
|
+
throw new Error("Artifact: invalid or oversized file");
|
|
52
|
+
size += Buffer.byteLength(file.data, "base64");
|
|
53
|
+
if (size > 48 * 1024 * 1024)
|
|
54
|
+
throw new Error("Artifact: decoded size limit");
|
|
55
|
+
paths.add(file.path);
|
|
56
|
+
}
|
|
57
|
+
for (const path of paths) {
|
|
58
|
+
for (let parent = posix.dirname(path); parent !== "."; parent = posix.dirname(parent))
|
|
59
|
+
if (paths.has(parent))
|
|
60
|
+
throw new Error("Artifact: file/directory path collision");
|
|
61
|
+
}
|
|
62
|
+
for (const required of ["src/cli.ts", "src/server.ts", "package.json", "scripts/private-runtime/format.ts", "scripts/private-runtime/installer.ts", "scripts/private-runtime/package-lock.json", "scripts/private-runtime/package.json"])
|
|
63
|
+
if (!paths.has(required))
|
|
64
|
+
throw new Error(`Artifact: missing ${required}`);
|
|
65
|
+
if (digest(stable(value.files)) !== value.build.sourceDigest)
|
|
66
|
+
throw new Error("Artifact: source integrity mismatch");
|
|
67
|
+
const lock = JSON.parse(Buffer.from(value.files.find((f) => f.path === "scripts/private-runtime/package-lock.json").data, "base64").toString());
|
|
68
|
+
if (digest(stable(lock)) !== value.build.dependencyLockDigest || lock.lockfileVersion !== 3 || lock.packages?.[""]?.dependencies?.["@earendil-works/pi-coding-agent"] !== value.build.piSdkVersion)
|
|
69
|
+
throw new Error("Artifact: dependency lock mismatch");
|
|
70
|
+
for (const [path, pkg] of Object.entries(lock.packages)) {
|
|
71
|
+
if (!path)
|
|
72
|
+
continue;
|
|
73
|
+
if (!path.startsWith("node_modules/") || path.includes("..") || pkg.link || !/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(pkg.version)
|
|
74
|
+
|| typeof pkg.resolved !== "string" || !pkg.resolved.startsWith("https://registry.npmjs.org/") || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(pkg.integrity))
|
|
75
|
+
throw new Error(`Artifact: dependency lacks official locked integrity: ${path}`);
|
|
76
|
+
}
|
|
77
|
+
return value;
|
|
78
|
+
}
|
|
79
|
+
export function validateStaged(value) {
|
|
80
|
+
if (!value || value.format !== 1)
|
|
81
|
+
throw new Error("Staging: invalid runtime manifest");
|
|
82
|
+
validateBuild(value.build);
|
|
83
|
+
for (const key of ["root", "node", "entrypoint", "manifestPath", "installRoot"])
|
|
84
|
+
if (typeof value[key] !== "string" || !isAbsolute(value[key]) || /[\0\r\n]/.test(value[key]) || posix.normalize(value[key]) !== value[key])
|
|
85
|
+
throw new Error(`Staging: invalid ${key}`);
|
|
86
|
+
if (value.root !== `${value.installRoot}/releases/${value.build.contentId}` || value.root.split("/").includes("node_modules")
|
|
87
|
+
|| value.node !== `${value.root}/node/bin/node` || value.entrypoint !== `${value.root}/src/cli.ts` || value.manifestPath !== `${value.root}/runtime.json`)
|
|
88
|
+
throw new Error("Staging: runtime path identity mismatch");
|
|
89
|
+
return value;
|
|
90
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
export function currentOwnerIdentity(token = randomUUID()) {
|
|
6
|
+
const { boot, start } = processIdentity(process.pid);
|
|
7
|
+
return { pid: process.pid, token, ...(boot ? { boot } : {}), ...(start ? { start } : {}) };
|
|
8
|
+
}
|
|
9
|
+
export function ownerIsAlive(owner) {
|
|
10
|
+
return alive(owner);
|
|
11
|
+
}
|
|
12
|
+
export function sameOwner(left, right) {
|
|
13
|
+
return typeof left.start === "string" && left.pid === right.pid && left.token === right.token
|
|
14
|
+
&& left.start === right.start && left.boot === right.boot;
|
|
15
|
+
}
|
|
16
|
+
export function ownerIdentityVerified(owner) {
|
|
17
|
+
const observed = processIdentity(owner.pid);
|
|
18
|
+
return typeof owner.start === "string" && observed.start === owner.start
|
|
19
|
+
&& (process.platform !== "linux" || typeof owner.boot === "string" && owner.boot === observed.boot)
|
|
20
|
+
&& alive(owner);
|
|
21
|
+
}
|
|
22
|
+
/** Matches the existing runner/worker start-token representation, without releasing fences. */
|
|
23
|
+
export function processMatchesStart(pid, start) {
|
|
24
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || typeof start !== "string")
|
|
25
|
+
return false;
|
|
26
|
+
if (!/^\d+$/.test(start)) {
|
|
27
|
+
// Background runner claims use ps lstart on both supported platforms;
|
|
28
|
+
// Subagent Linux records use /proc ticks. Compare in the recorded format.
|
|
29
|
+
try {
|
|
30
|
+
const observed = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
|
|
31
|
+
encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000,
|
|
32
|
+
env: { ...process.env, LC_ALL: "C" },
|
|
33
|
+
}).trim();
|
|
34
|
+
return observed.length > 0 && observed.replace(/\s+/g, " ") === start.trim().replace(/\s+/g, " ");
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const identity = processIdentity(pid);
|
|
41
|
+
return identity.start !== undefined && identity.start === start && alive({ pid, token: "observation", start: identity.start });
|
|
42
|
+
}
|
|
43
|
+
/** Read-only, fail-closed inspection using the same PID-reuse checks as claiming. */
|
|
44
|
+
export function inspectDaemonOwner(serverDir, lockName = "daemon-owner") {
|
|
45
|
+
const lock = join(serverDir, lockName);
|
|
46
|
+
try {
|
|
47
|
+
const names = readdirSync(lock);
|
|
48
|
+
if (names.length !== 1)
|
|
49
|
+
return { status: "ambiguous", reason: "Ownership directory is empty or has multiple entries" };
|
|
50
|
+
const owner = JSON.parse(readFileSync(join(lock, names[0]), "utf8"));
|
|
51
|
+
validateOwner(owner, names[0], lock);
|
|
52
|
+
return { status: alive(owner) ? "live" : "dead", owner };
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (error.code === "ENOENT") {
|
|
56
|
+
// A disappearing file inside a published directory is not proof of no owner.
|
|
57
|
+
try {
|
|
58
|
+
readdirSync(lock);
|
|
59
|
+
}
|
|
60
|
+
catch (again) {
|
|
61
|
+
if (again.code === "ENOENT")
|
|
62
|
+
return { status: "missing" };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return { status: "ambiguous", reason: String(error) };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export function validateDaemonOwnerIdentity(value) {
|
|
69
|
+
const owner = value;
|
|
70
|
+
validateOwner(owner, `owner-${owner?.token}.json`, "activation journal");
|
|
71
|
+
}
|
|
72
|
+
function validateOwner(previous, name, lock) {
|
|
73
|
+
if (!previous || typeof previous !== "object" || Array.isArray(previous)
|
|
74
|
+
|| !Number.isSafeInteger(previous.pid) || previous.pid <= 0 || previous.pid > 2_147_483_647
|
|
75
|
+
|| typeof previous.token !== "string" || !UUID.test(previous.token) || name !== `owner-${previous.token}.json`
|
|
76
|
+
|| (previous.boot !== undefined && (typeof previous.boot !== "string" || !UUID.test(previous.boot)))
|
|
77
|
+
|| (previous.start !== undefined && (typeof previous.start !== "string" || !/^\d+$/.test(previous.start))))
|
|
78
|
+
throw new Error(`Invalid daemon ownership in ${lock}`);
|
|
79
|
+
}
|
|
80
|
+
const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
81
|
+
function processIdentity(pid) {
|
|
82
|
+
if (process.platform === "darwin") {
|
|
83
|
+
try {
|
|
84
|
+
const start = execFileSync("/bin/ps", ["-p", String(pid), "-o", "lstart="], { encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 1000 }).trim();
|
|
85
|
+
const stamp = Date.parse(start);
|
|
86
|
+
return Number.isFinite(stamp) ? { start: String(stamp) } : {};
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return {};
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (process.platform !== "linux")
|
|
93
|
+
return {};
|
|
94
|
+
try {
|
|
95
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
96
|
+
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
97
|
+
return { boot: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), start: fields[19], state: fields[0] };
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return {};
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
function alive(owner) {
|
|
104
|
+
const identity = processIdentity(owner.pid);
|
|
105
|
+
if (owner.boot && identity.boot && owner.boot !== identity.boot)
|
|
106
|
+
return false;
|
|
107
|
+
if (owner.start && identity.start && owner.start !== identity.start)
|
|
108
|
+
return false;
|
|
109
|
+
// A kernel-confirmed exited process cannot own a socket even before its parent reaps it.
|
|
110
|
+
if (identity.state === "Z" || identity.state === "X")
|
|
111
|
+
return false;
|
|
112
|
+
try {
|
|
113
|
+
process.kill(owner.pid, 0);
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
return error.code !== "ESRCH";
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** Claim ownership before reading the index. A live owner is never reclaimed on a timer. */
|
|
121
|
+
export function claimDaemonOwner(serverDir, lockName = "daemon-owner", stagingDir = serverDir) {
|
|
122
|
+
const token = randomUUID();
|
|
123
|
+
const owner = currentOwnerIdentity(token);
|
|
124
|
+
const lock = join(serverDir, lockName);
|
|
125
|
+
const candidate = join(stagingDir, `.${lockName}-${token}`);
|
|
126
|
+
const name = `owner-${token}.json`;
|
|
127
|
+
mkdirSync(candidate, { mode: 0o700 });
|
|
128
|
+
let claimed = false;
|
|
129
|
+
try {
|
|
130
|
+
writeFileSync(join(candidate, name), `${JSON.stringify(owner)}\n`, { mode: 0o600 });
|
|
131
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
132
|
+
try {
|
|
133
|
+
// Publishing a fully populated directory avoids an ownerless mkdir/write window.
|
|
134
|
+
renameSync(candidate, lock);
|
|
135
|
+
claimed = true;
|
|
136
|
+
let released = false;
|
|
137
|
+
return () => {
|
|
138
|
+
if (released)
|
|
139
|
+
return;
|
|
140
|
+
try {
|
|
141
|
+
unlinkSync(join(lock, name));
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
if (error.code !== "ENOENT")
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
rmdirSync(lock);
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? ""))
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
released = true;
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
if (!["EEXIST", "ENOTEMPTY"].includes(error.code ?? ""))
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
let names;
|
|
162
|
+
try {
|
|
163
|
+
names = readdirSync(lock);
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
if (error.code === "ENOENT")
|
|
167
|
+
continue;
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
if (names.length === 0)
|
|
171
|
+
continue;
|
|
172
|
+
if (names.length !== 1 || !/^owner-[a-f0-9-]+\.json$/.test(names[0]))
|
|
173
|
+
throw new Error(`Unrecognized daemon ownership in ${lock}; refusing to remove it`);
|
|
174
|
+
const path = join(lock, names[0]);
|
|
175
|
+
let previous;
|
|
176
|
+
try {
|
|
177
|
+
previous = JSON.parse(readFileSync(path, "utf8"));
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
if (error.code === "ENOENT")
|
|
181
|
+
continue;
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
validateOwner(previous, names[0], lock);
|
|
185
|
+
if (alive(previous))
|
|
186
|
+
throw new Error(`Daemon owner ${previous.pid} is already running for ${serverDir}; refusing another writer`);
|
|
187
|
+
// Remove only the exact stale owner's file. A competing claimant publishes a different token.
|
|
188
|
+
try {
|
|
189
|
+
unlinkSync(path);
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
if (error.code === "ENOENT")
|
|
193
|
+
continue;
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
try {
|
|
197
|
+
rmdirSync(lock);
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? ""))
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
throw new Error(`Daemon ownership changed repeatedly for ${serverDir}; retry connecting`);
|
|
205
|
+
}
|
|
206
|
+
finally {
|
|
207
|
+
if (!claimed) {
|
|
208
|
+
try {
|
|
209
|
+
unlinkSync(join(candidate, name));
|
|
210
|
+
}
|
|
211
|
+
catch (error) {
|
|
212
|
+
if (error.code !== "ENOENT")
|
|
213
|
+
throw error;
|
|
214
|
+
}
|
|
215
|
+
rmdirSync(candidate);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { closeSync, openSync, readFileSync } from "node:fs";
|
|
3
|
+
import { connect } from "node:net";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { stageRuntime } from "../startup/install.mjs";
|
|
8
|
+
import { inspectDaemonOwner } from "../daemon-owner.mjs";
|
|
9
|
+
import { runtimeRoot } from "./root.mjs";
|
|
10
|
+
import { socketPathFor } from "./socket.mjs";
|
|
11
|
+
export { WorkClient } from "./work-client.mjs";
|
|
12
|
+
/** One bounded LF-JSON exchange; importing this module never loads the Pi SDK. */
|
|
13
|
+
export async function runtimeStatus(socketPath, agentDir, artifact, timeoutMs = 2000) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
const socket = connect(socketPath);
|
|
16
|
+
const timer = setTimeout(() => { socket.destroy(); reject(new Error(`runtime-unhealthy: no response at ${socketPath}; inspect the live owner`)); }, timeoutMs);
|
|
17
|
+
let buffer = "", greeted = false;
|
|
18
|
+
const fail = (error) => { clearTimeout(timer); socket.destroy(); reject(error); };
|
|
19
|
+
socket.on("error", fail);
|
|
20
|
+
socket.on("end", () => fail(new Error("runtime-unavailable: server closed the connection")));
|
|
21
|
+
socket.on("connect", () => socket.write(JSON.stringify({ id: "hello", type: "hello", protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-status-v1"] }) + "\n"));
|
|
22
|
+
socket.setEncoding("utf8");
|
|
23
|
+
socket.on("data", (chunk) => {
|
|
24
|
+
buffer += chunk;
|
|
25
|
+
if (buffer.length > 1024 * 1024)
|
|
26
|
+
return fail(new Error("runtime-unhealthy: response exceeds 1 MiB"));
|
|
27
|
+
while (buffer.includes("\n")) {
|
|
28
|
+
const index = buffer.indexOf("\n"), line = buffer.slice(0, index);
|
|
29
|
+
buffer = buffer.slice(index + 1);
|
|
30
|
+
try {
|
|
31
|
+
const reply = JSON.parse(line);
|
|
32
|
+
if (!reply.success)
|
|
33
|
+
throw new Error(reply.error ?? "runtime-unavailable");
|
|
34
|
+
const data = reply.data;
|
|
35
|
+
if (!greeted) {
|
|
36
|
+
if (reply.id !== "hello" || data?.protocolVersion !== 1 || data.agentDir !== agentDir
|
|
37
|
+
|| data.build?.contentId !== artifact.build.contentId || data.nodeVersion !== artifact.build.nodeVersion
|
|
38
|
+
|| !data.capabilities?.includes("runtime-status-v1") || !data.instanceId)
|
|
39
|
+
throw new Error("capability-mismatch: root, pinned build, Node or runtime capability differs; update the installed packages together");
|
|
40
|
+
greeted = true;
|
|
41
|
+
socket.write(JSON.stringify({ id: "status", type: "runtime_get_status" }) + "\n");
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
if (reply.id !== "status")
|
|
45
|
+
throw new Error("runtime-unhealthy: unexpected response");
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
socket.destroy();
|
|
48
|
+
resolve(data);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
return fail(error);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
const runLocal = (command, input, timeoutMs) => new Promise((resolve, reject) => {
|
|
59
|
+
const child = spawn("/bin/sh", ["-c", command], { stdio: "pipe", timeout: timeoutMs });
|
|
60
|
+
let stdout = "", stderr = "";
|
|
61
|
+
child.stdout.on("data", chunk => { stdout += chunk; });
|
|
62
|
+
child.stderr.on("data", chunk => { stderr += chunk; });
|
|
63
|
+
child.on("error", reject);
|
|
64
|
+
child.stdin.on("error", () => undefined);
|
|
65
|
+
child.on("close", (exitCode, signal) => resolve({ stdout, stderr, exitCode, timedOut: signal === "SIGTERM" }));
|
|
66
|
+
child.stdin.end(input);
|
|
67
|
+
});
|
|
68
|
+
export async function ensureRuntime(options) {
|
|
69
|
+
options.signal?.throwIfAborted();
|
|
70
|
+
const timeoutMs = options.timeoutMs ?? 15000;
|
|
71
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120000)
|
|
72
|
+
throw new Error("Runtime timeout must be from 1 to 120000 ms");
|
|
73
|
+
const platform = `${process.platform}-${process.arch}`;
|
|
74
|
+
const directory = fileURLToPath(new URL("../../artifacts/", import.meta.url));
|
|
75
|
+
let artifact;
|
|
76
|
+
try {
|
|
77
|
+
const manifest = JSON.parse(readFileSync(join(directory, `${platform}.json`), "utf8"));
|
|
78
|
+
artifact = { ...manifest, bytes: readFileSync(join(directory, `${platform}.gz`)) };
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
throw new Error(`runtime-unavailable: cannot read pinned artifact for ${platform}; reinstall the standalone package. ${String(error)}`);
|
|
82
|
+
}
|
|
83
|
+
const { decodeServerArtifact } = await import("../startup/artifact.mjs");
|
|
84
|
+
decodeServerArtifact(artifact);
|
|
85
|
+
const root = runtimeRoot(options.agentDir, options.serverDir ?? join(options.agentDir, "server"));
|
|
86
|
+
const socketPath = socketPathFor(root.serverDir);
|
|
87
|
+
const query = () => runtimeStatus(socketPath, root.agentDir, artifact, Math.min(timeoutMs, 2000));
|
|
88
|
+
try {
|
|
89
|
+
return await query();
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (!["ENOENT", "ECONNREFUSED"].includes(error.code ?? ""))
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
const owner = inspectDaemonOwner(root.serverDir);
|
|
96
|
+
if (owner.status === "live" || owner.status === "ambiguous")
|
|
97
|
+
throw new Error(`runtime-unhealthy: existing ${owner.status} owner at ${root.serverDir}; no replacement was started`);
|
|
98
|
+
let runtime;
|
|
99
|
+
try {
|
|
100
|
+
runtime = await stageRuntime({ run: runLocal, artifact, installRoot: options.installRoot ?? join(root.agentDir, "managed-runtime"), signal: options.signal, onProgress: options.onProgress, offline: options.offline });
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
throw new Error(`runtime-unavailable: ${String(error)}. Connect to the network to cache the pinned runtime, or repair the reported corrupt cache; no fallback manager was started.`);
|
|
104
|
+
}
|
|
105
|
+
const fd = openSync(join(root.serverDir, "daemon.log"), "a", 0o600);
|
|
106
|
+
try {
|
|
107
|
+
const env = { ...process.env, PI_SERVER_DIR: root.serverDir, PI_CODING_AGENT_DIR: root.agentDir, PI_SERVER_AGENT: "pi" };
|
|
108
|
+
for (const key of ["NODE_OPTIONS", "PI_SERVER_ACTIVATION_ID", "PI_SERVER_ROLLBACK_OPERATION_ID", "PI_SERVER_ROLLBACK_PERMIT"])
|
|
109
|
+
delete env[key];
|
|
110
|
+
const child = spawn(runtime.node, [runtime.entrypoint, "--agent", "pi"], { cwd: root.serverDir, env, detached: true, stdio: ["ignore", fd, fd] });
|
|
111
|
+
child.on("error", () => undefined);
|
|
112
|
+
child.unref();
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
closeSync(fd);
|
|
116
|
+
}
|
|
117
|
+
const deadline = Date.now() + timeoutMs;
|
|
118
|
+
while (Date.now() < deadline) {
|
|
119
|
+
options.signal?.throwIfAborted();
|
|
120
|
+
try {
|
|
121
|
+
return await query();
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (!["ENOENT", "ECONNREFUSED"].includes(error.code ?? ""))
|
|
125
|
+
throw error;
|
|
126
|
+
}
|
|
127
|
+
await delay(50, undefined, { signal: options.signal });
|
|
128
|
+
}
|
|
129
|
+
throw new Error(`runtime-unavailable: startup timed out; inspect ${join(root.serverDir, "daemon.log")}; owner was not replaced`);
|
|
130
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { linkSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
/** Transport selection is durable and independent of installation or package version. */
|
|
5
|
+
export function runtimeRoot(agentDir, requestedServerDir) {
|
|
6
|
+
mkdirSync(agentDir, { recursive: true, mode: 0o700 });
|
|
7
|
+
agentDir = realpathSync(agentDir);
|
|
8
|
+
const path = join(agentDir, "server-registration-v1.json");
|
|
9
|
+
const read = () => {
|
|
10
|
+
const registration = JSON.parse(readFileSync(path, "utf8"));
|
|
11
|
+
if (registration.version !== 1 || registration.agentDir !== agentDir || typeof registration.serverDir !== "string"
|
|
12
|
+
|| resolve(registration.serverDir) !== registration.serverDir || realpathSync(registration.serverDir) !== registration.serverDir) {
|
|
13
|
+
throw new Error(`runtime-unavailable: invalid registration at ${path}; inspect it before retrying`);
|
|
14
|
+
}
|
|
15
|
+
return { agentDir, serverDir: registration.serverDir };
|
|
16
|
+
};
|
|
17
|
+
try {
|
|
18
|
+
return read();
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (error.code !== "ENOENT")
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
const temporary = `${path}.${randomUUID()}`;
|
|
25
|
+
mkdirSync(requestedServerDir, { recursive: true, mode: 0o700 });
|
|
26
|
+
const proposed = { version: 1, agentDir, serverDir: realpathSync(requestedServerDir) };
|
|
27
|
+
writeFileSync(temporary, JSON.stringify(proposed), { mode: 0o600, flag: "wx" });
|
|
28
|
+
try {
|
|
29
|
+
try {
|
|
30
|
+
linkSync(temporary, path);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
if (error.code !== "EEXIST")
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
unlinkSync(temporary);
|
|
39
|
+
}
|
|
40
|
+
return read();
|
|
41
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
/** sockaddr_un.sun_path is 104 bytes on macOS; leave room for the NUL. */
|
|
3
|
+
export function socketPathFor(serverDir) {
|
|
4
|
+
const path = join(serverDir, "pi-server.sock");
|
|
5
|
+
if (Buffer.byteLength(path) > 103) {
|
|
6
|
+
throw new Error(`Socket path is too long for a unix socket (${Buffer.byteLength(path)} > 103 bytes): ${path}. Set PI_SERVER_DIR to a shorter directory.`);
|
|
7
|
+
}
|
|
8
|
+
return path;
|
|
9
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { ensureRuntime } from "./client.mjs";
|
|
5
|
+
try {
|
|
6
|
+
const status = await ensureRuntime({ agentDir: process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), serverDir: process.env.PI_SERVER_DIR,
|
|
7
|
+
offline: process.env.PI_OFFLINE === "1",
|
|
8
|
+
onProgress: stage => process.stderr.write(`Runtime: ${stage}\n`) });
|
|
9
|
+
process.stdout.write(JSON.stringify(status) + "\n");
|
|
10
|
+
}
|
|
11
|
+
catch (error) {
|
|
12
|
+
process.stderr.write(`${String(error)}\n`);
|
|
13
|
+
process.exitCode = 1;
|
|
14
|
+
}
|