pi-better-harness 0.45.8 → 0.46.1

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 (64) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +7 -0
  3. package/extensions/task-context/index.ts +12 -1
  4. package/extensions/task-context/workflow-plan-update.ts +11 -0
  5. package/node_modules/pi-better-background-tasks/README.md +13 -0
  6. package/node_modules/pi-better-background-tasks/package.json +3 -1
  7. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
  8. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -0
  9. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.gz +0 -0
  10. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -0
  11. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.gz +0 -0
  12. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -0
  13. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.gz +0 -0
  14. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -0
  15. package/node_modules/pi-better-background-tasks/runtime-client/scripts/private-runtime/format.mjs +90 -0
  16. package/node_modules/pi-better-background-tasks/runtime-client/src/daemon-owner.mjs +171 -0
  17. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/client.mjs +129 -0
  18. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/root.mjs +41 -0
  19. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/socket.mjs +9 -0
  20. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/status-cli.mjs +14 -0
  21. package/node_modules/pi-better-background-tasks/runtime-client/src/startup/artifact.mjs +76 -0
  22. package/node_modules/pi-better-background-tasks/runtime-client/src/startup/install.mjs +184 -0
  23. package/node_modules/pi-better-background-tasks/runtime-client/src/startup/managed-types.mjs +1 -0
  24. package/node_modules/pi-better-background-tasks/runtime-client/src/startup/runtime.mjs +120 -0
  25. package/node_modules/pi-better-background-tasks/src/shared-navigator.ts +4 -3
  26. package/node_modules/pi-better-goal/README.md +10 -3
  27. package/node_modules/pi-better-goal/package.json +1 -1
  28. package/node_modules/pi-better-goal/src/index.ts +46 -11
  29. package/node_modules/pi-better-goal/src/preferences.ts +6 -3
  30. package/node_modules/pi-better-goal/src/settings-page.ts +2 -1
  31. package/node_modules/pi-better-goal/src/task-context.ts +25 -3
  32. package/node_modules/pi-better-subagents/README.md +13 -0
  33. package/node_modules/pi-better-subagents/assignment-outcomes.ts +14 -3
  34. package/node_modules/pi-better-subagents/assignment-report.ts +92 -0
  35. package/node_modules/pi-better-subagents/child-operations.ts +2 -0
  36. package/node_modules/pi-better-subagents/child-ownership.ts +1 -1
  37. package/node_modules/pi-better-subagents/index.ts +101 -24
  38. package/node_modules/pi-better-subagents/navigator.mjs +2 -1
  39. package/node_modules/pi-better-subagents/operation-bridge-types.ts +18 -1
  40. package/node_modules/pi-better-subagents/package.json +3 -1
  41. package/node_modules/pi-better-subagents/registry.ts +4 -2
  42. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
  43. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -0
  44. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
  45. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -0
  46. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
  47. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -0
  48. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
  49. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -0
  50. package/node_modules/pi-better-subagents/runtime-client/scripts/private-runtime/format.mjs +90 -0
  51. package/node_modules/pi-better-subagents/runtime-client/src/daemon-owner.mjs +171 -0
  52. package/node_modules/pi-better-subagents/runtime-client/src/runtime/client.mjs +129 -0
  53. package/node_modules/pi-better-subagents/runtime-client/src/runtime/root.mjs +41 -0
  54. package/node_modules/pi-better-subagents/runtime-client/src/runtime/socket.mjs +9 -0
  55. package/node_modules/pi-better-subagents/runtime-client/src/runtime/status-cli.mjs +14 -0
  56. package/node_modules/pi-better-subagents/runtime-client/src/startup/artifact.mjs +76 -0
  57. package/node_modules/pi-better-subagents/runtime-client/src/startup/install.mjs +184 -0
  58. package/node_modules/pi-better-subagents/runtime-client/src/startup/managed-types.mjs +1 -0
  59. package/node_modules/pi-better-subagents/runtime-client/src/startup/runtime.mjs +120 -0
  60. package/node_modules/pi-better-subagents/session-store.ts +58 -16
  61. package/node_modules/pi-better-subagents/shared-navigator.ts +4 -3
  62. package/node_modules/pi-better-subagents/worker-operations-host.ts +3 -0
  63. package/node_modules/pi-better-subagents/worker-waits.ts +50 -13
  64. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.46.1] - 2026-11-15
