pi-better-subagents 0.34.0 → 0.36.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/README.md +1 -1
- package/assignment-outcomes.ts +52 -8
- package/assignment-report.ts +83 -19
- package/capacity.mjs +13 -0
- package/catalog-host-admission.ts +19 -3
- package/catalog-preferences.ts +1 -1
- package/catalog-resolver.ts +35 -1
- package/catalog-store.ts +27 -20
- package/child-apply-patch.ts +13 -0
- package/child-dependencies.mjs +25 -12
- package/child-operations.ts +80 -1
- package/child-preflight.mjs +8 -2
- package/child-process-list.ts +8 -0
- package/config.ts +46 -2
- package/continuation-authority.ts +31 -0
- package/continuation-runtime.ts +88 -0
- package/continuation.ts +21 -0
- package/docs/usage.md +53 -28
- package/extensions.mjs +11 -13
- package/failures.ts +7 -1
- package/finalization.ts +15 -0
- package/goal-provider.ts +44 -2
- package/health-observation.ts +43 -48
- package/health.ts +0 -1
- package/index.ts +522 -199
- package/launch-context.ts +23 -0
- package/launch-digest.mjs +6 -0
- package/log-cursor.ts +91 -15
- package/managed-background-capability.ts +9 -0
- package/managed-failure-worker.mjs +27 -0
- package/managed-launch-bootstrap.mjs +35 -0
- package/managed-launch-client.ts +59 -0
- package/managed-launch-host.ts +504 -0
- package/managed-launch-journal.mjs +14 -0
- package/managed-launch-ownership.ts +22 -0
- package/managed-launch-port.ts +25 -0
- package/managed-launch-recovery.ts +45 -0
- package/managed-worker-bridge.ts +48 -0
- package/managed-worker.mjs +11 -0
- package/operation-bridge-types.ts +27 -2
- package/owned-exit.ts +12 -0
- package/package.json +1 -1
- package/parse.ts +48 -6
- package/permission-policy.ts +53 -8
- package/process-identity.d.mts +1 -0
- package/process-identity.mjs +29 -0
- package/registry.ts +56 -33
- package/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/runtime-client/artifacts/darwin-x64.json +1 -1
- package/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/runtime-client/artifacts/linux-arm64.json +1 -1
- package/runtime-client/artifacts/linux-x64.gz +0 -0
- package/runtime-client/artifacts/linux-x64.json +1 -1
- package/runtime-client/src/runtime/client.mjs +30 -3
- package/runtime-client/src/runtime/work-client.mjs +150 -7
- package/shared-callback-batcher.ts +15 -3
- package/shared-catalog.ts +6 -14
- package/shared-failure-observations.ts +3 -0
- package/shared-navigator-panels.ts +26 -4
- package/shared-navigator.ts +220 -19
- package/shared-operation-coordinator/assignment-inbox.mjs +118 -0
- package/shared-operation-coordinator/assignment-observation.mjs +71 -33
- package/shared-operation-coordinator/index.ts +2 -0
- package/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
- package/shared-operation-coordinator/src/background-requests.ts +90 -0
- package/shared-operation-coordinator/src/discovery.ts +5 -3
- package/shared-operation-coordinator/src/operations.ts +50 -2
- package/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/shared-operation-coordinator/src/rows.ts +2 -0
- package/shared-operation-coordinator/src/schema.ts +71 -24
- package/shared-operation-coordinator/src/store.ts +50 -6
- package/shared-operation-coordinator/src/subagent-launch.ts +142 -0
- package/shared-operation-coordinator/src/types.ts +5 -1
- package/shared-operation-coordinator/src/upgrade.ts +22 -0
- package/shared-sandbox-core.ts +1 -1
- package/shared-task-exec.ts +12 -1
- package/shared-task-process-identity.ts +126 -0
- package/shared-task-process-list.ts +8 -2
- package/shared-task-sandbox.ts +5 -3
- package/shared-task-tools.ts +8 -5
- package/shared-work-client.d.mts +10 -0
- package/shared-work-client.mjs +150 -7
- package/subagent-tools.ts +28 -34
- package/task-policy.ts +3 -1
- package/task-runtime.mjs +1 -0
- package/timing-notifications.ts +37 -0
- package/timing.ts +11 -1
- package/tools.ts +10 -3
- package/work-observation.ts +86 -15
- package/worker-operations-host.ts +12 -4
- package/worker-waits.ts +138 -47
package/README.md
CHANGED
|
@@ -87,7 +87,7 @@ pi -e npm:pi-better-subagents
|
|
|
87
87
|
|
|
88
88
|
Sandboxing starts Off for fresh settings, including standalone subagents without published settings. Explicit saved profiles and session choices remain unchanged. Set `sandbox:true` for a confined launch; `sandbox:false` cannot bypass a human-enabled Subagents profile.
|
|
89
89
|
|
|
90
|
-
Linux confinement requires a usable `bubblewrap` backend and Pi SDK 0.82.1 or newer. `/sandbox` controls the independent Subagents profile, which each launch freezes. Pi handles its own startup, authentication, and provider connection; task tools obey the selected file, command, and network permissions. Outside project defaults to Write: tasks write across home and temp but can remove files outside the workspace only in temp, hidden home directories, and worktree folders (Linux keeps ordinary home folders read-only instead). Confined children admit `read`, `write`, `edit`, and policy-permitted `bash` or guarded `run_application`, the guarded `apply_patch` (Codex patches that follow the file rules), and the
|
|
90
|
+
Linux confinement requires a usable `bubblewrap` backend and Pi SDK 0.82.1 or newer. `/sandbox` controls the independent Subagents profile, which each launch freezes. Pi handles its own startup, authentication, and provider connection; task tools obey the selected file, command, and network permissions. Outside project defaults to Write: tasks write across home and temp but can remove files outside the workspace only in temp, hidden home directories, and worktree folders (Linux keeps ordinary home folders read-only instead). Confined children admit `read`, `write`, `edit`, and policy-permitted `bash` or guarded `run_application`, the guarded `apply_patch` (Codex patches that follow the file rules), and the selected extension tools with verified providers (defaults include `web_fetch` and `web_search`), which run outside the file rules. Other requested tools are reported as unavailable, with the reason. For direct applications without shell scripts, set Subagents → Sandbox On, Run applications On, Shell scripts Off, and Command time limit to 10 min in `/sandbox`, then press Ctrl+S. This is an explicit choice, not the default. New launches capture the policy; running children keep theirs. See [usage notes](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-subagents/docs/usage.md#write-sandbox) for the runtime boundary and supported configurations.
|
|
91
91
|
|
|
92
92
|
## Delegation Modes
|
|
93
93
|
|
package/assignment-outcomes.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { homedir } from "node:os";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import {
|
|
3
|
+
import { isDeepStrictEqual } from "node:util";
|
|
4
|
+
import { join, relative, isAbsolute, dirname, resolve } from "node:path";
|
|
4
5
|
import { openSync, closeSync, fstatSync, readSync, realpathSync, constants } from "node:fs";
|
|
5
|
-
import { openStore, type OwnerIdentity, type AssignmentOutcomeRecord } from "./shared-operation-coordinator/index.ts";
|
|
6
|
+
import { openStore, ownerDiff, type OwnerIdentity, type AssignmentOutcomeRecord } from "./shared-operation-coordinator/index.ts";
|
|
6
7
|
import type { RunMeta } from "./registry.ts";
|
|
7
|
-
import { processStartToken } from "./registry.ts";
|
|
8
|
+
import { processStartToken, readMeta } from "./registry.ts";
|
|
8
9
|
import type { PermissionSnapshot } from "./permission-policy.ts";
|
|
9
10
|
import { credentialFilePaths } from "./shared-sandbox-core.ts";
|
|
10
11
|
import { readAssignmentReport } from "./assignment-report.ts";
|
|
@@ -43,9 +44,30 @@ export function coordinatorPath(): string {
|
|
|
43
44
|
return join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite");
|
|
44
45
|
}
|
|
45
46
|
function withStore<T>(body: (store: ReturnType<typeof openStore>) => T): T {
|
|
46
|
-
const
|
|
47
|
+
const path = coordinatorPath();
|
|
48
|
+
const borrowed = runtimeStores.get(canonicalRoot(dirname(path)));
|
|
49
|
+
if (borrowed) return body(borrowed.store);
|
|
50
|
+
const store = openStore({ path });
|
|
47
51
|
try { return body(store); } finally { store.close(); }
|
|
48
52
|
}
|
|
53
|
+
const runtimeStores = new Map<string, { store: ReturnType<typeof openStore>; leases: number }>();
|
|
54
|
+
function canonicalRoot(root: string): string {
|
|
55
|
+
try { return realpathSync(root); } catch { return resolve(root); }
|
|
56
|
+
}
|
|
57
|
+
/** Fixed runtime adapter borrows its mutation connection; it retains ownership. */
|
|
58
|
+
export function bindRuntimeOutcomeStore(root: string, store: ReturnType<typeof openStore>): () => void {
|
|
59
|
+
const key = canonicalRoot(root);
|
|
60
|
+
let entry = runtimeStores.get(key);
|
|
61
|
+
if (entry && entry.store !== store) throw new Error("Assignment runtime store already bound");
|
|
62
|
+
if (!entry) { entry = { store, leases: 0 }; runtimeStores.set(key, entry); }
|
|
63
|
+
entry.leases++;
|
|
64
|
+
let released = false;
|
|
65
|
+
return () => {
|
|
66
|
+
if (released) return;
|
|
67
|
+
released = true;
|
|
68
|
+
if (--entry.leases === 0) runtimeStores.delete(key);
|
|
69
|
+
};
|
|
70
|
+
}
|
|
49
71
|
export function registerAssignmentAttempt(binding: AssignmentBinding, attemptId: string): void {
|
|
50
72
|
if (binding.version !== ASSIGNMENT_OUTCOMES_VERSION) throw new Error("Unsupported assignment outcome capability.");
|
|
51
73
|
withStore((store) => store.registerAssignment({ ...binding, attemptId }));
|
|
@@ -69,11 +91,15 @@ export function commitAssignmentTerminal(meta: RunMeta, recoveryFailure = false)
|
|
|
69
91
|
catch { if (meta.status === "completed") invalidReport = "Assignment completion is unverified: retained report evidence is unavailable or changed."; }
|
|
70
92
|
const complete = meta.status === "completed" && (report ? report.status === "complete"
|
|
71
93
|
: !invalidReport && waits.some((w) => w.acknowledgement?.disposition === "assignment-complete"));
|
|
72
|
-
|
|
94
|
+
const reportReason = report?.status === "incomplete" ? `Assignment incomplete: ${report.reason}`
|
|
95
|
+
+ (report.blocker ? ` Blocked (${report.blocker.kind}): ${report.blocker.reason}.` : "")
|
|
96
|
+
+ (report.remainingWork ? ` Remaining work: ${report.remainingWork.join("; ")}.` : "") : report?.reason;
|
|
97
|
+
try { return store.recordAssignmentOutcome({ ...binding, revision: 1,
|
|
73
98
|
outcome: complete ? "succeeded" : meta.status === "killed" ? "cancelled" : "failed",
|
|
74
|
-
reason: meta.failureReason || invalidReport || (meta.status === "completed" && report ?
|
|
99
|
+
reason: (meta.failureReason || invalidReport || (meta.status === "completed" && report ? reportReason : complete ? "Assigned work and required interpretation are complete."
|
|
100
|
+
: meta.status === "completed" && meta.assignmentReportRejection ? `Assignment report rejected: ${meta.assignmentReportRejection.reason}`
|
|
75
101
|
: meta.status === "completed" ? "Assignment completion is unverified: the attempt exited without an evidence-backed completion decision. Inspect retained output and continue unfinished work or report a concrete blocker."
|
|
76
|
-
: `Assignment ended ${meta.status}; retained attempt evidence is available.`),
|
|
102
|
+
: `Assignment ended ${meta.status}; retained attempt evidence is available.`)).slice(0, 8192),
|
|
77
103
|
processUncertain: meta.status === "lost" || typeof meta.exitCode !== "number"
|
|
78
104
|
|| waits.some((w) => w.dependencies.some((d) => d.terminalRevision === 0)
|
|
79
105
|
|| store.listResumeClaims({ waitId: w.waitId, generation: w.generation, state: "published" }).length > 0),
|
|
@@ -81,7 +107,25 @@ export function commitAssignmentTerminal(meta: RunMeta, recoveryFailure = false)
|
|
|
81
107
|
...(report ? [{ kind: "artifact" as const, ref: meta.assignmentReport!.path, summary: report.reason },
|
|
82
108
|
...report.evidence.map((e) => ({ kind: "artifact" as const, ref: e.path, summary: e.explanation }))] : [])],
|
|
83
109
|
waits: waits.map((w) => ({ waitId: w.waitId, generation: w.generation, cancelEpoch: w.cancelEpoch })),
|
|
84
|
-
});
|
|
110
|
+
}); } catch (error) {
|
|
111
|
+
// A competing finalizer may commit after our initial read. The store
|
|
112
|
+
// still refuses rewrites; return only the same captured binding's winner.
|
|
113
|
+
// Borrowed runtime stores use a different coordinator module's StoreError constructor.
|
|
114
|
+
if (error instanceof Error && error.name === "StoreError" && "code" in error
|
|
115
|
+
&& error.code === "validation" && error.message === "A terminal assignment cannot be rewritten or reopened.") {
|
|
116
|
+
const winner = store.getAssignmentOutcome(binding.assignmentId);
|
|
117
|
+
const current = readMeta(meta.id);
|
|
118
|
+
if (winner && winner.assignmentId === binding.assignmentId && winner.revision === 1 && ownerDiff(winner.owner, binding.owner) === "none"
|
|
119
|
+
&& ownerDiff(winner.recipient, binding.recipient) === "none"
|
|
120
|
+
&& current?.assignment?.assignmentId === binding.assignmentId
|
|
121
|
+
&& ownerDiff(current.assignment.owner, binding.owner) === "none" && ownerDiff(current.assignment.recipient, binding.recipient) === "none"
|
|
122
|
+
&& current.sessionId === meta.sessionId && current.cwd === meta.cwd && current.pid === meta.pid && current.pidStartTime === meta.pidStartTime
|
|
123
|
+
&& isDeepStrictEqual(current.management, meta.management)
|
|
124
|
+
&& current.operations?.resumeLaunchToken === meta.operations?.resumeLaunchToken
|
|
125
|
+
&& winner.evidence.some(evidence => evidence.kind === "log" && evidence.ref === meta.logPath)) return winner;
|
|
126
|
+
}
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
85
129
|
});
|
|
86
130
|
}
|
|
87
131
|
export function readOutcome(meta: RunMeta): AssignmentOutcomeRecord | null {
|
package/assignment-report.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { homedir } from "node:os";
|
|
|
5
5
|
import { runDir, writeMeta, type RunMeta } from "./registry.ts";
|
|
6
6
|
import { credentialFilePaths } from "./shared-sandbox-core.ts";
|
|
7
7
|
import type { PermissionSnapshot, PermissionProfile } from "./permission-policy.ts";
|
|
8
|
+
import { OperationBridgeError, redactSecret } from "./operation-bridge-types.ts";
|
|
8
9
|
|
|
9
10
|
const hash = (bytes: string | Buffer) => createHash("sha256").update(bytes).digest("hex");
|
|
10
11
|
const inside = (root: string, path: string) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
|
|
@@ -20,15 +21,47 @@ function retainedBytes(path: string, limit: number): Buffer {
|
|
|
20
21
|
}
|
|
21
22
|
export interface AssignmentReport {
|
|
22
23
|
version: 1; assignmentId: string; attemptId: string; requestDigest: string; status: "complete" | "incomplete"; reason: string;
|
|
23
|
-
|
|
24
|
+
remainingWork?: string[];
|
|
25
|
+
blocker?: { kind: "permission" | "external-input"; reason: string };
|
|
26
|
+
evidence: Array<{ path: string; digest: string; source: string; explanation: string; range?: { offset: number; bytes: number; sourceBytes: number } }>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface ReportInput {
|
|
30
|
+
status: string; reason: string;
|
|
31
|
+
remaining_work?: string[];
|
|
32
|
+
blocker?: AssignmentReport["blocker"];
|
|
33
|
+
evidence: Array<{ path: string; explanation: string; offset?: number; max_bytes?: number }>;
|
|
24
34
|
}
|
|
25
35
|
|
|
26
36
|
/** Runs synchronously under the authenticated handler: no yield between authority and persistence. */
|
|
27
37
|
export function recordAssignmentReport(id: string, input: unknown, assertAuthority: () => RunMeta, current?: PermissionSnapshot) {
|
|
28
38
|
const meta = assertAuthority();
|
|
29
|
-
|
|
39
|
+
try { return retainAssignmentReport(id, input, meta, assertAuthority, current); }
|
|
40
|
+
catch (error) {
|
|
41
|
+
// Refused input is not a committed report: the same writer may correct it.
|
|
42
|
+
// Recheck the live writer before retaining even diagnostic metadata.
|
|
43
|
+
recordAssignmentReportRejection(error instanceof Error ? error.message : String(error), assertAuthority);
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Also used for authenticated bridge refusals that never enter the report handler. */
|
|
49
|
+
export function recordAssignmentReportRejection(reason: string, assertAuthority: () => RunMeta): void {
|
|
50
|
+
const latest = assertAuthority();
|
|
51
|
+
if (!latest.assignmentReport) writeMeta({ ...latest, assignmentReportRejection: {
|
|
52
|
+
reason: redactSecret(reason), rejectedAt: Date.now(),
|
|
53
|
+
} });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function retainAssignmentReport(id: string, input: unknown, meta: RunMeta, assertAuthority: () => RunMeta, current?: PermissionSnapshot) {
|
|
57
|
+
const report = input as ReportInput;
|
|
30
58
|
if (!["complete", "incomplete"].includes(report.status) || !report.reason?.trim() || report.reason.length > 2048
|
|
31
59
|
|| !Array.isArray(report.evidence) || report.evidence.length < 1 || report.evidence.length > 4) throw new Error("Invalid assignment report.");
|
|
60
|
+
if (report.remaining_work !== undefined && (!Array.isArray(report.remaining_work) || report.remaining_work.length < 1 || report.remaining_work.length > 8
|
|
61
|
+
|| report.remaining_work.some((item) => typeof item !== "string" || !item.trim() || item.length > 1024))) throw new Error("Remaining work needs 1 to 8 bounded descriptions.");
|
|
62
|
+
if (report.blocker && (!["permission", "external-input"].includes(report.blocker.kind) || !report.blocker.reason?.trim()
|
|
63
|
+
|| report.blocker.reason.length > 1024)) throw new Error("A blocker needs its permission or external-input kind and a concrete reason.");
|
|
64
|
+
if (report.status === "complete" && (report.remaining_work || report.blocker)) throw new Error("A complete assignment cannot have remaining work or a blocker.");
|
|
32
65
|
const root = realpathSync(meta.cwd);
|
|
33
66
|
const directory = join(runDir(id), "assignment-report-v1");
|
|
34
67
|
const captured = (meta.operations?.policy.sandbox as { permissions?: Partial<PermissionProfile> } | null)?.permissions;
|
|
@@ -37,28 +70,22 @@ export function recordAssignmentReport(id: string, input: unknown, assertAuthori
|
|
|
37
70
|
if (policy?.enabled && policy.projectFiles !== "read" && policy.projectFiles !== "read-write") throw new Error("Current assignment evidence read permission refused.");
|
|
38
71
|
}
|
|
39
72
|
if (meta.operations?.policy.sandbox && !current?.permissions) throw new Error("Current assignment evidence read authority unavailable.");
|
|
40
|
-
|
|
73
|
+
// Keep the legacy digest for whole-file reports without the additive fields.
|
|
74
|
+
const request: unknown[] = [report.status, report.reason, report.evidence.map((e) => e.offset === undefined && e.max_bytes === undefined
|
|
75
|
+
? [e.path, e.explanation] : [e.path, e.explanation, e.offset ?? 0, e.max_bytes])];
|
|
76
|
+
if (report.remaining_work || report.blocker) request.push([report.remaining_work ?? null,
|
|
77
|
+
report.blocker ? [report.blocker.kind, report.blocker.reason] : null]);
|
|
78
|
+
const requestDigest = hash(JSON.stringify(request));
|
|
41
79
|
if (meta.assignmentReport) {
|
|
42
80
|
const accepted = readAssignmentReport(meta)!;
|
|
43
81
|
if (accepted.requestDigest !== requestDigest) throw new Error("Conflicting assignment report refused.");
|
|
44
82
|
return { reportId: meta.assignmentReport.digest, status: accepted.status, note: "Report retained. Assignment terminalization after exit and exact parent disposition remain separate." };
|
|
45
83
|
}
|
|
46
|
-
const snapshots = report.evidence.map((e) =>
|
|
47
|
-
if (!e.path || !e.explanation?.trim() || e.explanation.length > 1024) throw new Error("Evidence needs a bounded explanation.");
|
|
48
|
-
const source = realpathSync(resolve(root, e.path));
|
|
49
|
-
if (!inside(root, source) || credentialFilePaths(homedir()).some((p) => inside(p, source))) throw new Error("Foreign or credential assignment evidence refused.");
|
|
50
|
-
const fd = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
51
|
-
try {
|
|
52
|
-
const stat = fstatSync(fd);
|
|
53
|
-
if (!stat.isFile() || stat.size > 65536) throw new Error("Assignment evidence must be a file of at most 65536 bytes.");
|
|
54
|
-
const bytes = Buffer.alloc(stat.size);
|
|
55
|
-
if (readSync(fd, bytes, 0, bytes.length, 0) !== bytes.length) throw new Error("Assignment evidence changed during capture.");
|
|
56
|
-
return { bytes, digest: hash(bytes), source, explanation: e.explanation };
|
|
57
|
-
} finally { closeSync(fd); }
|
|
58
|
-
});
|
|
84
|
+
const snapshots = report.evidence.map((e) => captureEvidence(root, e));
|
|
59
85
|
const retained: AssignmentReport = { version: 1, assignmentId: meta.assignment!.assignmentId, attemptId: id, requestDigest,
|
|
60
86
|
status: report.status as AssignmentReport["status"], reason: report.reason,
|
|
61
|
-
|
|
87
|
+
...(report.remaining_work ? { remainingWork: report.remaining_work } : {}), ...(report.blocker ? { blocker: report.blocker } : {}),
|
|
88
|
+
evidence: snapshots.map(({ digest, source, explanation, range }) => ({ path: join(directory, digest), digest, source, explanation, ...(range ? { range } : {}) })) };
|
|
62
89
|
const text = JSON.stringify(retained);
|
|
63
90
|
if (Buffer.byteLength(text) > 65536) throw new Error("Assignment report exceeds its retained metadata bound.");
|
|
64
91
|
const digest = hash(text);
|
|
@@ -71,11 +98,44 @@ export function recordAssignmentReport(id: string, input: unknown, assertAuthori
|
|
|
71
98
|
for (const snapshot of snapshots) writeFileSync(join(directory, snapshot.digest), snapshot.bytes, { mode: 0o600 });
|
|
72
99
|
const path = join(directory, `${digest}.json`);
|
|
73
100
|
writeFileSync(path, text, { mode: 0o600 });
|
|
74
|
-
|
|
101
|
+
const updated = { ...latest, assignmentReport: { version: 1 as const, assignmentId: retained.assignmentId, attemptId: id, digest, path } };
|
|
102
|
+
delete updated.assignmentReportRejection;
|
|
103
|
+
writeMeta(updated);
|
|
75
104
|
}
|
|
76
105
|
return { reportId: digest, status: report.status, note: "Report retained. Assignment terminalization after exit and exact parent disposition remain separate." };
|
|
77
106
|
}
|
|
78
107
|
|
|
108
|
+
function captureEvidence(root: string, e: ReportInput["evidence"][number]) {
|
|
109
|
+
try {
|
|
110
|
+
if (!e.path || !e.explanation?.trim() || e.explanation.length > 1024) throw new Error("Evidence needs a bounded explanation.");
|
|
111
|
+
const source = realpathSync(resolve(root, e.path));
|
|
112
|
+
if (credentialFilePaths(homedir()).some((p) => inside(p, source))) throw new Error("Foreign or credential assignment evidence refused.");
|
|
113
|
+
if (!inside(root, source)) throw new Error(`Foreign assignment evidence refused: the source must resolve inside the assigned workspace ${JSON.stringify(root)}. A sibling directory is outside this boundary. Use an existing workspace file or place the reportable artifact inside the workspace, then retry.`);
|
|
114
|
+
const fd = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
115
|
+
try {
|
|
116
|
+
const stat = fstatSync(fd);
|
|
117
|
+
if (!stat.isFile()) throw new Error(`Assignment evidence ${JSON.stringify(e.path)} must be a regular file.`);
|
|
118
|
+
const offset = e.offset ?? 0;
|
|
119
|
+
if (!Number.isSafeInteger(offset) || offset < 0 || offset > stat.size || (offset === stat.size && offset !== 0)
|
|
120
|
+
|| (e.offset !== undefined && e.max_bytes === undefined)
|
|
121
|
+
|| (e.max_bytes !== undefined && (!Number.isSafeInteger(e.max_bytes) || e.max_bytes < 1 || e.max_bytes > 65536))) {
|
|
122
|
+
throw new Error(`Invalid assignment evidence range for ${JSON.stringify(e.path)} (${stat.size} bytes). Use offset within the file and max_bytes from 1 through 65536.`);
|
|
123
|
+
}
|
|
124
|
+
if (e.max_bytes === undefined && stat.size > 65536) {
|
|
125
|
+
throw new Error(`Assignment evidence ${JSON.stringify(e.path)} is ${stat.size} bytes; the retained limit is 65536 bytes. Retry with offset and max_bytes (at most 65536) for the relevant excerpt.`);
|
|
126
|
+
}
|
|
127
|
+
const bytes = Buffer.alloc(Math.min(stat.size - offset, e.max_bytes ?? stat.size));
|
|
128
|
+
if (readSync(fd, bytes, 0, bytes.length, offset) !== bytes.length) throw new Error("Assignment evidence changed during capture.");
|
|
129
|
+
const after = fstatSync(fd);
|
|
130
|
+
if (after.size !== stat.size || after.mtimeMs !== stat.mtimeMs || after.ctimeMs !== stat.ctimeMs) throw new Error("Assignment evidence changed during capture.");
|
|
131
|
+
return { bytes, digest: hash(bytes), source, explanation: e.explanation,
|
|
132
|
+
...(e.max_bytes === undefined ? {} : { range: { offset, bytes: bytes.length, sourceBytes: stat.size } }) };
|
|
133
|
+
} finally { closeSync(fd); }
|
|
134
|
+
} catch (error) {
|
|
135
|
+
throw new OperationBridgeError("tool-error", error instanceof Error ? error.message : String(error), true);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
79
139
|
export function readAssignmentReport(meta: RunMeta): AssignmentReport | null {
|
|
80
140
|
const ref = meta.assignmentReport;
|
|
81
141
|
if (!ref) return null;
|
|
@@ -86,7 +146,11 @@ export function readAssignmentReport(meta: RunMeta): AssignmentReport | null {
|
|
|
86
146
|
const report = JSON.parse(text) as AssignmentReport;
|
|
87
147
|
if (report.version !== 1 || report.assignmentId !== ref.assignmentId || report.attemptId !== meta.id) throw new Error("Foreign assignment report.");
|
|
88
148
|
for (const e of report.evidence) {
|
|
89
|
-
if (!/^[a-f0-9]{64}$/.test(e.digest) || e.path !== join(runDir(meta.id), "assignment-report-v1", e.digest)
|
|
149
|
+
if (!/^[a-f0-9]{64}$/.test(e.digest) || e.path !== join(runDir(meta.id), "assignment-report-v1", e.digest)) throw new Error("Retained assignment evidence changed.");
|
|
150
|
+
const bytes = retainedBytes(e.path, 65536);
|
|
151
|
+
if (hash(bytes) !== e.digest || (e.range && (!Number.isSafeInteger(e.range.offset) || e.range.offset < 0
|
|
152
|
+
|| !Number.isSafeInteger(e.range.sourceBytes) || e.range.sourceBytes < 0 || e.range.bytes !== bytes.length
|
|
153
|
+
|| e.range.offset + e.range.bytes > e.range.sourceBytes))) throw new Error("Retained assignment evidence changed.");
|
|
90
154
|
}
|
|
91
155
|
return report;
|
|
92
156
|
}
|
package/capacity.mjs
CHANGED
|
@@ -106,6 +106,19 @@ export function getSharedCapacityGate(countRunning) {
|
|
|
106
106
|
return sharedGate;
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
/** Server centralization retains each original process/start capacity domain. */
|
|
110
|
+
export function createOwnerCapacityGates(countOwner) {
|
|
111
|
+
const gates = new Map();
|
|
112
|
+
return owner => {
|
|
113
|
+
const key = JSON.stringify([owner.pid, owner.start]);
|
|
114
|
+
if (!gates.has(key)) {
|
|
115
|
+
const captured = { pid: owner.pid, start: owner.start };
|
|
116
|
+
gates.set(key, createCapacityGate(() => countOwner(captured)));
|
|
117
|
+
}
|
|
118
|
+
return gates.get(key);
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
109
122
|
/** Test-only: drop the singleton so a suite starts from a clean ledger. */
|
|
110
123
|
export function _resetSharedCapacityGateForTests() {
|
|
111
124
|
sharedGate = undefined;
|
|
@@ -2,7 +2,7 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
|
2
2
|
import { lstatSync, mkdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { processStartToken } from "./registry.ts";
|
|
5
|
-
import { WorkClient } from "./shared-work-client.mjs";
|
|
5
|
+
import { WorkClient, connectWorkClient } from "./shared-work-client.mjs";
|
|
6
6
|
import type { AgentSessionOverrides } from "./agent-session-settings.ts";
|
|
7
7
|
import { overlayDigest } from "./catalog-overlay.ts";
|
|
8
8
|
export { overlayDigest } from "./catalog-overlay.ts";
|
|
@@ -13,6 +13,8 @@ export function createCatalogHostAdapter() {
|
|
|
13
13
|
let live: { client: WorkClient; path: string; key: string; authority: Record<string, unknown> } | undefined;
|
|
14
14
|
let timer: ReturnType<typeof setInterval> | undefined;
|
|
15
15
|
let epoch = 0;
|
|
16
|
+
let pendingConnection: AbortController | undefined;
|
|
17
|
+
let refreshPending = false;
|
|
16
18
|
let admitting: Promise<Record<string, unknown> | undefined> = Promise.resolve(undefined);
|
|
17
19
|
|
|
18
20
|
/** Fixed Pi adapter only. Never exposed as a tool or socket issuance operation. */
|
|
@@ -22,6 +24,7 @@ export function createCatalogHostAdapter() {
|
|
|
22
24
|
|
|
23
25
|
function closeCatalogHost() {
|
|
24
26
|
epoch++;
|
|
27
|
+
pendingConnection?.abort(); pendingConnection = undefined;
|
|
25
28
|
clearInterval(timer); timer = undefined;
|
|
26
29
|
if (live) { live.client.close(); rmSync(live.path, { force: true }); live = undefined; }
|
|
27
30
|
current = undefined;
|
|
@@ -48,9 +51,13 @@ export function createCatalogHostAdapter() {
|
|
|
48
51
|
const id = randomUUID(), secret = randomBytes(32).toString("hex"), generation = randomUUID();
|
|
49
52
|
const path = join(root, `${id}.json`), staging = join(root, `.${id}`);
|
|
50
53
|
const authority = { id, secret, generation, cwd: scope.cwd, sessionId: scope.sessionId, branchId: scope.branchId };
|
|
51
|
-
const
|
|
54
|
+
const controller = new AbortController();
|
|
55
|
+
pendingConnection = controller;
|
|
56
|
+
const client = await connectWorkClient(socketPath, agentDir, ["runtime-catalog-v1"], { signal: controller.signal })
|
|
57
|
+
.finally(() => { if (pendingConnection === controller) pendingConnection = undefined; });
|
|
52
58
|
try {
|
|
53
59
|
const hello = await client.ready;
|
|
60
|
+
if (epoch !== admittedEpoch || !current) throw new Error("catalog-host-revoked");
|
|
54
61
|
const pidStartTime = processStartToken(process.pid);
|
|
55
62
|
if (!pidStartTime) throw new Error("catalog-host-identity-unavailable");
|
|
56
63
|
writeFileSync(staging, JSON.stringify({ version: 1, id, generation, serverInstance: hello.instanceId, pid: process.pid, pidStartTime, secretHash: hash(secret), ...scope }), { mode: 0o600, flag: "wx" });
|
|
@@ -58,7 +65,16 @@ export function createCatalogHostAdapter() {
|
|
|
58
65
|
await client.request("runtime_bind_catalog_host", { authority });
|
|
59
66
|
if (epoch !== admittedEpoch || !current) throw new Error("catalog-host-revoked");
|
|
60
67
|
live = { client, path, key, authority };
|
|
61
|
-
if (!timer) {
|
|
68
|
+
if (!timer) {
|
|
69
|
+
timer = setInterval(() => {
|
|
70
|
+
if (refreshPending) return;
|
|
71
|
+
refreshPending = true;
|
|
72
|
+
void catalogHostAuthority(agentDir, current?.ctx.cwd ?? cwd, socketPath)
|
|
73
|
+
.catch(() => { if (epoch === admittedEpoch) closeCatalogHost(); })
|
|
74
|
+
.finally(() => { refreshPending = false; });
|
|
75
|
+
}, 500);
|
|
76
|
+
timer.unref();
|
|
77
|
+
}
|
|
62
78
|
return authority;
|
|
63
79
|
} catch (error) { client.close(); rmSync(path, { force: true }); rmSync(staging, { force: true }); throw error; }
|
|
64
80
|
}
|
package/catalog-preferences.ts
CHANGED
|
@@ -32,7 +32,7 @@ function preferences(id: string, value: unknown): CatalogPreference {
|
|
|
32
32
|
}
|
|
33
33
|
|
|
34
34
|
function snapshot(values: CatalogPreferences): { settings: CatalogPreferences; digest: string } {
|
|
35
|
-
const settings = Object.freeze(Object.fromEntries(Object.keys(values).sort().map(id => [id, values[id]])));
|
|
35
|
+
const settings = Object.freeze(Object.fromEntries(Object.keys(values).sort().map(id => [id, values[id]!])));
|
|
36
36
|
return { settings, digest: createHash("sha256").update(JSON.stringify(settings)).digest("hex") };
|
|
37
37
|
}
|
|
38
38
|
|
package/catalog-resolver.ts
CHANGED
|
@@ -218,7 +218,41 @@ export function inspectCatalog(snapshot: CatalogSnapshot, id: string): CatalogIn
|
|
|
218
218
|
};
|
|
219
219
|
}
|
|
220
220
|
|
|
221
|
+
export const catalogResolutionMetrics = { assemblies: 0, hits: 0 };
|
|
222
|
+
const resolutions = new Map<string, Resolution>();
|
|
223
|
+
|
|
224
|
+
function resolveCached(snapshot: CatalogSnapshot, id: string, compute: () => Resolution): Resolution {
|
|
225
|
+
const entry = findEntry(snapshot, id);
|
|
226
|
+
if (!entry) return compute();
|
|
227
|
+
const roleId = entry.definition?.kind === "agent" ? entry.definition.roleId : undefined;
|
|
228
|
+
const role = roleId ? findEntry(snapshot, roleId) : undefined;
|
|
229
|
+
// Only the selected definition, its base role and their own preferences contribute.
|
|
230
|
+
const key = JSON.stringify([{ ...entry, unused: undefined }, role && { ...role, unused: undefined }, snapshot.savedSettings?.[id], roleId && snapshot.savedSettings?.[roleId],
|
|
231
|
+
snapshot.sessionSettings?.[id], roleId && snapshot.sessionSettings?.[roleId]]);
|
|
232
|
+
const cached = resolutions.get(key);
|
|
233
|
+
if (cached) {
|
|
234
|
+
catalogResolutionMetrics.hits++;
|
|
235
|
+
const result = structuredClone(cached);
|
|
236
|
+
result.entry = entry;
|
|
237
|
+
if (result.effective) result.effective.snapshotDigest = snapshot.digest;
|
|
238
|
+
return result;
|
|
239
|
+
}
|
|
240
|
+
catalogResolutionMetrics.assemblies++;
|
|
241
|
+
const result = compute();
|
|
242
|
+
if (new TextEncoder().encode(key).byteLength <= 64 * 1024) resolutions.set(key, structuredClone(result));
|
|
243
|
+
if (resolutions.size > 512) resolutions.delete(resolutions.keys().next().value!);
|
|
244
|
+
return result;
|
|
245
|
+
}
|
|
246
|
+
|
|
221
247
|
function resolveRole(snapshot: CatalogSnapshot, roleId: string): Resolution {
|
|
248
|
+
return resolveCached(snapshot, roleId, () => resolveRoleUncached(snapshot, roleId));
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function resolveAgent(snapshot: CatalogSnapshot, agentId: string): Resolution {
|
|
252
|
+
return resolveCached(snapshot, agentId, () => resolveAgentUncached(snapshot, agentId));
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function resolveRoleUncached(snapshot: CatalogSnapshot, roleId: string): Resolution {
|
|
222
256
|
const entry = findEntry(snapshot, roleId);
|
|
223
257
|
if (!entry || entry.kind !== "role") {
|
|
224
258
|
return {
|
|
@@ -268,7 +302,7 @@ function resolveRole(snapshot: CatalogSnapshot, roleId: string): Resolution {
|
|
|
268
302
|
};
|
|
269
303
|
}
|
|
270
304
|
|
|
271
|
-
function
|
|
305
|
+
function resolveAgentUncached(snapshot: CatalogSnapshot, agentId: string): Resolution {
|
|
272
306
|
const entry = findEntry(snapshot, agentId);
|
|
273
307
|
if (!entry || entry.kind !== "agent") {
|
|
274
308
|
return {
|
package/catalog-store.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Filesystem catalog: project, personal, and bundled sources.
|
|
3
3
|
*
|
|
4
|
-
* Discovery is deterministic
|
|
5
|
-
*
|
|
4
|
+
* Discovery is deterministic. Direct callers read disk on every call; the server
|
|
5
|
+
* can supply bounded source reuse after admission. Callers launching a batch retain the snapshot
|
|
6
6
|
* and reuse that object for every job.
|
|
7
7
|
*
|
|
8
8
|
* Project files are read only when `projectTrusted` is true. Pass Pi's
|
|
@@ -51,6 +51,13 @@ export const DEFAULT_PROJECT_CONFIG_DIR_NAME = ".pi";
|
|
|
51
51
|
export const SOURCE_PRECEDENCE = ["project", "user", "bundled"] as const;
|
|
52
52
|
|
|
53
53
|
export interface LoadCatalogInput {
|
|
54
|
+
/** Server-owned, bounded source reuse. Admission and discovery still run first. */
|
|
55
|
+
sources?: {
|
|
56
|
+
read(path: string): string;
|
|
57
|
+
parse(raw: string, path: string): ParseResult;
|
|
58
|
+
entry?(entry: CatalogEntry): CatalogEntry;
|
|
59
|
+
preferences?(root: string): ReturnType<typeof readCatalogPreferences>;
|
|
60
|
+
};
|
|
54
61
|
cwd: string;
|
|
55
62
|
/** Host trust decision. Untrusted projects do not contribute definitions. */
|
|
56
63
|
projectTrusted: boolean;
|
|
@@ -195,13 +202,13 @@ export function listScopedAgents(input: LoadCatalogInput, scope: "user" | "proje
|
|
|
195
202
|
if (!isSafeConfigDirName(config)) throw new Error("Unsafe project config directory");
|
|
196
203
|
const directory = scope === "project" ? projectCatalogPaths(input.cwd, config).agents : userCatalogPaths(input.userRoot).agents;
|
|
197
204
|
const occurrences = new Map<string, Occurrence[]>();
|
|
198
|
-
collectDirectory(directory, scope, "agent", occurrences, diagnostics);
|
|
205
|
+
collectDirectory(directory, scope, "agent", occurrences, diagnostics, input.sources);
|
|
199
206
|
const agents = [...occurrences.values()].flat().flatMap(item => item.parse.definition?.kind === "agent"
|
|
200
207
|
? [{ path: item.path, definition: item.parse.definition }] : []);
|
|
201
208
|
return { agents, diagnostics };
|
|
202
209
|
}
|
|
203
210
|
|
|
204
|
-
/**
|
|
211
|
+
/** Discover authorized sources. Identical bytes produce the same content digest. */
|
|
205
212
|
export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
|
|
206
213
|
const loadedAt = new Date().toISOString();
|
|
207
214
|
const diagnostics: Diagnostic[] = [];
|
|
@@ -219,8 +226,8 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
|
|
|
219
226
|
|
|
220
227
|
if (input.projectTrusted) {
|
|
221
228
|
const project = projectCatalogPaths(input.cwd, configDirName);
|
|
222
|
-
collectDirectory(project.roles, "project", "role", groups.get("project")!, diagnostics);
|
|
223
|
-
collectDirectory(project.agents, "project", "agent", groups.get("project")!, diagnostics);
|
|
229
|
+
collectDirectory(project.roles, "project", "role", groups.get("project")!, diagnostics, input.sources);
|
|
230
|
+
collectDirectory(project.agents, "project", "agent", groups.get("project")!, diagnostics, input.sources);
|
|
224
231
|
} else {
|
|
225
232
|
const project = projectCatalogPaths(input.cwd, configDirName);
|
|
226
233
|
if (pathExists(project.roles) || pathExists(project.agents) || pathExists(project.root)) {
|
|
@@ -233,8 +240,8 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
|
|
|
233
240
|
}
|
|
234
241
|
|
|
235
242
|
const user = userCatalogPaths(input.userRoot);
|
|
236
|
-
collectDirectory(user.roles, "user", "role", groups.get("user")!, diagnostics);
|
|
237
|
-
collectDirectory(user.agents, "user", "agent", groups.get("user")!, diagnostics);
|
|
243
|
+
collectDirectory(user.roles, "user", "role", groups.get("user")!, diagnostics, input.sources);
|
|
244
|
+
collectDirectory(user.agents, "user", "agent", groups.get("user")!, diagnostics, input.sources);
|
|
238
245
|
|
|
239
246
|
const bundledRoles = input.bundledRoot ?? bundledRolesRoot();
|
|
240
247
|
if (!existsSync(bundledRoles)) {
|
|
@@ -246,24 +253,22 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
|
|
|
246
253
|
severity: "warning",
|
|
247
254
|
}));
|
|
248
255
|
} else {
|
|
249
|
-
collectDirectory(bundledRoles, "bundled", "role", groups.get("bundled")!, diagnostics);
|
|
256
|
+
collectDirectory(bundledRoles, "bundled", "role", groups.get("bundled")!, diagnostics, input.sources);
|
|
250
257
|
}
|
|
251
258
|
if (input.bundledAgentsRoot) {
|
|
252
|
-
collectDirectory(input.bundledAgentsRoot, "bundled", "agent", groups.get("bundled")!, diagnostics);
|
|
259
|
+
collectDirectory(input.bundledAgentsRoot, "bundled", "agent", groups.get("bundled")!, diagnostics, input.sources);
|
|
253
260
|
}
|
|
254
261
|
|
|
255
262
|
const { entries, blocked } = selectIdentities(groups, diagnostics);
|
|
256
263
|
const savedSettings: Record<string, { model?: string | null; effort?: ThinkingLevel | null }> = {};
|
|
257
264
|
const preferenceSources: Record<string, Partial<Record<"model" | "effort", { scope: "user" | "project"; path: string; bundled?: boolean }>>> = {};
|
|
258
|
-
const preferenceDigests: string[] = [];
|
|
259
265
|
const scopes = [
|
|
260
266
|
{ scope: "user" as const, root: user.root },
|
|
261
267
|
...(input.projectTrusted ? [{ scope: "project" as const, root: projectCatalogPaths(input.cwd, configDirName).root }] : []),
|
|
262
268
|
];
|
|
263
269
|
for (const { scope, root } of scopes) {
|
|
264
270
|
try {
|
|
265
|
-
const preferences = readCatalogPreferences(root);
|
|
266
|
-
preferenceDigests.push(preferences.digest);
|
|
271
|
+
const preferences = input.sources?.preferences?.(root) ?? readCatalogPreferences(root);
|
|
267
272
|
for (const entry of entries) {
|
|
268
273
|
if (scope === "user" && entry.scope === "project") continue;
|
|
269
274
|
const own = preferences.settings[entry.id];
|
|
@@ -272,8 +277,8 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
|
|
|
272
277
|
if (own.bundled) {
|
|
273
278
|
const fallbacks = entry.scope === "bundled" ? [entry] : entry.unused.filter(source => source.scope === "bundled");
|
|
274
279
|
const fallback = fallbacks.length === 1 ? fallbacks[0] : undefined;
|
|
275
|
-
const raw = fallback ? readFileSync(fallback.path, "utf8") : undefined;
|
|
276
|
-
const parsed = raw === undefined ? undefined : parseDefinition(raw, fallback!.path);
|
|
280
|
+
const raw = fallback ? (input.sources?.read(fallback.path) ?? readFileSync(fallback.path, "utf8")) : undefined;
|
|
281
|
+
const parsed = raw === undefined ? undefined : (input.sources?.parse(raw, fallback!.path) ?? parseDefinition(raw, fallback!.path));
|
|
277
282
|
if (!fallback || !parsed?.ok || parsed.definition?.id !== entry.id || parsed.diagnostics.some(item => item.blocking)
|
|
278
283
|
|| contentDigest(raw!) !== fallback.contentDigest) {
|
|
279
284
|
const failure = diagnostic("catalog-preferences", `Cannot inherit bundled runtime defaults for ${entry.id}: a single valid bundled definition is required.`, {
|
|
@@ -309,8 +314,8 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
|
|
|
309
314
|
}
|
|
310
315
|
}
|
|
311
316
|
}
|
|
312
|
-
const snapshot = finishSnapshot(entries, blocked, diagnostics, loadedAt);
|
|
313
|
-
const digest = contentDigest(JSON.stringify([snapshot.digest,
|
|
317
|
+
const snapshot = finishSnapshot(entries, blocked, diagnostics, loadedAt, input.sources);
|
|
318
|
+
const digest = contentDigest(JSON.stringify([snapshot.digest, savedSettings, preferenceSources]));
|
|
314
319
|
return deepFreeze({ ...snapshot, digest, revision: digest, savedSettings, preferenceSources });
|
|
315
320
|
}
|
|
316
321
|
|
|
@@ -526,6 +531,7 @@ function collectDirectory(
|
|
|
526
531
|
directoryKind: CatalogKind,
|
|
527
532
|
into: Map<string, Occurrence[]>,
|
|
528
533
|
diagnostics: Diagnostic[],
|
|
534
|
+
sources?: LoadCatalogInput["sources"],
|
|
529
535
|
): void {
|
|
530
536
|
let stats;
|
|
531
537
|
try {
|
|
@@ -602,7 +608,7 @@ function collectDirectory(
|
|
|
602
608
|
if (!fileStats.isFile()) continue;
|
|
603
609
|
let raw: string;
|
|
604
610
|
try {
|
|
605
|
-
raw = readFileSync(path, "utf8");
|
|
611
|
+
raw = sources?.read(path) ?? readFileSync(path, "utf8");
|
|
606
612
|
} catch (error) {
|
|
607
613
|
diagnostics.push(diagnostic(DiagnosticCodes.ioError, `Could not read ${path}: ${(error as Error).message}`, {
|
|
608
614
|
scope,
|
|
@@ -614,7 +620,7 @@ function collectDirectory(
|
|
|
614
620
|
}
|
|
615
621
|
let parse: ParseResult;
|
|
616
622
|
try {
|
|
617
|
-
parse = parseDefinition(raw, path);
|
|
623
|
+
parse = sources?.parse(raw, path) ?? parseDefinition(raw, path);
|
|
618
624
|
} catch (error) {
|
|
619
625
|
const detail = error instanceof Error ? error.message : String(error);
|
|
620
626
|
diagnostics.push(diagnostic(
|
|
@@ -765,11 +771,12 @@ function finishSnapshot(
|
|
|
765
771
|
blocked: CatalogEntry[],
|
|
766
772
|
diagnostics: Diagnostic[],
|
|
767
773
|
loadedAt: string,
|
|
774
|
+
sources?: LoadCatalogInput["sources"],
|
|
768
775
|
): CatalogSnapshot {
|
|
769
776
|
const roleEntries: Array<readonly [string, CatalogEntry]> = [];
|
|
770
777
|
const agentEntries: Array<readonly [string, CatalogEntry]> = [];
|
|
771
778
|
for (const entry of entries) {
|
|
772
|
-
const frozen = deepFreeze(cloneEntry(entry));
|
|
779
|
+
const frozen = sources?.entry?.(entry) ?? deepFreeze(cloneEntry(entry));
|
|
773
780
|
if (frozen.kind === "role") roleEntries.push([frozen.id, frozen]);
|
|
774
781
|
else agentEntries.push([frozen.id, frozen]);
|
|
775
782
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { withFileMutationQueue, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { createApplyPatchToolDefinition } from "./shared-task-apply-patch.ts";
|
|
3
|
+
import { createTaskFileOperations } from "./shared-task-files.ts";
|
|
4
|
+
|
|
5
|
+
/** Ordinary worker implementation. Confined workers install their own guarded definition. */
|
|
6
|
+
export default function childApplyPatch(pi: ExtensionAPI): void {
|
|
7
|
+
const files = createTaskFileOperations({ requireLaunchPlan: () => ({ confined: false }) });
|
|
8
|
+
const tool = createApplyPatchToolDefinition(process.cwd(), {
|
|
9
|
+
readFile: files.read.readFile, writeFile: files.write.writeFile, mkdir: files.write.mkdir,
|
|
10
|
+
remove: files.remove.remove, checkWrite: files.check.write, checkRemove: files.check.remove,
|
|
11
|
+
}, withFileMutationQueue);
|
|
12
|
+
pi.registerTool(tool as Parameters<ExtensionAPI["registerTool"]>[0]);
|
|
13
|
+
}
|