pi-better-background-tasks 0.15.4 → 0.16.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.
Files changed (38) hide show
  1. package/README.md +13 -0
  2. package/package.json +5 -2
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -0
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -0
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -0
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -0
  11. package/runtime-client/scripts/private-runtime/format.mjs +90 -0
  12. package/runtime-client/src/daemon-owner.mjs +217 -0
  13. package/runtime-client/src/runtime/client.mjs +130 -0
  14. package/runtime-client/src/runtime/root.mjs +41 -0
  15. package/runtime-client/src/runtime/socket.mjs +9 -0
  16. package/runtime-client/src/runtime/status-cli.mjs +14 -0
  17. package/runtime-client/src/runtime/work-client.mjs +88 -0
  18. package/runtime-client/src/startup/artifact.mjs +76 -0
  19. package/runtime-client/src/startup/install.mjs +184 -0
  20. package/runtime-client/src/startup/managed-types.mjs +1 -0
  21. package/runtime-client/src/startup/runtime.mjs +120 -0
  22. package/src/goal-provider.ts +11 -7
  23. package/src/index.ts +3 -0
  24. package/src/observed-waits.ts +88 -26
  25. package/src/output.ts +16 -13
  26. package/src/registry.ts +15 -0
  27. package/src/shared-harness-settings.ts +4 -2
  28. package/src/shared-log-utils.ts +18 -7
  29. package/src/shared-navigator.ts +16 -4
  30. package/src/shared-operation-coordinator/assignment-observation.mjs +63 -3
  31. package/src/shared-operation-coordinator/index.ts +2 -0
  32. package/src/shared-operation-coordinator/src/errors.ts +2 -0
  33. package/src/shared-operation-coordinator/src/schema.ts +20 -0
  34. package/src/shared-operation-coordinator/src/store.ts +35 -0
  35. package/src/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  36. package/src/shared-work-client.mjs +88 -0
  37. package/src/tools.ts +28 -23
  38. package/src/work-observation.ts +117 -0
package/README.md CHANGED
@@ -6,6 +6,19 @@
6
6
 
7
7
  Use `pi-better-background-tasks` when a command should keep running while the foreground Pi session stays free. It is best for dev servers, long scripts, queue watchers, deploy checks, log tails, and other command-driven work.
8
8
 
9
+ ## Runtime Status
10
+
11
+ Run `pi-background-runtime-status` to ensure the manifest-pinned local server and
12
+ print its canonical agent root, build, Node version, instance and capabilities as JSON.
13
+ This command does not create a hosted Pi session or require Harness.
14
+ The first use installs a verified private Node 24 and locked server dependencies.
15
+ Set `PI_OFFLINE=1` to require the cached runtime without downloads.
16
+ `PI_CODING_AGENT_DIR` selects the agent root; `PI_SERVER_DIR` selects the initial
17
+ transport directory. Later calls for the same canonical root reuse the registered
18
+ transport, including calls from Subagents or another package installation.
19
+ An incompatible or unhealthy live owner is an error, not a reason to replace it.
20
+ The API is `runtime-client/src/runtime/client.mjs`, exporting `ensureRuntime`.
21
+
9
22
  ## Screenshots
10
23
 
11
24
  <p><img src="https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/pi-better-background-tasks.png" alt="pi-better-background-tasks rendered in Pi" width="49%" /><img src="https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/overview/pi-better-background-tasks.png" alt="pi-better-background-tasks package overview" width="49%" /></p>
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.15.4",
3
+ "version": "0.16.0",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
+ "bin": { "pi-background-runtime-status": "./runtime-client/src/runtime/status-cli.mjs" },
7
8
  "keywords": [
8
9
  "pi-package",
9
10
  "pi-extension",
@@ -31,7 +32,7 @@
31
32
  },
32
33
  "scripts": {
33
34
  "pretest": "node ../../scripts/sync-shared-log-utils.mjs && node ../../scripts/sync-shared-ssh-core.mjs && node ../../scripts/sync-shared-sandbox-core.mjs",
34
- "prepack": "node ../../scripts/sync-shared-log-utils.mjs && node ../../scripts/sync-shared-ssh-core.mjs && node ../../scripts/sync-shared-sandbox-core.mjs",
35
+ "prepack": "node ../../scripts/sync-shared-log-utils.mjs && node ../../scripts/sync-shared-ssh-core.mjs && node ../../scripts/sync-shared-sandbox-core.mjs && node ../../scripts/sync-runtime-client.mjs",
35
36
  "pretypecheck": "node ../../scripts/sync-shared-sandbox-core.mjs",
36
37
  "typecheck": "tsc --noEmit",
37
38
  "test": "vitest run",
@@ -43,8 +44,10 @@
43
44
  "test:sandbox": "vitest run src/sandbox.test.ts src/sandbox-kernel.test.ts"
44
45
  },
