pi-better-harness 0.63.4 → 0.63.6

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 (39) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +1 -0
  3. package/node_modules/pi-better-background-tasks/README.md +1 -0
  4. package/node_modules/pi-better-background-tasks/package.json +2 -2
  5. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
  6. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
  7. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
  8. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
  9. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/win32-x64.json +1 -0
  10. package/node_modules/pi-better-background-tasks/runtime-client/scripts/private-runtime/format.mjs +37 -14
  11. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/client.mjs +12 -3
  12. package/node_modules/pi-better-background-tasks/runtime-client/src/startup/artifact.mjs +2 -2
  13. package/node_modules/pi-better-background-tasks/runtime-client/src/startup/install.mjs +5 -6
  14. package/node_modules/pi-better-background-tasks/src/managed-authority.ts +7 -2
  15. package/node_modules/pi-better-background-tasks/src/shared-sandbox-core.ts +25 -1
  16. package/node_modules/pi-better-background-tasks/src/tools.ts +2 -2
  17. package/node_modules/pi-better-sandbox/README.md +4 -1
  18. package/node_modules/pi-better-sandbox/package.json +1 -1
  19. package/node_modules/pi-better-sandbox/shared-sandbox-core.ts +25 -1
  20. package/node_modules/pi-better-sandbox/shared-task-application.ts +21 -100
  21. package/node_modules/pi-better-sandbox/shared-task-exec.ts +46 -3
  22. package/node_modules/pi-better-subagents/README.md +1 -0
  23. package/node_modules/pi-better-subagents/child-runtime.mjs +5 -3
  24. package/node_modules/pi-better-subagents/index.ts +2 -15
  25. package/node_modules/pi-better-subagents/package.json +2 -2
  26. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
  27. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
  28. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
  29. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
  30. package/node_modules/pi-better-subagents/runtime-client/artifacts/win32-x64.json +1 -0
  31. package/node_modules/pi-better-subagents/runtime-client/scripts/private-runtime/format.mjs +37 -14
  32. package/node_modules/pi-better-subagents/runtime-client/src/runtime/client.mjs +12 -3
  33. package/node_modules/pi-better-subagents/runtime-client/src/startup/artifact.mjs +2 -2
  34. package/node_modules/pi-better-subagents/runtime-client/src/startup/install.mjs +5 -6
  35. package/node_modules/pi-better-subagents/shared-sandbox-core.ts +25 -1
  36. package/node_modules/pi-better-subagents/shared-task-application.ts +21 -100
  37. package/node_modules/pi-better-subagents/shared-task-exec.ts +46 -3
  38. package/node_modules/pi-better-subagents/spawn.ts +31 -3
  39. package/package.json +5 -5
@@ -3,7 +3,7 @@
3
3
  */
4
4
  import { spawn } from 'node:child_process';
5
5
  import { accessSync, constants, statSync } from 'node:fs';
6
- import { delimiter, resolve } from 'node:path';
6
+ import { delimiter, extname, resolve } from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import './child-preflight.mjs';
9
9
 
@@ -27,8 +27,10 @@ try {
27
27
  }
28
28
  // Older Node/platforms retain supervision and signal forwarding. Stay in the
29
29
  // bootstrap's process group so group termination reaches all descendants.
