pi-better-background-tasks 0.15.3 → 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.
- package/README.md +13 -0
- package/package.json +5 -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 +217 -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 +88 -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/src/goal-provider.ts +11 -7
- package/src/index.ts +3 -0
- package/src/observed-waits.ts +88 -26
- package/src/output.ts +16 -13
- package/src/registry.ts +15 -0
- package/src/shared-harness-settings.ts +4 -2
- package/src/shared-log-utils.ts +18 -7
- package/src/shared-navigator.ts +26 -8
- package/src/shared-operation-coordinator/assignment-observation.mjs +63 -3
- package/src/shared-operation-coordinator/index.ts +2 -0
- package/src/shared-operation-coordinator/src/errors.ts +2 -0
- package/src/shared-operation-coordinator/src/schema.ts +20 -0
- package/src/shared-operation-coordinator/src/store.ts +35 -0
- package/src/shared-operation-coordinator/src/task-cancellation.ts +224 -0
- package/src/shared-work-client.mjs +88 -0
- package/src/tools.ts +28 -23
- package/src/work-observation.ts +117 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { connect } from "node:net";
|
|
2
|
+
|
|
3
|
+
/** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
|
|
4
|
+
export class WorkClient {
|
|
5
|
+
socket;
|
|
6
|
+
snapshot;
|
|
7
|
+
pending = new Map();
|
|
8
|
+
listeners = new Set();
|
|
9
|
+
sequence = 0;
|
|
10
|
+
scope;
|
|
11
|
+
buffer = "";
|
|
12
|
+
closed = false;
|
|
13
|
+
|
|
14
|
+
constructor(socketPath, agentDir, requiredCapabilities = []) {
|
|
15
|
+
this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
|
|
16
|
+
this.socket.setEncoding("utf8");
|
|
17
|
+
this.socket.on("data", chunk => {
|
|
18
|
+
this.buffer += chunk;
|
|
19
|
+
if (Buffer.byteLength(this.buffer) > 4 * 1024 * 1024) return this.fail(new Error("runtime-unhealthy: oversized stream frame"));
|
|
20
|
+
while (this.buffer.includes("\n")) {
|
|
21
|
+
const index = this.buffer.indexOf("\n"), line = this.buffer.slice(0, index);
|
|
22
|
+
this.buffer = this.buffer.slice(index + 1);
|
|
23
|
+
try {
|
|
24
|
+
const message = JSON.parse(line);
|
|
25
|
+
if (message.type === "event") {
|
|
26
|
+
if (message.event.type === "resync_required") { this.degrade(message.event.reason); void this.resync().catch(error => this.degrade(String(error))); }
|
|
27
|
+
else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot);
|
|
28
|
+
} else {
|
|
29
|
+
const request = this.pending.get(message.id);
|
|
30
|
+
if (!request) continue;
|
|
31
|
+
this.pending.delete(message.id); clearTimeout(request.timer);
|
|
32
|
+
if (message.success) request.resolve(message.data); else request.reject(new Error(message.error));
|
|
33
|
+
}
|
|
34
|
+
} catch (error) { this.fail(error); }
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
this.socket.on("error", error => this.fail(error));
|
|
38
|
+
this.socket.on("close", () => this.fail(new Error("runtime-unavailable: disconnected; resync required")));
|
|
39
|
+
this.ready = this.request("hello", { protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-state-v1", "runtime-subscriptions-v1", ...requiredCapabilities] })
|
|
40
|
+
.then(async hello => { if (typeof socketPath === "string" && hello.capabilities?.includes("runtime-client-retention-v1")) await this.request("runtime_register_client", { clientId: `work-${process.pid}` }); return hello; });
|
|
41
|
+
}
|
|
42
|
+
request(type, params = {}) {
|
|
43
|
+
if (this.closed) return Promise.reject(new Error("runtime-unavailable: disconnected; resync required"));
|
|
44
|
+
if (this.pending.size >= 32) return Promise.reject(new Error("runtime-unhealthy: too many in-flight queries"));
|
|
45
|
+
const id = `work-${++this.sequence}`;
|
|
46
|
+
return new Promise((resolve, reject) => {
|
|
47
|
+
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`runtime-unhealthy: ${type} timed out`)); }, 5000);
|
|
48
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
49
|
+
this.socket.write(JSON.stringify({ id, type, ...params }) + "\n");
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
onChange(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
|
|
53
|
+
notify() { for (const listener of this.listeners) listener(this.snapshot); }
|
|
54
|
+
degrade(reason) {
|
|
55
|
+
this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
|
|
56
|
+
this.notify();
|
|
57
|
+
}
|
|
58
|
+
accept(snapshot) {
|
|
59
|
+
if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
|
|
60
|
+
if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
|
|
61
|
+
this.degrade("instance-changed: resync required");
|
|
62
|
+
snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
|
|
63
|
+
} else if (this.snapshot?.seq !== undefined && snapshot.seq > this.snapshot.seq + 1) {
|
|
64
|
+
this.degrade("sequence-gap: replacing with a full authoritative snapshot");
|
|
65
|
+
snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
|
|
66
|
+
}
|
|
67
|
+
// Every event contains a complete bounded snapshot; gaps do not require inferred deltas.
|
|
68
|
+
this.snapshot = Object.freeze(snapshot); this.notify();
|
|
69
|
+
}
|
|
70
|
+
async subscribe(scope) {
|
|
71
|
+
await this.ready;
|
|
72
|
+
this.scope = scope;
|
|
73
|
+
const snapshot = await this.request("runtime_subscribe", { scope });
|
|
74
|
+
this.accept(snapshot); return snapshot;
|
|
75
|
+
}
|
|
76
|
+
async resync() {
|
|
77
|
+
const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
|
|
78
|
+
this.accept(snapshot); return snapshot;
|
|
79
|
+
}
|
|
80
|
+
async get(scope) { await this.ready; return this.request("runtime_get_snapshot", { scope }); }
|
|
81
|
+
fail(error) {
|
|
82
|
+
if (this.closed) return;
|
|
83
|
+
this.closed = true;
|
|
84
|
+
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
|
|
85
|
+
this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
|
|
86
|
+
}
|
|
87
|
+
close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); }
|
|
88
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { readFileSync, readdirSync, lstatSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { gzipSync, gunzipSync } from "node:zlib";
|
|
5
|
+
import { digest, stable, validateBuild, validatePayload, validateStaged } from "../../scripts/private-runtime/format.mjs";
|
|
6
|
+
export const ownPackageDir = fileURLToPath(new URL("../../", import.meta.url));
|
|
7
|
+
/** Only shipped source and explicitly named runtime resources enter the build. */
|
|
8
|
+
export function createServerArtifact(options) {
|
|
9
|
+
const root = options.packageDir ?? ownPackageDir;
|
|
10
|
+
for (const path of ["package.json", "scripts", "scripts/private-runtime", "scripts/private-runtime/package-lock.json"]) {
|
|
11
|
+
if (lstatSync(join(root, path)).isSymbolicLink())
|
|
12
|
+
throw new Error(`Artifact: symlink is forbidden: ${path}`);
|
|
13
|
+
}
|
|
14
|
+
const metadata = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
15
|
+
const lock = JSON.parse(readFileSync(join(root, "scripts/private-runtime/package-lock.json"), "utf8"));
|
|
16
|
+
const files = [];
|
|
17
|
+
function add(path) {
|
|
18
|
+
const stat = lstatSync(join(root, path));
|
|
19
|
+
if (stat.isSymbolicLink())
|
|
20
|
+
throw new Error(`Artifact: symlink is forbidden: ${path}`);
|
|
21
|
+
if (stat.isDirectory()) {
|
|
22
|
+
for (const name of readdirSync(join(root, path)).sort()) {
|
|
23
|
+
if (["node_modules", ".git", "test-support"].includes(name) || name.startsWith(".env") || ["auth.json", "settings.json"].includes(name))
|
|
24
|
+
continue;
|
|
25
|
+
add(`${path}/${name}`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
else if (stat.isFile()) {
|
|
29
|
+
if (stat.size > 12 * 1024 * 1024)
|
|
30
|
+
throw new Error(`Artifact: oversized source file: ${path}`);
|
|
31
|
+
files.push({ path, data: readFileSync(join(root, path)).toString("base64") });
|
|
32
|
+
if (files.length > 10000)
|
|
33
|
+
throw new Error("Artifact: file count limit");
|
|
34
|
+
}
|
|
35
|
+
else
|
|
36
|
+
throw new Error(`Artifact: non-regular source: ${path}`);
|
|
37
|
+
}
|
|
38
|
+
add("src");
|
|
39
|
+
for (const name of ["format.ts", "installer.ts", "package.json", "package-lock.json"])
|
|
40
|
+
add(`scripts/private-runtime/${name}`);
|
|
41
|
+
files.push({ path: "package.json", data: Buffer.from(stable({ name: metadata.name, version: metadata.version, type: "module" })).toString("base64") });
|
|
42
|
+
files.sort((a, b) => a.path.localeCompare(b.path, "en"));
|
|
43
|
+
const identity = {
|
|
44
|
+
format: 1, sourceDigest: digest(stable(files)), piSdkVersion: lock.packages[""].dependencies["@earendil-works/pi-coding-agent"],
|
|
45
|
+
nodeVersion: "24.14.1", platform: options.platform, dependencyLockDigest: digest(stable(lock)), protocolVersion: 1, serverVersion: metadata.version,
|
|
46
|
+
};
|
|
47
|
+
const build = { ...identity, contentId: digest(stable(identity)) };
|
|
48
|
+
const payload = { format: 1, build, files };
|
|
49
|
+
validatePayload(payload);
|
|
50
|
+
const bytes = gzipSync(stable(payload), { level: 9 });
|
|
51
|
+
return { build, bytes, sha256: digest(bytes) };
|
|
52
|
+
}
|
|
53
|
+
export function decodeServerArtifact(artifact) {
|
|
54
|
+
if (artifact.bytes.length > 32 * 1024 * 1024 || digest(artifact.bytes) !== artifact.sha256)
|
|
55
|
+
throw new Error("Artifact: compressed integrity mismatch or size limit");
|
|
56
|
+
const payload = validatePayload(JSON.parse(gunzipSync(artifact.bytes, { maxOutputLength: 64 * 1024 * 1024 }).toString("utf8")));
|
|
57
|
+
if (stable(payload.build) !== stable(artifact.build))
|
|
58
|
+
throw new Error("Artifact: build identity mismatch");
|
|
59
|
+
return payload;
|
|
60
|
+
}
|
|
61
|
+
export function readOwnBuild() {
|
|
62
|
+
try {
|
|
63
|
+
return validateBuild(JSON.parse(readFileSync(join(ownPackageDir, "managed-build.json"), "utf8")));
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error.code === "ENOENT")
|
|
67
|
+
return undefined;
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
export function readStagedRuntime(manifestPath) {
|
|
72
|
+
const runtime = validateStaged(JSON.parse(readFileSync(manifestPath, "utf8")));
|
|
73
|
+
if (runtime.manifestPath !== manifestPath || dirname(manifestPath) !== runtime.root)
|
|
74
|
+
throw new Error("Staging: manifest location mismatch");
|
|
75
|
+
return runtime;
|
|
76
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { randomUUID, createHash } from "node:crypto";
|
|
2
|
+
import { posix } from "node:path";
|
|
3
|
+
import { decodeServerArtifact } from "./artifact.mjs";
|
|
4
|
+
import { absolutePath, probeRemoteRuntime, shellQuote } from "./runtime.mjs";
|
|
5
|
+
import { NODE_CHECKSUMS, NODE_EXECUTABLE_CHECKSUMS, validateStaged } from "../../scripts/private-runtime/format.mjs";
|
|
6
|
+
async function download(url, integrity, signal) {
|
|
7
|
+
const response = await fetch(url, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(120_000)]) : AbortSignal.timeout(120_000), redirect: "error" });
|
|
8
|
+
if (!response.ok || !response.body)
|
|
9
|
+
throw new Error(`Runtime download: HTTP ${response.status} for ${url}`);
|
|
10
|
+
const parts = [];
|
|
11
|
+
let size = 0;
|
|
12
|
+
for await (const chunk of response.body) {
|
|
13
|
+
size += chunk.length;
|
|
14
|
+
if (size > 128 * 1024 * 1024)
|
|
15
|
+
throw new Error("Runtime download: archive size limit");
|
|
16
|
+
parts.push(Buffer.from(chunk));
|
|
17
|
+
}
|
|
18
|
+
const bytes = Buffer.concat(parts);
|
|
19
|
+
const [algorithm, expected] = integrity.split("-", 2);
|
|
20
|
+
if (createHash(algorithm).update(bytes).digest(algorithm === "sha256" ? "hex" : "base64") !== expected)
|
|
21
|
+
throw new Error(`Runtime download: integrity mismatch for ${url}`);
|
|
22
|
+
return bytes;
|
|
23
|
+
}
|
|
24
|
+
/** Pure staging: never runs a launcher, starts a daemon, or writes a registration. */
|
|
25
|
+
export async function stageRuntime(options) {
|
|
26
|
+
const { run, artifact, signal, onProgress } = options;
|
|
27
|
+
const payload = decodeServerArtifact(artifact);
|
|
28
|
+
signal?.throwIfAborted();
|
|
29
|
+
onProgress?.("probe");
|
|
30
|
+
const probe = await probeRemoteRuntime(run, { signal, registration: false });
|
|
31
|
+
if (probe.explicitCommand)
|
|
32
|
+
throw new Error("Runtime staging: explicit PI_SERVER_COMMAND opts out of managed installation");
|
|
33
|
+
if (probe.platform !== artifact.build.platform)
|
|
34
|
+
throw new Error("Runtime staging: artifact platform does not match target");
|
|
35
|
+
const root = posix.normalize(absolutePath(options.installRoot ?? `${probe.home}/.pi-better-server/managed`, "installRoot"));
|
|
36
|
+
if (root === "/" || root.split("/").includes("node_modules"))
|
|
37
|
+
throw new Error("Runtime staging: releases must be outside node_modules");
|
|
38
|
+
const owner = randomUUID();
|
|
39
|
+
const work = `${root}/.stage-${owner}`;
|
|
40
|
+
const q = shellQuote;
|
|
41
|
+
const checked = async (command, input, timeoutMs = 30_000) => {
|
|
42
|
+
signal?.throwIfAborted();
|
|
43
|
+
const result = await run(command, input, timeoutMs);
|
|
44
|
+
signal?.throwIfAborted();
|
|
45
|
+
if (result.exitCode !== 0 || result.timedOut)
|
|
46
|
+
throw new Error(`Runtime staging: ${result.stderr || "remote command failed"}`);
|
|
47
|
+
return result;
|
|
48
|
+
};
|
|
49
|
+
let cancellation;
|
|
50
|
+
let setupAttempted = false;
|
|
51
|
+
const cancel = () => { cancellation = run(`: > ${q(`${work}/cancel`)}`, undefined, 5000).catch(() => undefined); };
|
|
52
|
+
try {
|
|
53
|
+
signal?.throwIfAborted();
|
|
54
|
+
setupAttempted = true;
|
|
55
|
+
const setup = await run(`set -eu; umask 077; p=${q(root)}; while [ "$p" != / ]; do [ ! -L "$p" ] || { echo 'permission: symlink install root' >&2; exit 1; }; p=$(dirname "$p"); done; mkdir -p ${q(root)}; mkdir ${q(work)}; printf %s ${q(owner)} > ${q(`${work}/.stage-owner`)}`, undefined, 30_000);
|
|
56
|
+
if (setup.exitCode !== 0 || setup.timedOut)
|
|
57
|
+
throw new Error(`Runtime staging setup: ${setup.stderr || "remote command failed"}`);
|
|
58
|
+
signal?.throwIfAborted();
|
|
59
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
60
|
+
const finalRoot = `${root}/releases/${artifact.build.contentId}`;
|
|
61
|
+
const cachedArtifact = `${finalRoot}/artifact.gz`;
|
|
62
|
+
const artifactPath = `${work}/artifact.gz`;
|
|
63
|
+
// Older releases may lack the archive. Its contents are authenticated by the fresh installer against the requested build.
|
|
64
|
+
const archiveCache = await checked(`set -eu
|
|
65
|
+
p=${q(finalRoot)}
|
|
66
|
+
while [ "$p" != / ]; do
|
|
67
|
+
[ ! -L "$p" ] || { echo 'corrupt cache: symlink release path' >&2; exit 1; }
|
|
68
|
+
[ ! -e "$p" ] || { [ -d "$p" ] && [ -x "$p" ]; } || { echo 'corrupt cache: unsafe release directory' >&2; exit 1; }
|
|
69
|
+
p=$(dirname "$p")
|
|
70
|
+
done
|
|
71
|
+
if [ -L ${q(cachedArtifact)} ]; then echo 'corrupt cache: artifact symlink' >&2; exit 1; fi
|
|
72
|
+
if [ ! -e ${q(cachedArtifact)} ]; then
|
|
73
|
+
if [ -e ${q(finalRoot)} ]; then printf 'legacy\\n'; else printf 'absent\\n'; fi
|
|
74
|
+
exit 0
|
|
75
|
+
fi
|
|
76
|
+
[ -f ${q(cachedArtifact)} ] || { echo 'corrupt cache: expected regular artifact' >&2; exit 1; }
|
|
77
|
+
[ "$(wc -c < ${q(cachedArtifact)})" -le 33554432 ] || { echo 'corrupt cache: artifact size limit' >&2; exit 1; }
|
|
78
|
+
cp ${q(cachedArtifact)} ${q(artifactPath)}
|
|
79
|
+
[ "$(wc -c < ${q(artifactPath)})" -le 33554432 ] || { echo 'corrupt cache: artifact size limit' >&2; exit 1; }
|
|
80
|
+
if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(artifactPath)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(artifactPath)} | cut -d ' ' -f 1); fi
|
|
81
|
+
printf 'reuse:%s\\n' "$actual"`, undefined, 120_000);
|
|
82
|
+
const archiveResponse = archiveCache.stdout.trim();
|
|
83
|
+
const archiveDigest = /^reuse:([a-f0-9]{64})$/.exec(archiveResponse)?.[1];
|
|
84
|
+
const archiveState = archiveDigest ? "reuse" : archiveResponse;
|
|
85
|
+
if (archiveState !== "reuse" && archiveState !== "absent" && archiveState !== "legacy")
|
|
86
|
+
throw new Error("Runtime staging: unexpected artifact cache probe result");
|
|
87
|
+
if (archiveState !== "reuse") {
|
|
88
|
+
onProgress?.("verification-upload");
|
|
89
|
+
await checked(`cat > ${q(artifactPath)}`, artifact.bytes, 120_000);
|
|
90
|
+
}
|
|
91
|
+
for (const name of ["installer.ts", "format.ts"]) {
|
|
92
|
+
const file = payload.files.find((entry) => entry.path === `scripts/private-runtime/${name}`);
|
|
93
|
+
await checked(`cat > ${q(`${work}/${name}`)}`, Buffer.from(file.data, "base64"));
|
|
94
|
+
}
|
|
95
|
+
const cachedNode = `${finalRoot}/node/bin/node`;
|
|
96
|
+
const node = `${work}/node/bin/node`;
|
|
97
|
+
onProgress?.("verifying");
|
|
98
|
+
// Authenticate the scratch copy before executing any bytes from the cached release.
|
|
99
|
+
const cached = await checked(`set -eu
|
|
100
|
+
p=${q(`${root}/releases`)}
|
|
101
|
+
while [ "$p" != / ]; do
|
|
102
|
+
[ ! -L "$p" ] || { echo 'corrupt cache: symlink release path' >&2; exit 1; }
|
|
103
|
+
[ ! -e "$p" ] || { [ -d "$p" ] && [ -x "$p" ]; } || { echo 'corrupt cache: unsafe release directory' >&2; exit 1; }
|
|
104
|
+
p=$(dirname "$p")
|
|
105
|
+
done
|
|
106
|
+
[ ! -L ${q(finalRoot)} ] || { echo 'corrupt cache: release symlink' >&2; exit 1; }
|
|
107
|
+
if [ ! -e ${q(finalRoot)} ]; then printf 'absent\\n'; exit 0; fi
|
|
108
|
+
[ -d ${q(finalRoot)} ] && [ -x ${q(finalRoot)} ] || { echo 'corrupt cache: expected accessible release directory' >&2; exit 1; }
|
|
109
|
+
p=${q(cachedNode)}
|
|
110
|
+
while [ "$p" != ${q(finalRoot)} ]; do
|
|
111
|
+
[ ! -L "$p" ] || { echo 'corrupt cache: symlink Node path' >&2; exit 1; }
|
|
112
|
+
p=$(dirname "$p")
|
|
113
|
+
done
|
|
114
|
+
[ -f ${q(cachedNode)} ] && [ -x ${q(cachedNode)} ] || { echo 'corrupt cache: expected regular Node executable' >&2; exit 1; }
|
|
115
|
+
mkdir -p ${q(`${work}/node/bin`)}
|
|
116
|
+
cp ${q(cachedNode)} ${q(node)}
|
|
117
|
+
if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(node)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(node)} | cut -d ' ' -f 1); fi
|
|
118
|
+
[ "$actual" = ${q(NODE_EXECUTABLE_CHECKSUMS[probe.platform])} ] || { echo 'Node executable integrity mismatch' >&2; exit 1; }
|
|
119
|
+
printf 'reuse\\n'`, undefined, 120_000);
|
|
120
|
+
const cachedState = cached.stdout.trim();
|
|
121
|
+
if (cachedState !== "reuse" && cachedState !== "absent")
|
|
122
|
+
throw new Error("Runtime staging: unexpected cache probe result");
|
|
123
|
+
if (cachedState === "absent" && archiveState !== "absent")
|
|
124
|
+
throw new Error("Runtime staging: cached release disappeared during verification");
|
|
125
|
+
const reuse = cachedState === "reuse";
|
|
126
|
+
if (!reuse) {
|
|
127
|
+
if (options.offline)
|
|
128
|
+
throw new Error(`Offline cache miss: pinned Node ${artifact.build.nodeVersion} and runtime ${artifact.build.contentId} are not cached at ${finalRoot}; connect once to install them`);
|
|
129
|
+
onProgress?.("node-download");
|
|
130
|
+
signal?.throwIfAborted();
|
|
131
|
+
const archive = `node-v${artifact.build.nodeVersion}-${probe.platform}`;
|
|
132
|
+
const url = `https://nodejs.org/dist/v${artifact.build.nodeVersion}/${archive}.tar.gz`;
|
|
133
|
+
const sha = NODE_CHECKSUMS[probe.platform];
|
|
134
|
+
const tar = `${work}/node.tar.gz`;
|
|
135
|
+
const remote = await run(`curl -q --fail --silent --show-error --location --proto '=https' --connect-timeout 10 --max-time 120 ${q(url)} -o ${q(tar)}`, undefined, 125_000);
|
|
136
|
+
signal?.throwIfAborted();
|
|
137
|
+
if (remote.exitCode !== 0 || remote.timedOut) {
|
|
138
|
+
onProgress?.("node-upload");
|
|
139
|
+
await checked(`cat > ${q(tar)}`, await download(url, `sha256-${sha}`, signal), 120_000);
|
|
140
|
+
}
|
|
141
|
+
await checked(`set -eu; if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(tar)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(tar)} | cut -d ' ' -f 1); fi; [ "$actual" = ${q(sha)} ] || { echo 'Node archive integrity mismatch' >&2; exit 1; }; tar -xzf ${q(tar)} -C ${q(work)}; mv ${q(`${work}/${archive}`)} ${q(`${work}/node`)}; rm ${q(tar)}`, undefined, 120_000);
|
|
142
|
+
}
|
|
143
|
+
const invoke = (mode) => `env -i HOME=${q(`${work}/home`)} PATH=${q(`${work}/node/bin:/usr/bin:/bin`)} ${q(node)} ${q(`${work}/installer.ts`)} ${q(work)} ${q(root)} ${q(archiveDigest ?? artifact.sha256)} ${mode} ${q(artifact.build.contentId)}`;
|
|
144
|
+
if (!reuse)
|
|
145
|
+
onProgress?.("dependencies");
|
|
146
|
+
signal?.throwIfAborted();
|
|
147
|
+
let installed = await run(invoke(reuse ? "reuse-only" : "online"), undefined, 600_000);
|
|
148
|
+
signal?.throwIfAborted();
|
|
149
|
+
if (!reuse && installed.exitCode === 75) {
|
|
150
|
+
onProgress?.("dependencies-upload");
|
|
151
|
+
const lock = JSON.parse(Buffer.from(payload.files.find((f) => f.path === "scripts/private-runtime/package-lock.json").data, "base64").toString());
|
|
152
|
+
await checked(`mkdir -p ${q(`${work}/archives`)}`);
|
|
153
|
+
const packages = new Map();
|
|
154
|
+
for (const pkg of Object.values(lock.packages))
|
|
155
|
+
if (pkg.resolved)
|
|
156
|
+
packages.set(pkg.integrity, pkg.resolved);
|
|
157
|
+
const entries = [...packages];
|
|
158
|
+
for (let offset = 0; offset < entries.length; offset += 4) {
|
|
159
|
+
const batch = await Promise.allSettled(entries.slice(offset, offset + 4).map(async ([integrity, url], index) => {
|
|
160
|
+
await checked(`cat > ${q(`${work}/archives/${offset + index}.tgz`)}`, await download(url, integrity, signal), 120_000);
|
|
161
|
+
}));
|
|
162
|
+
const failed = batch.find((result) => result.status === "rejected");
|
|
163
|
+
if (failed?.status === "rejected")
|
|
164
|
+
throw failed.reason;
|
|
165
|
+
}
|
|
166
|
+
installed = await run(invoke("offline"), undefined, 600_000);
|
|
167
|
+
signal?.throwIfAborted();
|
|
168
|
+
}
|
|
169
|
+
if (installed.exitCode !== 0 || installed.timedOut)
|
|
170
|
+
throw new Error(`Runtime staging: ${installed.stderr || "installer failed"}`);
|
|
171
|
+
const runtime = validateStaged(JSON.parse(installed.stdout));
|
|
172
|
+
if (runtime.build.contentId !== artifact.build.contentId || runtime.installRoot !== root)
|
|
173
|
+
throw new Error("Runtime staging: unexpected published identity");
|
|
174
|
+
onProgress?.("staged");
|
|
175
|
+
return runtime;
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
signal?.removeEventListener("abort", cancel);
|
|
179
|
+
await cancellation;
|
|
180
|
+
// Only this attempt's scratch directory. Published releases and other owners are never removed.
|
|
181
|
+
if (setupAttempted)
|
|
182
|
+
await run(`if [ ! -L ${q(work)} ] && [ -f ${q(`${work}/.stage-owner`)} ] && [ "$(cat ${q(`${work}/.stage-owner`)})" = ${q(owner)} ]; then if [ -f ${q(`${work}/installer.pid`)} ] && kill -0 "$(cat ${q(`${work}/installer.pid`)})" 2>/dev/null; then : > ${q(`${work}/cancel`)}; else rm -rf ${q(work)}; fi; fi`, undefined, 30_000).catch(() => undefined);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { accessSync, constants, readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
export const INSTALL_GUIDANCE = "Install/register pi-better-server with scripts/bootstrap-host.sh, or set PI_SERVER_COMMAND to an absolute installed pi-server launcher. No packages were installed.";
|
|
5
|
+
export function absolutePath(value, name) {
|
|
6
|
+
if (typeof value !== "string" || !isAbsolute(value) || /[\0\r\n]/.test(value)) {
|
|
7
|
+
throw new Error(`${name} must be a literal absolute path`);
|
|
8
|
+
}
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
export function parseRuntime(text) {
|
|
12
|
+
const data = JSON.parse(text);
|
|
13
|
+
if (!data || data.version !== 1 || data.agent !== "pi")
|
|
14
|
+
throw new Error("Unsupported installed Pi runtime registration (expected version 1, agent pi)");
|
|
15
|
+
return {
|
|
16
|
+
version: 1, agent: "pi",
|
|
17
|
+
launcher: absolutePath(data.launcher, "runtime.launcher"),
|
|
18
|
+
agentDir: absolutePath(data.agentDir, "runtime.agentDir"),
|
|
19
|
+
defaultServerDir: absolutePath(data.defaultServerDir, "runtime.defaultServerDir"),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export function registeredRuntime(env = process.env) {
|
|
23
|
+
const path = join(env.HOME || homedir(), ".pi", "remote-server.json");
|
|
24
|
+
let text;
|
|
25
|
+
try {
|
|
26
|
+
text = readFileSync(path, "utf8");
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (error.code === "ENOENT")
|
|
30
|
+
return undefined;
|
|
31
|
+
throw new Error(`Runtime discovery: cannot read ${path}: ${String(error)}`);
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
return parseRuntime(text);
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
throw new Error(`Runtime discovery: invalid ${path}: ${String(error)}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Used by a known launcher to describe itself, including pre-registration bootstrap installs. */
|
|
41
|
+
export function launcherRuntime(env = process.env) {
|
|
42
|
+
const home = env.HOME || homedir();
|
|
43
|
+
const agentDir = resolve(env.PI_CODING_AGENT_DIR || join(home, ".pi", "agent"));
|
|
44
|
+
return parseRuntime(JSON.stringify({
|
|
45
|
+
version: 1, agent: "pi",
|
|
46
|
+
launcher: env.PI_SERVER_COMMAND || env.PI_SERVER_LAUNCHER || join(home, ".pi-better-server", "bin", "pi-server"),
|
|
47
|
+
agentDir,
|
|
48
|
+
defaultServerDir: resolve(env.PI_SERVER_DIR || join(agentDir, "server")),
|
|
49
|
+
}));
|
|
50
|
+
}
|
|
51
|
+
export function discoverLocalRuntime() {
|
|
52
|
+
const explicit = process.env.PI_SERVER_COMMAND || process.env.PI_SERVER_LAUNCHER;
|
|
53
|
+
const registered = explicit ? undefined : registeredRuntime();
|
|
54
|
+
const runtime = explicit ? launcherRuntime() : registered ?? launcherRuntime();
|
|
55
|
+
try {
|
|
56
|
+
accessSync(runtime.launcher, constants.X_OK);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
// Local development/manual daemons never required an installed launcher. Keep that transport path.
|
|
60
|
+
if (!explicit && !registered && error.code === "ENOENT")
|
|
61
|
+
return undefined;
|
|
62
|
+
throw new Error(`Runtime discovery: launcher not executable: ${runtime.launcher}. ${INSTALL_GUIDANCE}`);
|
|
63
|
+
}
|
|
64
|
+
// Registration owns these paths; the client's agent/server environment must not rewrite its identity.
|
|
65
|
+
return registered ? { ...runtime, discoveryEnv: {
|
|
66
|
+
PI_CODING_AGENT_DIR: registered.agentDir,
|
|
67
|
+
PI_SERVER_DIR: registered.defaultServerDir,
|
|
68
|
+
} } : runtime;
|
|
69
|
+
}
|
|
70
|
+
/** Read-only managed probe. Legacy discovery deliberately keeps its existing failure contract. */
|
|
71
|
+
export async function probeRemoteRuntime(run, options = {}) {
|
|
72
|
+
options.signal?.throwIfAborted();
|
|
73
|
+
const command = options.command ? absolutePath(options.command, "PI_SERVER_COMMAND") : undefined;
|
|
74
|
+
const result = await run(`${command ? `PI_SERVER_COMMAND=${shellQuote(command)}; export PI_SERVER_COMMAND\n` : ""}if [ -n "\${PI_SERVER_COMMAND:-}" ]; then
|
|
75
|
+
case "$PI_SERVER_COMMAND" in /*) ;; *) printf '%s\\n' 'Runtime probe: PI_SERVER_COMMAND must be an absolute launcher path' >&2; exit 1 ;; esac
|
|
76
|
+
fi
|
|
77
|
+
printf '%s\\n' "$HOME" "$(uname -s)" "$(uname -m)" "\${PI_SERVER_COMMAND:-}"
|
|
78
|
+
if ${options.registration === false ? "false" : '[ -n "${PI_SERVER_COMMAND:-}" ]'}; then
|
|
79
|
+
printf 'registered\\n'
|
|
80
|
+
exec "$PI_SERVER_COMMAND" runtime --agent pi
|
|
81
|
+
elif ${options.registration === false ? "false" : '[ -e "$HOME/.pi/remote-server.json" ] || [ -L "$HOME/.pi/remote-server.json" ]'}; then
|
|
82
|
+
printf 'registered\\n'
|
|
83
|
+
cat "$HOME/.pi/remote-server.json"
|
|
84
|
+
elif ${options.registration === false ? "false" : '[ -x "$HOME/.pi-better-server/bin/pi-server" ]'}; then
|
|
85
|
+
printf 'registered\\n'
|
|
86
|
+
exec "$HOME/.pi-better-server/bin/pi-server" runtime --agent pi
|
|
87
|
+
else
|
|
88
|
+
printf 'absent\\n'
|
|
89
|
+
fi`, undefined, options.timeoutMs ?? 15_000);
|
|
90
|
+
options.signal?.throwIfAborted();
|
|
91
|
+
if (result.exitCode !== 0 || result.timedOut)
|
|
92
|
+
throw new Error(`Runtime probe: ${result.stderr || "remote command failed"}`);
|
|
93
|
+
const [home, os, arch, explicitCommand, state, ...registration] = result.stdout.split("\n");
|
|
94
|
+
absolutePath(home, "remote HOME");
|
|
95
|
+
const platform = `${os === "Linux" ? "linux" : os === "Darwin" ? "darwin" : "unsupported"}-${arch === "x86_64" ? "x64" : arch === "aarch64" || arch === "arm64" ? "arm64" : "unsupported"}`;
|
|
96
|
+
if (!["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64"].includes(platform))
|
|
97
|
+
throw new Error(`Runtime probe: unsupported platform ${os}/${arch}`);
|
|
98
|
+
const text = registration.join("\n").trim();
|
|
99
|
+
if (!text && state === "registered")
|
|
100
|
+
throw new Error("Runtime probe: registration or explicit launcher returned no registration");
|
|
101
|
+
return { home: home, platform: platform, ...(explicitCommand ? { explicitCommand: absolutePath(explicitCommand, "PI_SERVER_COMMAND") } : {}), ...(text ? { runtime: parseRuntime(text) } : {}) };
|
|
102
|
+
}
|
|
103
|
+
export function shellQuote(value) {
|
|
104
|
+
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
105
|
+
}
|
|
106
|
+
/** Discovery needs only the remote shell: JSON is parsed and validated by the caller, not by shell tools. */
|
|
107
|
+
export function remoteRuntimeScript(command) {
|
|
108
|
+
const override = command ? `PI_SERVER_COMMAND=${shellQuote(absolutePath(command, "PI_SERVER_COMMAND"))}; export PI_SERVER_COMMAND\n` : "";
|
|
109
|
+
return `${override}if [ -n "\${PI_SERVER_COMMAND:-}" ]; then
|
|
110
|
+
case "$PI_SERVER_COMMAND" in /*) ;; *) printf '%s\\n' 'Runtime discovery: PI_SERVER_COMMAND must be an absolute launcher path' >&2; exit 1 ;; esac
|
|
111
|
+
exec "$PI_SERVER_COMMAND" runtime --agent pi
|
|
112
|
+
elif [ -f "$HOME/.pi/remote-server.json" ]; then
|
|
113
|
+
cat "$HOME/.pi/remote-server.json"
|
|
114
|
+
elif [ -x "$HOME/.pi-better-server/bin/pi-server" ]; then
|
|
115
|
+
exec "$HOME/.pi-better-server/bin/pi-server" runtime --agent pi
|
|
116
|
+
else
|
|
117
|
+
printf '%s\\n' ${shellQuote(`Runtime discovery: ${INSTALL_GUIDANCE}`)} >&2
|
|
118
|
+
exit 1
|
|
119
|
+
fi`;
|
|
120
|
+
}
|
package/src/goal-provider.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { listMetas,
|
|
2
|
+
import { listMetas, onMetaChanged } from "./registry.js";
|
|
3
3
|
import { getObservedWaitHost, type DurableTaskProjection } from "./observed-waits.js";
|
|
4
4
|
import type { BackgroundTaskMeta } from "./types.js";
|
|
5
5
|
import { isTerminalStatus } from "./types.js";
|
|
6
6
|
import { backgroundTaskProgressAt, observeBackgroundTaskStall } from "./stall.js";
|
|
7
|
+
import { backgroundObservation, onBackgroundObservation } from "./work-observation.js";
|
|
7
8
|
|
|
8
9
|
const GOAL_READY_EVENT = "pi-better-goal:ready";
|
|
9
10
|
const GOAL_REGISTER_PROVIDER_EVENT = "pi-better-goal:register-provider";
|
|
@@ -53,19 +54,22 @@ export function registerBackgroundTasksGoalProvider(pi: ExtensionAPI): void {
|
|
|
53
54
|
pi.events?.emit(GOAL_REGISTER_PROVIDER_EVENT, {
|
|
54
55
|
id: "background-tasks",
|
|
55
56
|
label: "Background Tasks",
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
57
|
+
scope: "session",
|
|
58
|
+
getActivity: async (ctx: ExtensionContext) => {
|
|
59
|
+
const snapshot = await backgroundObservation(pi, ctx);
|
|
60
|
+
if (snapshot.status !== "ready") throw new Error(snapshot.reason ?? "Background activity is unverified");
|
|
61
|
+
const durable = snapshot.rows.filter((row: any) => row.meta.durable).map((row: any) => row.meta);
|
|
62
|
+
const legacy = snapshot.rows.filter((row: any) => !row.meta.durable).map((row: any) => row.meta);
|
|
63
|
+
return collectBackgroundTaskGoalActivity(legacy, ctx, Date.now(), durable);
|
|
62
64
|
},
|
|
63
65
|
// A durable operation change must refresh Goal activity even though it
|
|
64
66
|
// never writes a mutable legacy registry meta.
|
|
65
67
|
onActivityChanged: (notify: () => void) => {
|
|
68
|
+
const offRuntime = onBackgroundObservation(pi, notify);
|
|
66
69
|
const offMeta = onMetaChanged(notify);
|
|
67
70
|
const offDurable = getObservedWaitHost(pi)?.onDurableTaskChange(notify);
|
|
68
71
|
return () => {
|
|
72
|
+
offRuntime();
|
|
69
73
|
offMeta();
|
|
70
74
|
offDurable?.();
|
|
71
75
|
};
|
package/src/index.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { getCallbackBatcher } from "./shared-callback-batcher.js";
|
|
|
8
8
|
import { observeForegroundSandboxPolicy } from "./sandbox.js";
|
|
9
9
|
import { registerTools } from "./tools.js";
|
|
10
10
|
import { deliverBackgroundTasksPrompt } from "./prompt.js";
|
|
11
|
+
import { closeBackgroundObservation } from "./work-observation.js";
|
|
11
12
|
|
|
12
13
|
export default function backgroundTasksExtension(pi: ExtensionAPI): void {
|
|
13
14
|
// Each cached factory invocation owns its runtime, failure timers, navigator
|
|
@@ -55,10 +56,12 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
|
|
|
55
56
|
navigator.ensureBackgroundTasksNavigator(ctx);
|
|
56
57
|
});
|
|
57
58
|
pi.on("session_before_switch", async () => {
|
|
59
|
+
closeBackgroundObservation(pi);
|
|
58
60
|
observedWaits.close();
|
|
59
61
|
navigator.clearBackgroundTasksNavigatorSession();
|
|
60
62
|
});
|
|
61
63
|
pi.on("session_shutdown", async (_event, ctx) => {
|
|
64
|
+
closeBackgroundObservation(pi);
|
|
62
65
|
// /reload, session replacement, and quit load a fresh instance; stop this one's timers (#324).
|
|
63
66
|
observedWaits.close();
|
|
64
67
|
runtime.suspendScheduledWork();
|