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/child-dependencies.mjs
CHANGED
|
@@ -70,28 +70,33 @@ export async function resolveChildClosure({ resolution, model, virtual = false,
|
|
|
70
70
|
load = loadContract, configPaths = [] }) {
|
|
71
71
|
const result = { ...resolution, specs: [], reasons: { ...resolution.reasons }, paths: {}, declarations: [],
|
|
72
72
|
providers: [], modelGroups: [], fingerprints: configPaths.map(path => ({ path, hash: fingerprint(path) })) };
|
|
73
|
+
function requiredPath(spec, from) {
|
|
74
|
+
const path = resolvePath(spec, from);
|
|
75
|
+
if (path) return path;
|
|
76
|
+
const reason = (resolution.reasons[spec] ?? []).join(', ');
|
|
77
|
+
throw new Error(`Child dependency ${spec}${from ? ` required by ${from}` : ''} is not installed.${reason ? ` Selected for ${reason}.` : ''}`);
|
|
78
|
+
}
|
|
73
79
|
if (resolution.mode !== 'isolated') {
|
|
74
80
|
if (virtual) throw new Error(`Virtual model ${model} requires isolated mode with a declared supplier; ${resolution.mode} mode is unsupported.`);
|
|
75
|
-
return { ...result, specs: resolution.specs, paths: Object.fromEntries(resolution.specs.map(spec =>
|
|
76
|
-
const path = resolvePath(spec);
|
|
77
|
-
if (!path) throw new Error(`Child dependency ${spec} is not installed.`);
|
|
78
|
-
return [spec, path];
|
|
79
|
-
})) };
|
|
81
|
+
return { ...result, specs: resolution.specs, paths: Object.fromEntries(resolution.specs.map(spec => [spec, requiredPath(spec)])) };
|
|
80
82
|
}
|
|
81
83
|
const providerMap = { ...BUILTIN_PROVIDER_EXTENSIONS, ...(config.providerExtensions ?? {}) };
|
|
82
|
-
const active = [], done = new Set();
|
|
84
|
+
const active = [], done = new Set(), entrypoints = new Set();
|
|
83
85
|
let ownsVirtual = false;
|
|
84
86
|
const visit = async (spec, from) => {
|
|
85
|
-
const path =
|
|
86
|
-
if (!path) throw new Error(`Child dependency ${spec}${from ? ` required by ${from}` : ''} is not installed.`);
|
|
87
|
+
const path = requiredPath(spec, from);
|
|
87
88
|
const root = packageRoot(path);
|
|
88
89
|
const identity = root ?? realpathSync(path);
|
|
89
90
|
if (active.includes(identity)) throw new Error(`Child dependency cycle: ${[...active, identity].join(' -> ')}`);
|
|
90
|
-
|
|
91
|
-
|
|
91
|
+
// Different tool entrypoints can share a package and its dependency manifest.
|
|
92
|
+
const entrypoint = realpathSync(path);
|
|
93
|
+
if (entrypoints.has(entrypoint)) return;
|
|
94
|
+
entrypoints.add(entrypoint);
|
|
92
95
|
// Two packages may declare the same relative spec against different roots.
|
|
93
96
|
const key = result.paths[spec] && result.paths[spec] !== path ? path : spec;
|
|
94
97
|
result.specs.push(key); result.paths[key] = path;
|
|
98
|
+
if (done.has(identity)) return;
|
|
99
|
+
active.push(identity);
|
|
95
100
|
if (root) {
|
|
96
101
|
const manifestPath = join(root, 'package.json');
|
|
97
102
|
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
@@ -137,7 +142,7 @@ export async function resolveChildLaunch(options, trustedPaths = []) {
|
|
|
137
142
|
}
|
|
138
143
|
|
|
139
144
|
/** Validate actual child registration, never the parent's catalog. Groups require one physical candidate. */
|
|
140
|
-
export async function checkChildPreflight(plan, { registry, tools, model }, load = loadContract) {
|
|
145
|
+
export async function checkChildPreflight(plan, { registry, tools, registeredTools = [], model }, load = loadContract) {
|
|
141
146
|
if (plan.configSnapshot && JSON.stringify(configSnapshot(plan.configSnapshot.map(item => item.dir))) !== JSON.stringify(plan.configSnapshot))
|
|
142
147
|
throw new Error('Child configuration drift: agent or project JSON configuration changed. Launch again.');
|
|
143
148
|
for (const item of plan.fingerprints) if (fingerprint(item.path) !== item.hash)
|
|
@@ -157,5 +162,13 @@ export async function checkChildPreflight(plan, { registry, tools, model }, load
|
|
|
157
162
|
for (const group of plan.modelGroups) if (!available.some(m => m.provider === group.provider && m.api !== 'pi-virtual' &&
|
|
158
163
|
(group.ids.includes(m.id) || (group.prefix && m.id.startsWith(group.prefix)))))
|
|
159
164
|
throw new Error(`Child has no available candidate for ${group.provider}: ${group.ids.join(', ')}${group.prefix ? ` (prefix ${group.prefix})` : ''}. Check extension, models and credentials.`);
|
|
160
|
-
|
|
165
|
+
const inactive = [];
|
|
166
|
+
for (const tool of plan.tools) {
|
|
167
|
+
if (tools.includes(tool)) continue;
|
|
168
|
+
if (!plan.optionalTrustedTools?.includes(tool) || !registeredTools.includes(tool)) {
|
|
169
|
+
throw new Error(`Child requested tool ${tool} is unavailable.`);
|
|
170
|
+
}
|
|
171
|
+
inactive.push(tool);
|
|
172
|
+
}
|
|
173
|
+
return inactive;
|
|
161
174
|
}
|
package/child-operations.ts
CHANGED
|
@@ -20,6 +20,7 @@ import { connect, type Socket } from "node:net";
|
|
|
20
20
|
import * as piSdk from "@earendil-works/pi-coding-agent";
|
|
21
21
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
22
22
|
import { captureParkCheckpoint, type ParkCheckpoint } from "./park-checkpoint.ts";
|
|
23
|
+
import { supportsPromptSections } from "./shared-execution-policy.ts";
|
|
23
24
|
import {
|
|
24
25
|
ACKNOWLEDGE_OPERATION_TOOL,
|
|
25
26
|
OPERATION_BRIDGE_ENV_KEYS,
|
|
@@ -28,12 +29,14 @@ import {
|
|
|
28
29
|
OPERATIONS_ATTEMPT_ID_ENV,
|
|
29
30
|
OPERATIONS_CHILD_ID_ENV,
|
|
30
31
|
OPERATIONS_CONVERSATION_ID_ENV,
|
|
32
|
+
OPERATIONS_DEADLINE_AT_ENV,
|
|
31
33
|
OPERATIONS_ENABLED_ENV,
|
|
32
34
|
OPERATIONS_ENDPOINT_ENV,
|
|
33
35
|
OPERATIONS_RUN_ID_ENV,
|
|
34
36
|
OPERATIONS_TOKEN_ENV,
|
|
35
37
|
OPERATIONS_WRITER_LEASE_ID_ENV,
|
|
36
38
|
WAIT_OPERATIONS_TOOL,
|
|
39
|
+
assertWaitToolDependencies,
|
|
37
40
|
OperationBridgeError,
|
|
38
41
|
OperationToolError,
|
|
39
42
|
type JsonRecord,
|
|
@@ -54,6 +57,7 @@ import {
|
|
|
54
57
|
requiresParkCheckpoint,
|
|
55
58
|
parseBridgeEndpoint,
|
|
56
59
|
validateJsonSchemaSupport,
|
|
60
|
+
validateJsonSchema,
|
|
57
61
|
redactSecret,
|
|
58
62
|
} from "./operation-bridge-types.ts";
|
|
59
63
|
|
|
@@ -67,6 +71,7 @@ export interface ChildOperationBridgeConfig {
|
|
|
67
71
|
attemptId?: string;
|
|
68
72
|
writerLeaseId?: string;
|
|
69
73
|
childId?: string;
|
|
74
|
+
deadlineAt?: number | null;
|
|
70
75
|
requestTimeoutMs?: number;
|
|
71
76
|
}
|
|
72
77
|
|
|
@@ -120,6 +125,10 @@ export function readChildOperationBridgeConfig(env: NodeJS.ProcessEnv = process.
|
|
|
120
125
|
const token = env[OPERATIONS_TOKEN_ENV]!;
|
|
121
126
|
const runId = env[OPERATIONS_RUN_ID_ENV]!;
|
|
122
127
|
const conversationId = env[OPERATIONS_CONVERSATION_ID_ENV]!;
|
|
128
|
+
const deadline = env[OPERATIONS_DEADLINE_AT_ENV];
|
|
129
|
+
if (deadline !== undefined && (!/^\d+$/.test(deadline) || !Number.isSafeInteger(Number(deadline)))) {
|
|
130
|
+
return { status: "invalid", reason: "operation bridge assignment deadline is invalid" };
|
|
131
|
+
}
|
|
123
132
|
try {
|
|
124
133
|
parseBridgeEndpoint(endpoint);
|
|
125
134
|
} catch {
|
|
@@ -138,6 +147,7 @@ export function readChildOperationBridgeConfig(env: NodeJS.ProcessEnv = process.
|
|
|
138
147
|
token,
|
|
139
148
|
runId,
|
|
140
149
|
conversationId,
|
|
150
|
+
...(deadline !== undefined ? { deadlineAt: Number(deadline) || null } : {}),
|
|
141
151
|
...(env[OPERATIONS_ATTEMPT_ID_ENV] ? { attemptId: env[OPERATIONS_ATTEMPT_ID_ENV]! } : {}),
|
|
142
152
|
...(env[OPERATIONS_WRITER_LEASE_ID_ENV] ? { writerLeaseId: env[OPERATIONS_WRITER_LEASE_ID_ENV]! } : {}),
|
|
143
153
|
...(env[OPERATIONS_CHILD_ID_ENV] ? { childId: env[OPERATIONS_CHILD_ID_ENV]! } : {}),
|
|
@@ -488,6 +498,7 @@ export function verifyDescriptor(value: unknown, config: Pick<ChildOperationBrid
|
|
|
488
498
|
}));
|
|
489
499
|
}
|
|
490
500
|
const capabilities = validateCapabilities(record.capabilities);
|
|
501
|
+
assertWaitToolDependencies(capabilities, [...seen]);
|
|
491
502
|
if (seen.has(WAIT_OPERATIONS_TOOL) && !(capabilities.wait && capabilities.parking)) {
|
|
492
503
|
throw new OperationBridgeError("invalid-request", "parent exposed wait_for_operations without a parking capability");
|
|
493
504
|
}
|
|
@@ -809,7 +820,19 @@ export function installChildOperationBridge(
|
|
|
809
820
|
let installed = false;
|
|
810
821
|
let starting: Promise<void> | undefined;
|
|
811
822
|
let completingPark = false;
|
|
823
|
+
let completion = { correctionUsed: false, reported: false };
|
|
824
|
+
let reportError: string | undefined;
|
|
825
|
+
let bridgeConfig: ChildOperationBridgeConfig | undefined;
|
|
812
826
|
const env = options.env ?? process.env;
|
|
827
|
+
const completionEntryType = "pi-subagent-completion";
|
|
828
|
+
|
|
829
|
+
const canCorrectCompletion = (signal?: AbortSignal): boolean => state.status === "ready"
|
|
830
|
+
&& !completion.correctionUsed && !completion.reported && !signal?.aborted
|
|
831
|
+
&& (bridgeConfig?.deadlineAt == null || Date.now() < bridgeConfig.deadlineAt);
|
|
832
|
+
|
|
833
|
+
function saveCompletion(): void {
|
|
834
|
+
pi.appendEntry(completionEntryType, { attemptId: bridgeConfig?.attemptId ?? bridgeConfig?.runId, ...completion });
|
|
835
|
+
}
|
|
813
836
|
|
|
814
837
|
const handle: ChildOperationBridgeHandle = {
|
|
815
838
|
getState: () => ({ ...state, ...(state.descriptor ? { descriptor: state.descriptor } : {}) }),
|
|
@@ -843,7 +866,7 @@ export function installChildOperationBridge(
|
|
|
843
866
|
if (activeToolExecutions === 0) restoreBridgeEnvironment();
|
|
844
867
|
});
|
|
845
868
|
|
|
846
|
-
pi.on("session_start", async (_event,
|
|
869
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
847
870
|
if (installed || starting) return starting;
|
|
848
871
|
starting = (async () => {
|
|
849
872
|
const read = options.config
|
|
@@ -856,6 +879,7 @@ export function installChildOperationBridge(
|
|
|
856
879
|
return;
|
|
857
880
|
}
|
|
858
881
|
state.status = "connecting";
|
|
882
|
+
bridgeConfig = read.config;
|
|
859
883
|
options.onDiagnostic?.({ event: "connecting" });
|
|
860
884
|
const active = (options.clientFactory ?? ((config) => createOperationBridgeClient(config, {
|
|
861
885
|
requestTimeoutMs: options.requestTimeoutMs,
|
|
@@ -872,6 +896,17 @@ export function installChildOperationBridge(
|
|
|
872
896
|
}
|
|
873
897
|
client = active;
|
|
874
898
|
state.descriptor = descriptor;
|
|
899
|
+
if (descriptor.capabilities.reportAssignment) {
|
|
900
|
+
const entries = ctx.sessionManager.getEntries();
|
|
901
|
+
for (let index = entries.length - 1; index >= 0; index--) {
|
|
902
|
+
const entry = entries[index]!;
|
|
903
|
+
if (entry.type !== "custom" || entry.customType !== completionEntryType) continue;
|
|
904
|
+
const data = entry.data as { attemptId?: string; correctionUsed?: boolean; reported?: boolean } | undefined;
|
|
905
|
+
if (data?.attemptId !== (read.config.attemptId ?? read.config.runId)) continue;
|
|
906
|
+
completion = { correctionUsed: data.correctionUsed === true, reported: data.reported === true };
|
|
907
|
+
break;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
875
910
|
try {
|
|
876
911
|
registerTools(descriptor, state.parkingSupported === true);
|
|
877
912
|
} catch (error) {
|
|
@@ -889,6 +924,31 @@ export function installChildOperationBridge(
|
|
|
889
924
|
return starting;
|
|
890
925
|
});
|
|
891
926
|
|
|
927
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
928
|
+
if (!state.descriptor?.capabilities.reportAssignment) return;
|
|
929
|
+
const instruction = `Assignment completion: call report_assignment_result before returning. Evidence sources must resolve inside this assigned workspace: ${JSON.stringify(ctx.cwd)}. A sibling output directory is outside that boundary; use an existing workspace file or place the reportable artifact inside the workspace. Use offset and max_bytes for evidence larger than 65536 bytes. Continue remaining local work within the existing deadline, or report a concrete blocker; do not infer a tool-call budget from the number of calls you have made.`;
|
|
930
|
+
if (!supportsPromptSections(event.systemPromptOptions)) return { systemPrompt: `${event.systemPrompt}\n\n${instruction}` };
|
|
931
|
+
const prompt = event.systemPromptOptions as { sections?: Record<string, string> };
|
|
932
|
+
(prompt.sections ??= {}).assignment_completion = instruction;
|
|
933
|
+
});
|
|
934
|
+
|
|
935
|
+
pi.on("agent_end", (event, ctx) => {
|
|
936
|
+
if (!state.descriptor?.capabilities.reportAssignment || !canCorrectCompletion(ctx.signal)) return;
|
|
937
|
+
let last;
|
|
938
|
+
for (let index = event.messages.length - 1; index >= 0; index--) {
|
|
939
|
+
const message = event.messages[index]!;
|
|
940
|
+
if (message.role !== "assistant") continue;
|
|
941
|
+
last = message;
|
|
942
|
+
break;
|
|
943
|
+
}
|
|
944
|
+
if (last?.stopReason !== "stop") return;
|
|
945
|
+
completion.correctionUsed = true;
|
|
946
|
+
saveCompletion();
|
|
947
|
+
pi.sendMessage({ customType: "assignment-completion-correction", display: false,
|
|
948
|
+
content: `The assignment has no accepted report. ${reportError ? `The latest report was refused: ${reportError}. ` : ""}This is the one completion correction for this execution attempt, within its original authority and deadline. Finish available remaining work, inspect and acknowledge any outstanding operation evidence, then call report_assignment_result with workspace evidence. If progress is blocked or work remains, report incomplete with remaining_work and the concrete blocker. Do not claim completion from process exit or final prose.` },
|
|
949
|
+
{ deliverAs: "followUp", triggerTurn: true });
|
|
950
|
+
});
|
|
951
|
+
|
|
892
952
|
pi.on("message_end", (event) => {
|
|
893
953
|
const message = event.message as { role?: string; content?: unknown };
|
|
894
954
|
if (message.role !== "assistant" || !Array.isArray(message.content)) return;
|
|
@@ -963,6 +1023,7 @@ export function installChildOperationBridge(
|
|
|
963
1023
|
try {
|
|
964
1024
|
return await invokeTool(tool, toolCallId, params, signal);
|
|
965
1025
|
} catch (error) {
|
|
1026
|
+
if (tool.name === "report_assignment_result") reportError = redactSecret(error instanceof Error ? error.message : String(error)).slice(0, 2048);
|
|
966
1027
|
return toolErrorResult(error);
|
|
967
1028
|
}
|
|
968
1029
|
},
|
|
@@ -981,6 +1042,13 @@ export function installChildOperationBridge(
|
|
|
981
1042
|
throw new OperationToolError("tool parameters must be an object");
|
|
982
1043
|
}
|
|
983
1044
|
const params = rawParams as JsonRecord;
|
|
1045
|
+
if (tool.name === "report_assignment_result" && params.status === "incomplete" && !params.blocker
|
|
1046
|
+
&& Array.isArray(params.remaining_work) && params.remaining_work.length > 0
|
|
1047
|
+
&& validateJsonSchema(tool.parameters, params).ok && canCorrectCompletion(signal)) {
|
|
1048
|
+
completion.correctionUsed = true;
|
|
1049
|
+
saveCompletion();
|
|
1050
|
+
throw new OperationToolError("The incomplete report has not been accepted. Use the one completion correction to continue the listed remaining local work within the original authority and deadline, then report the result. If blocked or still incomplete, report that explicitly; no further automatic correction will be requested.");
|
|
1051
|
+
}
|
|
984
1052
|
if (isLaunchTool(tool.name, params)) {
|
|
985
1053
|
const bridgeEnvironmentField = findBridgeEnvironmentKey(params);
|
|
986
1054
|
if (bridgeEnvironmentField) {
|
|
@@ -991,6 +1059,17 @@ export function installChildOperationBridge(
|
|
|
991
1059
|
}
|
|
992
1060
|
}
|
|
993
1061
|
const raw = await client.request(tool.name, params, { signal });
|
|
1062
|
+
if (tool.name === "report_assignment_result" && raw && typeof raw === "object"
|
|
1063
|
+
&& ["complete", "incomplete"].includes(String((raw as JsonRecord).status))) {
|
|
1064
|
+
completion.reported = true;
|
|
1065
|
+
reportError = undefined;
|
|
1066
|
+
saveCompletion();
|
|
1067
|
+
}
|
|
1068
|
+
if (tool.name === ACKNOWLEDGE_OPERATION_TOOL && params.disposition === "assignment-complete"
|
|
1069
|
+
&& raw && typeof raw === "object" && (raw as JsonRecord).phase === "consumed") {
|
|
1070
|
+
completion.reported = true;
|
|
1071
|
+
saveCompletion();
|
|
1072
|
+
}
|
|
994
1073
|
if (tool.name === WAIT_OPERATIONS_TOOL) {
|
|
995
1074
|
return waitToolResult(toolCallId, raw);
|
|
996
1075
|
}
|
package/child-preflight.mjs
CHANGED
|
@@ -9,12 +9,18 @@ export default function childPreflight(pi) {
|
|
|
9
9
|
};
|
|
10
10
|
let plan;
|
|
11
11
|
try { plan = JSON.parse(readFileSync(process.env[PREFLIGHT_ENV], 'utf8')); } catch (error) { fail(error); }
|
|
12
|
+
const reported = new Set();
|
|
12
13
|
// The task guard activates its adapters on session_start. Check after every
|
|
13
14
|
// startup handler has finished, before the first request (and subsequent runs).
|
|
14
15
|
const check = async (ctx, tools) => {
|
|
15
16
|
try {
|
|
16
|
-
await checkChildPreflight({ ...plan, tools }, { registry: ctx.modelRegistry,
|
|
17
|
-
tools: pi.getActiveTools(), model: ctx.model });
|
|
17
|
+
const inactive = await checkChildPreflight({ ...plan, tools }, { registry: ctx.modelRegistry,
|
|
18
|
+
tools: pi.getActiveTools(), registeredTools: pi.getAllTools?.().map(tool => tool.name), model: ctx.model });
|
|
19
|
+
const newlyInactive = inactive.filter(tool => !reported.has(tool));
|
|
20
|
+
if (newlyInactive.length) {
|
|
21
|
+
for (const tool of newlyInactive) reported.add(tool);
|
|
22
|
+
process.stderr.write(`Subagent child preflight: inherited trusted tools are inactive in this child: ${newlyInactive.join(', ')}. Continuing without them.\n`);
|
|
23
|
+
}
|
|
18
24
|
} catch (error) { fail(error); }
|
|
19
25
|
};
|
|
20
26
|
pi.on('session_start', async (_event, ctx) => check(ctx, []));
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { createProcessListToolDefinition } from "./shared-task-process-list.ts";
|
|
3
|
+
|
|
4
|
+
/** Keep the fixed, bounded inventory contract when no task sandbox is active. */
|
|
5
|
+
export default function childProcessList(pi: ExtensionAPI): void {
|
|
6
|
+
const tool = createProcessListToolDefinition(process.cwd(), { requireLaunchPlan: () => ({ confined: false }) }, () => "read");
|
|
7
|
+
pi.registerTool(tool as Parameters<ExtensionAPI["registerTool"]>[0]);
|
|
8
|
+
}
|
package/config.ts
CHANGED
|
@@ -9,12 +9,14 @@
|
|
|
9
9
|
* `defaultSkills` absent → the child discovers the user-level skills catalog.
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
12
|
+
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
13
13
|
import { fileURLToPath } from "node:url";
|
|
14
14
|
import { dirname, isAbsolute, join } from "node:path";
|
|
15
15
|
import { homedir } from "node:os";
|
|
16
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
17
|
+
import { toolPackage, supportsChildProvider } from "./shared-task-tools.ts";
|
|
16
18
|
import { SELF_SPEC } from "./extensions.ts";
|
|
17
|
-
import { installedPackage } from "./child-dependencies.mjs";
|
|
19
|
+
import { installedPackage, packageRoot } from "./child-dependencies.mjs";
|
|
18
20
|
import { isDelegationMode, type DelegationMode } from "./delegation.ts";
|
|
19
21
|
import { normalizeSkillExposure } from "./skills.ts";
|
|
20
22
|
import { validatedTimingMinutes, type TimingSettings } from "./timing.ts";
|
|
@@ -251,6 +253,48 @@ export function normalizeTools(list: string): string {
|
|
|
251
253
|
return list.split(",").map((t) => t.trim()).filter(Boolean).join(",");
|
|
252
254
|
}
|
|
253
255
|
|
|
256
|
+
export const ORDINARY_TOOL_PROVIDERS: Readonly<Record<string, string>> = {
|
|
257
|
+
apply_patch: join(selfDir(), "child-apply-patch.ts"),
|
|
258
|
+
process_list: join(selfDir(), "child-process-list.ts"),
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
/** Check the owning package even when a mapping points directly to one of its files. */
|
|
262
|
+
export function supportedChildEntrypoint(name: string, pkg: string, path: string): boolean {
|
|
263
|
+
return supportsChildProvider(name, pkg, packageRoot(path) ?? path);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Capture exact user-installed entrypoints already active in the foreground. */
|
|
267
|
+
export function activeChildProviders(pi: Pick<ExtensionAPI, "getActiveTools" | "getAllTools">): Record<string, string> {
|
|
268
|
+
const active = new Set(pi.getActiveTools?.() ?? []);
|
|
269
|
+
const paths = new Map<string, string>();
|
|
270
|
+
const seen = new Set<string>();
|
|
271
|
+
for (const tool of pi.getAllTools?.() ?? []) {
|
|
272
|
+
if (!active.has(tool.name)) continue;
|
|
273
|
+
// The SDK reports active names. Conflicting registrations have no unique owner.
|
|
274
|
+
if (seen.has(tool.name)) { paths.delete(tool.name); continue; }
|
|
275
|
+
seen.add(tool.name);
|
|
276
|
+
if (tool.sourceInfo?.scope !== "user") continue;
|
|
277
|
+
const owner = toolPackage(tool);
|
|
278
|
+
if (!owner || !supportsChildProvider(tool.name, owner.package, owner.root)) continue;
|
|
279
|
+
try {
|
|
280
|
+
const path = realpathSync(tool.sourceInfo.path);
|
|
281
|
+
if (!statSync(path).isFile() || !supportedChildEntrypoint(tool.name, owner.package, path)) continue;
|
|
282
|
+
paths.set(tool.name, path);
|
|
283
|
+
} catch { /* An unavailable entrypoint cannot supply a new worker. */ }
|
|
284
|
+
}
|
|
285
|
+
return Object.fromEntries(paths);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export function ordinaryChildConfig(config: SubagentConfig, activeProviders: Record<string, string> = {}): SubagentConfig {
|
|
289
|
+
const packaged = config.toolExtensions === null ? undefined : bundledConfig().toolExtensions;
|
|
290
|
+
return { ...config, toolExtensions: { ...activeProviders, ...ORDINARY_TOOL_PROVIDERS, ...packaged, ...config.toolExtensions } };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function addEditablePatch(names: string[], excluded: ReadonlySet<string>): void {
|
|
294
|
+
const editable = names.some(name => (name === "edit" || name === "write") && !excluded.has(name));
|
|
295
|
+
if (editable && !excluded.has("apply_patch") && !names.includes("apply_patch")) names.push("apply_patch");
|
|
296
|
+
}
|
|
297
|
+
|
|
254
298
|
/** This package's own root — the extension dir, which is also `self`. */
|
|
255
299
|
export function selfDir(): string {
|
|
256
300
|
return dirname(fileURLToPath(import.meta.url));
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { parseSubagentTools } from "./shared-task-tools.ts";
|
|
2
|
+
/** Intersect captured permissions with the current mandatory profile. */
|
|
3
|
+
export function intersectContinuationPermissions(captured: any, current: any): any {
|
|
4
|
+
if (!captured || !current) throw new Error("Continuation permission authority unavailable");
|
|
5
|
+
const currentTools = parseSubagentTools(current.subagentTools);
|
|
6
|
+
const capturedTools = captured.subagentTools ? parseSubagentTools(captured.subagentTools) : currentTools;
|
|
7
|
+
const allowed = new Set(currentTools.trusted.map(tool => JSON.stringify([tool.name, tool.package])));
|
|
8
|
+
const tools = { applyPatch: capturedTools.applyPatch && currentTools.applyPatch,
|
|
9
|
+
trusted: capturedTools.trusted.filter(tool => allowed.has(JSON.stringify([tool.name, tool.package])))
|
|
10
|
+
.sort((a, b) => a.name.localeCompare(b.name) || a.package.localeCompare(b.package)) };
|
|
11
|
+
const intersect = (old: any, fresh: any) => {
|
|
12
|
+
if (!old || !fresh) throw new Error("Continuation permission profile unavailable");
|
|
13
|
+
if (!fresh.enabled) return old.enabled ? { ...old } : { ...fresh };
|
|
14
|
+
if (!old.enabled) return { ...fresh };
|
|
15
|
+
const access = ["off", "read", "write", "read-write"];
|
|
16
|
+
const value = { ...fresh };
|
|
17
|
+
for (const key of ["projectFiles", "outsideProject", "storedCredentials"]) {
|
|
18
|
+
if (!access.includes(old[key]) || !access.includes(fresh[key])) throw new Error("Invalid continuation permission profile");
|
|
19
|
+
value[key] = access[Math.min(access.indexOf(old[key]), access.indexOf(fresh[key]))];
|
|
20
|
+
}
|
|
21
|
+
for (const key of ["commands", "network"]) value[key] = old[key] && fresh[key];
|
|
22
|
+
value.shell = old.shell !== false && fresh.shell !== false;
|
|
23
|
+
value.processAccess = old.processAccess === "read" && fresh.processAccess === "read" ? "read" : "off";
|
|
24
|
+
const caps = [old.commandTimeoutSeconds, fresh.commandTimeoutSeconds].filter((n) => typeof n === "number" && n > 0);
|
|
25
|
+
value.commandTimeoutSeconds = caps.length ? Math.min(...caps) : null;
|
|
26
|
+
return value;
|
|
27
|
+
};
|
|
28
|
+
return { permissions: captured.permissions ? intersect(captured.permissions, current.main) : current.main,
|
|
29
|
+
subagentPermissions: captured.subagentPermissions ? intersect(captured.subagentPermissions, current.subagents) : current.subagents,
|
|
30
|
+
subagentTools: tools };
|
|
31
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/** Select a saved, installed worker closure without changing the server owner. */
|
|
2
|
+
import { readFileSync, realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, normalize, sep } from "node:path";
|
|
4
|
+
|
|
5
|
+
const DOMAIN = join("src", "runtime", "domain", "subagents");
|
|
6
|
+
type Recipe = { runtimeRoot?: string; baseExtensionArgs?: readonly string[]; extensionArgs?: readonly string[] };
|
|
7
|
+
type Command = { file: string; fileArgs: string[] };
|
|
8
|
+
|
|
9
|
+
export function managedRuntimeRoot(domain: string): string | undefined {
|
|
10
|
+
if (!domain.endsWith(`${sep}${DOMAIN}`)) return undefined;
|
|
11
|
+
const root = domain.slice(0, -(DOMAIN.length + 1));
|
|
12
|
+
return basename(dirname(root)) === "releases" && /^[a-f0-9]{64}$/.test(basename(root)) ? root : undefined;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ContinuationRuntime {
|
|
16
|
+
root: string;
|
|
17
|
+
mapPath(path: string): string;
|
|
18
|
+
mapArgs(args: readonly string[]): string[];
|
|
19
|
+
command(command: Command): Command;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Only sibling, published releases are eligible. User extensions retain their
|
|
24
|
+
* original identity check. Permission policy is still generated by the current
|
|
25
|
+
* server; a saved runtime does not grandfather its previous permission grants.
|
|
26
|
+
* Published releases are retained by the installer (it removes staging only).
|
|
27
|
+
* Any future release GC must treat LaunchRecipe.runtimeRoot as a reference.
|
|
28
|
+
*/
|
|
29
|
+
export function selectContinuationRuntime(options: { currentDir: string; recipe?: Recipe }): ContinuationRuntime | undefined {
|
|
30
|
+
const current = managedRuntimeRoot(options.currentDir);
|
|
31
|
+
if (!current || !options.recipe) return undefined;
|
|
32
|
+
const recipe = options.recipe;
|
|
33
|
+
// Upgrade recipes written before runtimeRoot existed using the mandatory
|
|
34
|
+
// harness control, never a user-selected/custom extension path.
|
|
35
|
+
const args = recipe.baseExtensionArgs ?? recipe.extensionArgs ?? [];
|
|
36
|
+
const steer = args.find((value, index) => args[index - 1] === "--extension" && value.endsWith(`${sep}${DOMAIN}${sep}child-steer.ts`));
|
|
37
|
+
const saved = recipe.runtimeRoot ?? (steer ? managedRuntimeRoot(dirname(steer)) : undefined);
|
|
38
|
+
if (!saved || saved === current) return undefined;
|
|
39
|
+
const unavailable = (detail: string): never => {
|
|
40
|
+
throw new Error(`Cannot resume: saved runtime ${basename(saved)} unavailable (${detail}). Restore that release or explicitly launch a replacement conversation; no worker was started.`);
|
|
41
|
+
};
|
|
42
|
+
if (normalize(saved) !== saved || dirname(saved) !== dirname(current) || !/^[a-f0-9]{64}$/.test(basename(saved))) {
|
|
43
|
+
return unavailable("not a sibling managed release");
|
|
44
|
+
}
|
|
45
|
+
function manifest(root: string) {
|
|
46
|
+
let value;
|
|
47
|
+
try {
|
|
48
|
+
if (realpathSync(root) !== root) return unavailable("release path is not canonical");
|
|
49
|
+
value = JSON.parse(readFileSync(join(root, "runtime.json"), "utf8"));
|
|
50
|
+
} catch { return unavailable("missing or unreadable release manifest"); }
|
|
51
|
+
if (value.format !== 1 || value.root !== root || value.build?.contentId !== basename(root)
|
|
52
|
+
|| value.node !== join(root, "node/bin/node") || value.installRoot !== dirname(dirname(root))) {
|
|
53
|
+
return unavailable("invalid release manifest");
|
|
54
|
+
}
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
const before = manifest(saved), now = manifest(current);
|
|
58
|
+
// These releases share the existing v1 worker admission/policy/bridge wire
|
|
59
|
+
// formats. Refuse SDK, Node, platform or protocol transitions rather than
|
|
60
|
+
// assuming that a new server can host any historic worker.
|
|
61
|
+
if (before.build.protocolVersion !== 1 || now.build.protocolVersion !== 1
|
|
62
|
+
|| ["piSdkVersion", "nodeVersion", "platform"].some(key => !before.build[key] || before.build[key] !== now.build[key])) {
|
|
63
|
+
throw new Error(`Cannot resume: saved runtime ${basename(saved)} is incompatible with the current worker protocol, SDK or platform. Explicit replacement is required; no worker was started.`);
|
|
64
|
+
}
|
|
65
|
+
function required(path: string, directory = false): string {
|
|
66
|
+
try {
|
|
67
|
+
const stat = statSync(path);
|
|
68
|
+
if (realpathSync(path) !== path || !(stat.isFile() || directory && stat.isDirectory())) return unavailable("worker file is missing or redirected");
|
|
69
|
+
} catch { return unavailable("worker file is missing or unreadable"); }
|
|
70
|
+
return path;
|
|
71
|
+
}
|
|
72
|
+
const node = required(before.node);
|
|
73
|
+
const mapPath = (path: string): string => path.startsWith(`${current}${sep}`)
|
|
74
|
+
? required(join(saved, path.slice(current.length + 1)), true) : path;
|
|
75
|
+
return {
|
|
76
|
+
root: saved,
|
|
77
|
+
mapPath,
|
|
78
|
+
mapArgs: values => values.map((value, index) => values[index - 1] === "--extension" ? mapPath(value) : value),
|
|
79
|
+
command: command => {
|
|
80
|
+
// Only executable slots are rewritten. A prompt or arbitrary CLI
|
|
81
|
+
// value that happens to contain a runtime path must stay untouched.
|
|
82
|
+
const fileArgs = [...command.fileArgs];
|
|
83
|
+
fileArgs[0] = mapPath(fileArgs[0]!);
|
|
84
|
+
if (basename(fileArgs[0]!) === "task-runtime.mjs") fileArgs[1] = mapPath(fileArgs[1]!);
|
|
85
|
+
return { file: node, fileArgs };
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
package/continuation.ts
CHANGED
|
@@ -1028,3 +1028,24 @@ export function readConversationLease(sessionId: string): (LeasePayload & { raw:
|
|
|
1028
1028
|
return undefined;
|
|
1029
1029
|
}
|
|
1030
1030
|
}
|
|
1031
|
+
|
|
1032
|
+
|
|
1033
|
+
/** Release exact undispatched server ownership under the ordinary conversation lock. */
|
|
1034
|
+
export function releaseUnspawnedConversationLease(input: {
|
|
1035
|
+
sessionId: string; attemptId: string; managerPid: number; managerStart: string;
|
|
1036
|
+
canProveUnspawned(): boolean;
|
|
1037
|
+
}): boolean {
|
|
1038
|
+
return withConversationMutation(input.sessionId, () => {
|
|
1039
|
+
const lease = readConversationLease(input.sessionId);
|
|
1040
|
+
if (!lease) return true;
|
|
1041
|
+
if (lease.attemptId !== input.attemptId || lease.pid !== input.managerPid || !lease.start
|
|
1042
|
+
|| Buffer.from(lease.start).toString("base64url") !== input.managerStart) return false;
|
|
1043
|
+
if (processExists(lease.pid)) {
|
|
1044
|
+
const start = processStartToken(lease.pid);
|
|
1045
|
+
if (!start || start === lease.start) return false;
|
|
1046
|
+
}
|
|
1047
|
+
if (!input.canProveUnspawned()) return false;
|
|
1048
|
+
releaseLeaseUnlocked(leasePathFor(input.sessionId), lease.raw);
|
|
1049
|
+
return readConversationLease(input.sessionId) === undefined;
|
|
1050
|
+
}, { waitMs: RELEASE_LOCK_WAIT_MS });
|
|
1051
|
+
}
|