pi-better-harness 0.45.7 → 0.46.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 (68) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +7 -0
  3. package/extensions/task-context/index.ts +10 -1
  4. package/node_modules/pi-better-background-tasks/README.md +13 -0
  5. package/node_modules/pi-better-background-tasks/package.json +4 -2
  6. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
  7. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -0
  8. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.gz +0 -0
  9. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -0
  10. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.gz +0 -0
  11. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -0
  12. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.gz +0 -0
  13. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -0
  14. package/node_modules/pi-better-background-tasks/runtime-client/scripts/private-runtime/format.mjs +90 -0
  15. package/node_modules/pi-better-background-tasks/runtime-client/src/daemon-owner.mjs +171 -0
  16. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/client.mjs +129 -0
  17. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/root.mjs +41 -0
  18. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/socket.mjs +9 -0
  19. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/status-cli.mjs +14 -0
  20. package/node_modules/pi-better-background-tasks/runtime-client/src/startup/artifact.mjs +76 -0
  21. package/node_modules/pi-better-background-tasks/runtime-client/src/startup/install.mjs +184 -0
  22. package/node_modules/pi-better-background-tasks/runtime-client/src/startup/managed-types.mjs +1 -0
  23. package/node_modules/pi-better-background-tasks/runtime-client/src/startup/runtime.mjs +120 -0
  24. package/node_modules/pi-better-background-tasks/src/shared-navigator.ts +10 -4
  25. package/node_modules/pi-better-goal/README.md +10 -3
  26. package/node_modules/pi-better-goal/package.json +1 -1
  27. package/node_modules/pi-better-goal/src/index.ts +46 -11
  28. package/node_modules/pi-better-goal/src/preferences.ts +6 -3
  29. package/node_modules/pi-better-goal/src/settings-page.ts +2 -1
  30. package/node_modules/pi-better-goal/src/shared-assignment-projection.mjs +1 -13
  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-projection.mjs +1 -13
  35. package/node_modules/pi-better-subagents/assignment-report.ts +92 -0
  36. package/node_modules/pi-better-subagents/child-operations.ts +2 -0
  37. package/node_modules/pi-better-subagents/child-ownership.ts +1 -1
  38. package/node_modules/pi-better-subagents/index.ts +101 -24
  39. package/node_modules/pi-better-subagents/list.mjs +2 -1
  40. package/node_modules/pi-better-subagents/navigator.mjs +2 -1
  41. package/node_modules/pi-better-subagents/operation-bridge-types.ts +18 -1
  42. package/node_modules/pi-better-subagents/output-payload.ts +2 -1
  43. package/node_modules/pi-better-subagents/package.json +4 -2
  44. package/node_modules/pi-better-subagents/registry.ts +4 -2
  45. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
  46. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -0
  47. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
  48. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -0
  49. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
  50. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -0
  51. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
  52. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -0
  53. package/node_modules/pi-better-subagents/runtime-client/scripts/private-runtime/format.mjs +90 -0
  54. package/node_modules/pi-better-subagents/runtime-client/src/daemon-owner.mjs +171 -0
  55. package/node_modules/pi-better-subagents/runtime-client/src/runtime/client.mjs +129 -0
  56. package/node_modules/pi-better-subagents/runtime-client/src/runtime/root.mjs +41 -0
  57. package/node_modules/pi-better-subagents/runtime-client/src/runtime/socket.mjs +9 -0
  58. package/node_modules/pi-better-subagents/runtime-client/src/runtime/status-cli.mjs +14 -0
  59. package/node_modules/pi-better-subagents/runtime-client/src/startup/artifact.mjs +76 -0
  60. package/node_modules/pi-better-subagents/runtime-client/src/startup/install.mjs +184 -0
  61. package/node_modules/pi-better-subagents/runtime-client/src/startup/managed-types.mjs +1 -0
  62. package/node_modules/pi-better-subagents/runtime-client/src/startup/runtime.mjs +120 -0
  63. package/node_modules/pi-better-subagents/session-store.ts +58 -16
  64. package/node_modules/pi-better-subagents/shared-navigator.ts +10 -4
  65. package/node_modules/pi-better-subagents/tools.ts +15 -2
  66. package/node_modules/pi-better-subagents/worker-operations-host.ts +3 -0
  67. package/node_modules/pi-better-subagents/worker-waits.ts +50 -13
  68. package/package.json +4 -4
