pi-better-harness 0.67.2 → 0.68.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 (53) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +6 -6
  3. package/lib/codex-model-prompt.mjs +1 -1
  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 -1
  10. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/client.mjs +35 -7
  11. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/root.mjs +38 -20
  12. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/windows-directory.mjs +190 -0
  13. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/windows-native.mjs +14 -4
  14. package/node_modules/pi-better-background-tasks/runtime-client/src/startup/stage-local.mjs +75 -47
  15. package/node_modules/pi-better-background-tasks/src/output.ts +4 -1
  16. package/node_modules/pi-better-background-tasks/src/registry.ts +1 -1
  17. package/node_modules/pi-better-background-tasks/src/shared-navigator.ts +27 -12
  18. package/node_modules/pi-better-background-tasks/src/shared-windows-native.mjs +14 -4
  19. package/node_modules/pi-better-background-tasks/src/supervisor/generated/shared-windows-native.mjs +14 -4
  20. package/node_modules/pi-better-goal/package.json +1 -1
  21. package/node_modules/pi-better-sandbox/package.json +1 -1
  22. package/node_modules/pi-better-subagents/README.md +28 -0
  23. package/node_modules/pi-better-subagents/agents-catalog-tool.ts +8 -2
  24. package/node_modules/pi-better-subagents/catalog-runtime.ts +4 -4
  25. package/node_modules/pi-better-subagents/config.ts +16 -0
  26. package/node_modules/pi-better-subagents/direct-owner.ts +92 -0
  27. package/node_modules/pi-better-subagents/direct-worker.mjs +20 -0
  28. package/node_modules/pi-better-subagents/effective-settings.ts +9 -1
  29. package/node_modules/pi-better-subagents/index.ts +162 -53
  30. package/node_modules/pi-better-subagents/managed-launch-client.ts +2 -2
  31. package/node_modules/pi-better-subagents/package.json +5 -2
  32. package/node_modules/pi-better-subagents/registry.ts +3 -0
  33. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
  34. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
  35. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
  36. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
  37. package/node_modules/pi-better-subagents/runtime-client/artifacts/win32-x64.json +1 -1
  38. package/node_modules/pi-better-subagents/runtime-client/src/runtime/client.mjs +35 -7
  39. package/node_modules/pi-better-subagents/runtime-client/src/runtime/root.mjs +38 -20
  40. package/node_modules/pi-better-subagents/runtime-client/src/runtime/windows-directory.mjs +190 -0
  41. package/node_modules/pi-better-subagents/runtime-client/src/runtime/windows-native.mjs +14 -4
  42. package/node_modules/pi-better-subagents/runtime-client/src/startup/stage-local.mjs +75 -47
  43. package/node_modules/pi-better-subagents/session-store.ts +6 -0
  44. package/node_modules/pi-better-subagents/settings-page.ts +11 -2
  45. package/node_modules/pi-better-subagents/shared-catalog.ts +15 -2
  46. package/node_modules/pi-better-subagents/shared-navigator.ts +27 -12
  47. package/node_modules/pi-better-subagents/shared-windows-native.d.mts +36 -0
  48. package/node_modules/pi-better-subagents/shared-windows-native.mjs +14 -4
  49. package/node_modules/pi-better-subagents/spawn.ts +16 -3
  50. package/node_modules/pi-better-subagents/stop.ts +6 -0
  51. package/node_modules/pi-better-subagents/tools.ts +1 -0
  52. package/node_modules/pi-better-subagents/work-observation.ts +64 -1
  53. package/package.json +8 -7
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.68.0] - 2026-12-04
4
+
5
+ ### Changed
6
+
7
+ - Choose managed, direct or automatic execution for Subagents. The bundled runtime includes the Windows cache and Git Bash startup fixes.
8
+ - Model instruction templates appear in the system prompt under `model_instructions`.
9
+
10
+ ## [0.67.3] - 2026-12-04
11
+
12
+ ### Fixed
13
+
14
+ - Play the Todo demo in the Pi gallery or select any of the three animated README previews to watch its full recording.
15
+
3
16
  ## [0.67.2] - 2026-12-04
4
17
 
5
18
  ### Changed
package/README.md CHANGED
@@ -28,25 +28,25 @@ Each recording uses the same CSV exporter project. **Native Pi** is on the left
28
28
 
29
29
  Watch the checklist go from **0/2 to 2/2** as Pi inspects the exporter and runs its tests. When Pi finishes, Harness folds the eight tool calls into one line by default.
30
30
 