4
+
5
+ ### Fixed
6
+
7
+ - Preserve optional answer-file links and source provenance when saving workflow decisions through the Todo tool and atomic plan writer. Legacy decisions, revision checks, profiling and completion guards are unchanged. (#780)
8
+ - Keep Navigator detail paints free of provider I/O, retaining refreshed detail state between paints. (#781)
9
+
10
+ ## [0.46.0] - 2026-11-15
11
+
12
+ ### Added
13
+
14
+ - Offer an **Auto-start Goal** switch directly in `/harness-settings`, defaulting Off. With Outcome & Todo hooks enabled, explicitly saving an active outcome with an objective and acceptance criteria creates and binds a Goal while preserving its Todo and boundaries.
15
+
3
16
  ## [0.45.8] - 2026-11-14
4
17
 
5
18
  ### Fixed
package/README.md CHANGED
@@ -55,6 +55,13 @@ changes. It does not rebuild reminders before each model call. Turning hooks off
55
55
  hooks without deleting saved state or starting a turn. `/goal` and skills never
56
56
  enable them.
57
57
 
58
+ In `/harness-settings`, **Auto-start Goal** optionally starts
59
+ a Goal after a successful explicit outcome save with an objective and nonempty
60
+ `doneWhen` criteria. It defaults Off; `/goal settings auto-start-from-outcome on`
61
+ enables it. Existing active, paused or budget-limited Goals stay unchanged, and
62
+ restoring state or toggling settings never starts work. The outcome and Todo are
63
+ preserved; subsequent continuation follows the existing Goal controls.
64
+
58
65
  Existing Plan session histories restore as Todo. Workflow task-plan files and
59
66
  revision checks stay unchanged; skills continue using their own records when the
60
67
  optional interface is off. See the [usage guide](docs/usage.md#outcome--todo).
@@ -10,6 +10,7 @@ import { OUTCOME_ENTRY, prepareOutcome, restoreOutcome, formatOutcome, type Outc
10
10
  import { changeOutcomeTodoPreference, parseOutcomeTodoPreferences } from "./preferences.js";
11
11
  import { canRenderTaskRuntime, renderCompactTaskHeader, type CompactTaskHeader } from "./compact-task-header.js";
12
12
  import type { GoalSnapshot } from "pi-better-goal/src/types.ts";
13
+ import { canStartGoalFromOutcome, OUTCOME_ACCEPTED_EVENT } from "pi-better-goal/src/task-context.ts";
13
14
 
14
15
  import {
15
16
  completedPlanClearDelay,
@@ -90,6 +91,8 @@ const WorkflowUpdateSchema = Type.Object({
90
91
  humanWords: Type.String({ description: "The human's words, quoted or closely paraphrased." }),
91
92
  changes: Type.String({ description: "What the decision changes: units, validation, forbidden actions." }),
92
93
  supersedes: Type.Optional(Type.String({ description: "Id of the earlier decision this one replaces." })),
94
+ answers: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Answer-file keys resolved by this decision, e.g. results/127-impl-1.json." })),
95
+ source: Type.Optional(Type.String({ minLength: 1, description: "Decision provenance, e.g. agent-recommendation." })),
93
96
  }, { description: "A human decision to record with this transition." })),
94
97
  profiling: Type.Optional(Type.Object({}, {
95
98
  additionalProperties: true,
@@ -585,6 +588,10 @@ export default function taskContextExtension(pi: ExtensionAPI): void {
585
588
  if (currentPlan) clearPlan();
586
589
  }
587
590
  saveOutcome(nextOutcome);
591
+ const sessionId = ctx.sessionManager.getSessionId?.();
592
+ if (typeof sessionId === "string") {
593
+ pi.events.emit(OUTCOME_ACCEPTED_EVENT, { sessionId, outcome: { ...nextOutcome } });
594
+ }
588
595
  };
589
596
  if (!input.workflow && input.todo === undefined) {
590
597
  commitOutcome();
@@ -869,7 +876,11 @@ export default function taskContextExtension(pi: ExtensionAPI): void {
869
876
  canRenderTaskRuntime(request.width, goalHeaderRuntime(goal)) && displayedWorkflowOwner === workflowPlanOwner(widgetContext));
870
877
  }
871
878
  if (!enabled || request.action === "inspect") return;
872
- if (request.action === "start" && request.goalId && request.objective?.trim()) {
879
+ if (request.action === "bind") {
880
+ if (request.goalId && request.objective?.trim() === outcome?.objective && canStartGoalFromOutcome(outcome)) {
881
+ saveOutcome({ ...outcome, goalId: request.goalId });
882
+ }
883
+ } else if (request.action === "start" && request.goalId && request.objective?.trim()) {
873
884
  if (outcome?.goalId === request.goalId) return;
874
885
  clearWorkflowPlan();
875
886
  if (currentPlan) clearPlan();
@@ -21,6 +21,8 @@ export interface RushDecisionInput {
21
21
  humanWords: string;
22
22
  changes: string;
23
23
  supersedes?: string | undefined;
24
+ answers?: string[] | undefined;
25
+ source?: string | undefined;
24
26
  }
25
27
 
26
28
  export interface RushPlanUpdate {
@@ -378,6 +380,13 @@ function appendDecision(plan: Record<string, unknown>, decision: RushDecisionInp
378
380
  for (const field of ["humanWords", "changes"] as const) {
379
381
  if (typeof decision[field] !== "string" || !decision[field].trim()) throw new Error(`workflow.decision.${field} is required.`);
380
382
  }
383
+ if (decision.answers !== undefined && (!Array.isArray(decision.answers) ||
384
+ !decision.answers.every((answer) => typeof answer === "string" && answer.trim().length > 0))) {
385
+ throw new Error("workflow.decision.answers must be a list of non-empty answer-file keys.");
386
+ }
387
+ if (decision.source !== undefined && (typeof decision.source !== "string" || !decision.source.trim())) {
388
+ throw new Error("workflow.decision.source must be non-empty text.");
389
+ }
381
390
  const decisions = plan.decisions === undefined || plan.decisions === null ? [] : plan.decisions;
382
391
  if (!Array.isArray(decisions)) throw new Error("The saved plan's decisions field is not a list.");
383
392
  const known = new Set(decisions.flatMap((entry) => isRecord(entry) && typeof entry.id === "string" ? [entry.id] : []));
@@ -388,6 +397,8 @@ function appendDecision(plan: Record<string, unknown>, decision: RushDecisionInp
388
397
  decisions.push({
389
398
  id, timestamp: ts, humanWords: decision.humanWords, changes: decision.changes,
390
399
  supersedes: decision.supersedes ?? null,
400
+ ...(decision.answers === undefined ? {} : { answers: [...decision.answers] }),
401
+ ...(decision.source === undefined ? {} : { source: decision.source }),
391
402
  });
392
403
  plan.decisions = decisions;
393
404
  return id;
@@ -6,6 +6,19 @@
6
6
 
7
7
  Use `pi-better-background-tasks` when a command should keep running while the foreground Pi session stays free. It is best for dev servers, long scripts, queue watchers, deploy checks, log tails, and other command-driven work.
8
8
 
9
+ ## Runtime Status
10
+
11
+ Run `pi-background-runtime-status` to ensure the manifest-pinned local server and
12
+ print its canonical agent root, build, Node version, instance and capabilities as JSON.
13
+ This command does not create a hosted Pi session or require Harness.
14
+ The first use installs a verified private Node 24 and locked server dependencies.
15
+ Set `PI_OFFLINE=1` to require the cached runtime without downloads.
16
+ `PI_CODING_AGENT_DIR` selects the agent root; `PI_SERVER_DIR` selects the initial
17
+ transport directory. Later calls for the same canonical root reuse the registered
18
+ transport, including calls from Subagents or another package installation.
19
+ An incompatible or unhealthy live owner is an error, not a reason to replace it.
20
+ The API is `runtime-client/src/runtime/client.mjs`, exporting `ensureRuntime`.
21
+
9
22
  ## Screenshots
10
23
 
11
24
  <p><img src="https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/pi-better-background-tasks.png" alt="pi-better-background-tasks rendered in Pi" width="49%" /><img src="https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/overview/pi-better-background-tasks.png" alt="pi-better-background-tasks package overview" width="49%" /></p>
@@ -4,6 +4,7 @@
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
+ "bin": { "pi-background-runtime-status": "./runtime-client/src/runtime/status-cli.mjs" },
7
8
  "keywords": [
8
9
  "pi-package",
9
10
  "pi-extension",
@@ -31,7 +32,7 @@
31
32
  },
32
33
  "scripts": {
33
34
  "pretest": "node ../../scripts/sync-shared-log-utils.mjs && node ../../scripts/sync-shared-ssh-core.mjs && node ../../scripts/sync-shared-sandbox-core.mjs",
34
- "prepack": "node ../../scripts/sync-shared-log-utils.mjs && node ../../scripts/sync-shared-ssh-core.mjs && node ../../scripts/sync-shared-sandbox-core.mjs",
35
+ "prepack": "node ../../scripts/sync-shared-log-utils.mjs && node ../../scripts/sync-shared-ssh-core.mjs && node ../../scripts/sync-shared-sandbox-core.mjs && node ../../scripts/sync-runtime-client.mjs",
35
36
  "pretypecheck": "node ../../scripts/sync-shared-sandbox-core.mjs",
36
37
  "typecheck": "tsc --noEmit",
37
38
  "test": "vitest run",
@@ -43,6 +44,7 @@
43
44
  "test:sandbox": "vitest run src/sandbox.test.ts src/sandbox-kernel.test.ts"
44
45
  },
45
46
  "files": [
47
+ "runtime-client/**",
46
48
  "src/**/*.ts",
47
49
  "src/shared-operation-coordinator/assignment-observation.mjs",
48
50
  "src/supervisor/**/*.mjs",
@@ -0,0 +1 @@
1
+ {"build":{"format":1,"sourceDigest":"4a2331d2ad22ef8c0dcab3df637dbb4ceed9652100bb0e9890bcc40297b33fc9","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.2.4","contentId":"229e6dffc9b3028cd9b2e852e01908c95e3c2bf6ca9bb9f38e71ce5930c545b5"},"sha256":"bf389c30f0de82c93dc57987115da4fc9d8f51f5131f6cc39cbcff2fe025f35a"}
@@ -0,0 +1 @@
1
+ {"build":{"format":1,"sourceDigest":"4a2331d2ad22ef8c0dcab3df637dbb4ceed9652100bb0e9890bcc40297b33fc9","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.2.4","contentId":"2ead9dfdf963382452c14e99e806df94869b1cc556ed8270ed8c398cb9984ad6"},"sha256":"fff673607c28a3191299b38558b03b0dfab4593892f569daf959fa4d8733442f"}
@@ -0,0 +1 @@
1
+ {"build":{"format":1,"sourceDigest":"4a2331d2ad22ef8c0dcab3df637dbb4ceed9652100bb0e9890bcc40297b33fc9","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.2.4","contentId":"a5cc13f3b6d41aa4feb36b52f04988435fa4440078947a1043095a08ca7ff205"},"sha256":"db62852b6e38a406fee2f0b284b7d9fc6e51af875a2cbe51f409b301ed6e9b8e"}
@@ -0,0 +1 @@
1
+ {"build":{"format":1,"sourceDigest":"4a2331d2ad22ef8c0dcab3df637dbb4ceed9652100bb0e9890bcc40297b33fc9","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.2.4","contentId":"9fe4ad3c210ccc4a20b8ea0b0db485b1f49bb88d7d2f829c7c0a1175df505f85"},"sha256":"a5a6b01ebf90a92c07144e6b12811427a97c128909cb440c95463a394f156d38"}
@@ -0,0 +1,90 @@
1
+ import { createHash } from "node:crypto";
2
+ import { isAbsolute, posix } from "node:path";
3
+ export const NODE_CHECKSUMS = {
4
+ "linux-x64": "ace9fa104992ed0829642629c46ca7bd7fd6e76278cb96c958c4b387d29658ea",
5
+ "linux-arm64": "734ff04fa7f8ed2e8a78d40cacf5ac3fc4515dac2858757cbab313eb483ba8a2",
6
+ "darwin-x64": "2526230ad7d922be82d4fdb1e7ee1e84303e133e3b4b0ec4c2897ab31de0253d",
7
+ "darwin-arm64": "25495ff85bd89e2d8a24d88566d7e2f827c6b0d3d872b2cebf75371f93fcb1fe",
8
+ };
9
+ // Extracted bin/node hashes from the archives authenticated by NODE_CHECKSUMS.
10
+ // Source: https://nodejs.org/dist/v24.14.1/SHASUMS256.txt
11
+ export const NODE_EXECUTABLE_CHECKSUMS = {
12
+ "linux-x64": "bf9112eb83a827dc9f9c8d19bb7bddcbf00f7b2fedae18fdcaee05406981f20a",
13
+ "linux-arm64": "7fac13c04c19207c3e904a7721f8c045e6b99493471e2df85444f764cdd21934",
14
+ "darwin-x64": "9ab4f6249a8de4671c3205ef58621dfb19d120a9c59fd96ed206571bafb0319c",
15
+ "darwin-arm64": "35d4bc736bbe4161f0c074aa140ddb74586e46969bc2ad63d32c838bec4463ff",
16
+ };
17
+ export function digest(value) { return createHash("sha256").update(value).digest("hex"); }
18
+ export function stable(value) {
19
+ if (Array.isArray(value))
20
+ return `[${value.map(stable).join(",")}]`;
21
+ if (value && typeof value === "object")
22
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable(value[key])}`).join(",")}}`;
23
+ return JSON.stringify(value);
24
+ }
25
+ export function validateBuild(value) {
26
+ if (!value || value.format !== 1 || !Object.hasOwn(NODE_CHECKSUMS, value.platform) || value.nodeVersion !== "24.14.1"
27
+ || !/^\d+\.\d+\.\d+$/.test(value.piSdkVersion) || !/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(value.serverVersion)
28
+ || !Number.isSafeInteger(value.protocolVersion) || value.protocolVersion < 1
29
+ || ![value.contentId, value.sourceDigest, value.dependencyLockDigest].every((v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v)))
30
+ throw new Error("Artifact: invalid build metadata or unsupported platform");
31
+ const { contentId, ...identity } = value;
32
+ if (digest(stable(identity)) !== contentId)
33
+ throw new Error("Artifact: content identity mismatch");
34
+ return value;
35
+ }
36
+ export function safeSourcePath(path) {
37
+ return typeof path === "string" && path.length <= 512 && !path.includes("\\") && !/[\0-\x1f\x7f]/.test(path)
38
+ && !isAbsolute(path) && path === posix.normalize(path) && !path.split("/").some((p) => !p || p === ".." || p === "." || p === "node_modules" || p === ".git" || p === "test-support" || p.startsWith(".env") || p === "auth.json" || p === "settings.json")
39
+ && (path.startsWith("src/") || ["package.json", "scripts/private-runtime/format.ts", "scripts/private-runtime/installer.ts", "scripts/private-runtime/package.json", "scripts/private-runtime/package-lock.json"].includes(path));
40
+ }
41
+ export function validatePayload(value) {
42
+ if (!value || value.format !== 1 || !Array.isArray(value.files) || value.files.length > 10000)
43
+ throw new Error("Artifact: invalid file table");
44
+ validateBuild(value.build);
45
+ const paths = new Set();
46
+ let size = 0;
47
+ for (const file of value.files) {
48
+ if (!file || Object.keys(file).sort().join(",") !== "data,path" || !safeSourcePath(file.path) || paths.has(file.path))
49
+ throw new Error("Artifact: unsafe or duplicate path");
50
+ if (typeof file.data !== "string" || file.data.length > 16 * 1024 * 1024 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(file.data))
51
+ throw new Error("Artifact: invalid or oversized file");
52
+ size += Buffer.byteLength(file.data, "base64");
53
+ if (size > 48 * 1024 * 1024)
54
+ throw new Error("Artifact: decoded size limit");
55
+ paths.add(file.path);
56
+ }
57
+ for (const path of paths) {
58
+ for (let parent = posix.dirname(path); parent !== "."; parent = posix.dirname(parent))
59
+ if (paths.has(parent))
60
+ throw new Error("Artifact: file/directory path collision");
61
+ }
62
+ for (const required of ["src/cli.ts", "src/server.ts", "package.json", "scripts/private-runtime/format.ts", "scripts/private-runtime/installer.ts", "scripts/private-runtime/package-lock.json", "scripts/private-runtime/package.json"])
63
+ if (!paths.has(required))
64
+ throw new Error(`Artifact: missing ${required}`);
65
+ if (digest(stable(value.files)) !== value.build.sourceDigest)
66
+ throw new Error("Artifact: source integrity mismatch");
67
+ const lock = JSON.parse(Buffer.from(value.files.find((f) => f.path === "scripts/private-runtime/package-lock.json").data, "base64").toString());
68
+ if (digest(stable(lock)) !== value.build.dependencyLockDigest || lock.lockfileVersion !== 3 || lock.packages?.[""]?.dependencies?.["@earendil-works/pi-coding-agent"] !== value.build.piSdkVersion)
69
+ throw new Error("Artifact: dependency lock mismatch");
70
+ for (const [path, pkg] of Object.entries(lock.packages)) {
71
+ if (!path)
72
+ continue;
73
+ if (!path.startsWith("node_modules/") || path.includes("..") || pkg.link || !/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(pkg.version)
74
+ || typeof pkg.resolved !== "string" || !pkg.resolved.startsWith("https://registry.npmjs.org/") || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(pkg.integrity))
75
+ throw new Error(`Artifact: dependency lacks official locked integrity: ${path}`);
76
+ }
77
+ return value;
78
+ }
79
+ export function validateStaged(value) {
80
+ if (!value || value.format !== 1)
81
+ throw new Error("Staging: invalid runtime manifest");
82
+ validateBuild(value.build);
83
+ for (const key of ["root", "node", "entrypoint", "manifestPath", "installRoot"])
84
+ if (typeof value[key] !== "string" || !isAbsolute(value[key]) || /[\0\r\n]/.test(value[key]) || posix.normalize(value[key]) !== value[key])
85
+ throw new Error(`Staging: invalid ${key}`);
86
+ if (value.root !== `${value.installRoot}/releases/${value.build.contentId}` || value.root.split("/").includes("node_modules")
87
+ || value.node !== `${value.root}/node/bin/node` || value.entrypoint !== `${value.root}/src/cli.ts` || value.manifestPath !== `${value.root}/runtime.json`)
88
+ throw new Error("Staging: runtime path identity mismatch");
89
+ return value;
90
+ }
@@ -0,0 +1,171 @@
1
+ import { mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { join } from "node:path";
4
+ export function currentOwnerIdentity(token = randomUUID()) {
5
+ return { pid: process.pid, token, ...linuxIdentity(process.pid) };
6
+ }
7
+ export function ownerIsAlive(owner) {
8
+ return alive(owner);
9
+ }
10
+ /** Read-only, fail-closed inspection using the same PID-reuse checks as claiming. */
11
+ export function inspectDaemonOwner(serverDir, lockName = "daemon-owner") {
12
+ const lock = join(serverDir, lockName);
13
+ try {
14
+ const names = readdirSync(lock);
15
+ if (names.length !== 1)
16
+ return { status: "ambiguous", reason: "Ownership directory is empty or has multiple entries" };
17
+ const owner = JSON.parse(readFileSync(join(lock, names[0]), "utf8"));
18
+ validateOwner(owner, names[0], lock);
19
+ return { status: alive(owner) ? "live" : "dead", owner };
20
+ }
21
+ catch (error) {
22
+ if (error.code === "ENOENT") {
23
+ // A disappearing file inside a published directory is not proof of no owner.
24
+ try {
25
+ readdirSync(lock);
26
+ }
27
+ catch (again) {
28
+ if (again.code === "ENOENT")
29
+ return { status: "missing" };
30
+ }
31
+ }
32
+ return { status: "ambiguous", reason: String(error) };
33
+ }
34
+ }
35
+ export function validateDaemonOwnerIdentity(value) {
36
+ const owner = value;
37
+ validateOwner(owner, `owner-${owner?.token}.json`, "activation journal");
38
+ }
39
+ function validateOwner(previous, name, lock) {
40
+ if (!previous || typeof previous !== "object" || Array.isArray(previous)
41
+ || !Number.isSafeInteger(previous.pid) || previous.pid <= 0 || previous.pid > 2_147_483_647
42
+ || typeof previous.token !== "string" || !UUID.test(previous.token) || name !== `owner-${previous.token}.json`
43
+ || (previous.boot !== undefined && (typeof previous.boot !== "string" || !UUID.test(previous.boot)))
44
+ || (previous.start !== undefined && (typeof previous.start !== "string" || !/^\d+$/.test(previous.start))))
45
+ throw new Error(`Invalid daemon ownership in ${lock}`);
46
+ }
47
+ const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
48
+ function linuxIdentity(pid) {
49
+ if (process.platform !== "linux")
50
+ return {};
51
+ try {
52
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
53
+ return { boot: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), start: stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] };
54
+ }
55
+ catch {
56
+ return {};
57
+ }
58
+ }
59
+ function alive(owner) {
60
+ const identity = linuxIdentity(owner.pid);
61
+ if (owner.boot && identity.boot && owner.boot !== identity.boot)
62
+ return false;
63
+ if (owner.start && identity.start && owner.start !== identity.start)
64
+ return false;
65
+ try {
66
+ process.kill(owner.pid, 0);
67
+ return true;
68
+ }
69
+ catch (error) {
70
+ return error.code !== "ESRCH";
71
+ }
72
+ }
73
+ /** Claim ownership before reading the index. A live owner is never reclaimed on a timer. */
74
+ export function claimDaemonOwner(serverDir, lockName = "daemon-owner", stagingDir = serverDir) {
75
+ const token = randomUUID();
76
+ const owner = currentOwnerIdentity(token);
77
+ const lock = join(serverDir, lockName);
78
+ const candidate = join(stagingDir, `.${lockName}-${token}`);
79
+ const name = `owner-${token}.json`;
80
+ mkdirSync(candidate, { mode: 0o700 });
81
+ let claimed = false;
82
+ try {
83
+ writeFileSync(join(candidate, name), `${JSON.stringify(owner)}\n`, { mode: 0o600 });
84
+ for (let attempt = 0; attempt < 20; attempt++) {
85
+ try {
86
+ // Publishing a fully populated directory avoids an ownerless mkdir/write window.
87
+ renameSync(candidate, lock);
88
+ claimed = true;
89
+ let released = false;
90
+ return () => {
91
+ if (released)
92
+ return;
93
+ try {
94
+ unlinkSync(join(lock, name));
95
+ }
96
+ catch (error) {
97
+ if (error.code !== "ENOENT")
98
+ throw error;
99
+ }
100
+ try {
101
+ rmdirSync(lock);
102
+ }
103
+ catch (error) {
104
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? ""))
105
+ throw error;
106
+ }
107
+ released = true;
108
+ };
109
+ }
110
+ catch (error) {
111
+ if (!["EEXIST", "ENOTEMPTY"].includes(error.code ?? ""))
112
+ throw error;
113
+ }
114
+ let names;
115
+ try {
116
+ names = readdirSync(lock);
117
+ }
118
+ catch (error) {
119
+ if (error.code === "ENOENT")
120
+ continue;
121
+ throw error;
122
+ }
123
+ if (names.length === 0)
124
+ continue;
125
+ if (names.length !== 1 || !/^owner-[a-f0-9-]+\.json$/.test(names[0]))
126
+ throw new Error(`Unrecognized daemon ownership in ${lock}; refusing to remove it`);
127
+ const path = join(lock, names[0]);
128
+ let previous;
129
+ try {
130
+ previous = JSON.parse(readFileSync(path, "utf8"));
131
+ }
132
+ catch (error) {
133
+ if (error.code === "ENOENT")
134
+ continue;
135
+ throw error;
136
+ }
137
+ validateOwner(previous, names[0], lock);
138
+ if (alive(previous))
139
+ throw new Error(`Daemon owner ${previous.pid} is already running for ${serverDir}; refusing another writer`);
140
+ // Remove only the exact stale owner's file. A competing claimant publishes a different token.
141
+ try {
142
+ unlinkSync(path);
143
+ }
144
+ catch (error) {
145
+ if (error.code === "ENOENT")
146
+ continue;
147
+ throw error;
148
+ }
149
+ try {
150
+ rmdirSync(lock);
151
+ }
152
+ catch (error) {
153
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? ""))
154
+ throw error;
155
+ }
156
+ }
157
+ throw new Error(`Daemon ownership changed repeatedly for ${serverDir}; retry connecting`);
158
+ }
159
+ finally {
160
+ if (!claimed) {
161
+ try {
162
+ unlinkSync(join(candidate, name));
163
+ }
164
+ catch (error) {
165
+ if (error.code !== "ENOENT")
166
+ throw error;
167
+ }
168
+ rmdirSync(candidate);
169
+ }
170
+ }
171
+ }
@@ -0,0 +1,129 @@
1
+ import { spawn } from "node:child_process";
2
+ import { closeSync, openSync, readFileSync } from "node:fs";
3
+ import { connect } from "node:net";
4
+ import { join } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { fileURLToPath } from "node:url";
7
+ import { stageRuntime } from "../startup/install.mjs";
8
+ import { inspectDaemonOwner } from "../daemon-owner.mjs";
9
+ import { runtimeRoot } from "./root.mjs";
10
+ import { socketPathFor } from "./socket.mjs";
11
+ /** One bounded LF-JSON exchange; importing this module never loads the Pi SDK. */
12
+ export async function runtimeStatus(socketPath, agentDir, artifact, timeoutMs = 2000) {
13
+ return new Promise((resolve, reject) => {
14
+ const socket = connect(socketPath);
15
+ const timer = setTimeout(() => { socket.destroy(); reject(new Error(`runtime-unhealthy: no response at ${socketPath}; inspect the live owner`)); }, timeoutMs);
16
+ let buffer = "", greeted = false;
17
+ const fail = (error) => { clearTimeout(timer); socket.destroy(); reject(error); };
18
+ socket.on("error", fail);
19
+ socket.on("end", () => fail(new Error("runtime-unavailable: server closed the connection")));
20
+ socket.on("connect", () => socket.write(JSON.stringify({ id: "hello", type: "hello", protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-status-v1"] }) + "\n"));
21
+ socket.setEncoding("utf8");
22
+ socket.on("data", (chunk) => {
23
+ buffer += chunk;
24
+ if (buffer.length > 1024 * 1024)
25
+ return fail(new Error("runtime-unhealthy: response exceeds 1 MiB"));
26
+ while (buffer.includes("\n")) {
27
+ const index = buffer.indexOf("\n"), line = buffer.slice(0, index);
28
+ buffer = buffer.slice(index + 1);
29
+ try {
30
+ const reply = JSON.parse(line);
31
+ if (!reply.success)
32
+ throw new Error(reply.error ?? "runtime-unavailable");
33
+ const data = reply.data;
34
+ if (!greeted) {
35
+ if (reply.id !== "hello" || data?.protocolVersion !== 1 || data.agentDir !== agentDir
36
+ || data.build?.contentId !== artifact.build.contentId || data.nodeVersion !== artifact.build.nodeVersion
37
+ || !data.capabilities?.includes("runtime-status-v1") || !data.instanceId)
38
+ throw new Error("capability-mismatch: root, pinned build, Node or runtime capability differs; update the installed packages together");
39
+ greeted = true;
40
+ socket.write(JSON.stringify({ id: "status", type: "runtime_get_status" }) + "\n");
41
+ }
42
+ else {
43
+ if (reply.id !== "status")
44
+ throw new Error("runtime-unhealthy: unexpected response");
45
+ clearTimeout(timer);
46
+ socket.destroy();
47
+ resolve(data);
48
+ }
49
+ }
50
+ catch (error) {
51
+ return fail(error);
52
+ }
53
+ }
54
+ });
55
+ });
56
+ }
57
+ const runLocal = (command, input, timeoutMs) => new Promise((resolve, reject) => {
58
+ const child = spawn("/bin/sh", ["-c", command], { stdio: "pipe", timeout: timeoutMs });
59
+ let stdout = "", stderr = "";
60
+ child.stdout.on("data", chunk => { stdout += chunk; });
61
+ child.stderr.on("data", chunk => { stderr += chunk; });
62
+ child.on("error", reject);
63
+ child.stdin.on("error", () => undefined);
64
+ child.on("close", (exitCode, signal) => resolve({ stdout, stderr, exitCode, timedOut: signal === "SIGTERM" }));
65
+ child.stdin.end(input);
66
+ });
67
+ export async function ensureRuntime(options) {
68
+ options.signal?.throwIfAborted();
69
+ const timeoutMs = options.timeoutMs ?? 15000;
70
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120000)
71
+ throw new Error("Runtime timeout must be from 1 to 120000 ms");
72
+ const platform = `${process.platform}-${process.arch}`;
73
+ const directory = fileURLToPath(new URL("../../artifacts/", import.meta.url));
74
+ let artifact;
75
+ try {
76
+ const manifest = JSON.parse(readFileSync(join(directory, `${platform}.json`), "utf8"));
77
+ artifact = { ...manifest, bytes: readFileSync(join(directory, `${platform}.gz`)) };
78
+ }
79
+ catch (error) {
80
+ throw new Error(`runtime-unavailable: cannot read pinned artifact for ${platform}; reinstall the standalone package. ${String(error)}`);
81
+ }
82
+ const { decodeServerArtifact } = await import("../startup/artifact.mjs");
83
+ decodeServerArtifact(artifact);
84
+ const root = runtimeRoot(options.agentDir, options.serverDir ?? join(options.agentDir, "server"));
85
+ const socketPath = socketPathFor(root.serverDir);
86
+ const query = () => runtimeStatus(socketPath, root.agentDir, artifact, Math.min(timeoutMs, 2000));
87
+ try {
88
+ return await query();
89
+ }
90
+ catch (error) {
91
+ if (!["ENOENT", "ECONNREFUSED"].includes(error.code ?? ""))
92
+ throw error;
93
+ }
94
+ const owner = inspectDaemonOwner(root.serverDir);
95
+ if (owner.status === "live" || owner.status === "ambiguous")
96
+ throw new Error(`runtime-unhealthy: existing ${owner.status} owner at ${root.serverDir}; no replacement was started`);
97
+ let runtime;
98
+ try {
99
+ runtime = await stageRuntime({ run: runLocal, artifact, installRoot: options.installRoot ?? join(root.agentDir, "managed-runtime"), signal: options.signal, onProgress: options.onProgress, offline: options.offline });
100
+ }
101
+ catch (error) {
102
+ 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.`);
103
+ }
104
+ const fd = openSync(join(root.serverDir, "daemon.log"), "a", 0o600);
105
+ try {
106
+ const env = { ...process.env, PI_SERVER_DIR: root.serverDir, PI_CODING_AGENT_DIR: root.agentDir, PI_SERVER_AGENT: "pi" };
107
+ for (const key of ["NODE_OPTIONS", "PI_SERVER_ACTIVATION_ID", "PI_SERVER_ROLLBACK_OPERATION_ID", "PI_SERVER_ROLLBACK_PERMIT"])
108
+ delete env[key];
109
+ const child = spawn(runtime.node, [runtime.entrypoint, "--agent", "pi"], { cwd: root.serverDir, env, detached: true, stdio: ["ignore", fd, fd] });
110
+ child.on("error", () => undefined);
111
+ child.unref();
112
+ }
113
+ finally {
114
+ closeSync(fd);
115
+ }
116
+ const deadline = Date.now() + timeoutMs;
117
+ while (Date.now() < deadline) {
118
+ options.signal?.throwIfAborted();
119
+ try {
120
+ return await query();
121
+ }
122
+ catch (error) {
123
+ if (!["ENOENT", "ECONNREFUSED"].includes(error.code ?? ""))
124
+ throw error;
125
+ }
126
+ await delay(50, undefined, { signal: options.signal });
127
+ }
128
+ throw new Error(`runtime-unavailable: startup timed out; inspect ${join(root.serverDir, "daemon.log")}; owner was not replaced`);
129
+ }
@@ -0,0 +1,41 @@
1
+ import { linkSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ /** Transport selection is durable and independent of installation or package version. */
5
+ export function runtimeRoot(agentDir, requestedServerDir) {
6
+ mkdirSync(agentDir, { recursive: true, mode: 0o700 });
7
+ agentDir = realpathSync(agentDir);
8
+ const path = join(agentDir, "server-registration-v1.json");
9
+ const read = () => {
10
+ const registration = JSON.parse(readFileSync(path, "utf8"));
11
+ if (registration.version !== 1 || registration.agentDir !== agentDir || typeof registration.serverDir !== "string"
12
+ || resolve(registration.serverDir) !== registration.serverDir || realpathSync(registration.serverDir) !== registration.serverDir) {
13
+ throw new Error(`runtime-unavailable: invalid registration at ${path}; inspect it before retrying`);
14
+ }
15
+ return { agentDir, serverDir: registration.serverDir };
16
+ };
17
+ try {
18
+ return read();
19
+ }
20
+ catch (error) {
21
+ if (error.code !== "ENOENT")
22
+ throw error;
23
+ }
24
+ const temporary = `${path}.${randomUUID()}`;
25
+ mkdirSync(requestedServerDir, { recursive: true, mode: 0o700 });
26
+ const proposed = { version: 1, agentDir, serverDir: realpathSync(requestedServerDir) };
27
+ writeFileSync(temporary, JSON.stringify(proposed), { mode: 0o600, flag: "wx" });
28
+ try {
29
+ try {
30
+ linkSync(temporary, path);
31
+ }
32
+ catch (error) {
33
+ if (error.code !== "EEXIST")
34
+ throw error;
35
+ }
36
+ }
37
+ finally {
38
+ unlinkSync(temporary);
39
+ }
40
+ return read();
41
+ }
@@ -0,0 +1,9 @@
1
+ import { join } from "node:path";
2
+ /** sockaddr_un.sun_path is 104 bytes on macOS; leave room for the NUL. */
3
+ export function socketPathFor(serverDir) {
4
+ const path = join(serverDir, "pi-server.sock");
5
+ if (Buffer.byteLength(path) > 103) {
6
+ throw new Error(`Socket path is too long for a unix socket (${Buffer.byteLength(path)} > 103 bytes): ${path}. Set PI_SERVER_DIR to a shorter directory.`);
7
+ }
8
+ return path;
9
+ }
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { ensureRuntime } from "./client.mjs";
5
+ try {
6
+ const status = await ensureRuntime({ agentDir: process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), serverDir: process.env.PI_SERVER_DIR,
7
+ offline: process.env.PI_OFFLINE === "1",
8
+ onProgress: stage => process.stderr.write(`Runtime: ${stage}\n`) });
9
+ process.stdout.write(JSON.stringify(status) + "\n");
10
+ }
11
+ catch (error) {
12
+ process.stderr.write(`${String(error)}\n`);
13
+ process.exitCode = 1;
14
+ }