45
46
  "files": [
47
+ "runtime-client/**",
46
48
  "src/**/*.ts",
47
49
  "src/shared-operation-coordinator/assignment-observation.mjs",
50
+ "src/shared-work-client.mjs",
48
51
  "src/supervisor/**/*.mjs",
49
52
  "src/supervisor/**/*.js",
50
53
  "!src/**/*.test.ts",
@@ -0,0 +1 @@
1
+ {"build":{"format":1,"sourceDigest":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"4a441dc74b227cdaaeebe9bf93580d18c4773acd30a43df8376205888314877f"},"sha256":"d605829c1323baa03ec1908337950c965d97e7ded4dc24479fff7300be296367"}
@@ -0,0 +1 @@
1
+ {"build":{"format":1,"sourceDigest":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"217c2fe0b4c39621f2d231c2ee13e675514f5800d3d0f88edd1d640982df1cf8"},"sha256":"cafcd27fc435dd8a94b75154af1e509c0fb649c79423e090755c014c6609296b"}
@@ -0,0 +1 @@
1
+ {"build":{"format":1,"sourceDigest":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"ad01e2a4639e88f1919d9aa628d6d5760ab0b8bd34d563f6adf7c81c106e90f6"},"sha256":"0b5c8649a160f17eae208389848f09655d8e77fdf00c606241598c76fb956acd"}
@@ -0,0 +1 @@
1
+ {"build":{"format":1,"sourceDigest":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"1e311f8fd34ed8dbea8660e1383e128e4f2916b18949cd1288ab5e0682b6a85a"},"sha256":"258a050dfbb9089e3876d2ffcafa85f85e40c9396e041145e43a6d90d2cdf8ab"}
@@ -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,217 @@
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
+ }).trim();
33
+ return observed.length > 0 && observed === start.trim();
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
39
+ const identity = processIdentity(pid);
40
+ return identity.start !== undefined && identity.start === start && alive({ pid, token: "observation", start: identity.start });
41
+ }
42
+ /** Read-only, fail-closed inspection using the same PID-reuse checks as claiming. */
43
+ export function inspectDaemonOwner(serverDir, lockName = "daemon-owner") {
44
+ const lock = join(serverDir, lockName);
45
+ try {
46
+ const names = readdirSync(lock);
47
+ if (names.length !== 1)
48
+ return { status: "ambiguous", reason: "Ownership directory is empty or has multiple entries" };
49
+ const owner = JSON.parse(readFileSync(join(lock, names[0]), "utf8"));
50
+ validateOwner(owner, names[0], lock);
51
+ return { status: alive(owner) ? "live" : "dead", owner };
52
+ }
53
+ catch (error) {
54
+ if (error.code === "ENOENT") {
55
+ // A disappearing file inside a published directory is not proof of no owner.
56
+ try {
57
+ readdirSync(lock);
58
+ }
59
+ catch (again) {
60
+ if (again.code === "ENOENT")
61
+ return { status: "missing" };
62
+ }
63
+ }
64
+ return { status: "ambiguous", reason: String(error) };
65
+ }
66
+ }
67
+ export function validateDaemonOwnerIdentity(value) {
68
+ const owner = value;
69
+ validateOwner(owner, `owner-${owner?.token}.json`, "activation journal");
70
+ }
71
+ function validateOwner(previous, name, lock) {
72
+ if (!previous || typeof previous !== "object" || Array.isArray(previous)
73
+ || !Number.isSafeInteger(previous.pid) || previous.pid <= 0 || previous.pid > 2_147_483_647
74
+ || typeof previous.token !== "string" || !UUID.test(previous.token) || name !== `owner-${previous.token}.json`
75
+ || (previous.boot !== undefined && (typeof previous.boot !== "string" || !UUID.test(previous.boot)))
76
+ || (previous.start !== undefined && (typeof previous.start !== "string" || !/^\d+$/.test(previous.start))))
77
+ throw new Error(`Invalid daemon ownership in ${lock}`);
78
+ }
79
+ const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
80
+ function processIdentity(pid) {
81
+ if (process.platform === "darwin") {
82
+ try {
83
+ const start = execFileSync("/bin/ps", ["-p", String(pid), "-o", "lstart="], { encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 1000 }).trim();
84
+ const stamp = Date.parse(start);
85
+ return Number.isFinite(stamp) ? { start: String(stamp) } : {};
86
+ }
87
+ catch {
88
+ return {};
89
+ }
90
+ }
91
+ if (process.platform !== "linux")
92
+ return {};
93
+ try {
94
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
95
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
96
+ return { boot: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), start: fields[19], state: fields[0] };
97
+ }
98
+ catch {
99
+ return {};
100
+ }
101
+ }
102
+ function alive(owner) {
103
+ const identity = processIdentity(owner.pid);
104
+ if (owner.boot && identity.boot && owner.boot !== identity.boot)
105
+ return false;
106
+ if (owner.start && identity.start && owner.start !== identity.start)
107
+ return false;
108
+ // A kernel-confirmed exited process cannot own a socket even before its parent reaps it.
109
+ if (identity.state === "Z" || identity.state === "X")
110
+ return false;
111
+ try {
112
+ process.kill(owner.pid, 0);
113
+ return true;
114
+ }
115
+ catch (error) {
116
+ return error.code !== "ESRCH";
117
+ }
118
+ }
119
+ /** Claim ownership before reading the index. A live owner is never reclaimed on a timer. */
120
+ export function claimDaemonOwner(serverDir, lockName = "daemon-owner", stagingDir = serverDir) {
121
+ const token = randomUUID();
122
+ const owner = currentOwnerIdentity(token);
123
+ const lock = join(serverDir, lockName);
124
+ const candidate = join(stagingDir, `.${lockName}-${token}`);
125
+ const name = `owner-${token}.json`;
126
+ mkdirSync(candidate, { mode: 0o700 });
127
+ let claimed = false;
128
+ try {
129
+ writeFileSync(join(candidate, name), `${JSON.stringify(owner)}\n`, { mode: 0o600 });
130
+ for (let attempt = 0; attempt < 20; attempt++) {
131
+ try {
132
+ // Publishing a fully populated directory avoids an ownerless mkdir/write window.
133
+ renameSync(candidate, lock);
134
+ claimed = true;
135
+ let released = false;
136
+ return () => {
137
+ if (released)
138
+ return;
139
+ try {
140
+ unlinkSync(join(lock, name));
141
+ }
142
+ catch (error) {
143
+ if (error.code !== "ENOENT")
144
+ throw error;
145
+ }
146
+ try {
147
+ rmdirSync(lock);
148
+ }
149
+ catch (error) {
150
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? ""))
151
+ throw error;
152
+ }
153
+ released = true;
154
+ };
155
+ }
156
+ catch (error) {
157
+ if (!["EEXIST", "ENOTEMPTY"].includes(error.code ?? ""))
158
+ throw error;
159
+ }
160
+ let names;
161
+ try {
162
+ names = readdirSync(lock);
163
+ }
164
+ catch (error) {
165
+ if (error.code === "ENOENT")
166
+ continue;
167
+ throw error;
168
+ }
169
+ if (names.length === 0)
170
+ continue;
171
+ if (names.length !== 1 || !/^owner-[a-f0-9-]+\.json$/.test(names[0]))
172
+ throw new Error(`Unrecognized daemon ownership in ${lock}; refusing to remove it`);
173
+ const path = join(lock, names[0]);
174
+ let previous;
175
+ try {
176
+ previous = JSON.parse(readFileSync(path, "utf8"));
177
+ }
178
+ catch (error) {
179
+ if (error.code === "ENOENT")
180
+ continue;
181
+ throw error;
182
+ }
183
+ validateOwner(previous, names[0], lock);
184
+ if (alive(previous))
185
+ throw new Error(`Daemon owner ${previous.pid} is already running for ${serverDir}; refusing another writer`);
186
+ // Remove only the exact stale owner's file. A competing claimant publishes a different token.
187
+ try {
188
+ unlinkSync(path);
189
+ }
190
+ catch (error) {
191
+ if (error.code === "ENOENT")
192
+ continue;
193
+ throw error;
194
+ }
195
+ try {
196
+ rmdirSync(lock);
197
+ }
198
+ catch (error) {
199
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? ""))
200
+ throw error;
201
+ }
202
+ }
203
+ throw new Error(`Daemon ownership changed repeatedly for ${serverDir}; retry connecting`);
204
+ }
205
+ finally {
206
+ if (!claimed) {
207
+ try {
208
+ unlinkSync(join(candidate, name));
209
+ }
210
+ catch (error) {
211
+ if (error.code !== "ENOENT")
212
+ throw error;
213
+ }
214
+ rmdirSync(candidate);
215
+ }
216
+ }
217
+ }
@@ -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
+ }