30
- const child = spawn(binary, launcherArgs, {
31
- stdio: 'inherit', env: process.env, detached: false,
30
+ // Windows cannot execute npm's shell shims or a JS bin directly.
31
+ const nodeCli = process.platform === 'win32' && /^\.[cm]?js$/i.test(extname(binary));
32
+ const child = spawn(nodeCli ? process.execPath : binary, nodeCli ? [binary, ...launcherArgs] : launcherArgs, {
33
+ stdio: 'inherit', env: process.env, detached: false, windowsHide: true,
32
34
  });
33
35
  const forwards = new Map(['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT'].map(signal => {
34
36
  const forward = () => child.kill(signal);
@@ -21,7 +21,6 @@ import { registerAssignmentAttempt, commitAssignmentTerminal, readOutcome, recei
21
21
  import { currentSandboxPermissions } from "./permission-policy.ts";
22
22
  import { assertWaitToolDependencies, createToolDescriptor } from "./operation-bridge-types.ts";
23
23
  import { requestResumeAdmission } from "./worker-waits.ts";
24
- import { execSync } from "node:child_process";
25
24
  import { Worker } from "node:worker_threads";
26
25
  import { writeFileSync, mkdirSync, renameSync, statSync } from "node:fs";
27
26
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
@@ -46,7 +45,7 @@ import {
46
45
  type BackgroundWorkProvider,
47
46
  type BackgroundWorkRow,
48
47
  } from "./shared-navigator.ts";
49
- import { spawnDetached, killProcessTree, type SpawnResult } from "./spawn.ts";
48
+ import { childRuntimeCommand, spawnDetached, killProcessTree, type SpawnResult } from "./spawn.ts";
50
49
  import { parseRun, parseRunForLifecycle, readRunTranscript, resetParseRunCursor, type Usage } from "./parse.ts";
51
50
  import { finalizeRun as finalizeRunCore, reconcileInterruptedRun } from "./finalization.ts";
52
51
  import { completeOwnedExit } from "./owned-exit.ts";
@@ -2064,18 +2063,6 @@ function ensureNavigator(ctx: ExtensionContext, owner?: symbol): void {
2064
2063
  } catch { /* ignore */ }
2065
2064
  }
2066
2065
 
2067
- /** Resolve the pi binary once per session. */
2068
- let cachedPi: string | undefined;
2069
- function resolvePiBinary(): string {
2070
- if (cachedPi !== undefined) return cachedPi;
2071
- try {
2072
- cachedPi = execSync("which pi", { encoding: "utf-8", timeout: 3000 }).trim();
2073
- } catch {
2074
- cachedPi = "pi";
2075
- }
2076
- return cachedPi;
2077
- }
2078
-
2079
2066
  function forgetRunCaches(id: string): void {
2080
2067
  spendCache.delete(id);
2081
2068
  healthLogCache.delete(id);
@@ -3474,7 +3461,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3474
3461
  }
3475
3462
  const currentCommand = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] }
3476
3463
  : managed ? managed.workerCommand(args)
3477
- : { file: process.execPath, fileArgs: [join(selfDir(), "child-runtime.mjs"), resolvePiBinary(), ...args] };
3464
+ : childRuntimeCommand(selfDir(), args, PiCodingAgent.getPackageDir);
3478
3465
  const cmd = continuationRuntime?.command(currentCommand) ?? currentCommand;
3479
3466
  const sandboxDir = taskRuntime ? requestedSandboxDir : undefined;
3480
3467
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.41.6",
3
+ "version": "0.41.8",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -81,7 +81,7 @@
81
81
  "@earendil-works/pi-tui": "*"
82
82
  },
83
83
  "dependencies": {
84
- "pi-better-server": "0.11.4",
84
+ "pi-better-server": "0.11.6",
85
85
  "proper-lockfile": "^4.1.2",
86
86
  "shell-quote": "1.12.0",
87
87
  "smol-toml": "1.9.0",
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"794c8a72e4397b041470ca9bd145090cda4cf8898b1c53aa5a02e0fb0eec78f0","piSdkVersion":"1.7.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"97fbfa01a6e5a49f4f29f5c2048549391417c545cbdd52ec799629aa867d8653","protocolVersion":1,"serverVersion":"0.11.4","contentId":"5b2ee10ce118f403061145c783b1619cd92c93000d60139fdf6a581b0de3e2d7"},"sha256":"f84ae252249310706729b06cf469d63a94976f7581401e4738a3e3805061ffc4"}
1
+ {"build":{"format":1,"sourceDigest":"e10ded28de27fb754b6a5104be710c438b08f92a9c8942ec6afcdf507421b69a","piSdkVersion":"1.7.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"97fbfa01a6e5a49f4f29f5c2048549391417c545cbdd52ec799629aa867d8653","protocolVersion":1,"serverVersion":"0.11.6","contentId":"5111beb2d95488d65046edcc37bc401332145e143a3ae62b37968099dfd25649"},"sha256":"dbb395f87e77127898863761e6acdec94d81f5e8b19ddea3bed9c8979600fde5"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"794c8a72e4397b041470ca9bd145090cda4cf8898b1c53aa5a02e0fb0eec78f0","piSdkVersion":"1.7.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"97fbfa01a6e5a49f4f29f5c2048549391417c545cbdd52ec799629aa867d8653","protocolVersion":1,"serverVersion":"0.11.4","contentId":"98b0fa0a42a6628c17a02102613f5dcdbdfdc0953875e8a46021c354f7e37a56"},"sha256":"eb9002919e13ce85f6ef838d80e2592a8debe41cd69b9a888387c2f3a9a5bd71"}
1
+ {"build":{"format":1,"sourceDigest":"e10ded28de27fb754b6a5104be710c438b08f92a9c8942ec6afcdf507421b69a","piSdkVersion":"1.7.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"97fbfa01a6e5a49f4f29f5c2048549391417c545cbdd52ec799629aa867d8653","protocolVersion":1,"serverVersion":"0.11.6","contentId":"a95c6df6bf8a4a8e9eab0909454171c9cd2c8e10cd9d98390a903d91bb3c6c64"},"sha256":"9be54c3ac83baecff25aa588b4c66cfb932e797b985a0bc38499ac9b9cbc67d5"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"794c8a72e4397b041470ca9bd145090cda4cf8898b1c53aa5a02e0fb0eec78f0","piSdkVersion":"1.7.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"97fbfa01a6e5a49f4f29f5c2048549391417c545cbdd52ec799629aa867d8653","protocolVersion":1,"serverVersion":"0.11.4","contentId":"c2039989db9695913739b6cacab0409818a9d9825d12a59cc3c2b8c4e37d5292"},"sha256":"9b79eb6ac53c74107f3f2593f44392c51735ee87de7f522f177a4edfc3d6762f"}
1
+ {"build":{"format":1,"sourceDigest":"e10ded28de27fb754b6a5104be710c438b08f92a9c8942ec6afcdf507421b69a","piSdkVersion":"1.7.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"97fbfa01a6e5a49f4f29f5c2048549391417c545cbdd52ec799629aa867d8653","protocolVersion":1,"serverVersion":"0.11.6","contentId":"f4ffd4c8efab0d1f9ee2cebedcb6c45da08e30bd4ab159c35a5cc76ca8917279"},"sha256":"250cb01fb789935e7ba216025debe94b72ec2a75603e0653cef9ddf16970bcc3"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"794c8a72e4397b041470ca9bd145090cda4cf8898b1c53aa5a02e0fb0eec78f0","piSdkVersion":"1.7.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"97fbfa01a6e5a49f4f29f5c2048549391417c545cbdd52ec799629aa867d8653","protocolVersion":1,"serverVersion":"0.11.4","contentId":"25862c01939a8c789aecafd570333b7d643d143a4be6cc74d29266ddf3120a9a"},"sha256":"c9f5e9fc4a3fc80ef093fe2d1d26d84aedc6a9869eae801458115cfcde98ead6"}
1
+ {"build":{"format":1,"sourceDigest":"e10ded28de27fb754b6a5104be710c438b08f92a9c8942ec6afcdf507421b69a","piSdkVersion":"1.7.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"97fbfa01a6e5a49f4f29f5c2048549391417c545cbdd52ec799629aa867d8653","protocolVersion":1,"serverVersion":"0.11.6","contentId":"e1b18f3f204d604676d57b2a3b7dc5358371f4bca82efe1ce92f429cae2c0515"},"sha256":"0345fe65c89c7d5b4ec3024e2991c9437c81c6c1083723945aa73eb1fd463929"}
@@ -0,0 +1 @@
1
+ {"build":{"format":1,"sourceDigest":"e10ded28de27fb754b6a5104be710c438b08f92a9c8942ec6afcdf507421b69a","piSdkVersion":"1.7.0","nodeVersion":"24.14.1","platform":"win32-x64","dependencyLockDigest":"97fbfa01a6e5a49f4f29f5c2048549391417c545cbdd52ec799629aa867d8653","protocolVersion":1,"serverVersion":"0.11.6","contentId":"d5d2962c8f2138a8c46f1b75486368e1f21184bb60af9507a288f6946cd44994"},"sha256":"0c152f013f1828decd9df87db6a15f4a6e78466fd58d7541717b3123160790c1"}
@@ -1,19 +1,42 @@
1
1
  import { createHash } from "node:crypto";
2
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",
3
+ export const PINNED_NODE_VERSION = "24.14.1";
4
+ // Artifact targets include distributions whose managed installer is still in development.
5
+ // Archive hashes come from nodejs.org/dist/v24.14.1/SHASUMS256.txt. Executable hashes
6
+ // identify the node binary extracted from each verified archive.
7
+ export const NODE_DISTRIBUTIONS = {
8
+ "darwin-arm64": {
9
+ archiveSha256: "25495ff85bd89e2d8a24d88566d7e2f827c6b0d3d872b2cebf75371f93fcb1fe",
10
+ executableSha256: "35d4bc736bbe4161f0c074aa140ddb74586e46969bc2ad63d32c838bec4463ff",
11
+ },
12
+ "darwin-x64": {
13
+ archiveSha256: "2526230ad7d922be82d4fdb1e7ee1e84303e133e3b4b0ec4c2897ab31de0253d",
14
+ executableSha256: "9ab4f6249a8de4671c3205ef58621dfb19d120a9c59fd96ed206571bafb0319c",
15
+ },
16
+ "linux-arm64": {
17
+ archiveSha256: "734ff04fa7f8ed2e8a78d40cacf5ac3fc4515dac2858757cbab313eb483ba8a2",
18
+ executableSha256: "7fac13c04c19207c3e904a7721f8c045e6b99493471e2df85444f764cdd21934",
19
+ },
20
+ "linux-x64": {
21
+ archiveSha256: "ace9fa104992ed0829642629c46ca7bd7fd6e76278cb96c958c4b387d29658ea",
22
+ executableSha256: "bf9112eb83a827dc9f9c8d19bb7bddcbf00f7b2fedae18fdcaee05406981f20a",
23
+ },
24
+ "win32-x64": {
25
+ archiveSha256: "6e50ce5498c0cebc20fd39ab3ff5df836ed2f8a31aa093cecad8497cff126d70",
26
+ executableSha256: "58e74bf02fc5bbacc41dcb8bef089961cd5bddd37830b87784e4fc624d145d1f",
27
+ },
16
28
  };
29
+ export function nodeDistribution(platform) {
30
+ const windows = platform === "win32-x64";
31
+ const directory = `node-v${PINNED_NODE_VERSION}-${windows ? "win-x64" : platform}`;
32
+ const filename = directory + (windows ? ".zip" : ".tar.gz");
33
+ return {
34
+ ...NODE_DISTRIBUTIONS[platform],
35
+ directory,
36
+ url: `https://nodejs.org/dist/v${PINNED_NODE_VERSION}/${filename}`,
37
+ executable: `${directory}/${windows ? "node.exe" : "bin/node"}`,
38
+ };
39
+ }
17
40
  export function digest(value) { return createHash("sha256").update(value).digest("hex"); }
18
41
  export function stable(value) {
19
42
  if (Array.isArray(value))
@@ -23,7 +46,7 @@ export function stable(value) {
23
46
  return JSON.stringify(value);
24
47
  }
25
48
  export function validateBuild(value) {
26
- if (!value || value.format !== 1 || !Object.hasOwn(NODE_CHECKSUMS, value.platform) || value.nodeVersion !== "24.14.1"
49
+ if (!value || value.format !== 1 || !Object.hasOwn(NODE_DISTRIBUTIONS, value.platform) || value.nodeVersion !== PINNED_NODE_VERSION
27
50
  || !/^\d+\.\d+\.\d+$/.test(value.piSdkVersion) || !/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(value.serverVersion)
28
51
  || !Number.isSafeInteger(value.protocolVersion) || value.protocolVersion < 1
29
52
  || ![value.contentId, value.sourceDigest, value.dependencyLockDigest].every((v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v)))
@@ -7,9 +7,12 @@ import { setTimeout as delay } from "node:timers/promises";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { stageRuntime } from "../startup/install.mjs";
9
9
  import { inspectDaemonOwner } from "../daemon-owner.mjs";
10
+ import { decodeServerArtifact } from "../startup/artifact.mjs";
10
11
  import { runtimeRoot } from "./root.mjs";
11
12
  import { socketPathFor } from "./socket.mjs";
12
13
  export { WorkClient } from "./work-client.mjs";
14
+ // End-to-end release support. Building an artifact for a new target does not enable it here.
15
+ const releasedManagedPlatforms = ["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"];
13
16
  /** One bounded LF-JSON exchange; importing this module never loads the Pi SDK. */
14
17
  export async function runtimeStatus(socketPath, agentDir, artifact, timeoutMs = 2000) {
15
18
  return new Promise((resolve, reject) => {
@@ -72,18 +75,24 @@ export async function ensureRuntime(options) {
72
75
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120000)
73
76
  throw new Error("Runtime timeout must be from 1 to 120000 ms");
74
77
  const platform = `${process.platform}-${process.arch}`;
78
+ if (!releasedManagedPlatforms.includes(platform)) {
79
+ const tracking = process.platform === "win32" ? " Track native Windows support at https://github.com/1aboveio/pi-better-harness/issues/917" : "";
80
+ throw new Error(`runtime-unavailable: this release does not support managed Subagents and Background Tasks on ${platform}. `
81
+ + `Use a supported host (${releasedManagedPlatforms.join(", ")}).${tracking}`);
82
+ }
75
83
  const directory = fileURLToPath(new URL("../../artifacts/", import.meta.url));
76
84
  let artifact;
77
85
  try {
78
86
  const manifest = JSON.parse(readFileSync(join(directory, `${platform}.json`), "utf8"));
79
87
  const archive = createRequire(import.meta.url).resolve(`pi-better-server/runtime-artifacts/${platform}.gz`);
80
88
  artifact = { ...manifest, bytes: readFileSync(archive) };
89
+ decodeServerArtifact(artifact);
90
+ if (artifact.build.platform !== platform)
91
+ throw new Error(`Artifact targets ${artifact.build.platform}, expected ${platform}`);
81
92
  }
82
93
  catch (error) {
83
- throw new Error(`runtime-unavailable: cannot read pinned artifact for ${platform}; reinstall the standalone package. ${String(error)}`);
94
+ throw new Error(`runtime-unavailable: invalid managed runtime installation for ${platform}. Reinstall the task package and its pinned pi-better-server dependency together. ${String(error)}`, { cause: error });
84
95
  }
85
- const { decodeServerArtifact } = await import("../startup/artifact.mjs");
86
- decodeServerArtifact(artifact);
87
96
  const root = runtimeRoot(options.agentDir, options.serverDir ?? join(options.agentDir, "server"));
88
97
  const socketPath = socketPathFor(root.serverDir);
89
98
  const query = () => runtimeStatus(socketPath, root.agentDir, artifact, Math.min(timeoutMs, 2000));
@@ -2,7 +2,7 @@ import { readFileSync, readdirSync, lstatSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { gzipSync, gunzipSync } from "node:zlib";
5
- import { digest, stable, validateBuild, validatePayload, validateStaged } from "../../scripts/private-runtime/format.mjs";
5
+ import { PINNED_NODE_VERSION, digest, stable, validateBuild, validatePayload, validateStaged } from "../../scripts/private-runtime/format.mjs";
6
6
  export const ownPackageDir = fileURLToPath(new URL("../../", import.meta.url));
7
7
  /** Only shipped source and explicitly named runtime resources enter the build. */
8
8
  export function createServerArtifact(options) {
@@ -42,7 +42,7 @@ export function createServerArtifact(options) {
42
42
  files.sort((a, b) => a.path.localeCompare(b.path, "en"));
43
43
  const identity = {
44
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,
45
+ nodeVersion: PINNED_NODE_VERSION, platform: options.platform, dependencyLockDigest: digest(stable(lock)), protocolVersion: 1, serverVersion: metadata.version,
46
46
  };
47
47
  const build = { ...identity, contentId: digest(stable(identity)) };
48
48
  const payload = { format: 1, build, files };
@@ -2,7 +2,7 @@ import { randomUUID, createHash } from "node:crypto";
2
2
  import { posix } from "node:path";
3
3
  import { decodeServerArtifact } from "./artifact.mjs";
4
4
  import { absolutePath, probeRemoteRuntime, shellQuote } from "./runtime.mjs";
5
- import { NODE_CHECKSUMS, NODE_EXECUTABLE_CHECKSUMS, validateStaged } from "../../scripts/private-runtime/format.mjs";
5
+ import { nodeDistribution, validateStaged } from "../../scripts/private-runtime/format.mjs";
6
6
  async function download(url, integrity, signal) {
7
7
  const response = await fetch(url, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(120_000)]) : AbortSignal.timeout(120_000), redirect: "error" });
8
8
  if (!response.ok || !response.body)
@@ -32,6 +32,7 @@ export async function stageRuntime(options) {
32
32
  throw new Error("Runtime staging: explicit PI_SERVER_COMMAND opts out of managed installation");
33
33
  if (probe.platform !== artifact.build.platform)
34
34
  throw new Error("Runtime staging: artifact platform does not match target");
35
+ const distribution = nodeDistribution(probe.platform);
35
36
  const root = posix.normalize(absolutePath(options.installRoot ?? `${probe.home}/.pi-better-server/managed`, "installRoot"));
36
37
  if (root === "/" || root.split("/").includes("node_modules"))
37
38
  throw new Error("Runtime staging: releases must be outside node_modules");
@@ -115,7 +116,7 @@ done
115
116
  mkdir -p ${q(`${work}/node/bin`)}
116
117
  cp ${q(cachedNode)} ${q(node)}
117
118
  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
+ [ "$actual" = ${q(distribution.executableSha256)} ] || { echo 'Node executable integrity mismatch' >&2; exit 1; }
119
120
  printf 'reuse\\n'`, undefined, 120_000);
120
121
  const cachedState = cached.stdout.trim();
121
122
  if (cachedState !== "reuse" && cachedState !== "absent")
@@ -128,9 +129,7 @@ printf 'reuse\\n'`, undefined, 120_000);
128
129
  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
130
  onProgress?.("node-download");
130
131
  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];
132
+ const { url, archiveSha256: sha } = distribution;
134
133
  const tar = `${work}/node.tar.gz`;
135
134
  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
135
  signal?.throwIfAborted();
@@ -138,7 +137,7 @@ printf 'reuse\\n'`, undefined, 120_000);
138
137
  onProgress?.("node-upload");
139
138
  await checked(`cat > ${q(tar)}`, await download(url, `sha256-${sha}`, signal), 120_000);
140
139
  }
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);
140
+ 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}/${distribution.directory}`)} ${q(`${work}/node`)}; rm ${q(tar)}`, undefined, 120_000);
142
141
  }
143
142
  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
143
  if (!reuse)
@@ -187,11 +187,35 @@ try {
187
187
  }
188
188
  `;
189
189
 
190
+ /** The helper runs fixed JavaScript inside confinement. Only the host selects its runtime. */
191
+ function applicationRunnerExecutable(): string {
192
+ const host = canonicalizePath(process.execPath);
193
+ if (!process.versions.bun) return host;
194
+
195
+ // A compiled Bun host interprets --eval as Pi input. Use a Node installation
196
+ // selected by the operator or a system prefix, independently of the task's PATH.
197
+ const configured = process.env.PI_BETTER_SANDBOX_NODE;
198
+ const candidates = configured ? [configured] : ["/opt/homebrew/bin/node", "/usr/local/bin/node", "/usr/bin/node", "/bin/node"];
199
+ const hostFile = statSync(host, { bigint: true, throwIfNoEntry: false });
200
+ for (const candidate of candidates) {
201
+ if (!isAbsolute(candidate)) continue;
202
+ try {
203
+ const path = realpathSync.native(candidate);
204
+ const file = statSync(path, { bigint: true });
205
+ if (!file.isFile() || (hostFile && file.dev === hostFile.dev && file.ino === hostFile.ino)) continue;
206
+ accessSync(path, constants.X_OK);
207
+ return path;
208
+ } catch { /* This installation may be absent or inaccessible. */ }
209
+ }
210
+ throw new Error("Direct application execution under standalone Pi requires Node.js with process.execve (22.15+ or 24+). " +
211
+ "Set PI_BETTER_SANDBOX_NODE to the absolute path of your Node.js executable.");
212
+ }
213
+
190
214
  /** Fixed post-boundary launcher for literal argv, without env assignment or shell fallback. */
191
215
  export function directApplicationTarget(
192
216
  executable: string, args: readonly string[], env: NodeJS.ProcessEnv, shell: boolean,
193
217
  ): SandboxTarget {
194
- return { execPath: canonicalizePath(process.execPath), execArgs: ["--eval", APPLICATION_RUNNER,
218
+ return { execPath: applicationRunnerExecutable(), execArgs: ["--eval", APPLICATION_RUNNER,
195
219
  JSON.stringify({ executable, args, env, shell, shellNames: SHELL_EXECUTABLE_NAMES })] };
196
220
  }
197
221
 
@@ -10,10 +10,8 @@
10
10
  * refused by requested and resolved identity. Descendants of an application can
11
11
  * still start a shell: this is an interface restriction, not an OS exec deny.
12
12
  */
13
- import { join } from "node:path";
14
- import { pathToFileURL } from "node:url";
15
13
  import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
16
- const { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize } = PiCodingAgent;
14
+ const { createBashToolDefinition, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES } = PiCodingAgent;
17
15
  import { validateTimeout, type TaskExec } from "./shared-task-exec.ts";
18
16
 
19
17
  export const RUN_APPLICATION_TOOL = "run_application";
@@ -21,7 +19,6 @@ export const RUN_APPLICATION_TOOL = "run_application";
21
19
  const MAX_EXECUTABLE_CHARS = 4096;
22
20
  const MAX_ARGS = 1024;
23
21
  const MAX_ARG_CHARS = 131_072;
24
- const UPDATE_THROTTLE_MS = 100;
25
22
 
26
23
  const parameters = {
27
24
  type: "object",
@@ -74,7 +71,7 @@ export function validateRunApplicationParams(params: unknown): RunApplicationPar
74
71
  return { executable, args: (args as string[] | undefined) ?? [], timeout: timeout as number | undefined };
75
72
  }
76
73
 
77
- type OutputSnapshot = { content: string; truncation: any; fullOutputPath?: string };
74
+ type BashExecute = ReturnType<typeof createBashToolDefinition>["execute"];
78
75
 
79
76
  export function createRunApplicationToolDefinition(cwd: string, run: TaskExec) {
80
77
  return {
@@ -83,103 +80,27 @@ export function createRunApplicationToolDefinition(cwd: string, run: TaskExec) {
83
80
  description: `Run one executable directly with a literal argument list. No shell parses the arguments, so pipes, redirects, globs, variables and quoting are not interpreted. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first); if truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,
84
81
  promptSnippet: "Run an executable directly with literal arguments (no shell parsing).",
85
82
  parameters,
86
- async execute(_toolCallId: string, params: unknown, signal?: AbortSignal,
87
- onUpdate?: (update: { content: { type: "text"; text: string }[]; details?: unknown }) => void) {
83
+ async execute(id: string, params: unknown, signal?: AbortSignal,
84
+ onUpdate?: Parameters<BashExecute>[3], ctx?: Parameters<BashExecute>[4]) {
88
85
  const { executable, args, timeout } = validateRunApplicationParams(params);
89
- const { OutputAccumulator } = await import(pathToFileURL(
90
- join(PiCodingAgent.getPackageDir(), "dist", "core", "tools", "output-accumulator.js")).href);
91
- const output = new OutputAccumulator({ tempFilePrefix: "pi-run-application" });
92
- let acceptingOutput = true;
93
- let updateTimer: NodeJS.Timeout | undefined;
94
- let updateDirty = false;
95
- let lastUpdateAt = 0;
96
- const emitOutputUpdate = () => {
97
- if (!onUpdate || !updateDirty) return;
98
- updateDirty = false;
99
- lastUpdateAt = Date.now();
100
- const snapshot = output.snapshot({ persistIfTruncated: true });
101
- onUpdate({
102
- content: [{ type: "text", text: snapshot.content || "" }],
103
- details: {
104
- truncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,
105
- fullOutputPath: snapshot.fullOutputPath,
106
- },
107
- });
108
- };
109
- const scheduleOutputUpdate = () => {
110
- if (!onUpdate) return;
111
- updateDirty = true;
112
- const delay = UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);
113
- if (delay <= 0) {
114
- if (updateTimer) { clearTimeout(updateTimer); updateTimer = undefined; }
115
- emitOutputUpdate();
116
- return;
117
- }
118
- updateTimer ??= setTimeout(() => { updateTimer = undefined; emitOutputUpdate(); }, delay);
119
- };
120
- onUpdate?.({ content: [], details: undefined });
121
- const handleData = (data: Buffer) => {
122
- if (!acceptingOutput) return;
123
- output.append(data);
124
- scheduleOutputUpdate();
125
- };
126
- let finishing: Promise<OutputSnapshot> | undefined;
127
- const finishOutput = () => finishing ??= (async () => {
128
- acceptingOutput = false;
129
- output.finish();
130
- if (updateTimer) { clearTimeout(updateTimer); updateTimer = undefined; }
131
- emitOutputUpdate();
132
- const snapshot = output.snapshot({ persistIfTruncated: true });
133
- await output.closeTempFile();
134
- return snapshot as OutputSnapshot;
135
- })();
136
- const formatOutput = (snapshot: OutputSnapshot, emptyText = "(no output)") => {
137
- const truncation = snapshot.truncation;
138
- let text = snapshot.content || emptyText;
139
- let details;
140
- if (truncation.truncated) {
141
- details = { truncation, fullOutputPath: snapshot.fullOutputPath };
142
- const startLine = truncation.totalLines - truncation.outputLines + 1;
143
- const endLine = truncation.totalLines;
144
- if (truncation.lastLinePartial) {
145
- const lastLineSize = formatSize(output.getLastLineBytes());
146
- text += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;
147
- } else if (truncation.truncatedBy === "lines") {
148
- text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;
149
- } else {
150
- text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;
151
- }
152
- }
153
- return { text, details };
154
- };
155
- const appendStatus = (text: string, status: string) => `${text ? `${text}\n\n` : ""}${status}`;
156
- try {
157
- let exitCode: number | null;
158
- try {
159
- const result = await run({ kind: "argv", execPath: executable, execArgs: args }, cwd,
160
- { onData: handleData, signal, timeout });
86
+ let exitCode: number | null = null;
87
+ // The SDK owns streaming, truncation and spill files, including in its
88
+ // standalone binary. The operation runs the captured argv directly.
89
+ const output = createBashToolDefinition(cwd, {
90
+ exposeSessionEnvironment: false,
91
+ operations: { async exec(_command, directory, options) {
92
+ const result = await run({ kind: "argv", execPath: executable, execArgs: args }, directory,
93
+ { onData: options.onData, signal: options.signal, timeout: options.timeout });
161
94
  exitCode = result.exitCode;
162
- } catch (error) {
163
- const snapshot = await finishOutput();
164
- const { text } = formatOutput(snapshot, "");
165
- if (error instanceof Error && error.message === "aborted") {
166
- throw new Error(appendStatus(text, "Command aborted"));
167
- }
168
- if (error instanceof Error && error.message.startsWith("timeout:")) {
169
- const timeoutSeconds = error.message.split(":")[1];
170
- throw new Error(appendStatus(text, `Command timed out after ${timeoutSeconds} seconds`));
171
- }
172
- throw error;
173
- }
174
- const snapshot = await finishOutput();
175
- const { text, details } = formatOutput(snapshot);
176
- if (exitCode !== 0 && exitCode !== null) {
177
- throw new Error(appendStatus(text, `Command exited with code ${exitCode}`));
178
- }
179
- return { content: [{ type: "text" as const, text }], details: { ...details, exitCode } };
180
- } finally {
181
- if (updateTimer) { clearTimeout(updateTimer); updateTimer = undefined; }
182
- }
95
+ return result;
96
+ } },
97
+ });
98
+ const command = timeout === undefined ? { command: executable } : { command: executable, timeout };
99
+ const result = await output.execute(id, command, signal, onUpdate, ctx!);
100
+ const text = result.content.find(block => block.type === "text")?.text ?? "(no output)";
101
+ // Some SDK versions return a tool error and others throw it.
102
+ if (exitCode !== null && exitCode !== 0) throw new Error(text);
103
+ return { content: [{ type: "text" as const, text }], details: { ...result.details, exitCode } };
183
104
  },
184
105
  };
185
106
  }
@@ -167,6 +167,51 @@ export function directShellInterpreter(
167
167
  return undefined;
168
168
  }
169
169
 
170
+ // The standalone SDK embeds its child-process utilities in the binary. Keep one
171
+ // exit hook for live groups and drain output until inherited pipes go quiet.
172
+ const standaloneGroups = new Set<number>();
173
+ function killStandaloneGroups(): void {
174
+ for (const pid of standaloneGroups) {
175
+ try { process.kill(-pid, "SIGKILL"); } catch { /* The group already exited. */ }
176
+ }
177
+ }
178
+ const standaloneChildren = {
179
+ trackDetachedChildPid(pid: number) {
180
+ if (!standaloneGroups.size) process.on("exit", killStandaloneGroups);
181
+ standaloneGroups.add(pid);
182
+ },
183
+ untrackDetachedChildPid(pid: number) {
184
+ standaloneGroups.delete(pid);
185
+ if (!standaloneGroups.size) process.off("exit", killStandaloneGroups);
186
+ },
187
+ waitForChildProcess(child: ReturnType<typeof spawn>): Promise<number | null> {
188
+ return new Promise((resolve, reject) => {
189
+ let idle: NodeJS.Timeout | undefined;
190
+ const refresh = () => idle?.refresh();
191
+ child.stdout?.on("data", refresh);
192
+ child.stderr?.on("data", refresh);
193
+ child.once("exit", () => {
194
+ idle = setTimeout(() => { child.stdout?.destroy(); child.stderr?.destroy(); }, 100);
195
+ });
196
+ child.once("error", reject);
197
+ child.once("close", code => {
198
+ clearTimeout(idle);
199
+ child.stdout?.off("data", refresh);
200
+ child.stderr?.off("data", refresh);
201
+ resolve(code);
202
+ });
203
+ });
204
+ },
205
+ };
206
+
207
+ async function childProcessLifecycle() {
208
+ if (process.versions.bun) return standaloneChildren;
209
+ const sdkUtils = join(PiCodingAgent.getPackageDir(), "dist", "utils");
210
+ const { waitForChildProcess } = await import(pathToFileURL(join(sdkUtils, "child-process.js")).href);
211
+ const { trackDetachedChildPid, untrackDetachedChildPid } = await import(pathToFileURL(join(sdkUtils, "shell.js")).href);
212
+ return { waitForChildProcess, trackDetachedChildPid, untrackDetachedChildPid };
213
+ }
214
+
170
215
  /** Spawn one process group, drain both pipes, and stop the group on cancel or timeout. */
171
216
  async function spawnTracked(file: string, fileArgs: readonly string[], options: {
172
217
  cwd: string;
@@ -176,9 +221,7 @@ async function spawnTracked(file: string, fileArgs: readonly string[], options:
176
221
  timeout?: number | undefined;
177
222
  reportSignal?: boolean;
178
223
  }): Promise<{ exitCode: number | null }> {
179
- const sdkUtils = join(PiCodingAgent.getPackageDir(), "dist", "utils");
180
- const { waitForChildProcess } = await import(pathToFileURL(join(sdkUtils, "child-process.js")).href);
181
- const { trackDetachedChildPid, untrackDetachedChildPid } = await import(pathToFileURL(join(sdkUtils, "shell.js")).href);
224
+ const { waitForChildProcess, trackDetachedChildPid, untrackDetachedChildPid } = await childProcessLifecycle();
182
225
  if (options.signal?.aborted) throw new Error("aborted");
183
226
  return await new Promise<{ exitCode: number | null }>((resolvePromise, reject) => {
184
227
  const child = spawn(file, [...fileArgs], { cwd: options.cwd, detached: true, shell: false,
@@ -7,9 +7,36 @@
7
7
  * from the foreground pi turn. Progress is read back later by tailing the file.
8
8
  */
9
9
 
10
- import { spawn } from "node:child_process";
11
- import { closeSync, mkdirSync, openSync, unlinkSync } from "node:fs";
12
- import { dirname } from "node:path";
10
+ import { execFileSync, spawn } from "node:child_process";
11
+ import { closeSync, mkdirSync, openSync, readFileSync, realpathSync, statSync, unlinkSync } from "node:fs";
12
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
13
+
14
+ let posixPi: string | undefined;
15
+
16
+ /** The active SDK owns its Windows npm bin. POSIX launchers keep their own interpreter. */
17
+ export function childRuntimeCommand(directory: string, args: string[], getPackageDir: () => string) {
18
+ let launcher: string;
19
+ if (process.platform === "win32") {
20
+ const root = realpathSync(getPackageDir());
21
+ const manifest = join(root, "package.json");
22
+ const { bin } = JSON.parse(readFileSync(manifest, "utf8"));
23
+ const entry = typeof bin === "string" ? bin : bin?.pi;
24
+ if (typeof entry !== "string" || !entry.trim()) throw new Error(`Missing Pi CLI bin in ${manifest}`);
25
+ launcher = realpathSync(resolve(root, entry));
26
+ const local = relative(root, launcher);
27
+ if (local === ".." || local.startsWith(`..${sep}`) || isAbsolute(local)
28
+ || !/^(?:\.[cm]?js|\.exe)$/i.test(extname(launcher)) || !statSync(launcher).isFile()) {
29
+ throw new Error(`Invalid Pi CLI bin ${entry} in ${manifest}: expected a JavaScript file or executable inside the package`);
30
+ }
31
+ } else {
32
+ if (posixPi === undefined) {
33
+ try { posixPi = execFileSync("which", ["pi"], { encoding: "utf8", timeout: 3000 }).trim(); }
34
+ catch { posixPi = "pi"; }
35
+ }
36
+ launcher = posixPi;
37
+ }
38
+ return { file: process.execPath, fileArgs: [join(directory, "child-runtime.mjs"), launcher, ...args] };
39
+ }
13
40
 
14
41
  export interface SpawnResult {
15
42
  pid: number;
@@ -35,6 +62,7 @@ export function spawnDetached(args: {
35
62
  stdio: ["ignore", outFd, outFd],
36
63
  cwd: args.cwd,
37
64
  detached: true,
65
+ windowsHide: true,
38
66
  env: { ...process.env, ...(args.env ?? {}) },
39
67
  });
40
68
  } finally {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-harness",
3
- "version": "0.63.4",
3
+ "version": "0.63.6",
4
4
  "description": "Pi extension bundle for a write sandbox, subagents, background tasks, SSH, Goals, and Todo lists.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -74,12 +74,12 @@
74
74
  "@xterm/xterm": "6.0.0",
75
75
  "marked": "18.0.5",
76
76
  "openai": "6.26.0",
77
- "pi-better-background-tasks": "0.21.13",
77
+ "pi-better-background-tasks": "0.21.15",
78
78
  "pi-better-goal": "0.18.4",
79
- "pi-better-sandbox": "0.15.2",
80
- "pi-better-server": "0.11.4",
79
+ "pi-better-sandbox": "0.15.3",
80
+ "pi-better-server": "0.11.6",
81
81
  "pi-better-ssh": "0.1.7",
82
- "pi-better-subagents": "0.41.6",
82
+ "pi-better-subagents": "0.41.8",
83
83
  "proper-lockfile": "^4.1.2",
84
84
  "shell-quote": "1.12.0",
85
85
  "smol-toml": "1.9.0",