31
- https://github.com/user-attachments/assets/daf84108-38c7-4402-81f2-7a563221036f
31
+ [![Play the Todo and tool call folding comparison](https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/compare/todo-preview.webp)](https://cdn.jsdelivr.net/gh/1aboveio/pi-better-harness@56098e09/docs/images/package-gallery/compare/todo.mp4)
32
32
 
33
- [Todo setup](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-harness/docs/usage.md#goal--todo) · [Tool output settings](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-harness/README.md#minimal-tool-output) · [MP4 · 18s](https://github.com/1aboveio/pi-better-harness/blob/main/docs/images/package-gallery/compare/todo.mp4)
33
+ [Todo setup](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-harness/docs/usage.md#goal--todo) · [Tool output settings](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-harness/README.md#minimal-tool-output) · [MP4 · 18s](https://cdn.jsdelivr.net/gh/1aboveio/pi-better-harness@56098e09/docs/images/package-gallery/compare/todo.mp4)
34
34
 
35
35
  ### Subagents
36
36
 
37
37
  Ask a second Pi to review how the exporter handles commas. **The main prompt is ready** while the reviewer works. Its findings come back to the same conversation.
38
38
 
39
- https://github.com/user-attachments/assets/c00b4ac0-9070-4831-b3de-b22c1b626bba
39
+ [![Play the subagent review comparison](https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/compare/subagent-preview.webp)](https://cdn.jsdelivr.net/gh/1aboveio/pi-better-harness@56098e09/docs/images/package-gallery/compare/subagent.mp4)
40
40
 
41
- [Subagent tools](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-subagents/docs/usage.md#tools) · [MP4 · 21s](https://github.com/1aboveio/pi-better-harness/blob/main/docs/images/package-gallery/compare/subagent.mp4)
41
+ [Subagent tools](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-subagents/docs/usage.md#tools) · [MP4 · 21s](https://cdn.jsdelivr.net/gh/1aboveio/pi-better-harness@56098e09/docs/images/package-gallery/compare/subagent.mp4)
42
42
 
43
43
  ### Background tasks
44
44
 
45
45
  Ask Pi a question while `npm test` runs. The task row shows elapsed time, and **Pi reports the result** when all three tests pass. An active Goal can check that result against its acceptance criteria.
46
46
 
47
- https://github.com/user-attachments/assets/44f54db3-6573-4859-8c30-ee8573c3d6a8
47
+ [![Play the background task comparison](https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/compare/background-task-preview.webp)](https://cdn.jsdelivr.net/gh/1aboveio/pi-better-harness@56098e09/docs/images/package-gallery/compare/background-task.mp4)
48
48
 
49
- [Background task tools](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-background-tasks/docs/usage.md#tools) · [Completion callbacks](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-background-tasks/docs/usage.md#completion-callbacks) · [MP4 · 37s](https://github.com/1aboveio/pi-better-harness/blob/main/docs/images/package-gallery/compare/background-task.mp4)
49
+ [Background task tools](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-background-tasks/docs/usage.md#tools) · [Completion callbacks](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-background-tasks/docs/usage.md#completion-callbacks) · [MP4 · 37s](https://cdn.jsdelivr.net/gh/1aboveio/pi-better-harness@56098e09/docs/images/package-gallery/compare/background-task.mp4)
50
50
 
51
51
  <a name="try-it"></a><a name="install-the-whole-harness"></a>
52
52
 
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { readHarnessDefaults } from "./install-settings.mjs";
4
4
 
5
- const section = "codex_model_instructions";
5
+ const section = "model_instructions";
6
6
  const pinType = "pi-better-harness:official-codex-release";
7
7
  const root = new URL("./codex-models/", import.meta.url);
8
8
  const texts = new Map();
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.21.20",
3
+ "version": "0.21.21",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -70,7 +70,7 @@
70
70
  "vitest": "^3.0.0"
71
71
  },
72
72
  "dependencies": {
73
- "pi-better-server": "0.11.11",
73
+ "pi-better-server": "0.11.12",
74
74
  "proper-lockfile": "^4.1.2"
75
75
  }
76
76
  }
@@ -1 +1 @@
1
- {"build":{"contentId":"7ea53a9ab306acdb807d91d40e390a626649719ab6c3dc68abac89a5bdf0a50b","dependencyLockDigest":"4643e416af0b366e78fbaf142d8f69b0591f8a4d3c9db6c07d2ae25157ec9180","format":1,"nodeVersion":"24.14.1","piSdkVersion":"1.7.0","platform":"darwin-arm64","protocolVersion":1,"serverVersion":"0.11.11","sourceDigest":"9201868088ad78f5d2c2ded80d7929df5bcbc5e6ce3455c042d80dede4cf384c"},"sha256":"8851a7e15b3082c98017b5d4d6ee11d68e28bab15028100dab71f462c25e939d"}
1
+ {"build":{"contentId":"7099606a67970c979b357f5767fa82bcf4228db18d80922b8d9cc1f0427e74e7","dependencyLockDigest":"4643e416af0b366e78fbaf142d8f69b0591f8a4d3c9db6c07d2ae25157ec9180","format":1,"nodeVersion":"24.14.1","piSdkVersion":"1.7.0","platform":"darwin-arm64","protocolVersion":1,"serverVersion":"0.11.12","sourceDigest":"6b4ceccb9c7abe7fd77b740f32afbc6d2760e5365a62b7e1c41c5073a2d02fe9"},"sha256":"7044f9249dcd1f2b54ca4dec496f31c66a8b6f78b35a4b7858d5d59af3ea0686"}
@@ -1 +1 @@
1
- {"build":{"contentId":"6b8c0f8e8dc0e8857f9b506f9b02e4656a55b906ba8e865d674cfd61ea52ccd4","dependencyLockDigest":"4643e416af0b366e78fbaf142d8f69b0591f8a4d3c9db6c07d2ae25157ec9180","format":1,"nodeVersion":"24.14.1","piSdkVersion":"1.7.0","platform":"darwin-x64","protocolVersion":1,"serverVersion":"0.11.11","sourceDigest":"9201868088ad78f5d2c2ded80d7929df5bcbc5e6ce3455c042d80dede4cf384c"},"sha256":"db7abb20bd5a0958676bff1bb8237cbfb01bcaa4fc73030656f72ea5b8046307"}
1
+ {"build":{"contentId":"54aff10aba9f28727743a4867bed277f7009859f2b9fe39ec57aca86d784cd48","dependencyLockDigest":"4643e416af0b366e78fbaf142d8f69b0591f8a4d3c9db6c07d2ae25157ec9180","format":1,"nodeVersion":"24.14.1","piSdkVersion":"1.7.0","platform":"darwin-x64","protocolVersion":1,"serverVersion":"0.11.12","sourceDigest":"6b4ceccb9c7abe7fd77b740f32afbc6d2760e5365a62b7e1c41c5073a2d02fe9"},"sha256":"e0a937b14b8a587c6b74de741e4eca01269bc225e1615650ead5e614d9118d96"}
@@ -1 +1 @@
1
- {"build":{"contentId":"41f305a8be6279c9d7772f298faaaa5d13ee5917fc5d594580f4d0020f4319f7","dependencyLockDigest":"4643e416af0b366e78fbaf142d8f69b0591f8a4d3c9db6c07d2ae25157ec9180","format":1,"nodeVersion":"24.14.1","piSdkVersion":"1.7.0","platform":"linux-arm64","protocolVersion":1,"serverVersion":"0.11.11","sourceDigest":"9201868088ad78f5d2c2ded80d7929df5bcbc5e6ce3455c042d80dede4cf384c"},"sha256":"430e3a1bce7f7f870c17e8da26562e0f77bb4c921ba58c4255418357005c0a29"}
1
+ {"build":{"contentId":"48fdbbc98eb3f5ea808ea52f11934eb8f4f677e64bf468bf747c2a8fdbb4ea43","dependencyLockDigest":"4643e416af0b366e78fbaf142d8f69b0591f8a4d3c9db6c07d2ae25157ec9180","format":1,"nodeVersion":"24.14.1","piSdkVersion":"1.7.0","platform":"linux-arm64","protocolVersion":1,"serverVersion":"0.11.12","sourceDigest":"6b4ceccb9c7abe7fd77b740f32afbc6d2760e5365a62b7e1c41c5073a2d02fe9"},"sha256":"17ccfee2c7401f57c3e66e37e3cc5cf8643dfd44cca6071d0ad50d2fd26e1ce0"}
@@ -1 +1 @@
1
- {"build":{"contentId":"59d0b5a9267847833cbe977d923b6ba71e01b60b10ab064a924a722a322d4498","dependencyLockDigest":"4643e416af0b366e78fbaf142d8f69b0591f8a4d3c9db6c07d2ae25157ec9180","format":1,"nodeVersion":"24.14.1","piSdkVersion":"1.7.0","platform":"linux-x64","protocolVersion":1,"serverVersion":"0.11.11","sourceDigest":"9201868088ad78f5d2c2ded80d7929df5bcbc5e6ce3455c042d80dede4cf384c"},"sha256":"d7a9a566e17d45a3122b903d471874dc2131f7ae28eb9b78e182bec3366d7a60"}
1
+ {"build":{"contentId":"c87b5a5e067c82c6f1989d8cf07ee94b3e8071c8c6157f99ae4a6b96945e11f6","dependencyLockDigest":"4643e416af0b366e78fbaf142d8f69b0591f8a4d3c9db6c07d2ae25157ec9180","format":1,"nodeVersion":"24.14.1","piSdkVersion":"1.7.0","platform":"linux-x64","protocolVersion":1,"serverVersion":"0.11.12","sourceDigest":"6b4ceccb9c7abe7fd77b740f32afbc6d2760e5365a62b7e1c41c5073a2d02fe9"},"sha256":"5c5edb2052c647f52efec8177de20cfde36fd604bfc326e9b695ff22fef95fe4"}
@@ -1 +1 @@
1
- {"build":{"contentId":"25560d031d54c564df55a5d21c7b5831bc26f0a821306e66608875a80691d031","dependencyLockDigest":"4643e416af0b366e78fbaf142d8f69b0591f8a4d3c9db6c07d2ae25157ec9180","format":1,"nodeVersion":"24.14.1","piSdkVersion":"1.7.0","platform":"win32-x64","protocolVersion":1,"serverVersion":"0.11.11","sourceDigest":"9201868088ad78f5d2c2ded80d7929df5bcbc5e6ce3455c042d80dede4cf384c"},"sha256":"6d6d0dfd2556e5723e03a6b419edb512cdaa254bbb073935ce265a9d6932e1ff"}
1
+ {"build":{"contentId":"36ea946550db535b8f7866c8227a04be9e16b9ef7d0e4ce6e6896862a8350ec9","dependencyLockDigest":"4643e416af0b366e78fbaf142d8f69b0591f8a4d3c9db6c07d2ae25157ec9180","format":1,"nodeVersion":"24.14.1","piSdkVersion":"1.7.0","platform":"win32-x64","protocolVersion":1,"serverVersion":"0.11.12","sourceDigest":"6b4ceccb9c7abe7fd77b740f32afbc6d2760e5365a62b7e1c41c5073a2d02fe9"},"sha256":"78a2a6cb33b219382653d38437da83fedf741a605abceece69f842149392ad8e"}
@@ -1,10 +1,11 @@
1
1
  import { spawn } from "node:child_process";
2
- import { closeSync, openSync, readFileSync } from "node:fs";
2
+ import { closeSync, lstatSync, openSync, readFileSync } from "node:fs";
3
+ import { checkWindowsContents, checkWindowsFile } from "./windows-directory.mjs";
3
4
  import { readFile } from "node:fs/promises";
4
5
  import { once } from "node:events";
5
6
  import { Worker } from "node:worker_threads";
6
7
  import { createRequire } from "node:module";
7
- import { connectRuntimeSocket as connect } from "./windows-native.mjs";
8
+ import { connectRuntimeSocket as connect, windowsSystemRoot } from "./windows-native.mjs";
8
9
  import { join } from "node:path";
9
10
  import { setTimeout as delay } from "node:timers/promises";
10
11
  import { fileURLToPath } from "node:url";
@@ -25,6 +26,19 @@ function supportedPlatform() {
25
26
  }
26
27
  return platform;
27
28
  }
29
+ function reportWindowsRuntimeRoot(root, preferred) {
30
+ const fallback = preferred && preferred.toLowerCase() !== root.toLowerCase();
31
+ // Both standalone clients may finish the same cold start concurrently.
32
+ try {
33
+ closeSync(openSync(join(root, fallback ? ".fallback-reported" : ".location-reported"), "wx", 0o600));
34
+ }
35
+ catch {
36
+ return;
37
+ }
38
+ process.stderr.write(fallback
39
+ ? `Pi: PI_SERVER_RUNTIME_ROOT was unavailable. Using runtime cache ${root}\n`
40
+ : `Pi: Using runtime cache ${root}\n`);
41
+ }
28
42
  const startupKey = Symbol.for("pi-better-runtime.foreground-starts.v1");
29
43
  const starts = globalThis[startupKey] ??= new Map();
30
44
  /** Both standalone packages can join the same cold start without staging an archive on Pi's event loop. */
@@ -37,10 +51,15 @@ export async function ensureRuntimeInBackground({ agentDir, serverDir = process.
37
51
  const pin = await readFile(new URL(`../../artifacts/${platform}.json`, import.meta.url), { encoding: "utf8", signal: deadline });
38
52
  deadline?.throwIfAborted();
39
53
  const offline = process.env.PI_OFFLINE === "1";
40
- const key = JSON.stringify([agentDir, pin, offline]);
54
+ const windowsEnv = process.platform === "win32" ? { SystemRoot: windowsSystemRoot(), LOCALAPPDATA: process.env.LOCALAPPDATA ?? "",
55
+ PI_SERVER_RUNTIME_ROOT: process.env.PI_SERVER_RUNTIME_ROOT ?? "" } : undefined;
56
+ const key = JSON.stringify([agentDir, pin, offline, windowsEnv]);
41
57
  let start = starts.get(key);
42
58
  if (!start) {
43
59
  const worker = new Worker(new URL("./startup-worker.mjs", import.meta.url), {
60
+ // Windows workers have case-sensitive environment copies. Git Bash can
61
+ // supply SYSTEMROOT while the native DLL and tar loaders use SystemRoot.
62
+ ...(windowsEnv ? { env: { ...process.env, ...windowsEnv } } : {}),
44
63
  execArgv: [], workerData: { client: import.meta.url, options: { agentDir, serverDir, offline, timeoutMs: 120000 } },
45
64
  });
46
65
  worker.setMaxListeners(0);
@@ -145,13 +164,17 @@ export async function ensureRuntime(options) {
145
164
  return recovered;
146
165
  let runtime;
147
166
  try {
148
- runtime = await stageLocalRuntime({ artifact, installRoot: options.installRoot ?? join(root.agentDir, "managed-runtime"), signal: options.signal, onProgress: options.onProgress, offline: options.offline });
167
+ runtime = await stageLocalRuntime({ artifact, agentDir: root.agentDir, installRoot: options.installRoot, signal: options.signal, onProgress: options.onProgress, offline: options.offline });
149
168
  }
150
169
  catch (error) {
151
- 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.`);
170
+ const guidance = error instanceof Error && error.message.startsWith("permission:") ? "" : " Connect to the network to cache the pinned runtime, or repair the reported corrupt cache.";
171
+ throw new Error(`runtime-unavailable: ${String(error)}.${guidance} No fallback manager was started.`, { cause: error });
152
172
  }
153
173
  options.signal?.throwIfAborted();
154
- const fd = openSync(join(root.serverDir, "daemon.log"), "a", 0o600);
174
+ const logPath = join(root.serverDir, "daemon.log");
175
+ if (process.platform === "win32" && lstatSync(logPath, { throwIfNoEntry: false }))
176
+ checkWindowsFile(logPath);
177
+ const fd = openSync(logPath, "a", 0o600);
155
178
  try {
156
179
  const env = { ...process.env, PI_SERVER_DIR: root.serverDir, PI_CODING_AGENT_DIR: root.agentDir, PI_SERVER_AGENT: "pi" };
157
180
  for (const key of ["NODE_OPTIONS", "PI_SERVER_ACTIVATION_ID", "PI_SERVER_ROLLBACK_OPERATION_ID", "PI_SERVER_ROLLBACK_PERMIT"])
@@ -167,7 +190,10 @@ export async function ensureRuntime(options) {
167
190
  while (Date.now() < deadline) {
168
191
  options.signal?.throwIfAborted();
169
192
  try {
170
- return await query();
193
+ const status = await query();
194
+ if (process.platform === "win32")
195
+ reportWindowsRuntimeRoot(runtime.installRoot, options.installRoot ?? process.env.PI_SERVER_RUNTIME_ROOT);
196
+ return status;
171
197
  }
172
198
  catch (error) {
173
199
  if (!["ENOENT", "ECONNREFUSED"].includes(error.code ?? ""))
@@ -182,6 +208,8 @@ export async function waitForRuntimeOwner(serverDir, query, timeoutMs, signal) {
182
208
  // A draining owner can outlive its listening socket. Wait for it rather than
183
209
  // treating the handoff window as failure or starting a competing writer.
184
210
  const ownerDeadline = Date.now() + timeoutMs;
211
+ if (process.platform === "win32")
212
+ checkWindowsContents(serverDir, ["daemon-owner"]);
185
213
  let backoff = 100;
186
214
  for (;;) {
187
215
  const owner = inspectDaemonOwner(serverDir);
@@ -1,36 +1,55 @@
1
1
  import { lstatSync, linkSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
2
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
2
+ import { join, resolve } from "node:path";
3
+ import { tmpdir } from "node:os";
3
4
  import { randomUUID } from "node:crypto";
4
- import { userInfo } from "node:os";
5
- import { isPrivateRuntimePath } from "./windows-native.mjs";
5
+ import { checkWindowsContents, checkWindowsFile, ensureWindowsDirectory, verifiedWindowsTemp } from "./windows-directory.mjs";
6
6
  import { socketPathFor } from "./socket.mjs";
7
- function checkWindowsStateDirectory(directory) {
8
- if (process.platform !== "win32")
9
- return;
10
- const profile = realpathSync(userInfo().homedir);
11
- const path = resolve(directory), within = relative(profile, path);
12
- if (!within || within === ".." || within.startsWith(`..${sep}`) || isAbsolute(within)) {
13
- throw new Error("Windows managed state must be in a private directory inside the user profile");
14
- }
15
- for (let ancestor = path; ancestor.toLowerCase() !== profile.toLowerCase(); ancestor = dirname(ancestor)) {
16
- const stat = lstatSync(ancestor);
17
- if (!stat.isDirectory() || !isPrivateRuntimePath(ancestor, stat))
18
- throw new Error(`Unsafe Windows managed state directory: ${ancestor}`);
7
+ function ensureDirectory(path) {
8
+ if (process.platform === "win32")
9
+ ensureWindowsDirectory(path);
10
+ else
11
+ mkdirSync(path, { recursive: true, mode: 0o700 });
12
+ }
13
+ /** A cold daemon may recover tasks from all of these roots. The release cache
14
+ * has its own verification immediately before executable reuse.
15
+ */
16
+ export function verifyWindowsRuntimeState({ agentDir, serverDir }) {
17
+ checkWindowsContents(serverDir);
18
+ const databases = ["operation-coordinator.sqlite", "runtime-log-checkpoints.sqlite", "supervisor-decisions.sqlite"];
19
+ checkWindowsContents(agentDir, [
20
+ "catalog-host-admission", "runtime-read-repair", "settings.json", "auth.json", "models.json", "models-store.json",
21
+ ...databases.flatMap(name => [name, name + "-shm", name + "-wal", name + "-journal"]),
22
+ ]);
23
+ // Windows can supply an 8.3 profile name in TEMP. Use the long name from the
24
+ // verified handle in the daemon and in workers inheriting its environment.
25
+ const temp = verifiedWindowsTemp(tmpdir());
26
+ process.env.TEMP = process.env.TMP = temp;
27
+ for (const name of ["pi-better-background-tasks", "pi-better-subagents", "pi-better-subagent-workspaces"]) {
28
+ const path = join(temp, name);
29
+ ensureWindowsDirectory(path);
30
+ checkWindowsContents(path);
19
31
  }
32
+ const durable = process.env.PI_SUBAGENT_DURABLE_DIR?.trim() || join(agentDir, "subagents");
33
+ ensureWindowsDirectory(durable);
34
+ checkWindowsContents(durable);
20
35
  }
21
36
  /** Transport selection is durable and independent of installation or package version. */
22
37
  export function runtimeRoot(agentDir, requestedServerDir) {
23
- mkdirSync(agentDir, { recursive: true, mode: 0o700 });
24
- checkWindowsStateDirectory(agentDir);
38
+ ensureDirectory(agentDir);
25
39
  agentDir = realpathSync(agentDir);
26
40
  const path = join(agentDir, "server-registration-v1.json");
27
41
  const read = () => {
42
+ if (process.platform === "win32") {
43
+ lstatSync(path); // Preserve ENOENT only for an absent registration.
44
+ checkWindowsFile(path);
45
+ }
28
46
  const registration = JSON.parse(readFileSync(path, "utf8"));
29
47
  if (registration.version !== 1 || registration.agentDir !== agentDir || typeof registration.serverDir !== "string"
30
48
  || resolve(registration.serverDir) !== registration.serverDir || realpathSync(registration.serverDir) !== registration.serverDir) {
31
49
  throw new Error(`runtime-unavailable: invalid registration at ${path}; inspect it before retrying`);
32
50
  }
33
- checkWindowsStateDirectory(registration.serverDir);
51
+ if (process.platform === "win32")
52
+ ensureWindowsDirectory(registration.serverDir, false);
34
53
  return { agentDir, serverDir: registration.serverDir };
35
54
  };
36
55
  try {
@@ -40,8 +59,7 @@ export function runtimeRoot(agentDir, requestedServerDir) {
40
59
  if (error.code !== "ENOENT")
41
60
  throw error;
42
61
  }
43
- mkdirSync(requestedServerDir, { recursive: true, mode: 0o700 });
44
- checkWindowsStateDirectory(requestedServerDir);
62
+ ensureDirectory(requestedServerDir);
45
63
  const serverDir = realpathSync(requestedServerDir);
46
64
  socketPathFor(serverDir);
47
65
  const proposed = { version: 1, agentDir, serverDir };
@@ -0,0 +1,190 @@
1
+ import { lstatSync, readdirSync } from "node:fs";
2
+ import { join, win32 } from "node:path";
3
+ import { userInfo } from "node:os";
4
+ import { sidString, userSid, windowsApi, windowsSystemRoot } from "./windows-native.mjs";
5
+ const trustedInstaller = "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
6
+ const remediation = "Use a private local NTFS directory. Set PI_SERVER_RUNTIME_ROOT before starting pi for the code cache, PI_SERVER_DIR for a new transport, or PI_CODING_AGENT_DIR for a new agent.";
7
+ function unsafe(path, reason) {
8
+ throw new Error(`permission: unsafe directory or file at ${path}: ${reason}. ${remediation}`);
9
+ }
10
+ function loadBindings() {
11
+ const os = windowsApi(), { ffi, kernel } = os;
12
+ const unicode = ffi.struct({ length: "uint16_t", maximumLength: "uint16_t", buffer: "str16" });
13
+ const attributes = ffi.struct({ length: "uint32_t", root: "void *", name: ffi.pointer(unicode),
14
+ flags: "uint32_t", descriptor: "void *", qos: "void *" });
15
+ const nt = ffi.load(join(windowsSystemRoot(), "System32", "ntdll.dll"));
16
+ return {
17
+ ...os,
18
+ openChild: nt.func("NtCreateFile", "int32_t", ["void *", "uint32_t", ffi.pointer(attributes), "void *",
19
+ "void *", "uint32_t", "uint32_t", "uint32_t", "uint32_t", "void *", "uint32_t"]),
20
+ info: kernel.func("int GetFileInformationByHandleEx(void *handle, int kind, void *info, uint32_t size)"),
21
+ driveType: kernel.func("uint32_t GetDriveTypeW(str16 root)"),
22
+ volume: kernel.func("int GetVolumeInformationByHandleW(void *handle, void *label, uint32_t n, void *serial, void *maxName, void *flags, void *fs, uint32_t size)"),
23
+ finalPath: kernel.func("uint32_t GetFinalPathNameByHandleW(void *handle, void *path, uint32_t size, uint32_t flags)"),
24
+ };
25
+ }
26
+ let bindings;
27
+ const api = () => bindings ??= loadBindings();
28
+ function checkObject(handle, path, ancestor, directory, codeAncestor = false) {
29
+ const os = api(), info = Buffer.alloc(8);
30
+ if (!os.info(handle, 9 /* FileAttributeTagInfo */, info, info.length))
31
+ unsafe(path, "unreadable file attributes");
32
+ const flags = info.readUInt32LE();
33
+ if (flags & 0x400)
34
+ unsafe(path, "reparse point");
35
+ if (Boolean(flags & 0x10) !== directory)
36
+ unsafe(path, "unexpected object type");
37
+ const owner = Buffer.alloc(8), dacl = Buffer.alloc(8), descriptor = Buffer.alloc(8);
38
+ if (os.handleSecurity(handle, 1, 5, owner, null, dacl, null, descriptor))
39
+ unsafe(path, "unreadable owner or DACL");
40
+ try {
41
+ const trusted = (sid) => sid === userSid() || sid === "S-1-5-18" || sid === "S-1-5-32-544" || (ancestor && sid === trustedInstaller);
42
+ if (!trusted(sidString(owner.readBigUInt64LE())))
43
+ unsafe(path, "untrusted owner");
44
+ const acl = dacl.readBigUInt64LE();
45
+ if (!acl)
46
+ unsafe(path, "missing DACL");
47
+ const count = os.decode.uint16(acl + 4n), entry = Buffer.alloc(8);
48
+ for (let i = 0; i < count; i++) {
49
+ if (!os.getAce(acl, i, entry))
50
+ unsafe(path, "unreadable ACE");
51
+ const ace = entry.readBigUInt64LE(), type = os.decode.uint8(ace), inheritOnly = os.decode.uint8(ace + 1n) & 8;
52
+ if (type === 1)
53
+ continue; // Ignoring deny ACEs can only narrow the accepted set.
54
+ if (type !== 0)
55
+ unsafe(path, `unsupported ACE type ${type}`);
56
+ const sid = sidString(ace + 8n);
57
+ if (trusted(sid) || (inheritOnly && (ancestor || sid === "S-1-3-0")))
58
+ continue;
59
+ const mask = os.decode.uint32(ace + 4n);
60
+ // Existing protected children cannot be displaced by grants to add siblings.
61
+ // NTFS permits setting a directory reparse point only while it is empty.
62
+ // The Node loader also searches code ancestors for dependencies and package metadata.
63
+ const allowed = codeAncestor ? 0x1200a9 : ancestor ? 0x1201bf : 0;
64
+ if ((mask & ~allowed) !== 0)
65
+ unsafe(path, `untrusted Allow access mask 0x${mask.toString(16)}`);
66
+ }
67
+ }
68
+ finally {
69
+ os.free(descriptor.readBigUInt64LE());
70
+ }
71
+ }
72
+ function checkPath(path, directory, create, code = false, expandShortName = false) {
73
+ const os = api(), root = win32.parse(path).root;
74
+ if (!/^[A-Za-z]:\\$/.test(root) || path === root || win32.normalize(path) !== path || os.driveType(root) !== 3)
75
+ unsafe(path, "expected a canonical path on a local fixed volume");
76
+ // Preserve the original system-managed namespace above the OS profile for
77
+ // profile installations. External caches must prove code ancestry to the volume.
78
+ const profile = code ? userInfo().homedir.toLowerCase() : "";
79
+ const inProfile = path.toLowerCase().startsWith(profile + "\\");
80
+ const codeAncestor = (component) => code && (!inProfile || component.length >= profile.length);
81
+ const names = path.slice(root.length).split("\\");
82
+ if (names.some(name => !name || /[:<>|"?*\x00-\x1f]|[. ]$/.test(name) || /^(?:con|prn|aux|nul|(?:com|lpt)[1-9¹²³])(?:\.|$)/i.test(name)))
83
+ unsafe(path, "ambiguous Windows path");
84
+ const handle = os.openPipe(root, 0x20080, 7, null, 3, 0x02200000, null);
85
+ if (!handle || BigInt.asIntN(64, handle) === -1n)
86
+ unsafe(root, "cannot open volume root");
87
+ const handles = [handle], descriptor = Buffer.alloc(8);
88
+ try {
89
+ const fs = Buffer.alloc(64), final = Buffer.alloc((expandShortName ? 32768 : path.length + 8) * 2);
90
+ const capacity = final.length / 2;
91
+ if (!os.volume(handle, null, 0, null, null, null, fs, 32) || fs.toString("utf16le").split("\0")[0] !== "NTFS")
92
+ unsafe(root, "expected NTFS");
93
+ const size = os.finalPath(handle, final, capacity, 0);
94
+ if (!size || size >= capacity || final.toString("utf16le", 0, size * 2).slice(4).toLowerCase() !== root.toLowerCase())
95
+ unsafe(root, "redirected drive root");
96
+ checkObject(handle, root, true, true, codeAncestor(root));
97
+ if (create && !os.descriptor(`D:P(A;OICI;FA;;;${userSid()})(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)`, 1, descriptor, null))
98
+ unsafe(path, "cannot prepare private DACL");
99
+ let current = root;
100
+ for (const [index, name] of names.entries()) {
101
+ current = join(current, name);
102
+ const ancestor = index < names.length - 1, length = Buffer.byteLength(name, "utf16le");
103
+ const attributes = { length: 48, root: handles.at(-1), name: { length, maximumLength: length + 2, buffer: name },
104
+ flags: 0x40 /* OBJ_CASE_INSENSITIVE */, descriptor: descriptor.readBigUInt64LE() || null, qos: null };
105
+ const out = Buffer.alloc(8);
106
+ // A single component, relative to the already checked handle. OPEN_REPARSE_POINT
107
+ // opens a link itself. FILE_OPEN_IF supplies the protected DACL at creation.
108
+ const access = code && !ancestor ? 0x20086 : 0x20080; // A cache must allow adding files and directories.
109
+ const status = os.openChild(out, access, attributes, Buffer.alloc(16), null, 0, 7, create ? 3 : 1, 0x00200000 | (ancestor || directory ? 1 : 0x40), null, 0);
110
+ if (status < 0)
111
+ unsafe(current, `cannot open verified component (NTSTATUS 0x${(status >>> 0).toString(16)})`);
112
+ const child = out.readBigUInt64LE();
113
+ handles.push(child);
114
+ checkObject(child, current, ancestor, ancestor || directory, ancestor && codeAncestor(current));
115
+ }
116
+ // A shared ancestor could have been empty when opened. Once its verified
117
+ // child exists and cannot be deleted by peers, NTFS prevents retagging it.
118
+ let ancestorPath = root;
119
+ for (let i = 0; i < handles.length - 1; i++) {
120
+ const tag = Buffer.alloc(8);
121
+ if (!os.info(handles[i], 9, tag, tag.length) || (tag.readUInt32LE() & 0x400))
122
+ unsafe(ancestorPath, "reparse point during verification");
123
+ ancestorPath = join(ancestorPath, names[i]);
124
+ }
125
+ // Catch drive aliases, short names and native/Win32 normalization differences.
126
+ const result = os.finalPath(handles.at(-1), final, capacity, 0);
127
+ if (!result || result >= capacity)
128
+ unsafe(path, "cannot resolve verified handle");
129
+ const canonical = final.toString("utf16le", 0, result * 2).slice(4);
130
+ if (!expandShortName && canonical.toLowerCase() !== path.toLowerCase())
131
+ unsafe(path, "noncanonical path");
132
+ return canonical;
133
+ }
134
+ finally {
135
+ for (const opened of handles.reverse())
136
+ os.close(opened);
137
+ if (descriptor.readBigUInt64LE())
138
+ os.free(descriptor.readBigUInt64LE());
139
+ }
140
+ }
141
+ export function ensureWindowsDirectory(path, create = true) { checkPath(path, true, create); }
142
+ export function verifiedWindowsTemp(path) { return checkPath(path, true, false, false, true); }
143
+ export function ensureWindowsCodeDirectory(path) { checkPath(path, true, true, true); }
144
+ export function checkWindowsFile(path) { checkPath(path, false, false); }
145
+ /** Check the effective NTFS access on a newly created private staging file. */
146
+ export function checkWindowsExecuteAccess(path) {
147
+ const os = api();
148
+ const handle = os.openPipe(win32.toNamespacedPath(path), 0x20 /* FILE_EXECUTE */, 7, null, 3, 0x00200000, null);
149
+ if (!handle || BigInt.asIntN(64, handle) === -1n)
150
+ unsafe(path, `cannot open for execution (Win32 ${os.lastError()})`);
151
+ os.close(handle);
152
+ }
153
+ /** Called on cold admission, inside a verified private directory, before reuse.
154
+ * Check parents before enumeration. An existing child can carry an explicit ACL.
155
+ */
156
+ export function checkWindowsContents(root, names = readdirSync(root)) {
157
+ const os = api();
158
+ for (const name of names) {
159
+ const path = join(root, name);
160
+ const stat = lstatSync(path, { throwIfNoEntry: false });
161
+ if (!stat)
162
+ continue;
163
+ const directory = stat.isDirectory();
164
+ const handle = os.openPipe(win32.toNamespacedPath(path), 0x20080, 7, null, 3, 0x02200000, null);
165
+ if (!handle || BigInt.asIntN(64, handle) === -1n) {
166
+ const code = os.lastError();
167
+ if (code === 2 || code === 3)
168
+ continue; // A trusted writer removed this entry.
169
+ unsafe(path, `cannot inspect existing object (Win32 ${code})`);
170
+ }
171
+ try {
172
+ checkObject(handle, path, false, directory);
173
+ }
174
+ finally {
175
+ os.close(handle);
176
+ }
177
+ if (directory) {
178
+ let children;
179
+ try {
180
+ children = readdirSync(path);
181
+ }
182
+ catch (error) {
183
+ if (error.code === "ENOENT")
184
+ continue;
185
+ throw error;
186
+ }
187
+ checkWindowsContents(path, children);
188
+ }
189
+ }
190
+ }
@@ -2,6 +2,14 @@ import { closeSync } from "node:fs";
2
2
  import { connect, Socket } from "node:net";
3
3
  import { createRequire } from "node:module";
4
4
  import { join } from "node:path";
5
+ // Worker threads get a case-sensitive environment copy, even on Windows.
6
+ export function windowsSystemRoot(env = process.env) {
7
+ const key = Object.keys(env).find(name => name.toUpperCase() === "SYSTEMROOT");
8
+ const root = key && env[key];
9
+ if (!root)
10
+ throw new Error("Windows runtime requires the SystemRoot environment variable");
11
+ return root;
12
+ }
5
13
  // Private, x64-only bindings. Library resolution and DLL loading are lazy so POSIX
6
14
  // clients and hosts that only inspect the package never load a native module.
7
15
  function loadWindowsApi() {
@@ -15,10 +23,11 @@ function loadWindowsApi() {
15
23
  binding = createRequire(require.resolve("pi-better-server/package.json")).resolve("@koromix/koffi-win32-x64");
16
24
  }
17
25
  const ffi = require(binding);
18
- const system = join(process.env.SystemRoot, "System32");
26
+ const system = join(windowsSystemRoot(), "System32");
19
27
  const kernel = ffi.load(join(system, "kernel32.dll"));
20
28
  const security = ffi.load(join(system, "advapi32.dll"));
21
29
  return {
30
+ ffi, kernel, security,
22
31
  openProcess: kernel.func("void *OpenProcess(uint32_t access, int inherit, uint32_t pid)"),
23
32
  terminate: kernel.func("int TerminateProcess(void *process, uint32_t code)"),
24
33
  createJob: kernel.func("void *CreateJobObjectW(void *attributes, void *name)"),
@@ -48,7 +57,8 @@ function loadWindowsApi() {
48
57
  };
49
58
  }
50
59
  let windows;
51
- function api() { return windows ??= loadWindowsApi(); }
60
+ export function windowsApi() { return windows ??= loadWindowsApi(); }
61
+ const api = windowsApi;
52
62
  function creationTime(handle) {
53
63
  const created = Buffer.alloc(8);
54
64
  if (!api().processTimes(handle, created, Buffer.alloc(8), Buffer.alloc(8), Buffer.alloc(8)))
@@ -113,7 +123,7 @@ export function ownWindowsWorkerTree() {
113
123
  os.close(job);
114
124
  }
115
125
  }
116
- function sidString(pointer) {
126
+ export function sidString(pointer) {
117
127
  const text = Buffer.alloc(8);
118
128
  const os = api();
119
129
  if (!pointer || !os.sidString(pointer, text))
@@ -126,7 +136,7 @@ function sidString(pointer) {
126
136
  }
127
137
  }
128
138
  let currentUserSid;
129
- function userSid() {
139
+ export function userSid() {
130
140
  if (currentUserSid)
131
141
  return currentUserSid;
132
142
  const os = api(), token = Buffer.alloc(8), user = Buffer.alloc(256);