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.
- package/CHANGELOG.md +13 -0
- package/README.md +6 -6
- package/lib/codex-model-prompt.mjs +1 -1
- package/node_modules/pi-better-background-tasks/package.json +2 -2
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/win32-x64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/client.mjs +35 -7
- package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/root.mjs +38 -20
- package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/windows-directory.mjs +190 -0
- package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/windows-native.mjs +14 -4
- package/node_modules/pi-better-background-tasks/runtime-client/src/startup/stage-local.mjs +75 -47
- package/node_modules/pi-better-background-tasks/src/output.ts +4 -1
- package/node_modules/pi-better-background-tasks/src/registry.ts +1 -1
- package/node_modules/pi-better-background-tasks/src/shared-navigator.ts +27 -12
- package/node_modules/pi-better-background-tasks/src/shared-windows-native.mjs +14 -4
- package/node_modules/pi-better-background-tasks/src/supervisor/generated/shared-windows-native.mjs +14 -4
- package/node_modules/pi-better-goal/package.json +1 -1
- package/node_modules/pi-better-sandbox/package.json +1 -1
- package/node_modules/pi-better-subagents/README.md +28 -0
- package/node_modules/pi-better-subagents/agents-catalog-tool.ts +8 -2
- package/node_modules/pi-better-subagents/catalog-runtime.ts +4 -4
- package/node_modules/pi-better-subagents/config.ts +16 -0
- package/node_modules/pi-better-subagents/direct-owner.ts +92 -0
- package/node_modules/pi-better-subagents/direct-worker.mjs +20 -0
- package/node_modules/pi-better-subagents/effective-settings.ts +9 -1
- package/node_modules/pi-better-subagents/index.ts +162 -53
- package/node_modules/pi-better-subagents/managed-launch-client.ts +2 -2
- package/node_modules/pi-better-subagents/package.json +5 -2
- package/node_modules/pi-better-subagents/registry.ts +3 -0
- package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/artifacts/win32-x64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/src/runtime/client.mjs +35 -7
- package/node_modules/pi-better-subagents/runtime-client/src/runtime/root.mjs +38 -20
- package/node_modules/pi-better-subagents/runtime-client/src/runtime/windows-directory.mjs +190 -0
- package/node_modules/pi-better-subagents/runtime-client/src/runtime/windows-native.mjs +14 -4
- package/node_modules/pi-better-subagents/runtime-client/src/startup/stage-local.mjs +75 -47
- package/node_modules/pi-better-subagents/session-store.ts +6 -0
- package/node_modules/pi-better-subagents/settings-page.ts +11 -2
- package/node_modules/pi-better-subagents/shared-catalog.ts +15 -2
- package/node_modules/pi-better-subagents/shared-navigator.ts +27 -12
- package/node_modules/pi-better-subagents/shared-windows-native.d.mts +36 -0
- package/node_modules/pi-better-subagents/shared-windows-native.mjs +14 -4
- package/node_modules/pi-better-subagents/spawn.ts +16 -3
- package/node_modules/pi-better-subagents/stop.ts +6 -0
- package/node_modules/pi-better-subagents/tools.ts +1 -0
- package/node_modules/pi-better-subagents/work-observation.ts +64 -1
- package/package.json +8 -7
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
|
-
import { chmodSync, copyFileSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
-
import {
|
|
4
|
-
import { dirname, isAbsolute, join, parse,
|
|
2
|
+
import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { checkWindowsContents, checkWindowsExecuteAccess, ensureWindowsCodeDirectory, ensureWindowsDirectory } from "../runtime/windows-directory.mjs";
|
|
4
|
+
import { basename, dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
|
|
5
5
|
import { promisify } from "node:util";
|
|
6
|
+
import { windowsSystemRoot } from "../runtime/windows-native.mjs";
|
|
6
7
|
import { digest, nodeDistribution, validateStaged } from "../../scripts/private-runtime/format.mjs";
|
|
7
8
|
import { decodeServerArtifact } from "./artifact.mjs";
|
|
8
9
|
import { download } from "./install.mjs";
|
|
@@ -26,40 +27,64 @@ function checkDirectory(path, create) {
|
|
|
26
27
|
}
|
|
27
28
|
return true;
|
|
28
29
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
30
|
+
function prepareRoot(path) {
|
|
31
|
+
const root = resolve(path);
|
|
32
|
+
if (!isAbsolute(path) || root === parse(root).root || root.toLowerCase().split(sep).includes("node_modules") || /[\0\r\n]/.test(root))
|
|
33
|
+
throw new Error("permission: unsafe install root; supply an absolute, dedicated runtime directory");
|
|
34
|
+
if (windows)
|
|
35
|
+
ensureWindowsCodeDirectory(path);
|
|
36
|
+
else
|
|
37
|
+
checkDirectory(root, true);
|
|
38
|
+
if (realpathSync(root) !== root || (process.getuid && lstatSync(root).uid !== process.getuid()))
|
|
39
|
+
throw new Error("permission: unsafe install root");
|
|
40
|
+
if (windows) {
|
|
41
|
+
const locks = join(root, "locks"), releases = join(root, "releases");
|
|
42
|
+
ensureWindowsDirectory(locks);
|
|
43
|
+
ensureWindowsDirectory(releases);
|
|
44
|
+
// Exercise the directory operations used to lock and publish a build.
|
|
45
|
+
let probe = mkdtempSync(join(root, ".probe-"));
|
|
46
|
+
try {
|
|
47
|
+
const file = join(probe, "check.exe");
|
|
48
|
+
writeFileSync(file, "Pi runtime directory probe\n", { flag: "wx" });
|
|
49
|
+
checkWindowsExecuteAccess(file);
|
|
50
|
+
for (const parent of [locks, releases]) {
|
|
51
|
+
const target = join(parent, basename(probe));
|
|
52
|
+
renameSync(probe, target);
|
|
53
|
+
probe = target;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
rmSync(probe, { recursive: true, maxRetries: 3 });
|
|
58
|
+
}
|
|
36
59
|
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
60
|
+
return root;
|
|
61
|
+
}
|
|
62
|
+
export function prepareLocalRuntimeRoot(options) {
|
|
63
|
+
if (options.installRoot !== undefined)
|
|
64
|
+
return prepareRoot(options.installRoot);
|
|
65
|
+
const legacy = join(options.agentDir, "managed-runtime");
|
|
66
|
+
if (!windows)
|
|
67
|
+
return prepareRoot(legacy);
|
|
68
|
+
const local = process.env.LOCALAPPDATA;
|
|
69
|
+
const candidates = [
|
|
70
|
+
process.env.PI_SERVER_RUNTIME_ROOT,
|
|
71
|
+
existsSync(legacy) ? legacy : undefined,
|
|
72
|
+
local && isAbsolute(local) ? join(local, "PiBetter", "managed-runtime") : undefined,
|
|
73
|
+
legacy,
|
|
74
|
+
local && isAbsolute(local) ? join(local, "Programs", "PiBetter", "managed-runtime") : undefined,
|
|
75
|
+
];
|
|
76
|
+
const failures = [];
|
|
77
|
+
for (const path of new Set(candidates)) {
|
|
78
|
+
if (!path)
|
|
79
|
+
continue;
|
|
80
|
+
try {
|
|
81
|
+
return prepareRoot(path);
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
failures.push(`${path}: ${error instanceof Error ? error.message : String(error)}`);
|
|
85
|
+
}
|
|
48
86
|
}
|
|
49
|
-
|
|
50
|
-
if ($path -eq $env:PI_INSTALL_PROFILE) { break }
|
|
51
|
-
$path = [IO.Path]::GetDirectoryName($path)
|
|
52
|
-
if (-not $path) { throw "installation path left the user profile" }
|
|
53
|
-
}`;
|
|
54
|
-
const systemRoot = process.env.SystemRoot;
|
|
55
|
-
const check = execute(join(systemRoot, "System32/WindowsPowerShell/v1.0/powershell.exe"), ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], {
|
|
56
|
-
env: { SystemRoot: systemRoot, USERPROFILE: profile, TEMP: join(profile, "AppData/Local/Temp"), PI_INSTALL_ROOT: root, PI_INSTALL_PROFILE: profile },
|
|
57
|
-
signal, windowsHide: true, timeout: 45_000,
|
|
58
|
-
});
|
|
59
|
-
check.child.stdin?.end();
|
|
60
|
-
await check.catch(cause => {
|
|
61
|
-
throw new Error(`permission: could not verify Windows runtime directory ownership: ${cause.stderr || cause.signal || cause.code}`, { cause });
|
|
62
|
-
});
|
|
87
|
+
throw new Error(`permission: no usable Windows runtime root. ${failures.join("\n")}\nSet PI_SERVER_RUNTIME_ROOT to an approved private directory before starting pi.`);
|
|
63
88
|
}
|
|
64
89
|
export async function stageLocalRuntime(options) {
|
|
65
90
|
const { artifact, signal, onProgress } = options;
|
|
@@ -70,14 +95,8 @@ export async function stageLocalRuntime(options) {
|
|
|
70
95
|
throw new Error("Runtime staging: explicit PI_SERVER_COMMAND opts out of managed installation");
|
|
71
96
|
if (artifact.build.platform !== `${process.platform}-${process.arch}`)
|
|
72
97
|
throw new Error("Runtime staging: artifact platform does not match target");
|
|
73
|
-
const root =
|
|
74
|
-
|
|
75
|
-
throw new Error("Runtime staging: unsafe install root");
|
|
76
|
-
if (windows)
|
|
77
|
-
await checkWindowsRoot(root, signal);
|
|
78
|
-
checkDirectory(root, true);
|
|
79
|
-
if (realpathSync(root) !== root || (process.getuid && lstatSync(root).uid !== process.getuid()))
|
|
80
|
-
throw new Error("permission: unsafe install root");
|
|
98
|
+
const root = prepareLocalRuntimeRoot(options);
|
|
99
|
+
const systemRoot = windows ? windowsSystemRoot() : undefined;
|
|
81
100
|
const distribution = nodeDistribution(artifact.build.platform);
|
|
82
101
|
const finalRoot = join(root, "releases", artifact.build.contentId);
|
|
83
102
|
const work = mkdtempSync(join(root, ".stage-"));
|
|
@@ -88,6 +107,10 @@ export async function stageLocalRuntime(options) {
|
|
|
88
107
|
try {
|
|
89
108
|
signal?.throwIfAborted();
|
|
90
109
|
const reuse = checkDirectory(finalRoot, false);
|
|
110
|
+
if (windows && reuse) {
|
|
111
|
+
ensureWindowsDirectory(finalRoot, false);
|
|
112
|
+
checkWindowsContents(finalRoot);
|
|
113
|
+
}
|
|
91
114
|
const archivePath = join(work, "artifact.gz");
|
|
92
115
|
let sha = artifact.sha256;
|
|
93
116
|
const cached = join(finalRoot, "artifact.gz");
|
|
@@ -124,9 +147,9 @@ export async function stageLocalRuntime(options) {
|
|
|
124
147
|
writeFileSync(archive, await download(distribution.url, `sha256-${distribution.archiveSha256}`, signal));
|
|
125
148
|
// The entire official distribution is pinned before passing it to the system extractor.
|
|
126
149
|
// Extract into an empty, private directory using tar's default path and link protections.
|
|
127
|
-
const tar =
|
|
150
|
+
const tar = systemRoot ? join(systemRoot, "System32", "tar.exe") : "/usr/bin/tar";
|
|
128
151
|
await execute(tar, ["-xf", archive], { cwd: work, signal, timeout: 120_000, windowsHide: true,
|
|
129
|
-
env:
|
|
152
|
+
env: systemRoot ? { SystemRoot: systemRoot } : { PATH: "/usr/bin:/bin" } });
|
|
130
153
|
renameSync(join(work, distribution.directory), join(work, "node"));
|
|
131
154
|
}
|
|
132
155
|
if (!lstatSync(node).isFile() || digest(readFileSync(node)) !== distribution.executableSha256)
|
|
@@ -136,9 +159,14 @@ export async function stageLocalRuntime(options) {
|
|
|
136
159
|
if (!reuse)
|
|
137
160
|
onProgress?.("dependencies");
|
|
138
161
|
const home = join(work, "home");
|
|
139
|
-
const env = { HOME: home, ...(
|
|
162
|
+
const env = { HOME: home, ...(systemRoot ? { SystemRoot: systemRoot, USERPROFILE: home, TEMP: work, TMP: work } : {}),
|
|
140
163
|
PATH: dirname(node) };
|
|
141
|
-
const result = await execute(node, [join(work, "installer.ts"), work, root, sha, reuse ? "reuse-only" : "online", artifact.build.contentId, "--caller-cleans"], { cwd: work, env, windowsHide: true, encoding: "utf8", maxBuffer: 4 * 1024 * 1024 })
|
|
164
|
+
const result = await execute(node, [join(work, "installer.ts"), work, root, sha, reuse ? "reuse-only" : "online", artifact.build.contentId, "--caller-cleans"], { cwd: work, env, windowsHide: true, encoding: "utf8", maxBuffer: 4 * 1024 * 1024 }).catch(error => {
|
|
165
|
+
if (windows && ["EPERM", "EACCES"].includes(error.code)) {
|
|
166
|
+
throw new Error(`permission: Windows refused to start the verified runtime in ${root}: ${error.message}`, { cause: error });
|
|
167
|
+
}
|
|
168
|
+
throw error;
|
|
169
|
+
});
|
|
142
170
|
signal?.throwIfAborted();
|
|
143
171
|
const runtime = validateStaged(JSON.parse(result.stdout));
|
|
144
172
|
if (runtime.root !== finalRoot)
|
|
@@ -858,7 +858,10 @@ export function formatList(options: OutputOptions = {}, index = listTaskRecords(
|
|
|
858
858
|
if (record.found) unreadable += 1;
|
|
859
859
|
continue;
|
|
860
860
|
}
|
|
861
|
-
const
|
|
861
|
+
const alias = index.page?.workspaceAlias;
|
|
862
|
+
const canonical = alias && options.origin?.cwd === alias.cwd && record.meta.callbackOrigin?.cwd === alias.target
|
|
863
|
+
&& (record.meta as BackgroundTaskMeta & { durable?: boolean }).durable;
|
|
864
|
+
const ownership = classifyOwnership(record.meta, canonical ? { ...options, origin: { ...options.origin!, cwd: alias.target } } : options);
|
|
862
865
|
if (ownership === "allow") {
|
|
863
866
|
if (!wanted || wanted.has(record.meta.status) || wanted.has("running") && (record.meta as BackgroundTaskMeta & { durable?: boolean; active?: boolean }).durable
|
|
864
867
|
&& (record.meta as BackgroundTaskMeta & { active?: boolean }).active) allowed.push(record.meta);
|
|
@@ -163,7 +163,7 @@ export function inspectMeta(id: string): MetaInspection {
|
|
|
163
163
|
export interface TaskIndex {
|
|
164
164
|
records: MetaInspection[];
|
|
165
165
|
indexError?: string;
|
|
166
|
-
page?: { resource?: string; total: number; before: number; contentRevision: string; failureRevision: string; unreadable: number; unknown: number };
|
|
166
|
+
page?: { resource?: string; workspaceAlias?: { cwd: string; target: string }; total: number; before: number; contentRevision: string; failureRevision: string; unreadable: number; unknown: number };
|
|
167
167
|
}
|
|
168
168
|
|
|
169
169
|
/** List every task directory, including unreadable metadata. */
|
|
@@ -87,6 +87,7 @@ export type BackgroundWorkProvider = {
|
|
|
87
87
|
parentRow?(now: number): BackgroundWorkRow | null;
|
|
88
88
|
listRows(now: number): BackgroundWorkRow[];
|
|
89
89
|
prepareDetail?(id: string, options?: {logTailLines?: number}): void;
|
|
90
|
+
observeDetail?(id: string, changed: () => void): (() => void) | undefined;
|
|
90
91
|
detail(id: string, now: number, options?: { logTailLines?: number }): BackgroundWorkDetail | null;
|
|
91
92
|
armCloseLabel(row: BackgroundWorkRow): string;
|
|
92
93
|
close(id: string): BackgroundWorkCloseOutcome;
|
|
@@ -1286,9 +1287,21 @@ function createOverlayComponent(
|
|
|
1286
1287
|
const initializedSections = new Set<string>();
|
|
1287
1288
|
let detailId: string = initialDetailId;
|
|
1288
1289
|
const initialRow = initialRows.find((row) => row.navigatorId === detailId);
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1290
|
+
let stopObservation: (() => void) | undefined;
|
|
1291
|
+
function observeDetail() {
|
|
1292
|
+
stopObservation?.();
|
|
1293
|
+
const { providerId, id } = splitRowKey(detailId);
|
|
1294
|
+
stopObservation = state().providers.get(providerId)?.observeDetail?.(id, refreshDetail);
|
|
1295
|
+
}
|
|
1296
|
+
function refreshDetail() {
|
|
1297
|
+
if (closed) return;
|
|
1298
|
+
prepareDetail(detailId,{logTailLines:logTailRows});
|
|
1299
|
+
detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
|
|
1300
|
+
applyDefaultExpandedSections(detail, expandedSections, initializedSections);
|
|
1301
|
+
startDetailTimer();
|
|
1302
|
+
requestRender();
|
|
1303
|
+
}
|
|
1304
|
+
let detail: BackgroundWorkDetail | null = initialRow ? fallbackDetail(initialRow) : null;
|
|
1292
1305
|
{
|
|
1293
1306
|
const idx = overlayState.rows.findIndex((row) => row.navigatorId === detailId);
|
|
1294
1307
|
if (idx >= 0) overlayState.selected = idx;
|
|
@@ -1379,7 +1392,10 @@ function createOverlayComponent(
|
|
|
1379
1392
|
const row = selectedRow();
|
|
1380
1393
|
if (!row) return;
|
|
1381
1394
|
clearCloseArm();
|
|
1382
|
-
detailId
|
|
1395
|
+
if (detailId !== row.navigatorId) {
|
|
1396
|
+
detailId = row.navigatorId;
|
|
1397
|
+
observeDetail();
|
|
1398
|
+
}
|
|
1383
1399
|
expandedSections.clear();
|
|
1384
1400
|
initializedSections.clear();
|
|
1385
1401
|
prepareDetail(detailId,{logTailLines:logTailRows});
|
|
@@ -1389,12 +1405,17 @@ function createOverlayComponent(
|
|
|
1389
1405
|
requestRender();
|
|
1390
1406
|
}
|
|
1391
1407
|
|
|
1408
|
+
observeDetail();
|
|
1409
|
+
prepareDetail(detailId,{logTailLines:logTailRows});
|
|
1410
|
+
detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
|
|
1411
|
+
applyDefaultExpandedSections(detail, expandedSections, initializedSections);
|
|
1392
1412
|
startDetailTimer();
|
|
1393
1413
|
|
|
1394
1414
|
function close(): void {
|
|
1395
1415
|
if (closed) return;
|
|
1396
1416
|
closed = true;
|
|
1397
1417
|
pointer.reset();
|
|
1418
|
+
stopObservation?.(); stopObservation = undefined;
|
|
1398
1419
|
clearCloseArm();
|
|
1399
1420
|
detailScheduler.dispose();
|
|
1400
1421
|
try { done(null); } catch { /* ignore */ }
|
|
@@ -1578,14 +1599,7 @@ function createOverlayComponent(
|
|
|
1578
1599
|
}
|
|
1579
1600
|
},
|
|
1580
1601
|
/** Observation arrival updates this row without resetting selection or folded sections. */
|
|
1581
|
-
refreshDetail
|
|
1582
|
-
if (closed) return;
|
|
1583
|
-
prepareDetail(detailId,{logTailLines:logTailRows});
|
|
1584
|
-
detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
|
|
1585
|
-
applyDefaultExpandedSections(detail, expandedSections, initializedSections);
|
|
1586
|
-
startDetailTimer();
|
|
1587
|
-
requestRender();
|
|
1588
|
-
},
|
|
1602
|
+
refreshDetail,
|
|
1589
1603
|
/** Show another row's detail in this overlay (the main list moved while it was unfocused). */
|
|
1590
1604
|
showDetail(navigatorId: string) {
|
|
1591
1605
|
if (closed) return;
|
|
@@ -1602,6 +1616,7 @@ function createOverlayComponent(
|
|
|
1602
1616
|
dispose() {
|
|
1603
1617
|
pointer.reset();
|
|
1604
1618
|
pointerTargets = [];
|
|
1619
|
+
stopObservation?.(); stopObservation = undefined;
|
|
1605
1620
|
clearCloseArm();
|
|
1606
1621
|
detailScheduler.dispose();
|
|
1607
1622
|
},
|
|
@@ -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(
|
|
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
|
|
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);
|
package/node_modules/pi-better-background-tasks/src/supervisor/generated/shared-windows-native.mjs
CHANGED
|
@@ -5,6 +5,14 @@ import { closeSync } from "node:fs";
|
|
|
5
5
|
import { connect, Socket } from "node:net";
|
|
6
6
|
import { createRequire } from "node:module";
|
|
7
7
|
import { join } from "node:path";
|
|
8
|
+
// Worker threads get a case-sensitive environment copy, even on Windows.
|
|
9
|
+
export function windowsSystemRoot(env = process.env) {
|
|
10
|
+
const key = Object.keys(env).find(name => name.toUpperCase() === "SYSTEMROOT");
|
|
11
|
+
const root = key && env[key];
|
|
12
|
+
if (!root)
|
|
13
|
+
throw new Error("Windows runtime requires the SystemRoot environment variable");
|
|
14
|
+
return root;
|
|
15
|
+
}
|
|
8
16
|
// Private, x64-only bindings. Library resolution and DLL loading are lazy so POSIX
|
|
9
17
|
// clients and hosts that only inspect the package never load a native module.
|
|
10
18
|
function loadWindowsApi() {
|
|
@@ -18,10 +26,11 @@ function loadWindowsApi() {
|
|
|
18
26
|
binding = createRequire(require.resolve("pi-better-server/package.json")).resolve("@koromix/koffi-win32-x64");
|
|
19
27
|
}
|
|
20
28
|
const ffi = require(binding);
|
|
21
|
-
const system = join(
|
|
29
|
+
const system = join(windowsSystemRoot(), "System32");
|
|
22
30
|
const kernel = ffi.load(join(system, "kernel32.dll"));
|
|
23
31
|
const security = ffi.load(join(system, "advapi32.dll"));
|
|
24
32
|
return {
|
|
33
|
+
ffi, kernel, security,
|
|
25
34
|
openProcess: kernel.func("void *OpenProcess(uint32_t access, int inherit, uint32_t pid)"),
|
|
26
35
|
terminate: kernel.func("int TerminateProcess(void *process, uint32_t code)"),
|
|
27
36
|
createJob: kernel.func("void *CreateJobObjectW(void *attributes, void *name)"),
|
|
@@ -51,7 +60,8 @@ function loadWindowsApi() {
|
|
|
51
60
|
};
|
|
52
61
|
}
|
|
53
62
|
let windows;
|
|
54
|
-
function
|
|
63
|
+
export function windowsApi() { return windows ??= loadWindowsApi(); }
|
|
64
|
+
const api = windowsApi;
|
|
55
65
|
function creationTime(handle) {
|
|
56
66
|
const created = Buffer.alloc(8);
|
|
57
67
|
if (!api().processTimes(handle, created, Buffer.alloc(8), Buffer.alloc(8), Buffer.alloc(8)))
|
|
@@ -116,7 +126,7 @@ export function ownWindowsWorkerTree() {
|
|
|
116
126
|
os.close(job);
|
|
117
127
|
}
|
|
118
128
|
}
|
|
119
|
-
function sidString(pointer) {
|
|
129
|
+
export function sidString(pointer) {
|
|
120
130
|
const text = Buffer.alloc(8);
|
|
121
131
|
const os = api();
|
|
122
132
|
if (!pointer || !os.sidString(pointer, text))
|
|
@@ -129,7 +139,7 @@ function sidString(pointer) {
|
|
|
129
139
|
}
|
|
130
140
|
}
|
|
131
141
|
let currentUserSid;
|
|
132
|
-
function userSid() {
|
|
142
|
+
export function userSid() {
|
|
133
143
|
if (currentUserSid)
|
|
134
144
|
return currentUserSid;
|
|
135
145
|
const os = api(), token = Buffer.alloc(8), user = Buffer.alloc(256);
|
|
@@ -207,3 +207,31 @@ reason. See the [projection contract](https://github.com/1aboveio/pi-better-harn
|
|
|
207
207
|
- Repository: https://github.com/1aboveio/pi-better-harness
|
|
208
208
|
- Detailed notes: https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-subagents/docs/usage.md
|
|
209
209
|
- License: https://github.com/1aboveio/pi-better-harness/blob/main/LICENSE
|
|
210
|
+
|
|
211
|
+
### Select an execution mode
|
|
212
|
+
|
|
213
|
+
Open `/harness-settings` and go to **Agents → Delegation → Execution mode**.
|
|
214
|
+
Press Enter or Space to cycle through `managed`, `direct` and `auto`.
|
|
215
|
+
The default, `auto`, tries the managed runtime for each launch. If the runtime
|
|
216
|
+
is unavailable before submission, eligible tasks run directly in the foreground.
|
|
217
|
+
The launch receipt reports the fallback. Permission refusals, cancellation and
|
|
218
|
+
missing receipts after submission never trigger another launch. Workflow
|
|
219
|
+
assignments, nested delegation and saved-session continuation require managed execution.
|
|
220
|
+
The menu saves your choice immediately in `piBetterHarness.subagents.executionMode`
|
|
221
|
+
and applies it to new launches. Managed work
|
|
222
|
+
keeps its original owner and can still be inspected by run ID. In auto mode,
|
|
223
|
+
`subagent_list` shows the backend used by the last launch; pass `source: "managed"`
|
|
224
|
+
or `source: "direct"` to list runs from a specific backend.
|
|
225
|
+
|
|
226
|
+
Direct runs use the foreground's Pi installation, role catalog, model and
|
|
227
|
+
tool settings, preflight checks and sandbox permissions. Use `agents_catalog`,
|
|
228
|
+
`subagent_spawn`, `subagent_spawn_batch`, `subagent_list`, `subagent_output`,
|
|
229
|
+
`subagent_result` and `subagent_stop` in the launching session. A launch
|
|
230
|
+
receipt identifies an attempt. Its exit and output determine its result.
|
|
231
|
+
Leave the foreground open for asynchronous work and completion callbacks.
|
|
232
|
+
Reloading, switching sessions and quitting stop Direct workers. Direct
|
|
233
|
+
execution requires private temporary storage. A forced exit can leave private
|
|
234
|
+
files in the OS temporary directory. Managed execution is required for saved
|
|
235
|
+
conversation continuation, worker waits, durable workflow outcomes and
|
|
236
|
+
cross-session supervision. Managed admission failures never change the mode.
|
|
237
|
+
|
|
@@ -7,7 +7,7 @@ import { presentCatalog, presentCatalogEntry, type LaunchEnricher, type ReadSkil
|
|
|
7
7
|
import { canonicalCatalogId } from "./catalog-schema.ts";
|
|
8
8
|
import { defaultUserRoot, loadCatalog } from "./catalog-store.ts";
|
|
9
9
|
import { withAgentSessionSettings, type AgentSessionOverrides, type AgentSessionSettings } from "./agent-session-settings.ts";
|
|
10
|
-
import { openSharedCatalog } from "./shared-catalog.ts";
|
|
10
|
+
import { ManagedRuntimeUnavailable, openSharedCatalog } from "./shared-catalog.ts";
|
|
11
11
|
|
|
12
12
|
type TypeModule = {
|
|
13
13
|
Object: (value: unknown) => unknown;
|
|
@@ -26,6 +26,7 @@ export interface DiscoveryHost {
|
|
|
26
26
|
|
|
27
27
|
export interface DiscoveryDeps {
|
|
28
28
|
sharedCatalog?: boolean;
|
|
29
|
+
allowLocalDiscovery?: boolean;
|
|
29
30
|
userRoot?: string;
|
|
30
31
|
bundledRoot?: string;
|
|
31
32
|
projectConfigDirName?: string;
|
|
@@ -74,7 +75,12 @@ export function agentsCatalogTool(Type: TypeModule, deps: DiscoveryDeps = {}) {
|
|
|
74
75
|
return toolError(`agents_catalog action must be list or inspect, got ${JSON.stringify(action ?? "")}. It does not create, import, reload, or launch. Nothing was written.`);
|
|
75
76
|
}
|
|
76
77
|
const host = resolveHost(ctx, deps);
|
|
77
|
-
const remote = (deps.sharedCatalog ?? !deps.userRoot) ? await openSharedCatalog(host.cwd, host.userRoot, "catalog-tool", host.projectTrusted)
|
|
78
|
+
const remote = (deps.sharedCatalog ?? !deps.userRoot) ? await openSharedCatalog(host.cwd, host.userRoot, "catalog-tool", host.projectTrusted, _signal)
|
|
79
|
+
.catch(error => {
|
|
80
|
+
_signal?.throwIfAborted();
|
|
81
|
+
if (!deps.allowLocalDiscovery || !(error instanceof ManagedRuntimeUnavailable)) throw error;
|
|
82
|
+
return undefined;
|
|
83
|
+
}) : undefined;
|
|
78
84
|
let snapshot;
|
|
79
85
|
try {
|
|
80
86
|
snapshot = remote ? await remote.get(host.sessionSettings ?? deps.sessionSettings?.snapshot())
|
|
@@ -172,16 +172,16 @@ export async function loadSharedLaunchSnapshot(host: CatalogHost): Promise<Catal
|
|
|
172
172
|
finally { remote.close(); }
|
|
173
173
|
}
|
|
174
174
|
|
|
175
|
-
export async function readConsoleCatalog(host: CatalogHost) {
|
|
176
|
-
const remote = await openSharedCatalog(host.cwd,host.userRoot,"console",host.projectTrusted,undefined,undefined,true);
|
|
175
|
+
export async function readConsoleCatalog(host: CatalogHost, direct = false) {
|
|
176
|
+
const remote = direct ? undefined : await openSharedCatalog(host.cwd,host.userRoot,"console",host.projectTrusted,undefined,undefined,true);
|
|
177
177
|
try {
|
|
178
|
-
const snapshot = await remote.get(host.getSessionSettings?.() ?? host.sessionSettings);
|
|
178
|
+
const snapshot = remote ? await remote.get(host.getSessionSettings?.() ?? host.sessionSettings) : loadLaunchSnapshot(host);
|
|
179
179
|
return [...snapshot.roles.values(), ...snapshot.agents.values()].map(entry => ({
|
|
180
180
|
...inspectCatalog(snapshot, entry.id), name:entry.id, source:entry.kind === "role" ? "Roles" : "Named Agents",
|
|
181
181
|
sessionSettings:snapshot.sessionSettings?.[entry.id], savedSettings:snapshot.savedSettings?.[entry.id],
|
|
182
182
|
preferenceSources:snapshot.preferenceSources?.[entry.id],
|
|
183
183
|
}));
|
|
184
|
-
} finally { remote
|
|
184
|
+
} finally { remote?.close(); }
|
|
185
185
|
}
|
|
186
186
|
|
|
187
187
|
export function createLaunchEnricher(pi?: unknown): LaunchEnricher {
|
|
@@ -22,7 +22,14 @@ import { normalizeSkillExposure } from "./skills.ts";
|
|
|
22
22
|
import { validatedTimingMinutes, type TimingSettings } from "./timing.ts";
|
|
23
23
|
import { harnessSettingsPath, readHarnessSetting, updateHarnessSetting } from "./shared-harness-settings.ts";
|
|
24
24
|
|
|
25
|
+
export const EXECUTION_MODES = ["managed", "direct", "auto"] as const;
|
|
26
|
+
export type ExecutionMode = typeof EXECUTION_MODES[number];
|
|
27
|
+
export function isExecutionMode(value: unknown): value is ExecutionMode {
|
|
28
|
+
return EXECUTION_MODES.some(mode => mode === value);
|
|
29
|
+
}
|
|
30
|
+
|
|
25
31
|
export interface SubagentConfig extends TimingSettings {
|
|
32
|
+
executionMode?: ExecutionMode;
|
|
26
33
|
/** Foreground delegation policy; /subagents mode overrides this for the current session. */
|
|
27
34
|
delegationMode?: DelegationMode | null;
|
|
28
35
|
gitWorkspace?: "clone" | "worktree";
|
|
@@ -193,6 +200,15 @@ export function writeDelegationMode(mode: DelegationMode, path = configPath()):
|
|
|
193
200
|
writeConfigSettings({ delegationMode: mode }, path);
|
|
194
201
|
}
|
|
195
202
|
|
|
203
|
+
export function executionMode(): ExecutionMode {
|
|
204
|
+
const mode = loadConfig().executionMode;
|
|
205
|
+
return isExecutionMode(mode) ? mode : "auto";
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function writeExecutionMode(mode: ExecutionMode): void {
|
|
209
|
+
writeConfigSettings({ executionMode: mode }, configPath());
|
|
210
|
+
}
|
|
211
|
+
|
|
196
212
|
/** Save human-facing defaults together, preserving unrelated configuration. */
|
|
197
213
|
export function writeSubagentSettings(
|
|
198
214
|
settings: {
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { lstatSync, mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
|
|
2
|
+
import { rm } from "node:fs/promises";
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { directStorage } from "./session-store.ts";
|
|
7
|
+
import { isPrivateRuntimePath } from "./shared-windows-native.mjs";
|
|
8
|
+
import type { SpawnResult } from "./spawn.ts";
|
|
9
|
+
|
|
10
|
+
const activeChildren = new Map<string, SpawnResult>();
|
|
11
|
+
const launchSignal = new AsyncLocalStorage<AbortSignal | undefined>();
|
|
12
|
+
export function stopDirectChild(id: string) {
|
|
13
|
+
const child = activeChildren.get(id);
|
|
14
|
+
if (!child) throw new Error("Direct worker ownership is unavailable.");
|
|
15
|
+
child.stopOwnedChild!();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Shared POSIX temp directories can be traversable. Their owner must still
|
|
19
|
+
// control every name beneath them. Individual Direct roots are owner-only.
|
|
20
|
+
export function ensureOwnedDirectory(path: string) {
|
|
21
|
+
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
22
|
+
const stat = lstatSync(path);
|
|
23
|
+
if (!stat.isDirectory() || (process.platform === "win32" ? !isPrivateRuntimePath(path, stat)
|
|
24
|
+
: stat.uid !== process.getuid?.() || (stat.mode & 0o022) !== 0)) {
|
|
25
|
+
throw new Error(`Direct execution needs a user-owned temporary directory protected against other writers: ${path}`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** A session owns capabilities (open pipes), never PIDs read from a run record. */
|
|
30
|
+
export class DirectOwner {
|
|
31
|
+
private root?: string;
|
|
32
|
+
private closed = false;
|
|
33
|
+
private children = new Map<string, Promise<void>>();
|
|
34
|
+
private timer?: NodeJS.Timeout;
|
|
35
|
+
private launches = new Set<Promise<unknown>>();
|
|
36
|
+
readonly runs = new Set<string>();
|
|
37
|
+
get runningCount(): number { return this.children.size; }
|
|
38
|
+
|
|
39
|
+
assertOpen(): void {
|
|
40
|
+
if (this.closed) throw new Error("The foreground session ended during Direct launch.");
|
|
41
|
+
launchSignal.getStore()?.throwIfAborted();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
run<T>(fn: () => T): T {
|
|
45
|
+
this.assertOpen();
|
|
46
|
+
if (!this.root) {
|
|
47
|
+
const parent = join(realpathSync(tmpdir()), "pi-better-subagents");
|
|
48
|
+
ensureOwnedDirectory(parent);
|
|
49
|
+
const path = mkdtempSync(join(parent, "direct-"));
|
|
50
|
+
if (!isPrivateRuntimePath(path, lstatSync(path))) {
|
|
51
|
+
rmSync(path, { recursive: true });
|
|
52
|
+
throw new Error("Direct execution needs a private temporary directory. Set the OS temp directory to a location accessible only to your account.");
|
|
53
|
+
}
|
|
54
|
+
this.root = path;
|
|
55
|
+
}
|
|
56
|
+
return directStorage.run(this.root, fn);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async launch<T>(signal: AbortSignal | undefined, fn: () => Promise<T>): Promise<T> {
|
|
60
|
+
const pending = this.run(() => launchSignal.run(signal, fn));
|
|
61
|
+
this.launches.add(pending);
|
|
62
|
+
try { return await pending; }
|
|
63
|
+
finally { this.launches.delete(pending); }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
track(id: string, child: SpawnResult, finalized: Promise<void>, tick: (id: string) => void, interval: number) {
|
|
67
|
+
this.runs.add(id);
|
|
68
|
+
this.children.set(id, finalized);
|
|
69
|
+
activeChildren.set(id, child);
|
|
70
|
+
this.timer ??= setInterval(() => {
|
|
71
|
+
for (const id of this.children.keys()) tick(id);
|
|
72
|
+
}, interval).unref();
|
|
73
|
+
void finalized.finally(() => {
|
|
74
|
+
activeChildren.delete(id);
|
|
75
|
+
this.children.delete(id);
|
|
76
|
+
if (!this.children.size) { clearInterval(this.timer); this.timer = undefined; }
|
|
77
|
+
}).catch(() => {});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
settled(id: string) {
|
|
81
|
+
return this.children.get(id);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async close() {
|
|
85
|
+
this.closed = true;
|
|
86
|
+
for (const id of this.children.keys()) stopDirectChild(id);
|
|
87
|
+
await Promise.allSettled(this.children.values());
|
|
88
|
+
await Promise.allSettled(this.launches);
|
|
89
|
+
if (this.root) await rm(this.root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
|
90
|
+
this.runs.clear();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Only the foreground holds the other end of this inherited channel. The CLI
|
|
2
|
+
// never inherits it and cannot impersonate the owner or report an exit code.
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { ownWindowsWorkerTree } from "./shared-windows-native.mjs";
|
|
5
|
+
|
|
6
|
+
function stopTree() {
|
|
7
|
+
if (process.platform === "win32") process.exit(1); // closes the job handle
|
|
8
|
+
process.kill(-process.pid, "SIGKILL"); // our own detached process group
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
if (!process.connected) process.exit(1);
|
|
12
|
+
process.on("disconnect", stopTree);
|
|
13
|
+
if (process.platform === "win32") ownWindowsWorkerTree();
|
|
14
|
+
const [file, ...args] = process.argv.slice(2);
|
|
15
|
+
const child = spawn(file, args, { stdio: "inherit", windowsHide: true });
|
|
16
|
+
child.on("error", error => process.stderr.write(`Direct worker failed: ${error.message}\n`));
|
|
17
|
+
child.on("close", code => {
|
|
18
|
+
if (!process.connected) return stopTree();
|
|
19
|
+
process.send({ exitCode: code }, stopTree);
|
|
20
|
+
});
|