pi-better-subagents 0.26.1 → 0.26.2
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/child-dependencies.mjs +161 -0
- package/child-preflight.mjs +22 -0
- package/child-runtime.mjs +57 -0
- package/config.ts +8 -4
- package/extensions.mjs +1 -0
- package/index.ts +26 -12
- package/package.json +1 -1
- package/task-runtime.mjs +2 -1
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/** Declared child dependency closure. Reading a contract never initializes its extension. */
|
|
2
|
+
import { readFileSync, existsSync, statSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { dirname, join, resolve, isAbsolute } from 'node:path';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { BUILTIN_PROVIDER_EXTENSIONS, providerOf } from './extensions.mjs';
|
|
8
|
+
|
|
9
|
+
export function packageRoot(path) {
|
|
10
|
+
let dir = statSync(path).isDirectory() ? path : dirname(path);
|
|
11
|
+
while (!existsSync(join(dir, 'package.json'))) {
|
|
12
|
+
const parent = dirname(dir);
|
|
13
|
+
if (parent === dir) return undefined;
|
|
14
|
+
dir = parent;
|
|
15
|
+
}
|
|
16
|
+
return realpathSync(dir);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Search the declaring package's dependencies first, then the caller's installed roots. */
|
|
20
|
+
export function installedPackage(name, roots) {
|
|
21
|
+
for (const root of roots.filter(Boolean)) {
|
|
22
|
+
let dir = root;
|
|
23
|
+
while (true) {
|
|
24
|
+
const candidate = join(dir, 'node_modules', name);
|
|
25
|
+
if (existsSync(join(candidate, 'package.json'))) return realpathSync(candidate);
|
|
26
|
+
const parent = dirname(dir);
|
|
27
|
+
if (parent === dir) break;
|
|
28
|
+
dir = parent;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function loadContract(path) {
|
|
34
|
+
// Use the host's TS loader, with fresh module state for every declaration read.
|
|
35
|
+
const sdkRequire = createRequire(fileURLToPath(import.meta.resolve('@earendil-works/pi-coding-agent')));
|
|
36
|
+
const { createJiti } = await import(pathToFileURL(sdkRequire.resolve('jiti')).href);
|
|
37
|
+
return createJiti(import.meta.url, { tryNative: false, fsCache: false, moduleCache: false })
|
|
38
|
+
.import(path, { default: true });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function strings(value, label) {
|
|
42
|
+
if (!Array.isArray(value) || value.some(x => typeof x !== 'string' || !x.trim()))
|
|
43
|
+
throw new Error(`Invalid child declaration: ${label} must be an array of nonempty strings.`);
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
export function validateRequirements(value) {
|
|
47
|
+
if (!value || typeof value !== 'object') throw new Error('Invalid childRequirements result.');
|
|
48
|
+
strings(value.providers, 'providers');
|
|
49
|
+
if (!Array.isArray(value.modelGroups)) throw new Error('Invalid childRequirements modelGroups.');
|
|
50
|
+
for (const group of value.modelGroups) {
|
|
51
|
+
if (!group || typeof group.provider !== 'string' || !group.provider.trim()) throw new Error('Invalid model group provider.');
|
|
52
|
+
strings(group.ids, 'modelGroups.ids');
|
|
53
|
+
if (group.prefix !== undefined && (typeof group.prefix !== 'string' || !group.prefix)) throw new Error('Invalid model group prefix.');
|
|
54
|
+
if (!group.ids.length && !group.prefix) throw new Error('Empty child model group.');
|
|
55
|
+
}
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function fingerprint(path) {
|
|
60
|
+
return existsSync(path) ? createHash('sha256').update(readFileSync(path)).digest('hex') : null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Credential refresh and catalog caches are runtime state, not dependency configuration.
|
|
64
|
+
const CONFIG_INPUTS = ['settings.json', 'harness-settings.json', 'model-router.json', 'models.json'];
|
|
65
|
+
export function configSnapshot(directories) {
|
|
66
|
+
return directories.map(dir => ({ dir, files: CONFIG_INPUTS.map(name => ({ name, hash: fingerprint(join(dir, name)) })) }));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function resolveChildClosure({ resolution, model, virtual = false, config = {}, resolvePath,
|
|
70
|
+
load = loadContract, configPaths = [] }) {
|
|
71
|
+
const result = { ...resolution, specs: [], reasons: { ...resolution.reasons }, paths: {}, declarations: [],
|
|
72
|
+
providers: [], modelGroups: [], fingerprints: configPaths.map(path => ({ path, hash: fingerprint(path) })) };
|
|
73
|
+
if (resolution.mode !== 'isolated') {
|
|
74
|
+
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
|
+
})) };
|
|
80
|
+
}
|
|
81
|
+
const providerMap = { ...BUILTIN_PROVIDER_EXTENSIONS, ...(config.providerExtensions ?? {}) };
|
|
82
|
+
const active = [], done = new Set();
|
|
83
|
+
let ownsVirtual = false;
|
|
84
|
+
const visit = async (spec, from) => {
|
|
85
|
+
const path = resolvePath(spec, from);
|
|
86
|
+
if (!path) throw new Error(`Child dependency ${spec}${from ? ` required by ${from}` : ''} is not installed.`);
|
|
87
|
+
const root = packageRoot(path);
|
|
88
|
+
const identity = root ?? realpathSync(path);
|
|
89
|
+
if (active.includes(identity)) throw new Error(`Child dependency cycle: ${[...active, identity].join(' -> ')}`);
|
|
90
|
+
if (done.has(identity)) return;
|
|
91
|
+
active.push(identity);
|
|
92
|
+
// Two packages may declare the same relative spec against different roots.
|
|
93
|
+
const key = result.paths[spec] && result.paths[spec] !== path ? path : spec;
|
|
94
|
+
result.specs.push(key); result.paths[key] = path;
|
|
95
|
+
if (root) {
|
|
96
|
+
const manifestPath = join(root, 'package.json');
|
|
97
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
98
|
+
result.fingerprints.push({ path: manifestPath, hash: fingerprint(manifestPath) });
|
|
99
|
+
const declaration = manifest.pi ?? {};
|
|
100
|
+
for (const dependency of strings(declaration.childDependencies ?? [], 'pi.childDependencies')) await visit(dependency, root);
|
|
101
|
+
if (declaration.childRequirements !== undefined) {
|
|
102
|
+
if (typeof declaration.childRequirements !== 'string' || isAbsolute(declaration.childRequirements)) throw new Error(`Invalid childRequirements path in ${root}`);
|
|
103
|
+
const entry = resolve(root, declaration.childRequirements);
|
|
104
|
+
if (!entry.startsWith(root + '/')) throw new Error(`childRequirements escapes ${root}`);
|
|
105
|
+
const fn = await load(entry);
|
|
106
|
+
if (typeof fn !== 'function') throw new Error(`childRequirements in ${root} has no default function.`);
|
|
107
|
+
const requirements = await fn({ model });
|
|
108
|
+
result.fingerprints.push({ path: entry, hash: fingerprint(entry) });
|
|
109
|
+
result.declarations.push({ entry, requirements: requirements ?? null });
|
|
110
|
+
if (requirements !== undefined) {
|
|
111
|
+
validateRequirements(requirements);
|
|
112
|
+
if ((resolution.reasons[spec] ?? []).includes(`provider:${providerOf(model)}`)) ownsVirtual = true;
|
|
113
|
+
result.providers.push(...requirements.providers);
|
|
114
|
+
result.modelGroups.push(...requirements.modelGroups);
|
|
115
|
+
for (const provider of requirements.providers) {
|
|
116
|
+
const mapped = providerMap[provider];
|
|
117
|
+
for (const supplier of typeof mapped === 'string' ? [mapped] : mapped ?? []) await visit(supplier, root);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
active.pop(); done.add(identity);
|
|
123
|
+
};
|
|
124
|
+
for (const spec of resolution.specs) await visit(spec);
|
|
125
|
+
if (virtual && !ownsVirtual) throw new Error(`Virtual model ${model} has no mapped supplier with a childRequirements contract for this selection.`);
|
|
126
|
+
result.providers = [...new Set(result.providers)];
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Both passes start with declared roots; expanded specs retain their declaring context only inside a traversal. */
|
|
131
|
+
export async function resolveChildLaunch(options, trustedPaths = []) {
|
|
132
|
+
const resolution = await resolveChildClosure(options);
|
|
133
|
+
const fullResolution = await resolveChildClosure({ ...options, resolution: {
|
|
134
|
+
...options.resolution, specs: [...options.resolution.specs, ...new Set(trustedPaths)],
|
|
135
|
+
} });
|
|
136
|
+
return { resolution, fullResolution };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 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) {
|
|
141
|
+
if (plan.configSnapshot && JSON.stringify(configSnapshot(plan.configSnapshot.map(item => item.dir))) !== JSON.stringify(plan.configSnapshot))
|
|
142
|
+
throw new Error('Child configuration drift: agent or project JSON configuration changed. Launch again.');
|
|
143
|
+
for (const item of plan.fingerprints) if (fingerprint(item.path) !== item.hash)
|
|
144
|
+
throw new Error(`Child configuration/declaration drift: ${item.path}. Launch again with current configuration.`);
|
|
145
|
+
for (const declaration of plan.declarations) {
|
|
146
|
+
const fn = await load(declaration.entry);
|
|
147
|
+
const current = await fn({ model: plan.model });
|
|
148
|
+
if (JSON.stringify(current ?? null) !== JSON.stringify(declaration.requirements))
|
|
149
|
+
throw new Error(`Child requirements changed: ${declaration.entry}. Launch again.`);
|
|
150
|
+
}
|
|
151
|
+
if (plan.model && (!model || `${model.provider}/${model.id}` !== plan.model)) throw new Error(`Selected child model ${plan.model} is missing or changed.`);
|
|
152
|
+
const available = registry.getAvailable();
|
|
153
|
+
if (plan.model && !available.some(m => `${m.provider}/${m.id}` === plan.model))
|
|
154
|
+
throw new Error(`Selected child model ${plan.model} is not available; check its provider and credentials.`);
|
|
155
|
+
for (const provider of plan.providers) if (!available.some(m => m.provider === provider && m.api !== 'pi-virtual'))
|
|
156
|
+
throw new Error(`Child requires available provider ${provider}; check its extension and credentials.`);
|
|
157
|
+
for (const group of plan.modelGroups) if (!available.some(m => m.provider === group.provider && m.api !== 'pi-virtual' &&
|
|
158
|
+
(group.ids.includes(m.id) || (group.prefix && m.id.startsWith(group.prefix)))))
|
|
159
|
+
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
|
+
for (const tool of plan.tools) if (!tools.includes(tool)) throw new Error(`Child requested tool ${tool} is unavailable.`);
|
|
161
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Mandatory child check. Hook errors alone are nonfatal in Pi, so explicitly exit on failure. */
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { checkChildPreflight } from './child-dependencies.mjs';
|
|
4
|
+
export const PREFLIGHT_ENV = 'PI_SUBAGENT_PREFLIGHT';
|
|
5
|
+
export default function childPreflight(pi) {
|
|
6
|
+
const fail = error => {
|
|
7
|
+
process.stderr.write(`Subagent child preflight failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
8
|
+
process.exit(1);
|
|
9
|
+
};
|
|
10
|
+
let plan;
|
|
11
|
+
try { plan = JSON.parse(readFileSync(process.env[PREFLIGHT_ENV], 'utf8')); } catch (error) { fail(error); }
|
|
12
|
+
// The task guard activates its adapters on session_start. Check after every
|
|
13
|
+
// startup handler has finished, before the first request (and subsequent runs).
|
|
14
|
+
const check = async (ctx, tools) => {
|
|
15
|
+
try {
|
|
16
|
+
await checkChildPreflight({ ...plan, tools }, { registry: ctx.modelRegistry,
|
|
17
|
+
tools: pi.getActiveTools(), model: ctx.model });
|
|
18
|
+
} catch (error) { fail(error); }
|
|
19
|
+
};
|
|
20
|
+
pi.on('session_start', async (_event, ctx) => check(ctx, []));
|
|
21
|
+
pi.on('before_agent_start', async (_event, ctx) => check(ctx, plan.tools));
|
|
22
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** Validate preflight before CLI discovery can downgrade import errors, then
|
|
2
|
+
* execute the selected launcher with its own interpreter and SDK.
|
|
3
|
+
*/
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { accessSync, constants, statSync } from 'node:fs';
|
|
6
|
+
import { delimiter, resolve } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import './child-preflight.mjs';
|
|
9
|
+
|
|
10
|
+
try {
|
|
11
|
+
const [binary, ...args] = process.argv.slice(2);
|
|
12
|
+
const launcherArgs = ['--extension', fileURLToPath(new URL('./child-preflight.mjs', import.meta.url)), ...args];
|
|
13
|
+
if (process.platform !== 'win32' && typeof process.execve === 'function') {
|
|
14
|
+
// execve does not search PATH. Resolve only executable files; let spawn
|
|
15
|
+
// report lookup errors below rather than invoking Node's fatal execve error.
|
|
16
|
+
const candidates = binary.includes('/') ? [binary]
|
|
17
|
+
: (process.env.PATH ?? '/usr/bin:/bin').split(delimiter).map(dir => resolve(dir, binary));
|
|
18
|
+
const executable = candidates.find(candidate => {
|
|
19
|
+
try { accessSync(candidate, constants.X_OK); return statSync(candidate).isFile(); }
|
|
20
|
+
catch { return false; }
|
|
21
|
+
});
|
|
22
|
+
if (executable) {
|
|
23
|
+
// Replace the bootstrap so the recorded launch PID is the launcher's PID.
|
|
24
|
+
// The executable retains its own shebang/interpreter and exact arguments.
|
|
25
|
+
process.execve(resolve(executable), [binary, ...launcherArgs], process.env);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
// Older Node/platforms retain supervision and signal forwarding. Stay in the
|
|
29
|
+
// bootstrap's process group so group termination reaches all descendants.
|
|
30
|
+
const child = spawn(binary, launcherArgs, {
|
|
31
|
+
stdio: 'inherit', env: process.env, detached: false,
|
|
32
|
+
});
|
|
33
|
+
const forwards = new Map(['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT'].map(signal => {
|
|
34
|
+
const forward = () => child.kill(signal);
|
|
35
|
+
process.on(signal, forward);
|
|
36
|
+
return [signal, forward];
|
|
37
|
+
}));
|
|
38
|
+
const cleanup = () => {
|
|
39
|
+
for (const [signal, forward] of forwards) process.off(signal, forward);
|
|
40
|
+
process.off('exit', stopChild);
|
|
41
|
+
};
|
|
42
|
+
const stopChild = () => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); };
|
|
43
|
+
process.on('exit', stopChild);
|
|
44
|
+
child.on('error', error => {
|
|
45
|
+
cleanup();
|
|
46
|
+
process.stderr.write(`Subagent bootstrap failed: ${error.message}\n`);
|
|
47
|
+
process.exitCode = 1;
|
|
48
|
+
});
|
|
49
|
+
child.on('exit', (code, signal) => {
|
|
50
|
+
cleanup();
|
|
51
|
+
if (signal) process.kill(process.pid, signal);
|
|
52
|
+
else process.exitCode = code ?? 1;
|
|
53
|
+
});
|
|
54
|
+
} catch (error) {
|
|
55
|
+
process.stderr.write(`Subagent bootstrap failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
56
|
+
process.exit(1);
|
|
57
|
+
}
|
package/config.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { fileURLToPath } from "node:url";
|
|
|
13
13
|
import { dirname, join } from "node:path";
|
|
14
14
|
import { homedir } from "node:os";
|
|
15
15
|
import { SELF_SPEC } from "./extensions.ts";
|
|
16
|
+
import { installedPackage } from "./child-dependencies.mjs";
|
|
16
17
|
import { isDelegationMode, type DelegationMode } from "./delegation.ts";
|
|
17
18
|
import type { TimingSettings } from "./timing.ts";
|
|
18
19
|
import { harnessSettingsPath, readHarnessSetting, updateHarnessSetting } from "./shared-harness-settings.ts";
|
|
@@ -222,10 +223,13 @@ function piAgentDir(): string {
|
|
|
222
223
|
* a missing dependency instead of silently launching a child without it.
|
|
223
224
|
* (`-e` accepts either a package directory or an entrypoint file — verified.)
|
|
224
225
|
*/
|
|
225
|
-
export function resolveExtensionPath(spec: string): string | undefined {
|
|
226
|
+
export function resolveExtensionPath(spec: string, declaringRoot?: string): string | undefined {
|
|
226
227
|
if (spec === SELF_SPEC) return selfDir();
|
|
227
228
|
const path = spec.startsWith("npm:")
|
|
228
|
-
? join(piAgentDir(), "npm", "node_modules", spec.slice(4))
|
|
229
|
-
|
|
230
|
-
|
|
229
|
+
? (declaringRoot && installedPackage(spec.slice(4), [declaringRoot])) ?? (existsSync(join(piAgentDir(), "npm", "node_modules", spec.slice(4)))
|
|
230
|
+
? join(piAgentDir(), "npm", "node_modules", spec.slice(4))
|
|
231
|
+
: installedPackage(spec.slice(4), [declaringRoot, join(piAgentDir(), "npm"), selfDir(),
|
|
232
|
+
join(piAgentDir(), "npm", "node_modules", "pi-better-harness")]))
|
|
233
|
+
: declaringRoot && !spec.startsWith("/") ? join(declaringRoot, spec) : spec;
|
|
234
|
+
return path && existsSync(path) ? path : undefined;
|
|
231
235
|
}
|
package/extensions.mjs
CHANGED
package/index.ts
CHANGED
|
@@ -36,7 +36,7 @@ import { parseRun, parseRunForLifecycle, readRunTranscript, resetParseRunCursor,
|
|
|
36
36
|
import { finalizeRun as finalizeRunCore } from "./finalization.ts";
|
|
37
37
|
import { selectSessionByName } from "./session-selection.ts";
|
|
38
38
|
import { isWithinWorkspace } from "./workspace-scope.ts";
|
|
39
|
-
import { loadConfig, writeDelegationMode, writeSubagentSettings, isConcurrencyCap, normalizeConcurrencyCap, normalizeTools, resolveExtensionPath, selfDir, SAFE_DEFAULT_TOOLS, SAFE_CLEAN_TOOLS } from "./config.ts";
|
|
39
|
+
import { loadConfig, writeDelegationMode, writeSubagentSettings, isConcurrencyCap, normalizeConcurrencyCap, normalizeTools, resolveExtensionPath, configPath, selfDir, SAFE_DEFAULT_TOOLS, SAFE_CLEAN_TOOLS } from "./config.ts";
|
|
40
40
|
import { createSubagentSettingsPage } from "./settings-page.ts";
|
|
41
41
|
import { effectiveSubagentSettings, formatSubagentSettings, subagentSettingsTool, SUBAGENT_SETTINGS_CONTEXT } from "./effective-settings.ts";
|
|
42
42
|
import { STEER_FILE_ENV, readSteerReceipt } from "./child-steer.ts";
|
|
@@ -57,6 +57,8 @@ import {
|
|
|
57
57
|
import { readAppendedLines, type LogCursor } from "./log-cursor.ts";
|
|
58
58
|
import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeDelegationMode, type DelegationMode } from "./delegation.ts";
|
|
59
59
|
import { appendExecutionPolicy } from "./shared-execution-policy.ts";
|
|
60
|
+
import { resolveChildClosure, resolveChildLaunch, configSnapshot } from "./child-dependencies.mjs";
|
|
61
|
+
import { PREFLIGHT_ENV } from "./child-preflight.mjs";
|
|
60
62
|
import { resolveExtensions, extensionArgs } from "./extensions.ts";
|
|
61
63
|
import { prepareTaskRuntime, applyDirectApplicationLoadout, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.ts";
|
|
62
64
|
import { canonicalizePath, takeRecoverySnapshot } from "./shared-sandbox-core.ts";
|
|
@@ -66,7 +68,7 @@ import {
|
|
|
66
68
|
announceExecutionAdapter, observeSandboxPermissions, resolveCommandSettings, resolveSubagentPermissions,
|
|
67
69
|
} from "./permission-policy.ts";
|
|
68
70
|
import { resolveSubagentWorkspace } from "./git-workspace.ts";
|
|
69
|
-
import { join } from "node:path";
|
|
71
|
+
import { dirname, join } from "node:path";
|
|
70
72
|
import {
|
|
71
73
|
baseDir,
|
|
72
74
|
taskWorkspaceDir,
|
|
@@ -2263,15 +2265,22 @@ export default function (pi: ExtensionAPI) {
|
|
|
2263
2265
|
builtins: [...TASK_BUILTINS, "codemode"], registered: pi.getAllTools?.() ?? [],
|
|
2264
2266
|
toolExtensions: cfg.toolExtensions, resolvePath: resolveExtensionPath,
|
|
2265
2267
|
}) : undefined;
|
|
2266
|
-
const
|
|
2268
|
+
const dependencyOptions = {
|
|
2269
|
+
model, virtual: (() => {
|
|
2270
|
+
const slash = model?.indexOf("/") ?? -1;
|
|
2271
|
+
return slash > 0 && ctx.modelRegistry?.find?.(model!.slice(0, slash), model!.slice(slash + 1))?.api === "pi-virtual";
|
|
2272
|
+
})(), config: cfg, resolvePath: resolveExtensionPath,
|
|
2273
|
+
configPaths: [configPath(), join(selfDir(), "config.json")],
|
|
2274
|
+
};
|
|
2275
|
+
const { resolution, fullResolution } = await resolveChildLaunch({ ...dependencyOptions, resolution: resolveExtensions({
|
|
2267
2276
|
// Only SDK builtins reach `--tools` and extension resolution: process_list and run_application
|
|
2268
2277
|
// are task builtins that the mandatory guard installs and activates itself.
|
|
2269
2278
|
tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : allow,
|
|
2270
2279
|
model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
|
|
2271
|
-
});
|
|
2272
|
-
const { args: resolvedExtArgs, missing } = extensionArgs(resolution, resolveExtensionPath);
|
|
2273
|
-
const trustedExtArgs =
|
|
2274
|
-
.filter(
|
|
2280
|
+
}) }, taskTools?.trusted.map(tool => tool.loadPath) ?? []);
|
|
2281
|
+
const { args: resolvedExtArgs, missing } = extensionArgs(resolution, (spec) => resolution.paths[spec] ?? resolveExtensionPath(spec));
|
|
2282
|
+
const trustedExtArgs = fullResolution.specs.map(spec => fullResolution.paths[spec])
|
|
2283
|
+
.filter(path => !resolvedExtArgs.includes(path)).flatMap(path => ["--extension", path]);
|
|
2275
2284
|
// Harness child controls ride along in every mode, including clean and unsandboxed runs.
|
|
2276
2285
|
// They deliver deadline steers and keep external monitoring with the coordinator.
|
|
2277
2286
|
const codemodeArgs = !sandboxEnabled && allow.split(",").includes("codemode") && !requestedExcludes.has("codemode")
|
|
@@ -2285,11 +2294,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
2285
2294
|
if (resume?.recipe.extensionArgs) {
|
|
2286
2295
|
// A model escalation may change provider auth, but an unchanged tool
|
|
2287
2296
|
// must not silently switch implementations with current configuration.
|
|
2288
|
-
const reference = model === resume.recipe.model ? resolution :
|
|
2297
|
+
const reference = model === resume.recipe.model ? resolution : await resolveChildClosure({
|
|
2298
|
+
...dependencyOptions, model: resume.recipe.model, virtual: false, resolution: resolveExtensions({
|
|
2289
2299
|
tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : allow,
|
|
2290
2300
|
model: resume.recipe.model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
|
|
2291
|
-
});
|
|
2292
|
-
const referenceArgs = [...extensionArgs(reference, resolveExtensionPath).args, ...codemodeArgs,
|
|
2301
|
+
}) });
|
|
2302
|
+
const referenceArgs = [...extensionArgs(reference, (spec) => reference.paths[spec] ?? resolveExtensionPath(spec)).args, ...codemodeArgs,
|
|
2293
2303
|
...(!resume.recipe.baseExtensionArgs ? trustedExtArgs : []),
|
|
2294
2304
|
"--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
|
|
2295
2305
|
.map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
|
|
@@ -2361,7 +2371,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2361
2371
|
try { ctx.ui?.notify?.(`Subagent ${id}: recovery snapshot failed (run continues): ${outcome.detail}`, "warning"); } catch { /* ignore */ }
|
|
2362
2372
|
});
|
|
2363
2373
|
}
|
|
2364
|
-
const cmd = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] } : { file:
|
|
2374
|
+
const cmd = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] } : { file: process.execPath, fileArgs: [join(selfDir(), "child-runtime.mjs"), piBin, ...args] };
|
|
2365
2375
|
const sandboxDir = taskRuntime ? requestedSandboxDir : undefined;
|
|
2366
2376
|
|
|
2367
2377
|
// Reservations prevent competing admissions, but do not grandfather
|
|
@@ -2384,8 +2394,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
2384
2394
|
// built from, so `--session` can never reopen a file another sweep
|
|
2385
2395
|
// removed as an empty replacement.
|
|
2386
2396
|
if (resume) revalidateContinuationUnderLease(resume, callbackOrigin);
|
|
2397
|
+
const preflightPath = join(runDir(id), "child-preflight.json");
|
|
2398
|
+
writeFileSync(preflightPath, JSON.stringify({ ...fullResolution, model, tools: selectedTools,
|
|
2399
|
+
configSnapshot: configSnapshot([dirname(configPath()), join(cwd, ".pi")]),
|
|
2400
|
+
}));
|
|
2387
2401
|
spawned = spawnDetached({ file: cmd.file, fileArgs: cmd.fileArgs, cwd, logPath: logPathFor(id),
|
|
2388
|
-
env: { [STEER_FILE_ENV]: steerPathFor(id) } });
|
|
2402
|
+
env: { [STEER_FILE_ENV]: steerPathFor(id), [PREFLIGHT_ENV]: preflightPath } });
|
|
2389
2403
|
// Record process identity (pgid, start-time token) so health
|
|
2390
2404
|
// reconciliation can tell a supervised child from a recycled pid
|
|
2391
2405
|
// or an orphaned process group (#63). Best-effort: when the OS
|
package/package.json
CHANGED
package/task-runtime.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/** Trusted native entry point. Any failure before/inside guard installation is fatal. */
|
|
2
|
+
import preflight from "./child-preflight.mjs";
|
|
2
3
|
import { readFileSync } from "node:fs";
|
|
3
4
|
import { createRequire } from "node:module";
|
|
4
5
|
import { dirname, isAbsolute, join } from "node:path";
|
|
@@ -33,7 +34,7 @@ try {
|
|
|
33
34
|
// source before provider/trusted packages, but keep activation in the final guard.
|
|
34
35
|
const ownerPath = fileURLToPath(new URL("./task-tool-owner.ts", import.meta.url));
|
|
35
36
|
await main(["--extension", ownerPath, ...args], {
|
|
36
|
-
extensionFactories: [{ name: "task-sandbox", factory: async (pi) => {
|
|
37
|
+
extensionFactories: [...(process.env.PI_SUBAGENT_PREFLIGHT ? [{ name: "subagent-preflight", factory: preflight }] : []), { name: "task-sandbox", factory: async (pi) => {
|
|
37
38
|
try { await guard(pi, policy, fail, true); } catch (error) { fail(error); }
|
|
38
39
|
} }],
|
|
39
40
|
});
|