@@ -0,0 +1,76 @@
1
+ import { readFileSync, readdirSync, lstatSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { gzipSync, gunzipSync } from "node:zlib";
5
+ import { digest, stable, validateBuild, validatePayload, validateStaged } from "../../scripts/private-runtime/format.mjs";
6
+ export const ownPackageDir = fileURLToPath(new URL("../../", import.meta.url));
7
+ /** Only shipped source and explicitly named runtime resources enter the build. */
8
+ export function createServerArtifact(options) {
9
+ const root = options.packageDir ?? ownPackageDir;
10
+ for (const path of ["package.json", "scripts", "scripts/private-runtime", "scripts/private-runtime/package-lock.json"]) {
11
+ if (lstatSync(join(root, path)).isSymbolicLink())
12
+ throw new Error(`Artifact: symlink is forbidden: ${path}`);
13
+ }
14
+ const metadata = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
15
+ const lock = JSON.parse(readFileSync(join(root, "scripts/private-runtime/package-lock.json"), "utf8"));
16
+ const files = [];
17
+ function add(path) {
18
+ const stat = lstatSync(join(root, path));
19
+ if (stat.isSymbolicLink())
20
+ throw new Error(`Artifact: symlink is forbidden: ${path}`);
21
+ if (stat.isDirectory()) {
22
+ for (const name of readdirSync(join(root, path)).sort()) {
23
+ if (["node_modules", ".git", "test-support"].includes(name) || name.startsWith(".env") || ["auth.json", "settings.json"].includes(name))
24
+ continue;
25
+ add(`${path}/${name}`);
26
+ }
27
+ }
28
+ else if (stat.isFile()) {
29
+ if (stat.size > 12 * 1024 * 1024)
30
+ throw new Error(`Artifact: oversized source file: ${path}`);
31
+ files.push({ path, data: readFileSync(join(root, path)).toString("base64") });
32
+ if (files.length > 10000)
33
+ throw new Error("Artifact: file count limit");
34
+ }
35
+ else
36
+ throw new Error(`Artifact: non-regular source: ${path}`);
37
+ }
38
+ add("src");
39
+ for (const name of ["format.ts", "installer.ts", "package.json", "package-lock.json"])
40
+ add(`scripts/private-runtime/${name}`);
41
+ files.push({ path: "package.json", data: Buffer.from(stable({ name: metadata.name, version: metadata.version, type: "module" })).toString("base64") });
42
+ files.sort((a, b) => a.path.localeCompare(b.path, "en"));
43
+ const identity = {
44
+ format: 1, sourceDigest: digest(stable(files)), piSdkVersion: lock.packages[""].dependencies["@earendil-works/pi-coding-agent"],
45
+ nodeVersion: "24.14.1", platform: options.platform, dependencyLockDigest: digest(stable(lock)), protocolVersion: 1, serverVersion: metadata.version,
46
+ };
47
+ const build = { ...identity, contentId: digest(stable(identity)) };
48
+ const payload = { format: 1, build, files };
49
+ validatePayload(payload);
50
+ const bytes = gzipSync(stable(payload), { level: 9 });
51
+ return { build, bytes, sha256: digest(bytes) };
52
+ }
53
+ export function decodeServerArtifact(artifact) {
54
+ if (artifact.bytes.length > 32 * 1024 * 1024 || digest(artifact.bytes) !== artifact.sha256)
55
+ throw new Error("Artifact: compressed integrity mismatch or size limit");
56
+ const payload = validatePayload(JSON.parse(gunzipSync(artifact.bytes, { maxOutputLength: 64 * 1024 * 1024 }).toString("utf8")));
57
+ if (stable(payload.build) !== stable(artifact.build))
58
+ throw new Error("Artifact: build identity mismatch");
59
+ return payload;
60
+ }
61
+ export function readOwnBuild() {
62
+ try {
63
+ return validateBuild(JSON.parse(readFileSync(join(ownPackageDir, "managed-build.json"), "utf8")));
64
+ }
65
+ catch (error) {
66
+ if (error.code === "ENOENT")
67
+ return undefined;
68
+ throw error;
69
+ }
70
+ }
71
+ export function readStagedRuntime(manifestPath) {
72
+ const runtime = validateStaged(JSON.parse(readFileSync(manifestPath, "utf8")));
73
+ if (runtime.manifestPath !== manifestPath || dirname(manifestPath) !== runtime.root)
74
+ throw new Error("Staging: manifest location mismatch");
75
+ return runtime;
76
+ }
@@ -0,0 +1,184 @@
1
+ import { randomUUID, createHash } from "node:crypto";
2
+ import { posix } from "node:path";
3
+ import { decodeServerArtifact } from "./artifact.mjs";
4
+ import { absolutePath, probeRemoteRuntime, shellQuote } from "./runtime.mjs";
5
+ import { NODE_CHECKSUMS, NODE_EXECUTABLE_CHECKSUMS, validateStaged } from "../../scripts/private-runtime/format.mjs";
6
+ async function download(url, integrity, signal) {
7
+ const response = await fetch(url, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(120_000)]) : AbortSignal.timeout(120_000), redirect: "error" });
8
+ if (!response.ok || !response.body)
9
+ throw new Error(`Runtime download: HTTP ${response.status} for ${url}`);
10
+ const parts = [];
11
+ let size = 0;
12
+ for await (const chunk of response.body) {
13
+ size += chunk.length;
14
+ if (size > 128 * 1024 * 1024)
15
+ throw new Error("Runtime download: archive size limit");
16
+ parts.push(Buffer.from(chunk));
17
+ }
18
+ const bytes = Buffer.concat(parts);
19
+ const [algorithm, expected] = integrity.split("-", 2);
20
+ if (createHash(algorithm).update(bytes).digest(algorithm === "sha256" ? "hex" : "base64") !== expected)
21
+ throw new Error(`Runtime download: integrity mismatch for ${url}`);
22
+ return bytes;
23
+ }
24
+ /** Pure staging: never runs a launcher, starts a daemon, or writes a registration. */
25
+ export async function stageRuntime(options) {
26
+ const { run, artifact, signal, onProgress } = options;
27
+ const payload = decodeServerArtifact(artifact);
28
+ signal?.throwIfAborted();
29
+ onProgress?.("probe");
30
+ const probe = await probeRemoteRuntime(run, { signal, registration: false });
31
+ if (probe.explicitCommand)
32
+ throw new Error("Runtime staging: explicit PI_SERVER_COMMAND opts out of managed installation");
33
+ if (probe.platform !== artifact.build.platform)
34
+ throw new Error("Runtime staging: artifact platform does not match target");
35
+ const root = posix.normalize(absolutePath(options.installRoot ?? `${probe.home}/.pi-better-server/managed`, "installRoot"));
36
+ if (root === "/" || root.split("/").includes("node_modules"))
37
+ throw new Error("Runtime staging: releases must be outside node_modules");
38
+ const owner = randomUUID();
39
+ const work = `${root}/.stage-${owner}`;
40
+ const q = shellQuote;
41
+ const checked = async (command, input, timeoutMs = 30_000) => {
42
+ signal?.throwIfAborted();
43
+ const result = await run(command, input, timeoutMs);
44
+ signal?.throwIfAborted();
45
+ if (result.exitCode !== 0 || result.timedOut)
46
+ throw new Error(`Runtime staging: ${result.stderr || "remote command failed"}`);
47
+ return result;
48
+ };
49
+ let cancellation;
50
+ let setupAttempted = false;
51
+ const cancel = () => { cancellation = run(`: > ${q(`${work}/cancel`)}`, undefined, 5000).catch(() => undefined); };
52
+ try {
53
+ signal?.throwIfAborted();
54
+ setupAttempted = true;
55
+ const setup = await run(`set -eu; umask 077; p=${q(root)}; while [ "$p" != / ]; do [ ! -L "$p" ] || { echo 'permission: symlink install root' >&2; exit 1; }; p=$(dirname "$p"); done; mkdir -p ${q(root)}; mkdir ${q(work)}; printf %s ${q(owner)} > ${q(`${work}/.stage-owner`)}`, undefined, 30_000);
56
+ if (setup.exitCode !== 0 || setup.timedOut)
57
+ throw new Error(`Runtime staging setup: ${setup.stderr || "remote command failed"}`);
58
+ signal?.throwIfAborted();
59
+ signal?.addEventListener("abort", cancel, { once: true });
60
+ const finalRoot = `${root}/releases/${artifact.build.contentId}`;
61
+ const cachedArtifact = `${finalRoot}/artifact.gz`;
62
+ const artifactPath = `${work}/artifact.gz`;
63
+ // Older releases may lack the archive. Its contents are authenticated by the fresh installer against the requested build.
64
+ const archiveCache = await checked(`set -eu
65
+ p=${q(finalRoot)}
66
+ while [ "$p" != / ]; do
67
+ [ ! -L "$p" ] || { echo 'corrupt cache: symlink release path' >&2; exit 1; }
68
+ [ ! -e "$p" ] || { [ -d "$p" ] && [ -x "$p" ]; } || { echo 'corrupt cache: unsafe release directory' >&2; exit 1; }
69
+ p=$(dirname "$p")
70
+ done
71
+ if [ -L ${q(cachedArtifact)} ]; then echo 'corrupt cache: artifact symlink' >&2; exit 1; fi
72
+ if [ ! -e ${q(cachedArtifact)} ]; then
73
+ if [ -e ${q(finalRoot)} ]; then printf 'legacy\\n'; else printf 'absent\\n'; fi
74
+ exit 0
75
+ fi
76
+ [ -f ${q(cachedArtifact)} ] || { echo 'corrupt cache: expected regular artifact' >&2; exit 1; }
77
+ [ "$(wc -c < ${q(cachedArtifact)})" -le 33554432 ] || { echo 'corrupt cache: artifact size limit' >&2; exit 1; }
78
+ cp ${q(cachedArtifact)} ${q(artifactPath)}
79
+ [ "$(wc -c < ${q(artifactPath)})" -le 33554432 ] || { echo 'corrupt cache: artifact size limit' >&2; exit 1; }
80
+ if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(artifactPath)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(artifactPath)} | cut -d ' ' -f 1); fi
81
+ printf 'reuse:%s\\n' "$actual"`, undefined, 120_000);
82
+ const archiveResponse = archiveCache.stdout.trim();
83
+ const archiveDigest = /^reuse:([a-f0-9]{64})$/.exec(archiveResponse)?.[1];
84
+ const archiveState = archiveDigest ? "reuse" : archiveResponse;
85
+ if (archiveState !== "reuse" && archiveState !== "absent" && archiveState !== "legacy")
86
+ throw new Error("Runtime staging: unexpected artifact cache probe result");
87
+ if (archiveState !== "reuse") {
88
+ onProgress?.("verification-upload");
89
+ await checked(`cat > ${q(artifactPath)}`, artifact.bytes, 120_000);
90
+ }
91
+ for (const name of ["installer.ts", "format.ts"]) {
92
+ const file = payload.files.find((entry) => entry.path === `scripts/private-runtime/${name}`);
93
+ await checked(`cat > ${q(`${work}/${name}`)}`, Buffer.from(file.data, "base64"));
94
+ }
95
+ const cachedNode = `${finalRoot}/node/bin/node`;
96
+ const node = `${work}/node/bin/node`;
97
+ onProgress?.("verifying");
98
+ // Authenticate the scratch copy before executing any bytes from the cached release.
99
+ const cached = await checked(`set -eu
100
+ p=${q(`${root}/releases`)}
101
+ while [ "$p" != / ]; do
102
+ [ ! -L "$p" ] || { echo 'corrupt cache: symlink release path' >&2; exit 1; }
103
+ [ ! -e "$p" ] || { [ -d "$p" ] && [ -x "$p" ]; } || { echo 'corrupt cache: unsafe release directory' >&2; exit 1; }
104
+ p=$(dirname "$p")
105
+ done
106
+ [ ! -L ${q(finalRoot)} ] || { echo 'corrupt cache: release symlink' >&2; exit 1; }
107
+ if [ ! -e ${q(finalRoot)} ]; then printf 'absent\\n'; exit 0; fi
108
+ [ -d ${q(finalRoot)} ] && [ -x ${q(finalRoot)} ] || { echo 'corrupt cache: expected accessible release directory' >&2; exit 1; }
109
+ p=${q(cachedNode)}
110
+ while [ "$p" != ${q(finalRoot)} ]; do
111
+ [ ! -L "$p" ] || { echo 'corrupt cache: symlink Node path' >&2; exit 1; }
112
+ p=$(dirname "$p")
113
+ done
114
+ [ -f ${q(cachedNode)} ] && [ -x ${q(cachedNode)} ] || { echo 'corrupt cache: expected regular Node executable' >&2; exit 1; }
115
+ mkdir -p ${q(`${work}/node/bin`)}
116
+ cp ${q(cachedNode)} ${q(node)}
117
+ if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(node)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(node)} | cut -d ' ' -f 1); fi
118
+ [ "$actual" = ${q(NODE_EXECUTABLE_CHECKSUMS[probe.platform])} ] || { echo 'Node executable integrity mismatch' >&2; exit 1; }
119
+ printf 'reuse\\n'`, undefined, 120_000);
120
+ const cachedState = cached.stdout.trim();
121
+ if (cachedState !== "reuse" && cachedState !== "absent")
122
+ throw new Error("Runtime staging: unexpected cache probe result");
123
+ if (cachedState === "absent" && archiveState !== "absent")
124
+ throw new Error("Runtime staging: cached release disappeared during verification");
125
+ const reuse = cachedState === "reuse";
126
+ if (!reuse) {
127
+ if (options.offline)
128
+ throw new Error(`Offline cache miss: pinned Node ${artifact.build.nodeVersion} and runtime ${artifact.build.contentId} are not cached at ${finalRoot}; connect once to install them`);
129
+ onProgress?.("node-download");
130
+ signal?.throwIfAborted();
131
+ const archive = `node-v${artifact.build.nodeVersion}-${probe.platform}`;
132
+ const url = `https://nodejs.org/dist/v${artifact.build.nodeVersion}/${archive}.tar.gz`;
133
+ const sha = NODE_CHECKSUMS[probe.platform];
134
+ const tar = `${work}/node.tar.gz`;
135
+ const remote = await run(`curl -q --fail --silent --show-error --location --proto '=https' --connect-timeout 10 --max-time 120 ${q(url)} -o ${q(tar)}`, undefined, 125_000);
136
+ signal?.throwIfAborted();
137
+ if (remote.exitCode !== 0 || remote.timedOut) {
138
+ onProgress?.("node-upload");
139
+ await checked(`cat > ${q(tar)}`, await download(url, `sha256-${sha}`, signal), 120_000);
140
+ }
141
+ await checked(`set -eu; if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(tar)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(tar)} | cut -d ' ' -f 1); fi; [ "$actual" = ${q(sha)} ] || { echo 'Node archive integrity mismatch' >&2; exit 1; }; tar -xzf ${q(tar)} -C ${q(work)}; mv ${q(`${work}/${archive}`)} ${q(`${work}/node`)}; rm ${q(tar)}`, undefined, 120_000);
142
+ }
143
+ const invoke = (mode) => `env -i HOME=${q(`${work}/home`)} PATH=${q(`${work}/node/bin:/usr/bin:/bin`)} ${q(node)} ${q(`${work}/installer.ts`)} ${q(work)} ${q(root)} ${q(archiveDigest ?? artifact.sha256)} ${mode} ${q(artifact.build.contentId)}`;
144
+ if (!reuse)
145
+ onProgress?.("dependencies");
146
+ signal?.throwIfAborted();
147
+ let installed = await run(invoke(reuse ? "reuse-only" : "online"), undefined, 600_000);
148
+ signal?.throwIfAborted();
149
+ if (!reuse && installed.exitCode === 75) {
150
+ onProgress?.("dependencies-upload");
151
+ const lock = JSON.parse(Buffer.from(payload.files.find((f) => f.path === "scripts/private-runtime/package-lock.json").data, "base64").toString());
152
+ await checked(`mkdir -p ${q(`${work}/archives`)}`);
153
+ const packages = new Map();
154
+ for (const pkg of Object.values(lock.packages))
155
+ if (pkg.resolved)
156
+ packages.set(pkg.integrity, pkg.resolved);
157
+ const entries = [...packages];
158
+ for (let offset = 0; offset < entries.length; offset += 4) {
159
+ const batch = await Promise.allSettled(entries.slice(offset, offset + 4).map(async ([integrity, url], index) => {
160
+ await checked(`cat > ${q(`${work}/archives/${offset + index}.tgz`)}`, await download(url, integrity, signal), 120_000);
161
+ }));
162
+ const failed = batch.find((result) => result.status === "rejected");
163
+ if (failed?.status === "rejected")
164
+ throw failed.reason;
165
+ }
166
+ installed = await run(invoke("offline"), undefined, 600_000);
167
+ signal?.throwIfAborted();
168
+ }
169
+ if (installed.exitCode !== 0 || installed.timedOut)
170
+ throw new Error(`Runtime staging: ${installed.stderr || "installer failed"}`);
171
+ const runtime = validateStaged(JSON.parse(installed.stdout));
172
+ if (runtime.build.contentId !== artifact.build.contentId || runtime.installRoot !== root)
173
+ throw new Error("Runtime staging: unexpected published identity");
174
+ onProgress?.("staged");
175
+ return runtime;
176
+ }
177
+ finally {
178
+ signal?.removeEventListener("abort", cancel);
179
+ await cancellation;
180
+ // Only this attempt's scratch directory. Published releases and other owners are never removed.
181
+ if (setupAttempted)
182
+ await run(`if [ ! -L ${q(work)} ] && [ -f ${q(`${work}/.stage-owner`)} ] && [ "$(cat ${q(`${work}/.stage-owner`)})" = ${q(owner)} ]; then if [ -f ${q(`${work}/installer.pid`)} ] && kill -0 "$(cat ${q(`${work}/installer.pid`)})" 2>/dev/null; then : > ${q(`${work}/cancel`)}; else rm -rf ${q(work)}; fi; fi`, undefined, 30_000).catch(() => undefined);
183
+ }
184
+ }
@@ -0,0 +1,120 @@
1
+ import { accessSync, constants, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join, resolve } from "node:path";
4
+ export const INSTALL_GUIDANCE = "Install/register pi-better-server with scripts/bootstrap-host.sh, or set PI_SERVER_COMMAND to an absolute installed pi-server launcher. No packages were installed.";
5
+ export function absolutePath(value, name) {
6
+ if (typeof value !== "string" || !isAbsolute(value) || /[\0\r\n]/.test(value)) {
7
+ throw new Error(`${name} must be a literal absolute path`);
8
+ }
9
+ return value;
10
+ }
11
+ export function parseRuntime(text) {
12
+ const data = JSON.parse(text);
13
+ if (!data || data.version !== 1 || data.agent !== "pi")
14
+ throw new Error("Unsupported installed Pi runtime registration (expected version 1, agent pi)");
15
+ return {
16
+ version: 1, agent: "pi",
17
+ launcher: absolutePath(data.launcher, "runtime.launcher"),
18
+ agentDir: absolutePath(data.agentDir, "runtime.agentDir"),
19
+ defaultServerDir: absolutePath(data.defaultServerDir, "runtime.defaultServerDir"),
20
+ };
21
+ }
22
+ export function registeredRuntime(env = process.env) {
23
+ const path = join(env.HOME || homedir(), ".pi", "remote-server.json");
24
+ let text;
25
+ try {
26
+ text = readFileSync(path, "utf8");
27
+ }
28
+ catch (error) {
29
+ if (error.code === "ENOENT")
30
+ return undefined;
31
+ throw new Error(`Runtime discovery: cannot read ${path}: ${String(error)}`);
32
+ }
33
+ try {
34
+ return parseRuntime(text);
35
+ }
36
+ catch (error) {
37
+ throw new Error(`Runtime discovery: invalid ${path}: ${String(error)}`);
38
+ }
39
+ }
40
+ /** Used by a known launcher to describe itself, including pre-registration bootstrap installs. */
41
+ export function launcherRuntime(env = process.env) {
42
+ const home = env.HOME || homedir();
43
+ const agentDir = resolve(env.PI_CODING_AGENT_DIR || join(home, ".pi", "agent"));
44
+ return parseRuntime(JSON.stringify({
45
+ version: 1, agent: "pi",
46
+ launcher: env.PI_SERVER_COMMAND || env.PI_SERVER_LAUNCHER || join(home, ".pi-better-server", "bin", "pi-server"),
47
+ agentDir,
48
+ defaultServerDir: resolve(env.PI_SERVER_DIR || join(agentDir, "server")),
49
+ }));
50
+ }
51
+ export function discoverLocalRuntime() {
52
+ const explicit = process.env.PI_SERVER_COMMAND || process.env.PI_SERVER_LAUNCHER;
53
+ const registered = explicit ? undefined : registeredRuntime();
54
+ const runtime = explicit ? launcherRuntime() : registered ?? launcherRuntime();
55
+ try {
56
+ accessSync(runtime.launcher, constants.X_OK);
57
+ }
58
+ catch (error) {
59
+ // Local development/manual daemons never required an installed launcher. Keep that transport path.
60
+ if (!explicit && !registered && error.code === "ENOENT")
61
+ return undefined;
62
+ throw new Error(`Runtime discovery: launcher not executable: ${runtime.launcher}. ${INSTALL_GUIDANCE}`);
63
+ }
64
+ // Registration owns these paths; the client's agent/server environment must not rewrite its identity.
65
+ return registered ? { ...runtime, discoveryEnv: {
66
+ PI_CODING_AGENT_DIR: registered.agentDir,
67
+ PI_SERVER_DIR: registered.defaultServerDir,
68
+ } } : runtime;
69
+ }
70
+ /** Read-only managed probe. Legacy discovery deliberately keeps its existing failure contract. */
71
+ export async function probeRemoteRuntime(run, options = {}) {
72
+ options.signal?.throwIfAborted();
73
+ const command = options.command ? absolutePath(options.command, "PI_SERVER_COMMAND") : undefined;
74
+ const result = await run(`${command ? `PI_SERVER_COMMAND=${shellQuote(command)}; export PI_SERVER_COMMAND\n` : ""}if [ -n "\${PI_SERVER_COMMAND:-}" ]; then
75
+ case "$PI_SERVER_COMMAND" in /*) ;; *) printf '%s\\n' 'Runtime probe: PI_SERVER_COMMAND must be an absolute launcher path' >&2; exit 1 ;; esac
76
+ fi
77
+ printf '%s\\n' "$HOME" "$(uname -s)" "$(uname -m)" "\${PI_SERVER_COMMAND:-}"
78
+ if ${options.registration === false ? "false" : '[ -n "${PI_SERVER_COMMAND:-}" ]'}; then
79
+ printf 'registered\\n'
80
+ exec "$PI_SERVER_COMMAND" runtime --agent pi
81
+ elif ${options.registration === false ? "false" : '[ -e "$HOME/.pi/remote-server.json" ] || [ -L "$HOME/.pi/remote-server.json" ]'}; then
82
+ printf 'registered\\n'
83
+ cat "$HOME/.pi/remote-server.json"
84
+ elif ${options.registration === false ? "false" : '[ -x "$HOME/.pi-better-server/bin/pi-server" ]'}; then
85
+ printf 'registered\\n'
86
+ exec "$HOME/.pi-better-server/bin/pi-server" runtime --agent pi
87
+ else
88
+ printf 'absent\\n'
89
+ fi`, undefined, options.timeoutMs ?? 15_000);
90
+ options.signal?.throwIfAborted();
91
+ if (result.exitCode !== 0 || result.timedOut)
92
+ throw new Error(`Runtime probe: ${result.stderr || "remote command failed"}`);
93
+ const [home, os, arch, explicitCommand, state, ...registration] = result.stdout.split("\n");
94
+ absolutePath(home, "remote HOME");
95
+ const platform = `${os === "Linux" ? "linux" : os === "Darwin" ? "darwin" : "unsupported"}-${arch === "x86_64" ? "x64" : arch === "aarch64" || arch === "arm64" ? "arm64" : "unsupported"}`;
96
+ if (!["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64"].includes(platform))
97
+ throw new Error(`Runtime probe: unsupported platform ${os}/${arch}`);
98
+ const text = registration.join("\n").trim();
99
+ if (!text && state === "registered")
100
+ throw new Error("Runtime probe: registration or explicit launcher returned no registration");
101
+ return { home: home, platform: platform, ...(explicitCommand ? { explicitCommand: absolutePath(explicitCommand, "PI_SERVER_COMMAND") } : {}), ...(text ? { runtime: parseRuntime(text) } : {}) };
102
+ }
103
+ export function shellQuote(value) {
104
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
105
+ }
106
+ /** Discovery needs only the remote shell: JSON is parsed and validated by the caller, not by shell tools. */
107
+ export function remoteRuntimeScript(command) {
108
+ const override = command ? `PI_SERVER_COMMAND=${shellQuote(absolutePath(command, "PI_SERVER_COMMAND"))}; export PI_SERVER_COMMAND\n` : "";
109
+ return `${override}if [ -n "\${PI_SERVER_COMMAND:-}" ]; then
110
+ case "$PI_SERVER_COMMAND" in /*) ;; *) printf '%s\\n' 'Runtime discovery: PI_SERVER_COMMAND must be an absolute launcher path' >&2; exit 1 ;; esac
111
+ exec "$PI_SERVER_COMMAND" runtime --agent pi
112
+ elif [ -f "$HOME/.pi/remote-server.json" ]; then
113
+ cat "$HOME/.pi/remote-server.json"
114
+ elif [ -x "$HOME/.pi-better-server/bin/pi-server" ]; then
115
+ exec "$HOME/.pi-better-server/bin/pi-server" runtime --agent pi
116
+ else
117
+ printf '%s\\n' ${shellQuote(`Runtime discovery: ${INSTALL_GUIDANCE}`)} >&2
118
+ exit 1
119
+ fi`;
120
+ }
@@ -90,6 +90,7 @@ type NavigatorState = {
90
90
  lastHint?: string | null;
91
91
  lastMainListLines?: string[];
92
92
  lastMainListSignature?: string;
93
+ mainListRows?: InternalRow[];
93
94
  mainListWidgetInstalled?: boolean;
94
95
  mainListRequestRender?: () => void;
95
96
  mainListSelectedId?: string;
@@ -121,6 +122,7 @@ export const NAVIGATOR_STATUS_KEY = "background-work-nav";
121
122
  export const CLOSE_CONFIRM_STATUS_KEY = "background-work-close";
122
123
  export const MAIN_LIST_WIDGET_KEY = "background-work-list";
123
124
  export const DETAIL_TICK_MS = 10_000;
125
+ export const MAIN_LIST_REFRESH_MS = 1_000;
124
126
  export const CLOSE_ARM_MS = 3000;
125
127
  export const DEFAULT_LOG_TAIL_ROWS = 25;
126
128
  export const LOG_TAIL_ROW_CHOICES = [10, 25] as const;
@@ -208,6 +210,7 @@ export function ensureBackgroundWorkNavigator(ctx: ExtensionContext, deps: HostD
208
210
  try { setNavigatorPanel(ctx, MAIN_LIST_WIDGET_KEY, undefined); } catch { /* ignore */ }
209
211
  s.mainListWidgetInstalled = false;
210
212
  s.mainListRequestRender = undefined;
213
+ s.mainListRows = undefined;
211
214
  s.mainListDeadlineScheduler?.dispose();
212
215
  s.mainListDeadlineScheduler = createRenderScheduler(() => refreshMainListWidget());
213
216
  installNavigatorEditor(ctx.ui as any, deps);
@@ -242,6 +245,7 @@ export function disposeBackgroundWorkNavigator(ctx?: ExtensionContext, owner?: s
242
245
  s.lastHint = undefined;
243
246
  s.lastMainListLines = undefined;
244
247
  s.lastMainListSignature = undefined;
248
+ s.mainListRows = undefined;
245
249
  s.mainListDeadlineScheduler?.dispose();
246
250
  s.mainListDeadlineScheduler = undefined;
247
251
  s.mainListWidgetInstalled = false;
@@ -290,13 +294,15 @@ function refreshMainListWidget(): void {
290
294
  if (!ctx || !deps || !isNavigatorUiAvailable(ctx)) return;
291
295
  const now = Date.now();
292
296
  const rows = listRows(now);
297
+ s.mainListRows = rows;
293
298
  s.mainListDeadlineScheduler?.cancel();
294
299
  const nextExpiry = rows.reduce<number | undefined>((next, row) => {
295
300
  if (row.expiresAt === undefined || row.expiresAt <= now) return next;
296
301
  return next === undefined ? row.expiresAt : Math.min(next, row.expiresAt);
297
302
  }, undefined);
298
- if (nextExpiry !== undefined) {
299
- s.mainListDeadlineScheduler?.schedule(nextExpiry - now);
303
+ if (rows.length) {
304
+ // External writers cannot notify this host. Refresh independently of paint frequency.
305
+ s.mainListDeadlineScheduler?.schedule(Math.min(MAIN_LIST_REFRESH_MS, nextExpiry === undefined ? Infinity : nextExpiry - now));
300
306
  }
301
307
  syncMainListSelection(rows);
302
308
  const nextSignature = rows.length ? mainListSignature(rows, {
@@ -409,12 +415,12 @@ function createMainListWidget(tui: { requestRender?(): void }, theme: unknown, d
409
415
  if (!Number.isFinite(event.x) || event.x < 0 || event.x >= width) return undefined;
410
416
  if (!Number.isInteger(event.y) || event.y < 0 || event.y >= lineOwners.length) return undefined;
411
417
  const id = lineOwners[event.y];
412
- return id && listRows().some((row) => row.navigatorId === id) ? id : undefined;
418
+ return id && state().mainListRows?.some((row) => row.navigatorId === id) ? id : undefined;
413
419
  };
414
420
  const pointer = createPointerNavigation(rowAt, openNavigatorRow);
415
421
  return {
416
422
  render(width: number): string[] {
417
- const rows = listRows();
423
+ const rows = state().mainListRows ?? [];
418
424
  syncMainListSelection(rows);
419
425
  if (!rows.length) {
420
426
  state().lastMainListLines = undefined;
@@ -13,7 +13,7 @@ Use `pi-better-goal` when a Pi session should keep an explicit objective visible
13
13
  ## Core Features
14
14
 
15
15
  - `/goal` runtime for starting, pausing, resuming, completing, and clearing the current objective.
16
- - `/goal settings` opens an interactive settings page in the TUI. Select a row with Up/Down and toggle with Space/Enter; changes save immediately, and Escape closes the page. All three controls default to `on`. Automatic continuation controls idle and background-drain wakes; conversational resume controls the agent's Escape-pause resume tool; **Pause on Esc** controls whether editor Escape pauses the active goal. Goal kickoff, `/goal resume`, and `alt+g` remain available with these controls off. For scripts or non-interactive sessions, use `/goal settings auto-continue on|off`, `/goal settings conversational-resume on|off`, and `/goal settings pause-on-escape on|off`; bare `/goal settings` prints the saved values outside the TUI.
16
+ - `/goal settings` opens an interactive settings page in the TUI. Select a row with Up/Down and toggle with Space/Enter; changes save immediately, and Escape closes the page. Automatic continuation, conversational resume, and **Pause on Esc** default to `on`. **Auto-start Goal** defaults to `off` and is also available directly on the `/harness-settings` main page. Automatic continuation controls idle and background-drain wakes; conversational resume controls the agent's Escape-pause resume tool; Pause on Esc controls whether editor Escape pauses the active goal. Goal kickoff, `/goal resume`, and `alt+g` remain available with these controls off. For scripts or non-interactive sessions, use `/goal settings auto-continue on|off`, `/goal settings conversational-resume on|off`, `/goal settings pause-on-escape on|off`, or `/goal settings auto-start-from-outcome on|off`; bare `/goal settings` prints the saved values outside the TUI.
17
17
  - `escape` pauses the active goal by default, and it stays paused while you talk to the agent. With **Pause on Esc** off, observed editor Escape leaves the goal active while preserving native streaming interruption and menu/dialog cancellation. Automatic continuation remains independent. Hosts without terminal/focus inspection and unknown custom editors retain generic abort-to-pause behavior because they cannot identify Escape reliably. With conversational resume enabled, say "go" (the agent then calls `goal_resume`), or use `/goal resume` or `alt+g`. `/goal pause` resumes only through `/goal resume` or `alt+g`. Paused goals are never poked. On a macOS terminal without Option-as-Meta, `alt+g` types `©`; use `/goal resume` there.
18
18
  - Background work that finishes while an `ask_user_question` is pending is handed to the agent right after the answer.
19
19
  - A compact goal widget that does not replace Pi's footer.
@@ -28,13 +28,20 @@ When `pi-better-harness` is installed, its optional **Outcome & Todo** runtime o
28
28
 
29
29
  `/goal` does not install, enable, or configure Outcome & Todo. Install Harness and enable **Outcome & Todo** in `/harness-settings` if you want that shared outcome and checklist. Without Harness, this package keeps its standalone prompts and behavior unchanged. The stored Goal objective remains the raw original trigger (for example, a bound command invocation) so `/goal resume` can re-enter the work; it is not the authoritative business outcome when Harness owns one.
30
30
 
31
+ With **Auto-start Goal** enabled, a successful explicit `update_todo` outcome save can create and bind a Goal. The outcome must be active, unbound, have a nonempty objective and at least one nonempty `doneWhen` acceptance criterion. All criteria must contain text. Slash-shaped command invocations do not qualify; invoke those commands explicitly. Outcome & Todo hooks must also be enabled. The existing outcome, boundaries and Todo stay intact. No kickoff message is queued for the already-running tool turn; subsequent idle/background continuation obeys its existing setting and gates.
32
+
33
+ Existing active, paused or budget-limited Goals are never replaced or resumed. Refinements of a bound outcome do not create another Goal. A new unbound task can start after the previous Goal completes. Session restore, branch navigation and enabling the preference do not replay saved outcomes; the next explicit qualifying save is the trigger. Completing a checklist or outcome does not complete the Goal.
34
+
35
+ When a workflow already owns the session, the new Goal binds its registered coordinator without invoking it again. Its scheduler and completion checks continue to apply. An unavailable or invalid workflow coordinator prevents automatic creation.
36
+
31
37
  ## Settings Storage
32
38
 
33
39
  Goal preferences are saved only in Pi's global `~/.pi/agent/settings.json` under
34
40
  `piBetterHarness.goal` (or `$PI_CODING_AGENT_DIR/settings.json` when overridden).
35
41
  The payload retains `version: 1` and the boolean `autoContinue`,
36
- `conversationalResume`, and `pauseOnEscape` fields; omitted controls default to
37
- `true`. Updates preserve other Pi settings and other `piBetterHarness` keys.
42
+ `conversationalResume`, `pauseOnEscape`, and `autoStartFromOutcome` fields. The
43
+ first three default to `true`; `autoStartFromOutcome` defaults to `false`.
44
+ Updates preserve other Pi settings and other `piBetterHarness` keys.
38
45
 
39
46
  On first read, an existing `extensions/pi-better-goal-preferences.json` in the
40
47
  agent directory is validated and migrated when the global Goal key is absent.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-goal",
3
- "version": "0.13.2",
3
+ "version": "0.14.0",
4
4
  "description": "Pi extension for goal tracking with background-aware continuation.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -45,7 +45,7 @@ import { collectSubagentActivity } from "./subagents.js";
45
45
  import { currentWorkflowOwner, ISSUE_WORKFLOW_SKILLS, skillCommandName, workflowEntry, workflowOwnerFromSkill, WORKFLOW_ENTRY_TYPE } from "./workflow.js";
46
46
  import { completionGate, pauseGate, schedulerWaitUntil, operationResumeSchedulerGate } from "./workflow-gates.js";
47
47
  import { workflowRehydrateMessage, WORKFLOW_REHYDRATE_MESSAGE_TYPE } from "./rehydrate.js";
48
- import { requestTaskContext } from "./task-context.js";
48
+ import { canStartGoalFromOutcome, OUTCOME_ACCEPTED_EVENT, requestTaskContext, type OutcomeAcceptedEvent } from "./task-context.js";
49
49
  import {
50
50
  EVENT_ACTIVITY,
51
51
  EVENT_READY,
@@ -125,10 +125,10 @@ const GOAL_ACTIONS: readonly AutocompleteItem[] = [
125
125
  { value: "resume", label: "resume", description: "Resume the paused goal" },
126
126
  { value: "clear", label: "clear", description: "Remove the current goal" },
127
127
  { value: "complete", label: "complete", description: "Mark the current goal complete" },
128
- { value: "settings", label: "settings", description: "Inspect or persist goal continuation, conversational resume, and Escape pause controls" },
128
+ { value: "settings", label: "settings", description: "Inspect or persist goal continuation, resume, Escape pause, and Outcome auto-start controls" },
129
129
  ];
130
130
 
131
- const GOAL_SETTINGS = ["auto-continue", "conversational-resume", "pause-on-escape"] as const;
131
+ const GOAL_SETTINGS = ["auto-continue", "conversational-resume", "pause-on-escape", "auto-start-from-outcome"] as const;
132
132
 
133
133
  export function goalArgumentCompletions(argumentPrefix: string): AutocompleteItem[] | null {
134
134
  const prefix = argumentPrefix.trimStart().toLowerCase();
@@ -244,7 +244,7 @@ function formatGoal(
244
244
  goal: GoalSnapshot | null,
245
245
  continuation: ReturnType<typeof currentContinuationState> = null,
246
246
  stall = observeGoalStall(goal, continuation),
247
- preferences: GoalPreferences = { autoContinue: true, conversationalResume: true, pauseOnEscape: true },
247
+ preferences: GoalPreferences = { autoContinue: true, conversationalResume: true, pauseOnEscape: true, autoStartFromOutcome: false },
248
248
  permissions?: PermissionHold | null,
249
249
  ): string {
250
250
  const settings = formatPreferences(preferences);
@@ -285,6 +285,7 @@ function formatPreferences(preferences: GoalPreferences): string {
285
285
  `Automatic continuation setting: ${preferences.autoContinue ? "on" : "off"}${WAKE_DISABLED ? " (disabled by environment)" : ""}`,
286
286
  `Conversational resume setting: ${preferences.conversationalResume ? "on" : "off"}`,
287
287
  `Pause on Esc setting: ${preferences.pauseOnEscape ? "on" : "off"}`,
288
+ `Auto-start Goal setting: ${preferences.autoStartFromOutcome ? "on" : "off"}`,
288
289
  ].join("\n");
289
290
  }
290
291
 
@@ -341,7 +342,7 @@ export default function (pi: ExtensionAPI): void {
341
342
  let terminalInputIsEditor: (() => boolean) | undefined;
342
343
  let uiPromptDepth = 0;
343
344
  let lastAgentEvidence: ContinuationEvidence | null = null;
344
- let preferences: GoalPreferences = { autoContinue: true, conversationalResume: true, pauseOnEscape: true };
345
+ let preferences: GoalPreferences = { autoContinue: true, conversationalResume: true, pauseOnEscape: true, autoStartFromOutcome: false };
345
346
  /** Background items active when each pending blocking question started, keyed by tool call id. */
346
347
  const pendingQuestions = new Map<string, Map<string, BackgroundWorkItem>>();
347
348
 
@@ -396,7 +397,7 @@ export default function (pi: ExtensionAPI): void {
396
397
  ctx.ui.notify(message, type);
397
398
  };
398
399
 
399
- const setGoal = (goal: GoalSnapshot, ctx: ExtensionContext, source: GoalEntrySource): void => {
400
+ const setGoal = (goal: GoalSnapshot, ctx: ExtensionContext, source: GoalEntrySource, bindOutcome = false): void => {
400
401
  executionGeneration += 1;
401
402
  lastAgentEvidence = null;
402
403
  const previous = getGoal(ctx);
@@ -405,7 +406,7 @@ export default function (pi: ExtensionAPI): void {
405
406
  // Bridge lifecycle after the raw Goal entry is durable. Harness may own the
406
407
  // structured outcome, but Goal still owns its trigger, clocks, pauses, and wakes.
407
408
  if (!previous || previous.goalId !== goal.goalId) {
408
- requestTaskContext(pi, "start", goal);
409
+ requestTaskContext(pi, bindOutcome ? "bind" : "start", goal);
409
410
  } else if (goal.status === "complete") {
410
411
  requestTaskContext(pi, "complete", goal);
411
412
  } else if (goal.status === "paused" || goal.status === "budgetLimited") {
@@ -897,6 +898,24 @@ export default function (pi: ExtensionAPI): void {
897
898
  if (latestSnapshot) collectIfPossible();
898
899
  });
899
900
 
901
+ const unsubscribeOutcomeAccepted = pi.events.on(OUTCOME_ACCEPTED_EVENT, (value: unknown) => {
902
+ const ctx = currentCtx;
903
+ const event = value as Partial<OutcomeAcceptedEvent> | null;
904
+ if (!preferences.autoStartFromOutcome || !ctx || !event ||
905
+ typeof event.sessionId !== "string" || event.sessionId !== ctx.sessionManager.getSessionId() ||
906
+ !canStartGoalFromOutcome(event.outcome)) return;
907
+ const current = getGoal(ctx);
908
+ if (current && current.status !== "complete") return;
909
+ const objective = event.outcome.objective.trim();
910
+ if (validateObjective(objective)) return;
911
+ const owner = getWorkflow(ctx);
912
+ if (owner && !workflowAvailable(owner)) return;
913
+ const command = owner ? resolveGoalCommand(pi, `/skill:${owner.name}`) : null;
914
+ const goal = createGoalSnapshot(objective, null, undefined, command ?? undefined);
915
+ setGoal(goal, ctx, "runtime", true);
916
+ resetContinuationState(goal);
917
+ });
918
+
900
919
  const changePreference = async (ctx: ExtensionCommandContext, key: keyof GoalPreferences, enabled: boolean): Promise<void> => {
901
920
  const previous = preferences;
902
921
  preferences = writeGoalPreference(key, enabled);
@@ -923,7 +942,20 @@ export default function (pi: ExtensionAPI): void {
923
942
  }
924
943
  };
925
944
  const contribution = { id: "goal", label: "Goal", command: "/goal settings", open: openSettings };
926
- const registerSettings = () => pi.events.emit("harness-settings:register", contribution);
945
+ const autoStartControl = {
946
+ id: "goal-auto-start",
947
+ label: "Auto-start Goal",
948
+ values: ["Off", "On"],
949
+ get: () => preferences.autoStartFromOutcome ? "On" : "Off",
950
+ async change(value: string, ctx: ExtensionCommandContext) {
951
+ if (value !== "On" && value !== "Off") throw new Error("Invalid Auto-start Goal mode.");
952
+ await changePreference(ctx, "autoStartFromOutcome", value === "On");
953
+ },
954
+ };
955
+ const registerSettings = () => {
956
+ pi.events.emit("harness-settings:register", contribution);
957
+ pi.events.emit("harness-settings:register", autoStartControl);
958
+ };
927
959
  const unsubscribeSettingsRequest = pi.events.on("harness-settings:request", registerSettings);
928
960
  registerSettings();
929
961
 
@@ -943,13 +975,14 @@ export default function (pi: ExtensionAPI): void {
943
975
  const [, setting, mode, ...extra] = trimmed.split(/\s+/);
944
976
  if (setting !== undefined && (!GOAL_SETTINGS.includes(setting as typeof GOAL_SETTINGS[number]) ||
945
977
  (mode !== "on" && mode !== "off") || extra.length > 0)) {
946
- notifyGoal(ctx, "Usage: /goal settings [auto-continue|conversational-resume|pause-on-escape on|off]", "warning");
978
+ notifyGoal(ctx, "Usage: /goal settings [auto-continue|conversational-resume|pause-on-escape|auto-start-from-outcome on|off]", "warning");
947
979
  return;
948
980
  }
949
981
  if (setting !== undefined) {
950
982
  try {
951
983
  const key = setting === "auto-continue" ? "autoContinue"
952
- : setting === "conversational-resume" ? "conversationalResume" : "pauseOnEscape";
984
+ : setting === "conversational-resume" ? "conversationalResume"
985
+ : setting === "pause-on-escape" ? "pauseOnEscape" : "autoStartFromOutcome";
953
986
  await changePreference(ctx, key, mode === "on");
954
987
  } catch (error) {
955
988
  notifyGoal(ctx, error instanceof Error ? error.message : String(error), "error");
@@ -1232,6 +1265,7 @@ export default function (pi: ExtensionAPI): void {
1232
1265
  try {
1233
1266
  preferences = readGoalPreferences();
1234
1267
  } catch (error) {
1268
+ preferences = { ...preferences, autoStartFromOutcome: false };
1235
1269
  notifyGoal(ctx, error instanceof Error ? error.message : String(error), "error");
1236
1270
  }
1237
1271
  const restoredGoal = getGoal(ctx);
@@ -1559,6 +1593,7 @@ export default function (pi: ExtensionAPI): void {
1559
1593
  pi.on("session_shutdown", async (_event, ctx) => {
1560
1594
  if (typeof unsubscribeSettingsRequest === "function") unsubscribeSettingsRequest();
1561
1595
  if (typeof unsubscribeOperationAdmission === "function") unsubscribeOperationAdmission();
1596
+ if (typeof unsubscribeOutcomeAccepted === "function") unsubscribeOutcomeAccepted();
1562
1597
 
1563
1598
  executionGeneration += 1;
1564
1599
  sessionGeneration += 1;
@@ -1580,4 +1615,4 @@ export default function (pi: ExtensionAPI): void {
1580
1615
  // Best-effort cleanup.
1581
1616
  }
1582
1617
  });
1583
- }
1618
+ }