oira666_pi-subagent 0.5.8 → 0.5.10
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/docs/configuration.md +5 -3
- package/docs/sessions.md +4 -2
- package/extension/execution.ts +6 -1
- package/extension/launch-tool.ts +6 -4
- package/extension/resume-tool.ts +16 -18
- package/extension/schemas.ts +23 -23
- package/names.ts +8 -1
- package/package.json +1 -1
- package/runner/arguments.ts +76 -19
- package/runner/options.ts +5 -3
- package/runner/parallel.ts +5 -1
- package/runner/resource-paths.ts +25 -0
- package/runner/session-target.ts +58 -0
- package/runner/single.ts +45 -8
- package/storage/name-records.ts +8 -5
- package/storage/names-registry.ts +3 -1
- package/storage/session-fork.ts +2 -1
- package/storage/session-settings.ts +66 -0
- package/types/contracts.ts +2 -1
- package/types/details.ts +1 -0
- package/types/outcomes.ts +15 -15
- package/ui/detail-model.ts +2 -0
- package/ui/detail-transcript.ts +7 -2
- package/ui/pager-view.ts +5 -1
package/README.md
CHANGED
|
@@ -105,7 +105,7 @@ Collapsed results show each child's name, task, status, and most recent activity
|
|
|
105
105
|
|
|
106
106
|
`/subagent-expand <name>` opens a saved worker transcript. With no name, it opens a searchable picker. Name completion is fuzzy. Each task or resume shows its actual provider/model and thinking level from the worker's session, not the parent's settings. Selected presets also appear as an intelligence label, kept separately for each run. Missing historical model/thinking metadata appears as `unknown`.
|
|
107
107
|
|
|
108
|
-
[Model presets](docs/configuration.md#caller-selected-intelligence) show labels such as `Nicolas (Junior/code-writer)` in regular tool results. One enabled preset applies automatically to
|
|
108
|
+
[Model presets](docs/configuration.md#caller-selected-intelligence) show labels such as `Nicolas (Junior/code-writer)` in regular tool results. One enabled preset applies automatically to new launches without exposing an `intelligence` argument. Two or more require an explicit `intelligence` choice on every launch item. Omitted or `null` choices reject the whole launch batch before any worker starts. Zero or disabled presets keep the existing launch defaults and show no intelligence label. Named resumes do not accept `intelligence`; they retain the original effective model, thinking, and label, even after configuration or parent settings change.
|
|
109
109
|
|
|
110
110
|
| Key | Action |
|
|
111
111
|
| --- | --- |
|
package/docs/configuration.md
CHANGED
|
@@ -58,7 +58,7 @@ Missing descriptions retain their defaults. Overrides change written guidance, n
|
|
|
58
58
|
|
|
59
59
|
## Caller-selected intelligence
|
|
60
60
|
|
|
61
|
-
Define named model presets in `pi-subagent.json`. With two or more enabled presets, the calling model must choose a configured `intelligence` preset for every launch
|
|
61
|
+
Define named model presets in `pi-subagent.json`. With two or more enabled presets, the calling model must choose a configured `intelligence` preset for every launch item. With exactly one enabled preset, the launch tool hides the argument and automatically uses that preset. With no presets, the argument is absent and existing model/thinking defaults apply to launches. Named resumes never offer or accept an intelligence choice. No router or separate model-selection request is used.
|
|
62
62
|
|
|
63
63
|
```json
|
|
64
64
|
{
|
|
@@ -98,11 +98,13 @@ Use models available in your Pi installation. Names are arbitrary, unique, non-e
|
|
|
98
98
|
}
|
|
99
99
|
```
|
|
100
100
|
|
|
101
|
-
|
|
101
|
+
A selected or automatic preset overrides the parent model and agent model/thinking settings for a launch. The parent's explicit `--provider` and `--api-key` are not forwarded when a preset is selected. Named resumes use their saved provider and retain a CLI `--api-key` only when that provider matches the parent's explicit `--provider`; otherwise they drop the key. Worker providers use their configured Pi credentials. With multiple presets, omitted or `null` choices reject the entire launch batch before any worker starts or budget changes.
|
|
102
|
+
|
|
103
|
+
`resume_subagents` retains the original effective model, thinking level, and intelligence label. This also applies to private forks and after restart, preset changes, disabling intelligence, changing the parent model, or editing/deleting the agent definition. A worker launched without a preset remains unlabelled. Pass only `{ subagent, task }` and an optional `max_subagents_allowed`; any `intelligence` argument, including `null`, rejects the resume batch.
|
|
102
104
|
|
|
103
105
|
Tool result rows show the selected preset, for example `Nicolas (Junior/code-writer)`. Display names capitalize only the first character; configured spelling and argument values otherwise stay unchanged. Runs without a preset show `Nicolas (code-writer)`. Durable results retain their own preset name, and the name registry retains the initial choice. The `/subagent-expand` picker shows the initial preset beside each agent type and lets you search by preset name. Its transcript view shows each task's or resume's recorded intelligence alongside its actual transcript model and thinking level. Later resumes do not relabel earlier work. Missing model or thinking metadata remains `unknown`, even when a preset name is known.
|
|
104
106
|
|
|
105
|
-
`PI_SUBAGENT_INTELLIGENCE=true` enables presets when they exist, which is the default. Set it to `false` or `0` to treat the configuration as having no presets:
|
|
107
|
+
`PI_SUBAGENT_INTELLIGENCE=true` enables presets when they exist, which is the default. Set it to `false` or `0` to treat the configuration as having no presets for new launches: the launch tool hides the argument and no automatic preset applies. Named resumes still retain their original settings. Unknown choices or attempts to pass a named hidden argument fail before launching workers. When the argument is hidden, omission or `null` still uses the automatic sole preset or existing defaults.
|
|
106
108
|
|
|
107
109
|
Configuration follows the trust checks and file order above. A later `subagents-models` block replaces the entire earlier block. An empty list disables selection. Invalid blocks warn and disable selection rather than using a partial list. Nested workers load configuration using the same rules. Reload Pi after changing settings.
|
|
108
110
|
|
package/docs/sessions.md
CHANGED
|
@@ -30,7 +30,7 @@ The ledger uses immutable files and atomic hard links beside saved worker sessio
|
|
|
30
30
|
}
|
|
31
31
|
```
|
|
32
32
|
|
|
33
|
-
The override replaces the worker's lifetime descendant cap, excluding itself. It does not grant ten fresh launches. Omit it to retain the existing cap.
|
|
33
|
+
The override replaces the worker's lifetime descendant cap, excluding itself. It does not grant ten fresh launches. Omit it to retain the existing cap. Provider-generated `null` for this optional field also keeps the cap; explicit `0` still replaces it with zero.
|
|
34
34
|
|
|
35
35
|
- Increases reserve only additional capacity from the original launcher's allowance.
|
|
36
36
|
- Decreases cannot remove slots already spent or assigned. They do not refund the parent. Raising a cap to a previously funded value needs no new reservation.
|
|
@@ -47,7 +47,9 @@ The shared name registry and ownership identity are recorded in session metadata
|
|
|
47
47
|
|
|
48
48
|
The agent that launched a worker owns its original session. A child may receive an ancestor's worker name in its task. Resuming that name creates a private session fork, leaving the owner's context untouched. Each caller reuses one fork per name, including across restarts. Forks retain the same budget.
|
|
49
49
|
|
|
50
|
-
Concurrent resumes of the same session are rejected using both in-process checks and crash-tolerant registry markers. Removed agent definitions do not prevent resume; the registry retains model/tool restrictions and the saved session retains context.
|
|
50
|
+
Concurrent resumes of the same session are rejected using both in-process checks and crash-tolerant registry markers. Removed agent definitions do not prevent resume; the registry retains model/tool restrictions and the saved session retains context. Resumes open the saved transcript explicitly, preserving its original working directory even when the caller's directory differs. They do not use Pi's cwd-filtered `--continue` discovery. The runner selects that transcript once before extension discovery and uses its working directory for discovery and process startup. Caller approval applies only when that directory matches the caller's project; otherwise the saved project is explicitly unapproved, including when extension exclusions are disabled.
|
|
51
|
+
|
|
52
|
+
Relative `--skill`, `--prompt-template`, and theme file/directory arguments keep the parent's startup directory as their base, even when a resumed worker runs in another project. Named theme selections and non-filesystem references are forwarded unchanged.
|
|
51
53
|
|
|
52
54
|
## Crash recovery
|
|
53
55
|
|
package/extension/execution.ts
CHANGED
|
@@ -119,7 +119,12 @@ export async function executeParallel(
|
|
|
119
119
|
resumeExistingSessions: boolean,
|
|
120
120
|
fallbackModel: string | undefined,
|
|
121
121
|
topLevelBaseId: number,
|
|
122
|
-
extras?: {
|
|
122
|
+
extras?: {
|
|
123
|
+
names?: Array<string | undefined>;
|
|
124
|
+
rawPrompts?: boolean;
|
|
125
|
+
budgets?: Array<SubagentBudget | undefined>;
|
|
126
|
+
resumeSettings?: Array<import("../storage/name-records.js").SubagentModelSettings>;
|
|
127
|
+
},
|
|
123
128
|
) {
|
|
124
129
|
const taskIds = new Map<number, number>();
|
|
125
130
|
try {
|
package/extension/launch-tool.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createIntelligenceSchemas, validatePreparedArguments } from "./schemas.js";
|
|
2
2
|
import { selectIntelligence } from "../intelligence.js";
|
|
3
|
+
import { resolveLaunchModelSettings } from "../runner/arguments.js";
|
|
3
4
|
import * as path from "node:path";
|
|
4
5
|
import { discoverAgents } from "../agents.js";
|
|
5
6
|
import {
|
|
@@ -218,10 +219,11 @@ export function registerSubagentsTool(state: ExtensionState) {
|
|
|
218
219
|
agent: task.agent,
|
|
219
220
|
task: task.task,
|
|
220
221
|
budget: budgets[index],
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
222
|
+
...resolveLaunchModelSettings(
|
|
223
|
+
agentConfig ?? {},
|
|
224
|
+
formatModelFlag(getParentModelForSubagent(state, ctx)),
|
|
225
|
+
preset,
|
|
226
|
+
),
|
|
225
227
|
tools: agentConfig?.tools,
|
|
226
228
|
sessionDir:
|
|
227
229
|
resumePlan?.details?.results[index]?.sessionDir ??
|
package/extension/resume-tool.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { ResumeSubagentsParams, validatePreparedArguments } from "./schemas.js";
|
|
2
|
+
import { originalModelSettings } from "../storage/session-settings.js";
|
|
3
|
+
import type { SubagentModelSettings } from "../storage/name-records.js";
|
|
3
4
|
import * as fs from "node:fs";
|
|
4
5
|
import * as path from "node:path";
|
|
5
6
|
import { discoverAgents, isAgentEnabledAtLayer, type AgentConfig } from "../agents.js";
|
|
@@ -23,32 +24,28 @@ import {
|
|
|
23
24
|
import { updateLatestBroadcastTargets } from "./broadcast.js";
|
|
24
25
|
import { makeDetailsFactory } from "./details.js";
|
|
25
26
|
import { executeParallel } from "./execution.js";
|
|
26
|
-
import { formatModelFlag } from "./models.js";
|
|
27
27
|
import { resumableSubagentsDisabled } from "./policy.js";
|
|
28
28
|
import { trackProgress } from "./progress.js";
|
|
29
|
-
import { ensureBudget
|
|
30
|
-
import { normalizeResumes
|
|
29
|
+
import { ensureBudget } from "./runtime.js";
|
|
30
|
+
import { normalizeResumes } from "./schemas.js";
|
|
31
31
|
import type { ExtensionState } from "./state.js";
|
|
32
32
|
|
|
33
33
|
export function registerResumeSubagentsTool(state: ExtensionState) {
|
|
34
34
|
if (resumableSubagentsDisabled()) return;
|
|
35
|
-
const parameters =
|
|
35
|
+
const parameters = ResumeSubagentsParams;
|
|
36
36
|
state.pi.registerTool({
|
|
37
37
|
name: RESUME_SUBAGENTS_TOOL_NAME,
|
|
38
38
|
label: "Resume subagents",
|
|
39
39
|
description:
|
|
40
40
|
state.configuredToolPrompts[RESUME_SUBAGENTS_TOOL_NAME] ??
|
|
41
41
|
[
|
|
42
|
-
"Continue agents by their returned names, keeping their previous context.",
|
|
42
|
+
"Continue agents by their returned names, keeping their previous context and original model, thinking, and intelligence label. Resume does not accept an intelligence choice.",
|
|
43
43
|
"Optional max_subagents_allowed replaces the lifetime descendant cap, excluding the resumed agent. Past launches and assigned slots still count. Increases reserve extra slots from the original launcher; omitting it keeps the current allowance.",
|
|
44
44
|
"Pass { resumes: [{ subagent, task }] }. Resumes in one call run in parallel; wait between dependent tasks.",
|
|
45
45
|
].join("\n"),
|
|
46
46
|
parameters,
|
|
47
47
|
prepareArguments(args) {
|
|
48
|
-
return validatePreparedArguments(
|
|
49
|
-
parameters,
|
|
50
|
-
prepareIntelligenceArguments(prepareResumeArguments(args), "resumes"),
|
|
51
|
-
);
|
|
48
|
+
return validatePreparedArguments(parameters, prepareResumeArguments(args));
|
|
52
49
|
},
|
|
53
50
|
|
|
54
51
|
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
@@ -73,8 +70,6 @@ export function registerResumeSubagentsTool(state: ExtensionState) {
|
|
|
73
70
|
);
|
|
74
71
|
}
|
|
75
72
|
|
|
76
|
-
for (const resume of resumes) selectIntelligence(state.intelligencePresets, resume.intelligence);
|
|
77
|
-
|
|
78
73
|
const duplicates = resumes
|
|
79
74
|
.map((resume) => resume.name)
|
|
80
75
|
.filter((name, index, all) => all.indexOf(name) !== index);
|
|
@@ -124,7 +119,7 @@ export function registerResumeSubagentsTool(state: ExtensionState) {
|
|
|
124
119
|
tools?: string[];
|
|
125
120
|
budget: SubagentBudget;
|
|
126
121
|
max_subagents_allowed?: number;
|
|
127
|
-
|
|
122
|
+
settings: SubagentModelSettings;
|
|
128
123
|
}> = [];
|
|
129
124
|
const hasSessionFiles = (dir: string): boolean => {
|
|
130
125
|
try {
|
|
@@ -174,7 +169,7 @@ export function registerResumeSubagentsTool(state: ExtensionState) {
|
|
|
174
169
|
budget:
|
|
175
170
|
resolution.record.budget ?? createBudget(path.join(resolution.record.sessionDir, "legacy-budget"), 0),
|
|
176
171
|
max_subagents_allowed: resume.max_subagents_allowed,
|
|
177
|
-
|
|
172
|
+
settings: originalModelSettings(resolution.record),
|
|
178
173
|
});
|
|
179
174
|
}
|
|
180
175
|
if (errors.length > 0) {
|
|
@@ -213,7 +208,10 @@ export function registerResumeSubagentsTool(state: ExtensionState) {
|
|
|
213
208
|
overrideResumeBudgets(ensureBudget(state), overrides, state.currentDepth === 0 ? "main" : "subagent");
|
|
214
209
|
}
|
|
215
210
|
for (const target of targets) {
|
|
216
|
-
await updateNameRecord(state.currentNamesFile, target.name, {
|
|
211
|
+
await updateNameRecord(state.currentNamesFile, target.name, {
|
|
212
|
+
lastResumePrompt: target.task,
|
|
213
|
+
...target.settings,
|
|
214
|
+
});
|
|
217
215
|
}
|
|
218
216
|
|
|
219
217
|
// Resumed agents may reference agent types whose definition files no
|
|
@@ -237,7 +235,6 @@ export function registerResumeSubagentsTool(state: ExtensionState) {
|
|
|
237
235
|
const tasks = targets.map((target) => ({
|
|
238
236
|
agent: target.agent,
|
|
239
237
|
task: target.task,
|
|
240
|
-
intelligence: target.intelligence,
|
|
241
238
|
}));
|
|
242
239
|
const topLevelBaseId = state.nextActiveSubagentId;
|
|
243
240
|
state.nextActiveSubagentId += tasks.length;
|
|
@@ -254,12 +251,13 @@ export function registerResumeSubagentsTool(state: ExtensionState) {
|
|
|
254
251
|
undefined,
|
|
255
252
|
(index) => targets[index].sessionDir,
|
|
256
253
|
true,
|
|
257
|
-
|
|
254
|
+
undefined,
|
|
258
255
|
topLevelBaseId,
|
|
259
256
|
{
|
|
260
257
|
names: targets.map((target) => target.name),
|
|
261
258
|
budgets: targets.map((target) => target.budget),
|
|
262
259
|
rawPrompts: true,
|
|
260
|
+
resumeSettings: targets.map((target) => target.settings),
|
|
263
261
|
},
|
|
264
262
|
);
|
|
265
263
|
} finally {
|
package/extension/schemas.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Value } from "@sinclair/typebox/value";
|
|
2
2
|
import type { Static, TSchema, TLiteral } from "@sinclair/typebox";
|
|
3
3
|
import { Type } from "@sinclair/typebox";
|
|
4
4
|
import { isBranchBudgetAmount, SubagentBudgetError } from "../budget.js";
|
|
@@ -58,7 +58,8 @@ export const ResumeItem = Type.Object(
|
|
|
58
58
|
|
|
59
59
|
export const ResumeSubagentsParams = Type.Object(
|
|
60
60
|
{
|
|
61
|
-
resumes: Type.
|
|
61
|
+
resumes: Type.Array(ResumeItem, {
|
|
62
|
+
minItems: 1,
|
|
62
63
|
description: "Array of {subagent, task} objects. Each named subagent is resumed in parallel with its new task.",
|
|
63
64
|
}),
|
|
64
65
|
},
|
|
@@ -77,26 +78,19 @@ export function createIntelligenceSchemas(presets: IntelligencePreset[] = []) {
|
|
|
77
78
|
{
|
|
78
79
|
enum: presets.map((preset) => preset.name),
|
|
79
80
|
description: [
|
|
80
|
-
"Required named model/provider/reasoning preset. Choose a configured preset for every launch
|
|
81
|
+
"Required named model/provider/reasoning preset. Choose a configured preset for every launch.",
|
|
82
|
+
"Use the cheapest capable preset; juniors suit simple repetitive work, pricier models suit complex tasks.",
|
|
81
83
|
...presets.map((preset) => `${preset.name}${preset.description ? `: ${preset.description}` : ""}`),
|
|
82
84
|
].join("\n"),
|
|
83
85
|
},
|
|
84
86
|
),
|
|
85
87
|
};
|
|
86
88
|
const task = Type.Object({ ...TaskItem.properties, ...intelligence }, { additionalProperties: false });
|
|
87
|
-
const resume = Type.Object({ ...ResumeItem.properties, ...intelligence }, { additionalProperties: false });
|
|
88
89
|
const subagents = Type.Object(
|
|
89
90
|
{ tasks: Type.Array(task, { minItems: 1, description: SubagentParams.properties.tasks.description }) },
|
|
90
91
|
{ additionalProperties: false },
|
|
91
92
|
);
|
|
92
|
-
const resumes =
|
|
93
|
-
{
|
|
94
|
-
resumes: Type.Union([Type.Array(resume, { minItems: 1 }), resume], {
|
|
95
|
-
description: ResumeSubagentsParams.properties.resumes.description,
|
|
96
|
-
}),
|
|
97
|
-
},
|
|
98
|
-
{ additionalProperties: false },
|
|
99
|
-
);
|
|
93
|
+
const resumes = ResumeSubagentsParams;
|
|
100
94
|
return presets.length >= 2 && intelligenceEnabled(presets)
|
|
101
95
|
? { subagents, resumes }
|
|
102
96
|
: {
|
|
@@ -105,18 +99,16 @@ export function createIntelligenceSchemas(presets: IntelligencePreset[] = []) {
|
|
|
105
99
|
};
|
|
106
100
|
}
|
|
107
101
|
|
|
108
|
-
export function normalizeResumes(
|
|
109
|
-
raw: unknown,
|
|
110
|
-
): Array<{ name: string; task: string; intelligence?: string; max_subagents_allowed?: number }> {
|
|
102
|
+
export function normalizeResumes(raw: unknown): Array<{ name: string; task: string; max_subagents_allowed?: number }> {
|
|
111
103
|
const items = Array.isArray(raw) ? raw : raw && typeof raw === "object" ? [raw] : [];
|
|
112
|
-
const normalized: Array<{ name: string; task: string;
|
|
104
|
+
const normalized: Array<{ name: string; task: string; max_subagents_allowed?: number }> = [];
|
|
113
105
|
for (const item of items) {
|
|
114
106
|
if (!isRecord(item)) continue;
|
|
115
107
|
const name =
|
|
116
108
|
typeof item.subagent === "string" ? item.subagent : typeof item.name === "string" ? item.name : undefined;
|
|
117
109
|
const task = typeof item.task === "string" ? item.task : typeof item.prompt === "string" ? item.prompt : undefined;
|
|
118
|
-
if (
|
|
119
|
-
throw new Error("Resume intelligence
|
|
110
|
+
if (Object.hasOwn(item, "intelligence")) {
|
|
111
|
+
throw new Error("Resume does not accept intelligence; it retains the original run settings.");
|
|
120
112
|
}
|
|
121
113
|
if (item.max_subagents_allowed !== undefined && !isBranchBudgetAmount(item.max_subagents_allowed)) {
|
|
122
114
|
throw new SubagentBudgetError(
|
|
@@ -127,16 +119,15 @@ export function normalizeResumes(
|
|
|
127
119
|
normalized.push({
|
|
128
120
|
name,
|
|
129
121
|
task,
|
|
130
|
-
...(item.intelligence !== undefined ? { intelligence: item.intelligence } : {}),
|
|
131
122
|
...(item.max_subagents_allowed !== undefined ? { max_subagents_allowed: item.max_subagents_allowed } : {}),
|
|
132
123
|
});
|
|
133
124
|
}
|
|
134
125
|
return normalized;
|
|
135
126
|
}
|
|
136
127
|
|
|
137
|
-
/** Normalize provider nulls to omission.
|
|
128
|
+
/** Normalize launch provider nulls to omission. Named resumes never accept intelligence. */
|
|
138
129
|
export function prepareIntelligenceArguments(args: unknown, key: "tasks" | "resumes"): unknown {
|
|
139
|
-
if (!isRecord(args) || !Object.hasOwn(args, key)) return args;
|
|
130
|
+
if (key === "resumes" || !isRecord(args) || !Object.hasOwn(args, key)) return args;
|
|
140
131
|
const omitNull = (item: unknown): unknown => {
|
|
141
132
|
if (!isRecord(item) || item.intelligence !== null) return item;
|
|
142
133
|
const { intelligence: _intelligence, ...rest } = item;
|
|
@@ -198,6 +189,15 @@ export function prepareRecoveryArguments(
|
|
|
198
189
|
|
|
199
190
|
/** SDK argument preparation must return a schema-validated value. */
|
|
200
191
|
export function validatePreparedArguments<T extends TSchema>(schema: T, value: unknown): Static<T> {
|
|
201
|
-
|
|
202
|
-
|
|
192
|
+
if (Value.Check(schema, value)) return value;
|
|
193
|
+
// Pi aliases TypeBox imports to its installed version. Newer Assert errors say only "Assert".
|
|
194
|
+
// Read validation issues directly so both TypeBox versions report useful paths without echoing input.
|
|
195
|
+
const issues = Array.from(Value.Errors(schema, value), (error) => {
|
|
196
|
+
const at = "instancePath" in error && typeof error.instancePath === "string" ? error.instancePath : error.path;
|
|
197
|
+
const params = "params" in error && isRecord(error.params) ? error.params : {};
|
|
198
|
+
const keys = params.additionalProperties ?? params.requiredProperties;
|
|
199
|
+
const properties = Array.isArray(keys) ? ` (${keys.filter((key) => typeof key === "string").join(", ")})` : "";
|
|
200
|
+
return `${at || "root"}: ${error.message}${properties}`;
|
|
201
|
+
});
|
|
202
|
+
throw new Error(`Invalid tool arguments:\n${issues.join("\n")}`);
|
|
203
203
|
}
|
package/names.ts
CHANGED
|
@@ -22,6 +22,7 @@ export interface AllocateNameRequest {
|
|
|
22
22
|
task: string;
|
|
23
23
|
sessionDir: string;
|
|
24
24
|
model?: string;
|
|
25
|
+
thinking?: string;
|
|
25
26
|
intelligence?: string;
|
|
26
27
|
tools?: string[];
|
|
27
28
|
}
|
|
@@ -52,6 +53,7 @@ export async function allocateSubagentNames(
|
|
|
52
53
|
agent: request.agent,
|
|
53
54
|
task: request.task,
|
|
54
55
|
...(request.model !== undefined ? { model: request.model } : {}),
|
|
56
|
+
...(request.thinking !== undefined ? { thinking: request.thinking } : {}),
|
|
55
57
|
...(request.intelligence !== undefined ? { intelligence: request.intelligence } : {}),
|
|
56
58
|
...(request.budget !== undefined ? { budget: request.budget } : {}),
|
|
57
59
|
...(request.tools !== undefined ? { tools: request.tools } : {}),
|
|
@@ -70,7 +72,9 @@ export async function allocateSubagentNames(
|
|
|
70
72
|
export async function updateNameRecord(
|
|
71
73
|
file: string,
|
|
72
74
|
name: string,
|
|
73
|
-
patch: Partial<
|
|
75
|
+
patch: Partial<
|
|
76
|
+
Pick<SubagentNameRecord, "sessionDir" | "task" | "lastResumePrompt" | "model" | "thinking" | "intelligence">
|
|
77
|
+
>,
|
|
74
78
|
): Promise<void> {
|
|
75
79
|
await updateNamesRegistry(file, (registry) => {
|
|
76
80
|
const record = registry.agents[name];
|
|
@@ -78,6 +82,9 @@ export async function updateNameRecord(
|
|
|
78
82
|
if (patch.sessionDir !== undefined) record.sessionDir = patch.sessionDir;
|
|
79
83
|
if (patch.task !== undefined) record.task = patch.task;
|
|
80
84
|
if (patch.lastResumePrompt !== undefined) record.lastResumePrompt = patch.lastResumePrompt;
|
|
85
|
+
if (patch.model !== undefined) record.model = patch.model;
|
|
86
|
+
if (patch.thinking !== undefined) record.thinking = patch.thinking;
|
|
87
|
+
if (patch.intelligence !== undefined) record.intelligence = patch.intelligence;
|
|
81
88
|
});
|
|
82
89
|
}
|
|
83
90
|
|
package/package.json
CHANGED
package/runner/arguments.ts
CHANGED
|
@@ -2,8 +2,11 @@ import * as fs from "node:fs";
|
|
|
2
2
|
import * as os from "node:os";
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
import type { AgentConfig } from "../agents.js";
|
|
5
|
+
import type { SubagentModelSettings } from "../storage/name-records.js";
|
|
6
|
+
import { latestSessionFile } from "../storage/session-fork.js";
|
|
5
7
|
import { SUBAGENT_FALLBACK_MODEL_ENV } from "./constants.js";
|
|
6
8
|
import { childExtensionArgs, excludedExtensions } from "./extension-policy.js";
|
|
9
|
+
import { resolveInheritedResource } from "./resource-paths.js";
|
|
7
10
|
function resolveExtensionArg(value: string): string {
|
|
8
11
|
if (!value) return value;
|
|
9
12
|
if (value.startsWith("npm:") || value.startsWith("git:")) return value;
|
|
@@ -17,8 +20,10 @@ function resolveExtensionArg(value: string): string {
|
|
|
17
20
|
interface InheritedCliArgs {
|
|
18
21
|
/** --extension/-e and --no-extensions/-ne args (with path resolution) */
|
|
19
22
|
extensionArgs: string[];
|
|
20
|
-
/**
|
|
23
|
+
/** Other non-blocked flags, with filesystem resources anchored to the startup cwd. */
|
|
21
24
|
alwaysProxy: string[];
|
|
25
|
+
/** Explicit CLI provider associated with a forwarded --api-key. */
|
|
26
|
+
explicitProvider: string | undefined;
|
|
22
27
|
/** Parent --model value; used only when agent config doesn't specify model */
|
|
23
28
|
fallbackModel: string | undefined;
|
|
24
29
|
/** Parent --thinking value; used only when agent config doesn't specify thinking */
|
|
@@ -42,9 +47,10 @@ interface InheritedCliArgs {
|
|
|
42
47
|
* Unknown flags use a heuristic: if the next token doesn't start with "-",
|
|
43
48
|
* it is treated as the flag's value.
|
|
44
49
|
*/
|
|
45
|
-
function parseInheritedCliArgs(argv: string[]): InheritedCliArgs {
|
|
50
|
+
function parseInheritedCliArgs(argv: string[], startupCwd = process.cwd()): InheritedCliArgs {
|
|
46
51
|
const extensionArgs: string[] = [];
|
|
47
52
|
const alwaysProxy: string[] = [];
|
|
53
|
+
let explicitProvider: string | undefined;
|
|
48
54
|
let fallbackModel: string | undefined;
|
|
49
55
|
let fallbackThinking: string | undefined;
|
|
50
56
|
let fallbackTools: string | undefined;
|
|
@@ -144,7 +150,13 @@ function parseInheritedCliArgs(argv: string[]): InheritedCliArgs {
|
|
|
144
150
|
)
|
|
145
151
|
) {
|
|
146
152
|
const [value, skip] = getVal();
|
|
147
|
-
if (value !== undefined)
|
|
153
|
+
if (value !== undefined) {
|
|
154
|
+
const forwarded = ["--skill", "--prompt-template", "--theme"].includes(flagName)
|
|
155
|
+
? resolveInheritedResource(flagName, value, startupCwd)
|
|
156
|
+
: value;
|
|
157
|
+
alwaysProxy.push(flagName, forwarded);
|
|
158
|
+
if (flagName === "--provider") explicitProvider = value;
|
|
159
|
+
}
|
|
148
160
|
i += skip;
|
|
149
161
|
continue;
|
|
150
162
|
}
|
|
@@ -197,15 +209,30 @@ function parseInheritedCliArgs(argv: string[]): InheritedCliArgs {
|
|
|
197
209
|
i++;
|
|
198
210
|
}
|
|
199
211
|
|
|
200
|
-
return {
|
|
212
|
+
return {
|
|
213
|
+
extensionArgs,
|
|
214
|
+
alwaysProxy,
|
|
215
|
+
explicitProvider,
|
|
216
|
+
fallbackModel,
|
|
217
|
+
fallbackThinking,
|
|
218
|
+
fallbackTools,
|
|
219
|
+
fallbackNoTools,
|
|
220
|
+
};
|
|
201
221
|
}
|
|
202
222
|
|
|
203
223
|
/** Cached once — process.argv is immutable at runtime */
|
|
204
224
|
const _inheritedCliArgs = parseInheritedCliArgs(process.argv);
|
|
205
225
|
|
|
206
|
-
export async function resolveChildExtensionArgs(
|
|
226
|
+
export async function resolveChildExtensionArgs(
|
|
227
|
+
cwd: string,
|
|
228
|
+
projectTrusted?: boolean,
|
|
229
|
+
forceTrustDecision = false,
|
|
230
|
+
): Promise<string[] | undefined> {
|
|
207
231
|
const excludes = excludedExtensions();
|
|
208
|
-
if (excludes.length === 0)
|
|
232
|
+
if (excludes.length === 0)
|
|
233
|
+
return forceTrustDecision
|
|
234
|
+
? [..._inheritedCliArgs.extensionArgs, projectTrusted ? "--approve" : "--no-approve"]
|
|
235
|
+
: undefined;
|
|
209
236
|
return childExtensionArgs(_inheritedCliArgs.extensionArgs, cwd, projectTrusted, excludes);
|
|
210
237
|
}
|
|
211
238
|
|
|
@@ -217,6 +244,18 @@ export function resolveSubagentModel(agentModel?: string, currentParentModel?: s
|
|
|
217
244
|
);
|
|
218
245
|
}
|
|
219
246
|
|
|
247
|
+
export function resolveLaunchModelSettings(
|
|
248
|
+
agent: Pick<AgentConfig, "model" | "thinking">,
|
|
249
|
+
fallbackModel?: string,
|
|
250
|
+
selection?: { name: string; provider: string; model: string; thinking: string },
|
|
251
|
+
): SubagentModelSettings {
|
|
252
|
+
return {
|
|
253
|
+
model: selection ? `${selection.provider}/${selection.model}` : resolveSubagentModel(agent.model, fallbackModel),
|
|
254
|
+
thinking: selection?.thinking ?? agent.thinking ?? _inheritedCliArgs.fallbackThinking,
|
|
255
|
+
intelligence: selection?.name,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
220
259
|
export function buildPiArgs(
|
|
221
260
|
agent: AgentConfig,
|
|
222
261
|
systemPromptPath: string | null,
|
|
@@ -227,14 +266,19 @@ export function buildPiArgs(
|
|
|
227
266
|
rawPrompt = false,
|
|
228
267
|
selection?: { provider: string; model: string; thinking: string },
|
|
229
268
|
extensionArgsOverride?: string[],
|
|
269
|
+
resumeSettings?: SubagentModelSettings,
|
|
270
|
+
savedSessionFile?: string | null,
|
|
230
271
|
): { args: string[]; prompt: string } {
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
272
|
+
const provider = resumeSettings?.model?.includes("/") ? resumeSettings.model.split("/", 1)[0] : selection?.provider;
|
|
273
|
+
// Named resumes can reuse CLI-only auth, but only for the explicitly matching provider.
|
|
274
|
+
const keepResumeApiKey = !!resumeSettings && !!provider && provider === _inheritedCliArgs.explicitProvider;
|
|
275
|
+
const blocked = keepResumeApiKey ? ["--provider"] : ["--provider", "--api-key"];
|
|
276
|
+
const proxyArgs =
|
|
277
|
+
selection || resumeSettings
|
|
278
|
+
? _inheritedCliArgs.alwaysProxy.filter(
|
|
279
|
+
(arg, index, args) => !blocked.includes(arg) && !blocked.includes(args[index - 1]),
|
|
280
|
+
)
|
|
281
|
+
: _inheritedCliArgs.alwaysProxy;
|
|
238
282
|
const args: string[] = [
|
|
239
283
|
"--mode",
|
|
240
284
|
"rpc",
|
|
@@ -246,14 +290,27 @@ export function buildPiArgs(
|
|
|
246
290
|
if (extensionArgsOverride) args.push(...extensionArgsOverride);
|
|
247
291
|
|
|
248
292
|
if (sessionDir) args.push("--session-dir", sessionDir);
|
|
249
|
-
if (resumeSession)
|
|
293
|
+
if (resumeSession || resumeSettings) {
|
|
294
|
+
// The runner pins this before resource discovery. Only standalone callers select here.
|
|
295
|
+
const savedFile =
|
|
296
|
+
savedSessionFile === undefined ? (sessionDir ? latestSessionFile(sessionDir) : undefined) : savedSessionFile;
|
|
297
|
+
if (savedFile) args.push("--session", savedFile);
|
|
298
|
+
else if (resumeSettings)
|
|
299
|
+
throw new Error(`Cannot resume named subagent: no saved session file in ${sessionDir ?? "(missing directory)"}.`);
|
|
300
|
+
else args.push("--continue"); // Legacy recovery without a saved transcript can start from its task.
|
|
301
|
+
}
|
|
250
302
|
|
|
251
|
-
//
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
303
|
+
// Named resumes bypass today's parent, agent definition, CLI defaults, and presets.
|
|
304
|
+
// Missing legacy settings are left to the saved session rather than replaced with current defaults.
|
|
305
|
+
const model = resumeSettings
|
|
306
|
+
? resumeSettings.model
|
|
307
|
+
: (selection?.model ?? resolveSubagentModel(agent.model, fallbackModelOverride));
|
|
308
|
+
if (provider) args.push("--provider", provider);
|
|
309
|
+
if (model) args.push("--model", resumeSettings && provider ? model.slice(provider.length + 1) : model);
|
|
255
310
|
|
|
256
|
-
const thinking =
|
|
311
|
+
const thinking = resumeSettings
|
|
312
|
+
? resumeSettings.thinking
|
|
313
|
+
: (selection?.thinking ?? agent.thinking ?? _inheritedCliArgs.fallbackThinking);
|
|
257
314
|
if (thinking) args.push("--thinking", thinking);
|
|
258
315
|
|
|
259
316
|
// agent.tools is set only when the agent file specifies tools (length > 0)
|
package/runner/options.ts
CHANGED
|
@@ -15,7 +15,7 @@ export interface RunningSubagentHandle {
|
|
|
15
15
|
export type RunningSubagentStartedCallback = (handle: RunningSubagentHandle) => void;
|
|
16
16
|
|
|
17
17
|
export interface RunAgentOptions {
|
|
18
|
-
/**
|
|
18
|
+
/** Caller working directory; saved-session resumes run in the saved project's cwd. */
|
|
19
19
|
cwd: string;
|
|
20
20
|
/** Effective trust for this cwd; absent SDK callers fail closed. */
|
|
21
21
|
projectTrusted?: boolean;
|
|
@@ -56,13 +56,15 @@ export interface RunAgentOptions {
|
|
|
56
56
|
* self-set env var would then masquerade as "inherited from a parent".
|
|
57
57
|
*/
|
|
58
58
|
namesFile?: string;
|
|
59
|
-
/**
|
|
59
|
+
/** Select and pin the most recent saved session in sessionDir instead of creating a new one. */
|
|
60
60
|
resumeSession?: boolean;
|
|
61
61
|
/** Previously captured state for this same subagent, used to render resumed nested trees. */
|
|
62
62
|
initialResult?: SingleResult;
|
|
63
63
|
/** Fallback model to use when the agent config does not pin one. */
|
|
64
64
|
fallbackModel?: string;
|
|
65
|
-
/**
|
|
65
|
+
/** Original settings for a named resume. Even an empty object bypasses current presets/defaults. */
|
|
66
|
+
resumeSettings?: import("../storage/name-records.js").SubagentModelSettings;
|
|
67
|
+
/** Caller-selected preset for a launch. Omission keeps existing defaults. */
|
|
66
68
|
intelligence?: string;
|
|
67
69
|
/** Valid presets loaded from trusted configuration. */
|
|
68
70
|
intelligencePresets?: IntelligencePreset[];
|
package/runner/parallel.ts
CHANGED
|
@@ -41,6 +41,7 @@ export async function executeParallelSubprocess(
|
|
|
41
41
|
namesFile?: string;
|
|
42
42
|
budgets?: Array<SubagentBudget | undefined>;
|
|
43
43
|
intelligencePresets?: RunAgentOptions["intelligencePresets"];
|
|
44
|
+
resumeSettings?: Array<NonNullable<RunAgentOptions["resumeSettings"]>>;
|
|
44
45
|
projectTrusted?: boolean;
|
|
45
46
|
},
|
|
46
47
|
): Promise<{
|
|
@@ -69,7 +70,9 @@ export async function executeParallelSubprocess(
|
|
|
69
70
|
if (previous && isResultSuccess(previous)) return previous;
|
|
70
71
|
let intelligence: string | undefined;
|
|
71
72
|
try {
|
|
72
|
-
intelligence =
|
|
73
|
+
intelligence = extras?.resumeSettings
|
|
74
|
+
? extras.resumeSettings[index].intelligence
|
|
75
|
+
: selectIntelligence(extras?.intelligencePresets, t.intelligence)?.name;
|
|
73
76
|
} catch {
|
|
74
77
|
// Let the single runner report invalid selections as aligned task failures.
|
|
75
78
|
}
|
|
@@ -155,6 +158,7 @@ export async function executeParallelSubprocess(
|
|
|
155
158
|
fallbackModel,
|
|
156
159
|
intelligence: t.intelligence,
|
|
157
160
|
intelligencePresets: extras?.intelligencePresets,
|
|
161
|
+
resumeSettings: extras?.resumeSettings?.[index],
|
|
158
162
|
onHandle: (handle) => onHandleForTask?.(index, t, handle),
|
|
159
163
|
onUpdate: (partial) => {
|
|
160
164
|
if (partial.details?.results[0]) {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as os from "node:os";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
/** Pin explicit filesystem resources before a resume switches the child to another project. */
|
|
7
|
+
export function resolveInheritedResource(flag: string, value: string, startupCwd: string): string {
|
|
8
|
+
if (path.isAbsolute(value)) return value;
|
|
9
|
+
if (value.startsWith("file://")) return fileURLToPath(value);
|
|
10
|
+
// Keep package/URL/builtin references, but do not mistake Windows drive paths for URI schemes.
|
|
11
|
+
if (!/^[a-z]:/i.test(value) && (/^[a-z][a-z\d+.-]*:/i.test(value) || value.startsWith("git@"))) return value;
|
|
12
|
+
if (value === "~") return os.homedir();
|
|
13
|
+
if (value.startsWith("~/") || (process.platform === "win32" && value.startsWith("~\\")))
|
|
14
|
+
return path.join(os.homedir(), value.slice(2));
|
|
15
|
+
// Bare theme identifiers stay names; explicit paths and existing local theme resources are pinned.
|
|
16
|
+
if (
|
|
17
|
+
flag === "--theme" &&
|
|
18
|
+
!/[\\/]/.test(value) &&
|
|
19
|
+
!value.endsWith(".json") &&
|
|
20
|
+
!fs.existsSync(path.resolve(startupCwd, value))
|
|
21
|
+
)
|
|
22
|
+
return value;
|
|
23
|
+
// Resolve even missing files so a same-named file in the saved project cannot replace them.
|
|
24
|
+
return path.resolve(startupCwd, value);
|
|
25
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { latestSessionFile } from "../storage/session-fork.js";
|
|
4
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { isRecord } from "../storage/values.js";
|
|
6
|
+
|
|
7
|
+
export interface SessionTarget {
|
|
8
|
+
cwd: string;
|
|
9
|
+
sessionDir: string | undefined;
|
|
10
|
+
/** null pins the absence of a transcript, so argument building must not rediscover one. */
|
|
11
|
+
sessionFile: string | null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Select once, before asynchronous resource discovery, and use this target throughout the launch. */
|
|
15
|
+
export function resolveSessionTarget(
|
|
16
|
+
callerCwd: string,
|
|
17
|
+
sessionDir: string | undefined,
|
|
18
|
+
resumeSession: boolean,
|
|
19
|
+
namedResume = false,
|
|
20
|
+
): SessionTarget {
|
|
21
|
+
const target: SessionTarget = {
|
|
22
|
+
cwd: path.resolve(callerCwd),
|
|
23
|
+
sessionDir: sessionDir ? path.resolve(callerCwd, sessionDir) : undefined,
|
|
24
|
+
sessionFile: null,
|
|
25
|
+
};
|
|
26
|
+
if (!resumeSession && !namedResume) return target;
|
|
27
|
+
target.sessionFile = target.sessionDir ? (latestSessionFile(target.sessionDir) ?? null) : null;
|
|
28
|
+
if (!target.sessionFile) {
|
|
29
|
+
if (namedResume)
|
|
30
|
+
throw new Error(`Cannot resume named subagent: no saved session file in ${sessionDir ?? "(missing directory)"}.`);
|
|
31
|
+
return target;
|
|
32
|
+
}
|
|
33
|
+
// Like Pi's header scan, skip blank/malformed lines but require the first parsed entry to be a header.
|
|
34
|
+
let header: unknown;
|
|
35
|
+
for (const line of fs.readFileSync(target.sessionFile, "utf8").split("\n")) {
|
|
36
|
+
try {
|
|
37
|
+
header = JSON.parse(line);
|
|
38
|
+
} catch {
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (header) break;
|
|
42
|
+
}
|
|
43
|
+
if (!isRecord(header) || header.type !== "session" || typeof header.id !== "string")
|
|
44
|
+
throw new Error(`Cannot resume subagent: invalid saved session header in ${target.sessionFile}.`);
|
|
45
|
+
if (header.cwd !== undefined && typeof header.cwd !== "string")
|
|
46
|
+
throw new Error(`Cannot resume subagent: invalid saved working directory in ${target.sessionFile}.`);
|
|
47
|
+
// Pi-created headers store native absolute paths. Reject ambiguous manually edited paths rather
|
|
48
|
+
// than approving one cwd while Pi interprets another. Legacy headers without cwd inherit the caller.
|
|
49
|
+
if (typeof header.cwd === "string" && header.cwd) {
|
|
50
|
+
if (!path.isAbsolute(header.cwd))
|
|
51
|
+
throw new Error(`Cannot resume subagent: saved working directory must be absolute in ${target.sessionFile}.`);
|
|
52
|
+
// Reuse Pi's normalization, including Windows shell paths; this does not open or mutate a session.
|
|
53
|
+
target.cwd = SessionManager.inMemory(header.cwd).getCwd();
|
|
54
|
+
}
|
|
55
|
+
if (!fs.statSync(target.cwd).isDirectory())
|
|
56
|
+
throw new Error(`Cannot resume subagent: saved working directory is not a directory: ${target.cwd}.`);
|
|
57
|
+
return target;
|
|
58
|
+
}
|
package/runner/single.ts
CHANGED
|
@@ -7,11 +7,15 @@ import {
|
|
|
7
7
|
STARTUP_RETRY_BASE_BACKOFF_MS,
|
|
8
8
|
} from "./constants.js";
|
|
9
9
|
import type { RunAgentOptions } from "./options.js";
|
|
10
|
-
import { buildPiArgs, resolveChildExtensionArgs } from "./arguments.js";
|
|
10
|
+
import { buildPiArgs, resolveChildExtensionArgs, resolveLaunchModelSettings } from "./arguments.js";
|
|
11
|
+
import { readOriginalSessionSettings } from "../storage/session-settings.js";
|
|
12
|
+
import { updateNameRecord } from "../names.js";
|
|
11
13
|
import { writePromptToTempFile, cleanupTempDir, sessionDirExists } from "./files.js";
|
|
12
14
|
import { appendBoundedStderr, priorDescendantUsage, endedWithSyntheticResumeFailure } from "./result.js";
|
|
13
15
|
import { runAttempt } from "./attempt.js";
|
|
14
16
|
import { selectIntelligence } from "../intelligence.js";
|
|
17
|
+
import * as path from "node:path";
|
|
18
|
+
import { resolveSessionTarget } from "./session-target.js";
|
|
15
19
|
export async function runAgentSubprocess(opts: RunAgentOptions): Promise<SingleResult> {
|
|
16
20
|
const {
|
|
17
21
|
agents,
|
|
@@ -65,7 +69,9 @@ export async function runAgentSubprocess(opts: RunAgentOptions): Promise<SingleR
|
|
|
65
69
|
stderr: initialResult?.stderr ?? "",
|
|
66
70
|
usage: initialResult?.usage ? { ...initialResult.usage } : emptyUsage(),
|
|
67
71
|
toolCalls: initialResult?.toolCalls ? { ...initialResult.toolCalls } : {},
|
|
68
|
-
model: initialResult?.model ?? agent.model,
|
|
72
|
+
model: opts.resumeSettings?.model ?? initialResult?.model ?? agent.model,
|
|
73
|
+
thinking: opts.resumeSettings?.thinking,
|
|
74
|
+
intelligence: opts.resumeSettings?.intelligence,
|
|
69
75
|
completedTurns: initialResult?.completedTurns ?? 0,
|
|
70
76
|
turnInProgress: false,
|
|
71
77
|
liveToolExecutions: initialResult?.liveToolExecutions,
|
|
@@ -110,7 +116,6 @@ export async function runAgentSubprocess(opts: RunAgentOptions): Promise<SingleR
|
|
|
110
116
|
}
|
|
111
117
|
|
|
112
118
|
try {
|
|
113
|
-
const extensionArgs = await resolveChildExtensionArgs(opts.cwd, opts.projectTrusted);
|
|
114
119
|
if (opts.signal?.aborted) {
|
|
115
120
|
result.exitCode = 130;
|
|
116
121
|
result.stopReason = "aborted";
|
|
@@ -118,20 +123,36 @@ export async function runAgentSubprocess(opts: RunAgentOptions): Promise<SingleR
|
|
|
118
123
|
emitUpdate();
|
|
119
124
|
return result;
|
|
120
125
|
}
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
|
|
126
|
+
const target = resolveSessionTarget(opts.cwd, sessionDir, shouldContinueSession, !!opts.resumeSettings);
|
|
127
|
+
// Approval is scoped to the caller's project, never transferable to a saved project's cwd.
|
|
128
|
+
const projectTrusted = target.cwd === path.resolve(opts.cwd) ? opts.projectTrusted : false;
|
|
129
|
+
const childOpts = { ...opts, cwd: target.cwd, sessionDir: target.sessionDir, projectTrusted };
|
|
130
|
+
const extensionArgs = await resolveChildExtensionArgs(target.cwd, projectTrusted, !!target.sessionFile);
|
|
131
|
+
if (opts.signal?.aborted) {
|
|
132
|
+
result.exitCode = 130;
|
|
133
|
+
result.stopReason = "aborted";
|
|
134
|
+
result.errorMessage = "Subagent was aborted.";
|
|
135
|
+
emitUpdate();
|
|
136
|
+
return result;
|
|
137
|
+
}
|
|
138
|
+
const selection = opts.resumeSettings ? undefined : selectIntelligence(opts.intelligencePresets, opts.intelligence);
|
|
139
|
+
const settings = opts.resumeSettings ?? resolveLaunchModelSettings(agent, fallbackModel, selection);
|
|
140
|
+
result.intelligence = settings.intelligence;
|
|
141
|
+
result.model = settings.model;
|
|
142
|
+
result.thinking = settings.thinking;
|
|
124
143
|
emitUpdate();
|
|
125
144
|
const { args: piArgs, prompt: taskPrompt } = buildPiArgs(
|
|
126
145
|
agent,
|
|
127
146
|
promptTmpPath,
|
|
128
147
|
task,
|
|
129
|
-
sessionDir,
|
|
148
|
+
target.sessionDir,
|
|
130
149
|
shouldContinueSession,
|
|
131
150
|
fallbackModel,
|
|
132
151
|
opts.rawPrompt === true,
|
|
133
152
|
selection,
|
|
134
153
|
extensionArgs,
|
|
154
|
+
opts.resumeSettings,
|
|
155
|
+
target.sessionFile,
|
|
135
156
|
);
|
|
136
157
|
const prompt =
|
|
137
158
|
result.budget && readBudget(result.budget).limit > 0
|
|
@@ -144,7 +165,14 @@ export async function runAgentSubprocess(opts: RunAgentOptions): Promise<SingleR
|
|
|
144
165
|
|
|
145
166
|
for (let attempt = 0; ; attempt++) {
|
|
146
167
|
startupTimedOut = false;
|
|
147
|
-
const outcome = await runAttempt(
|
|
168
|
+
const outcome = await runAttempt(
|
|
169
|
+
opts.resumeSettings ? { ...childOpts, fallbackModel: settings.model } : childOpts,
|
|
170
|
+
result,
|
|
171
|
+
piArgs,
|
|
172
|
+
prompt,
|
|
173
|
+
attempt,
|
|
174
|
+
emitUpdate,
|
|
175
|
+
);
|
|
148
176
|
exitCode = outcome.exitCode;
|
|
149
177
|
startupTimedOut = outcome.startupTimedOut;
|
|
150
178
|
wasAborted = outcome.wasAborted;
|
|
@@ -214,5 +242,14 @@ export async function runAgentSubprocess(opts: RunAgentOptions): Promise<SingleR
|
|
|
214
242
|
return result;
|
|
215
243
|
} finally {
|
|
216
244
|
cleanupTempDir(promptTmpDir);
|
|
245
|
+
if (!resumeSession && opts.namesFile && opts.subagentName && sessionDir) {
|
|
246
|
+
const original = readOriginalSessionSettings(sessionDir);
|
|
247
|
+
result.thinking = original.thinking ?? result.thinking;
|
|
248
|
+
await updateNameRecord(opts.namesFile, opts.subagentName, {
|
|
249
|
+
model: original.model ?? result.model,
|
|
250
|
+
thinking: result.thinking,
|
|
251
|
+
intelligence: result.intelligence,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
217
254
|
}
|
|
218
255
|
}
|
package/storage/name-records.ts
CHANGED
|
@@ -4,7 +4,14 @@ export interface SubagentForkRecord {
|
|
|
4
4
|
createdAt: number;
|
|
5
5
|
}
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
/** Original effective settings, independent of current presets and parent settings. */
|
|
8
|
+
export interface SubagentModelSettings {
|
|
9
|
+
model?: string;
|
|
10
|
+
thinking?: string;
|
|
11
|
+
intelligence?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SubagentNameRecord extends SubagentModelSettings {
|
|
8
15
|
name: string;
|
|
9
16
|
/** Agent type this name was generated from (e.g. "code-writer"). */
|
|
10
17
|
agent: string;
|
|
@@ -12,10 +19,6 @@ export interface SubagentNameRecord {
|
|
|
12
19
|
task: string;
|
|
13
20
|
/** Original branch budget. Resumes and private forks share it. */
|
|
14
21
|
budget?: import("../budget.js").SubagentBudget;
|
|
15
|
-
/** Model pinned by the agent config at spawn time, if any. */
|
|
16
|
-
model?: string;
|
|
17
|
-
/** Preset selected for the initial task only. Resume labels live in their transcripts. */
|
|
18
|
-
intelligence?: string;
|
|
19
22
|
/** Tool restriction from the agent config at spawn time, if any. */
|
|
20
23
|
tools?: string[];
|
|
21
24
|
/** Session id of the pi process that spawned this subagent (its owner). */
|
|
@@ -30,7 +30,9 @@ function isNameRecord(value: unknown): value is SubagentNameRecord {
|
|
|
30
30
|
(!Array.isArray(value.tools) || !value.tools.every((tool) => typeof tool === "string"))
|
|
31
31
|
)
|
|
32
32
|
return false;
|
|
33
|
-
return ["model", "lastResumePrompt"].every(
|
|
33
|
+
return ["model", "thinking", "intelligence", "lastResumePrompt"].every(
|
|
34
|
+
(key) => value[key] === undefined || typeof value[key] === "string",
|
|
35
|
+
);
|
|
34
36
|
}
|
|
35
37
|
|
|
36
38
|
function isNamesRegistry(value: unknown): value is NamesRegistry {
|
package/storage/session-fork.ts
CHANGED
|
@@ -3,7 +3,8 @@ import * as path from "node:path";
|
|
|
3
3
|
import { SUBAGENT_NAMES_CUSTOM_TYPE } from "./names-identity.js";
|
|
4
4
|
import { isRecord } from "./values.js";
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
/** Select the saved file directly; Pi's --continue filters custom session dirs by cwd. */
|
|
7
|
+
export function latestSessionFile(sessionDir: string): string | undefined {
|
|
7
8
|
try {
|
|
8
9
|
const entries = fs
|
|
9
10
|
.readdirSync(sessionDir)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { SUBAGENT_INTELLIGENCE_CUSTOM_TYPE } from "../intelligence.js";
|
|
4
|
+
import type { SubagentModelSettings, SubagentNameRecord } from "./name-records.js";
|
|
5
|
+
import { isRecord } from "./values.js";
|
|
6
|
+
|
|
7
|
+
/** Read the first task's settings, never those appended by a later resume. */
|
|
8
|
+
export function readOriginalSessionSettings(sessionDir: string): SubagentModelSettings {
|
|
9
|
+
const settings: SubagentModelSettings = {};
|
|
10
|
+
try {
|
|
11
|
+
const files = fs
|
|
12
|
+
.readdirSync(sessionDir)
|
|
13
|
+
.filter((name) => name.endsWith(".jsonl"))
|
|
14
|
+
.map((name) => ({ file: path.join(sessionDir, name), at: fs.statSync(path.join(sessionDir, name)).mtimeMs }))
|
|
15
|
+
.sort((a, b) => b.at - a.at);
|
|
16
|
+
if (!files[0]) return settings;
|
|
17
|
+
let started = false;
|
|
18
|
+
for (const line of fs.readFileSync(files[0].file, "utf8").split("\n")) {
|
|
19
|
+
let entry: unknown;
|
|
20
|
+
try {
|
|
21
|
+
entry = JSON.parse(line);
|
|
22
|
+
} catch {
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (!isRecord(entry)) continue;
|
|
26
|
+
if (!started && entry.type === "model_change" && typeof entry.modelId === "string") {
|
|
27
|
+
settings.model = typeof entry.provider === "string" ? `${entry.provider}/${entry.modelId}` : entry.modelId;
|
|
28
|
+
}
|
|
29
|
+
if (!started && entry.type === "thinking_level_change" && typeof entry.thinkingLevel === "string") {
|
|
30
|
+
settings.thinking = entry.thinkingLevel;
|
|
31
|
+
}
|
|
32
|
+
if (!started && entry.type === "custom" && entry.customType === SUBAGENT_INTELLIGENCE_CUSTOM_TYPE) {
|
|
33
|
+
const label = isRecord(entry.data) ? entry.data.intelligence : undefined;
|
|
34
|
+
if (typeof label === "string") settings.intelligence = label;
|
|
35
|
+
else if (label === null) delete settings.intelligence;
|
|
36
|
+
}
|
|
37
|
+
const message = entry.type === "message" && isRecord(entry.message) ? entry.message : undefined;
|
|
38
|
+
if (message?.role === "user") {
|
|
39
|
+
if (started) break;
|
|
40
|
+
started = true;
|
|
41
|
+
}
|
|
42
|
+
if (message?.role === "assistant" && message.provider !== "pi-subagent-resume") {
|
|
43
|
+
if (typeof message.model === "string" && message.model !== "synthetic-tool-call") {
|
|
44
|
+
settings.model =
|
|
45
|
+
typeof message.provider === "string" ? `${message.provider}/${message.model}` : message.model;
|
|
46
|
+
}
|
|
47
|
+
if (typeof message.thinkingLevel === "string") settings.thinking = message.thinkingLevel;
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
} catch {
|
|
52
|
+
// Missing/partial transcripts can still use the settings saved before spawning.
|
|
53
|
+
}
|
|
54
|
+
return settings;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Recover actual settings from the original, not a private fork. This also covers interrupted launches
|
|
58
|
+
* whose registry still contains requested settings before Pi clamped thinking or resolved a model alias. */
|
|
59
|
+
export function originalModelSettings(record: SubagentNameRecord): SubagentModelSettings {
|
|
60
|
+
const recorded = {
|
|
61
|
+
model: record.model,
|
|
62
|
+
thinking: record.thinking,
|
|
63
|
+
intelligence: record.intelligence,
|
|
64
|
+
};
|
|
65
|
+
return { ...recorded, ...readOriginalSessionSettings(record.sessionDir) };
|
|
66
|
+
}
|
package/types/contracts.ts
CHANGED
|
@@ -68,7 +68,7 @@ export interface SingleResult {
|
|
|
68
68
|
task: string;
|
|
69
69
|
/** Unique resumable human name within the delegation tree (e.g. "John"). */
|
|
70
70
|
name?: string;
|
|
71
|
-
/**
|
|
71
|
+
/** Original configured preset label, retained by named resumes. */
|
|
72
72
|
intelligence?: string;
|
|
73
73
|
/** Durable branch allowance, shared by this agent's resumes and session forks. */
|
|
74
74
|
budget?: import("../budget.js").SubagentBudget;
|
|
@@ -82,6 +82,7 @@ export interface SingleResult {
|
|
|
82
82
|
usage: UsageStats;
|
|
83
83
|
toolCalls: ToolCallCounts;
|
|
84
84
|
model?: string;
|
|
85
|
+
thinking?: string;
|
|
85
86
|
stopReason?: string;
|
|
86
87
|
errorMessage?: string;
|
|
87
88
|
/** Cached final assistant text so durable details can omit full transcripts. */
|
package/types/details.ts
CHANGED
|
@@ -80,6 +80,7 @@ export function compactSingleResultForDurableDetails(result: SingleResult): Sing
|
|
|
80
80
|
...(result.stopReason !== undefined ? { stopReason: result.stopReason } : {}),
|
|
81
81
|
...(result.errorMessage !== undefined ? { errorMessage: result.errorMessage } : {}),
|
|
82
82
|
...(result.model !== undefined ? { model: result.model } : {}),
|
|
83
|
+
...(result.thinking !== undefined ? { thinking: result.thinking } : {}),
|
|
83
84
|
...(result.sessionDir !== undefined ? { sessionDir: result.sessionDir } : {}),
|
|
84
85
|
...(result.budget !== undefined ? { budget: result.budget } : {}),
|
|
85
86
|
...(result.sessionId !== undefined ? { sessionId: result.sessionId } : {}),
|
package/types/outcomes.ts
CHANGED
|
@@ -18,26 +18,26 @@ export function subagentDetailsHaveErrors(value: unknown): boolean {
|
|
|
18
18
|
return isSubagentDetails(value) && value.results.some((result) => isResultError(result));
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
/** Normalize
|
|
21
|
+
/** Normalize resume shorthands and strict-provider nulls before schema validation.
|
|
22
|
+
* Only the optional budget accepts null as omission; required fields and intelligence remain invalid. */
|
|
22
23
|
export function prepareResumeArguments(args: unknown): unknown {
|
|
23
24
|
if (!args || typeof args !== "object" || Array.isArray(args)) return args;
|
|
24
25
|
const record = args as Record<string, unknown>;
|
|
26
|
+
const omitNullBudget = (item: unknown): unknown => {
|
|
27
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) return item;
|
|
28
|
+
const resume = item as Record<string, unknown>;
|
|
29
|
+
if (resume.max_subagents_allowed !== null) return item;
|
|
30
|
+
const { max_subagents_allowed: _budget, ...rest } = resume;
|
|
31
|
+
return rest;
|
|
32
|
+
};
|
|
25
33
|
if (record.resumes === undefined && typeof record.subagent === "string" && typeof record.task === "string") {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
subagent: record.subagent,
|
|
30
|
-
task: record.task,
|
|
31
|
-
...(record.intelligence !== undefined ? { intelligence: record.intelligence } : {}),
|
|
32
|
-
...(record.max_subagents_allowed !== undefined
|
|
33
|
-
? { max_subagents_allowed: record.max_subagents_allowed }
|
|
34
|
-
: {}),
|
|
35
|
-
},
|
|
36
|
-
],
|
|
37
|
-
};
|
|
34
|
+
// Preserve unknown fields so validation still rejects intelligence and misspelled arguments.
|
|
35
|
+
const { resumes: _resumes, ...item } = record;
|
|
36
|
+
return { resumes: [omitNullBudget(item)] };
|
|
38
37
|
}
|
|
39
|
-
if (record.resumes
|
|
40
|
-
|
|
38
|
+
if (Array.isArray(record.resumes)) return { ...record, resumes: record.resumes.map(omitNullBudget) };
|
|
39
|
+
if (record.resumes && typeof record.resumes === "object") {
|
|
40
|
+
return { ...record, resumes: [omitNullBudget(record.resumes)] };
|
|
41
41
|
}
|
|
42
42
|
return args;
|
|
43
43
|
}
|
package/ui/detail-model.ts
CHANGED
|
@@ -36,6 +36,8 @@ export interface DetailUsage {
|
|
|
36
36
|
export interface SubagentDetail {
|
|
37
37
|
name: string;
|
|
38
38
|
agent: string;
|
|
39
|
+
/** Original preset label from the name registry or first task's session metadata. */
|
|
40
|
+
intelligence?: string;
|
|
39
41
|
model?: string;
|
|
40
42
|
thinkingLevel?: string;
|
|
41
43
|
tools?: string[];
|
package/ui/detail-transcript.ts
CHANGED
|
@@ -90,6 +90,7 @@ export function findNameRecord(registry: NamesRegistry, name: string): SubagentN
|
|
|
90
90
|
}
|
|
91
91
|
|
|
92
92
|
export interface ParsedTranscript {
|
|
93
|
+
intelligence?: string;
|
|
93
94
|
blocks: DetailBlock[];
|
|
94
95
|
usage: DetailUsage;
|
|
95
96
|
toolCallCount: number;
|
|
@@ -231,11 +232,13 @@ export function parseTranscriptMessages(messages: unknown[]): ParsedTranscript {
|
|
|
231
232
|
}
|
|
232
233
|
}
|
|
233
234
|
|
|
234
|
-
|
|
235
|
+
const intelligence = blocks.length ? blocks[0].intelligence : pendingIntelligence;
|
|
236
|
+
return { blocks, usage, toolCallCount, model, thinkingLevel, intelligence };
|
|
235
237
|
}
|
|
236
238
|
|
|
237
239
|
export function buildSubagentDetail(record: SubagentNameRecord, options: { sessionDir?: string } = {}): SubagentDetail {
|
|
238
240
|
const sessionDir = options.sessionDir ?? record.sessionDir;
|
|
241
|
+
let intelligence = record.intelligence;
|
|
239
242
|
const notes: string[] = [];
|
|
240
243
|
const files = sessionFilesIn(sessionDir);
|
|
241
244
|
const sessionFile = files[files.length - 1];
|
|
@@ -250,6 +253,7 @@ export function buildSubagentDetail(record: SubagentNameRecord, options: { sessi
|
|
|
250
253
|
notes.push(`No session transcript found in ${shortenPath(sessionDir)}`);
|
|
251
254
|
} else {
|
|
252
255
|
const parsed = parseTranscriptMessages(readSessionEntries(sessionFile));
|
|
256
|
+
intelligence ??= parsed.intelligence;
|
|
253
257
|
model = parsed.model;
|
|
254
258
|
thinkingLevel = parsed.thinkingLevel;
|
|
255
259
|
blocks = parsed.blocks;
|
|
@@ -269,7 +273,7 @@ export function buildSubagentDetail(record: SubagentNameRecord, options: { sessi
|
|
|
269
273
|
at: record.createdAt,
|
|
270
274
|
model,
|
|
271
275
|
thinkingLevel,
|
|
272
|
-
intelligence
|
|
276
|
+
intelligence,
|
|
273
277
|
events: [],
|
|
274
278
|
},
|
|
275
279
|
];
|
|
@@ -281,6 +285,7 @@ export function buildSubagentDetail(record: SubagentNameRecord, options: { sessi
|
|
|
281
285
|
return {
|
|
282
286
|
name: record.name,
|
|
283
287
|
agent: record.agent,
|
|
288
|
+
intelligence,
|
|
284
289
|
model,
|
|
285
290
|
thinkingLevel,
|
|
286
291
|
tools: record.tools,
|
package/ui/pager-view.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { overlayFrame } from "./frame.js";
|
|
2
|
+
import { displayIntelligence } from "../intelligence.js";
|
|
2
3
|
import { stripTerminalSequences } from "@earendil-works/pi-tui";
|
|
3
4
|
import {
|
|
4
5
|
TOOL_LIST_HEADER_LINES,
|
|
@@ -183,7 +184,10 @@ export class PagerView {
|
|
|
183
184
|
: this.mode === "children"
|
|
184
185
|
? "children"
|
|
185
186
|
: `${turn} • tool ${this.selectedToolIndex() + 1}`;
|
|
186
|
-
|
|
187
|
+
const agent = this.detail.intelligence
|
|
188
|
+
? `${displayIntelligence(this.detail.intelligence)}/${this.detail.agent}`
|
|
189
|
+
: this.detail.agent;
|
|
190
|
+
return `${this.detail.name} (${agent}) • ${suffix}`;
|
|
187
191
|
}
|
|
188
192
|
|
|
189
193
|
protected footer(): string {
|