oira666_pi-subagent 0.5.4 → 0.5.7

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 CHANGED
@@ -103,7 +103,9 @@ See [configuration](docs/configuration.md) for frontmatter, layer restrictions,
103
103
 
104
104
  Collapsed results show each child's name, task, status, and most recent activity anywhere in its subtree. `Ctrl+O` expands the newest call from memory without reading historical transcripts.
105
105
 
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. Missing historical metadata appears as `unknown`.
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
+
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 all launches and resumes without exposing an `intelligence` argument. Two or more expose an optional choice; zero or disabled presets keep the existing defaults and show no intelligence label.
107
109
 
108
110
  | Key | Action |
109
111
  | --- | --- |
package/config.ts CHANGED
@@ -3,13 +3,14 @@ import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
5
 
6
- import { parseSmartDecisionConfig, type SmartDecisionConfig } from "./runner/smart-decision.js";
6
+ import { intelligenceEnabled, parseIntelligencePresets, type IntelligencePreset } from "./intelligence.js";
7
7
 
8
8
  export const PI_SUBAGENTS_CONFIG_FILE = "pi-subagents.json";
9
+ export const PI_SUBAGENT_CONFIG_FILE = "pi-subagent.json";
9
10
 
10
11
  export interface PiSubagentsConfig {
11
12
  toolPrompts: Record<string, string>;
12
- smartDecision?: SmartDecisionConfig;
13
+ intelligencePresets: IntelligencePreset[];
13
14
  }
14
15
 
15
16
  function readConfig(filePath: string): Record<string, unknown> {
@@ -24,81 +25,15 @@ function readConfig(filePath: string): Record<string, unknown> {
24
25
 
25
26
  return parsed as Record<string, unknown>;
26
27
  } catch {
27
- // JSON parser errors can contain source text, including the API key.
28
+ // Do not expose configuration contents in parser errors.
28
29
  console.warn(`[pi-subagent] Failed to read config "${filePath}".`);
29
30
  return {};
30
31
  }
31
32
  }
32
33
 
33
- function isRecord(value: unknown): value is Record<string, unknown> {
34
- return typeof value === "object" && value !== null && !Array.isArray(value);
35
- }
36
-
37
- let tempFileCounter = 0;
38
-
39
- /** Add the explicit default without allowing a failed write to change runtime behavior. */
40
- function persistSmartDecisionFallback(config: Record<string, unknown>, filePath: string): void {
41
- const smartDecision = config["smart-decision"];
42
- if (!isRecord(smartDecision) || Object.hasOwn(smartDecision, "fallback")) return;
43
-
44
- smartDecision.fallback = true;
45
- let tempPath: string | undefined;
46
- let ownsTemp = false;
47
- try {
48
- // Replace the target rather than a symlink that points to it.
49
- const targetPath = fs.realpathSync(filePath);
50
- // Re-read immediately before writing so unrelated edits made since the initial load survive.
51
- // Retrying also makes concurrent nested-worker migrations converge without clobbering one another.
52
- for (let attempt = 0; attempt < 3; attempt++) {
53
- const source = fs.readFileSync(targetPath, "utf8");
54
- const latest = JSON.parse(source) as unknown;
55
- if (!isRecord(latest)) return;
56
- const latestSmartDecision = latest["smart-decision"];
57
- if (!isRecord(latestSmartDecision)) return;
58
- if (Object.hasOwn(latestSmartDecision, "fallback")) {
59
- smartDecision.fallback = latestSmartDecision.fallback;
60
- return;
61
- }
62
-
63
- latestSmartDecision.fallback = true;
64
- const mode = fs.statSync(targetPath).mode & 0o7777;
65
- const candidatePath = path.join(
66
- path.dirname(targetPath),
67
- `.${path.basename(targetPath)}.${process.pid}.${tempFileCounter++}.tmp`,
68
- );
69
- const fd = fs.openSync(candidatePath, "wx", mode);
70
- tempPath = candidatePath;
71
- ownsTemp = true;
72
- try {
73
- fs.writeFileSync(fd, `${JSON.stringify(latest, null, 2)}\n`, "utf8");
74
- fs.fchmodSync(fd, mode);
75
- fs.fsyncSync(fd);
76
- } finally {
77
- fs.closeSync(fd);
78
- }
79
-
80
- if (fs.readFileSync(targetPath, "utf8") !== source) {
81
- fs.unlinkSync(tempPath);
82
- tempPath = undefined;
83
- ownsTemp = false;
84
- continue;
85
- }
86
- fs.renameSync(tempPath, targetPath);
87
- tempPath = undefined;
88
- ownsTemp = false;
89
- return;
90
- }
91
- throw new Error("config changed during fallback migration");
92
- } catch {
93
- if (ownsTemp && tempPath) {
94
- try {
95
- fs.unlinkSync(tempPath);
96
- } catch {
97
- // Best-effort cleanup. Do not expose filesystem errors or configuration contents.
98
- }
99
- }
100
- console.warn("[pi-subagent] Failed to save the default smart-decision fallback.");
101
- }
34
+ function configAtLocation(dir: string): string {
35
+ const singular = path.join(dir, PI_SUBAGENT_CONFIG_FILE);
36
+ return fs.existsSync(singular) ? singular : path.join(dir, PI_SUBAGENTS_CONFIG_FILE);
102
37
  }
103
38
 
104
39
  function readToolPrompts(config: Record<string, unknown>, filePath: string): Record<string, string> {
@@ -124,11 +59,11 @@ function readToolPrompts(config: Record<string, unknown>, filePath: string): Rec
124
59
  return result;
125
60
  }
126
61
 
127
- /** Find the nearest project-local .pi/pi-subagents.json while walking up from cwd. */
62
+ /** Find the nearest project-local config while walking up from cwd. */
128
63
  export function findProjectConfig(cwd: string): string | null {
129
64
  let dir = path.resolve(cwd);
130
65
  while (true) {
131
- const candidate = path.join(dir, ".pi", PI_SUBAGENTS_CONFIG_FILE);
66
+ const candidate = configAtLocation(path.join(dir, ".pi"));
132
67
  if (fs.existsSync(candidate)) return candidate;
133
68
  const parent = path.dirname(dir);
134
69
  if (parent === dir) return null;
@@ -141,26 +76,28 @@ export function findProjectConfig(cwd: string): string | null {
141
76
  * ~/.pi/pi-subagents.json
142
77
  * $PI_CODING_AGENT_DIR/pi-subagents.json (normally ~/.pi/agent/pi-subagents.json)
143
78
  * nearest project .pi/pi-subagents.json (trusted projects only)
79
+ * pi-subagent.json replaces pi-subagents.json at each location when present.
144
80
  */
145
81
  export function loadPiSubagentsConfig(cwd?: string, includeProject = false): PiSubagentsConfig {
146
- const paths = [
147
- path.join(os.homedir(), ".pi", PI_SUBAGENTS_CONFIG_FILE),
148
- path.join(getAgentDir(), PI_SUBAGENTS_CONFIG_FILE),
149
- ];
82
+ const paths = [configAtLocation(path.join(os.homedir(), ".pi")), configAtLocation(getAgentDir())];
150
83
  if (cwd && includeProject) {
151
84
  const projectConfig = findProjectConfig(cwd);
152
85
  if (projectConfig) paths.push(projectConfig);
153
86
  }
154
87
 
155
88
  const toolPrompts: Record<string, string> = {};
156
- let smartDecision: SmartDecisionConfig | undefined;
89
+ let intelligencePresets: IntelligencePreset[] = [];
157
90
  for (const filePath of new Set(paths)) {
158
91
  const config = readConfig(filePath);
159
- persistSmartDecisionFallback(config, filePath);
160
92
  Object.assign(toolPrompts, readToolPrompts(config, filePath));
161
- if (Object.hasOwn(config, "smart-decision")) {
162
- smartDecision = parseSmartDecisionConfig(config["smart-decision"]);
93
+ if (Object.hasOwn(config, "subagents-models")) {
94
+ intelligencePresets = [];
95
+ try {
96
+ intelligencePresets = parseIntelligencePresets(config["subagents-models"]);
97
+ } catch {
98
+ console.warn(`[pi-subagent] Ignoring invalid subagents-models in "${filePath}".`);
99
+ }
163
100
  }
164
101
  }
165
- return { toolPrompts, ...(smartDecision ? { smartDecision } : {}) };
102
+ return { toolPrompts, intelligencePresets: intelligenceEnabled(intelligencePresets) ? intelligencePresets : [] };
166
103
  }
@@ -37,11 +37,13 @@ At maximum depth 1, combining `first-layer: only` with `last-layer: disabled` bl
37
37
 
38
38
  ## Tool descriptions
39
39
 
40
- Use `pi-subagents.json` to replace either tool's full model-facing description. Files load in this order, with later values overriding earlier values per tool:
40
+ Use `pi-subagent.json` to configure model presets or replace either tool's full model-facing description. Files load in this order, with later values overriding earlier values per tool:
41
41
 
42
- 1. `~/.pi/pi-subagents.json`
43
- 2. `$PI_CODING_AGENT_DIR/pi-subagents.json`, normally `~/.pi/agent/pi-subagents.json`
44
- 3. The nearest trusted `.pi/pi-subagents.json`, walking upward from the working directory
42
+ 1. `~/.pi/pi-subagent.json`
43
+ 2. `$PI_CODING_AGENT_DIR/pi-subagent.json`, normally `~/.pi/agent/pi-subagent.json`
44
+ 3. The nearest trusted `.pi/pi-subagent.json`, walking upward from the working directory
45
+
46
+ The legacy filename `pi-subagents.json` is also supported. At each location, the singular filename takes precedence over the plural filename.
45
47
 
46
48
  ```json
47
49
  {
@@ -54,43 +56,57 @@ Use `pi-subagents.json` to replace either tool's full model-facing description.
54
56
 
55
57
  Missing descriptions retain their defaults. Overrides change written guidance, not schemas, budget checks, or runtime limits. Keep instructions to estimate worker counts and avoid unnecessary delegation.
56
58
 
57
- ## Smart-decision assistance
59
+ ## Caller-selected intelligence
58
60
 
59
- Optionally let TypeSafe's Jev choose a model for each subagent task. Add this section to `.pi/pi-subagents.json` in a trusted project, or to either user configuration file listed above:
61
+ Define named model presets in `pi-subagent.json`. With two or more enabled presets, the calling model chooses through each task's optional `intelligence` argument. With exactly one enabled preset, both tools hide the argument and automatically use that preset for every launch and resume. With no presets, the argument is absent and existing model/thinking defaults apply. No router or separate model-selection request is used.
60
62
 
61
63
  ```json
62
64
  {
63
- "smart-decision": {
64
- "enabled": true,
65
- "fallback": true,
66
- "timeout_seconds": 1200,
67
- "model": "jev",
68
- "provider_url": "https://api.typesafe.ai",
69
- "api_key": "YOUR_TYPESAFE_API_KEY",
70
- "use_models": [
71
- {
72
- "openai-codex/gpt-6-astra/high": "Frontier model for the most complicated tasks. Expensive and slow; use for difficult planning, architecture, and non-trivial problems.",
73
- "openai/gpt-4.1-mini/off": "Fast, inexpensive model for small, well-defined edits and straightforward tasks."
65
+ "subagents-models": [
66
+ {
67
+ "junior": {
68
+ "model": "gpt-4.1-mini",
69
+ "provider": "openai",
70
+ "reasoning-level": "off",
71
+ "description": "Small, well-defined edits and lookups."
74
72
  }
75
- ]
76
- }
73
+ },
74
+ {
75
+ "senior": {
76
+ "model": "gpt-6-astra",
77
+ "provider": "openai-codex",
78
+ "reasoning-level": "high",
79
+ "description": "Difficult architecture and cross-system debugging."
80
+ }
81
+ }
82
+ ]
83
+ }
84
+ ```
85
+
86
+ Use models available in your Pi installation. Names are arbitrary, unique, non-empty strings without leading or trailing whitespace. Each array entry defines one preset. `model`, `provider`, and `reasoning-level` are required. Accepted reasoning levels are `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`; support depends on the selected model and Pi version. `description` is optional. The tool schema shows each name with its description, or just its name when omitted.
87
+
88
+ ```json
89
+ {
90
+ "tasks": [
91
+ {
92
+ "agent": "code-writer",
93
+ "task": "Fix the button label.",
94
+ "max_subagents_allowed": 0,
95
+ "intelligence": "junior"
96
+ }
97
+ ]
77
98
  }
78
99
  ```
79
100
 
80
- Replace the example choices with models available in your Pi installation. Each key has the form `provider/model/thinking-level`; model IDs may contain slashes. Thinking levels are `off`, `minimal`, `low`, `medium`, `high`, and `xhigh`. Each value is a non-empty description of when to use that choice. You can put choices in one object or separate objects in `use_models`, up to 255 entries. Duplicate keys keep the first description.
101
+ With multiple presets, `resume_subagents` also accepts `intelligence` on each resume item. A selected or automatic preset overrides the parent model and agent model/thinking settings for that run. The parent's explicit `--provider` and `--api-key` are not forwarded when a preset is selected. Worker providers use their configured Pi credentials. With multiple presets, omitting `intelligence` preserves existing defaults; it does not remember a previous preset choice.
81
102
 
82
- - `enabled` must be `true`. Missing settings, disabled settings, or an empty model list leave existing behavior unchanged and make no Jev requests.
83
- - `model` selects the decision model, not the worker model. `jev` maps to TypeSafe's `jev-latest`; explicit TypeSafe model IDs also work.
84
- - `timeout_seconds` defaults to `1200` seconds and bounds the whole Jev request, including reading the response body. Set a number from `0.001` to `2147483.647` seconds. Invalid values follow the `fallback` policy.
85
- - `provider_url` is the provider base URL, defaulting to `https://api.typesafe.ai`. For a local compatible server, use `http://localhost:8765`. The extension appends `/v1/systemone`; trailing slashes are ignored. Use an HTTP or HTTPS URL without credentials, query parameters, or a fragment.
86
- - `api_key` is your TypeSafe API key. Worker providers still need their own Pi credentials.
87
- - `fallback` defaults to `true`. When a loaded `smart-decision` object omits it, the extension adds `"fallback": true` and saves that configuration file at runtime. Existing values, including `false`, are left untouched. Untrusted project files are never changed. If saving fails, a warning is emitted and the runtime default still applies. If selection fails, a short warning is written and the worker uses the original launch settings. Set it to `false` to return a tool error without launching the affected worker. This covers network errors, the configured request timeout, API errors, invalid answers, and invalid enabled configuration. Cancellation cancels the task instead of falling back.
103
+ 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. `/subagent-expand` 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.
88
104
 
89
- Each fresh launch and actual resume sends the agent definition's system prompt, the assigned task, and the candidate descriptions to `<provider_url>/v1/systemone`. Jev must select a configured candidate. When a task refers to a separate task-description or handoff file whose contents were not supplied, Jev is instructed to assume higher complexity and prefer a more capable model or higher reasoning level. It does not read that file. Mentioning a source filename alone does not trigger this guidance. Its provider, model, and thinking level override the parent model and agent frontmatter for that run. The parent's explicit `--provider` and `--api-key` are not forwarded when a Jev choice is applied. Startup retries reuse the choice. Finished results reused without launching a process make no request.
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: both tools hide the argument and no automatic preset applies. Unknown choices or attempts to pass a hidden argument fail before launching workers.
90
106
 
91
- Configuration uses the same trust checks and file order as tool descriptions. A later `smart-decision` section replaces the entire earlier section, rather than merging credentials or choices. Reload Pi after editing settings. Nested workers load configuration through the same rules.
107
+ 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.
92
108
 
93
- Enabling this sends prompt contents and the configured API key to the selected provider and may incur separate API charges. Use only a provider you trust. Do not commit API keys to source control. The key is not included in worker arguments or saved tool results. Jev usage is not included in worker token totals.
109
+ The old `smart-decision` block is ignored. Remove it and its router credentials when migrating. Configuration files are no longer modified at runtime.
94
110
 
95
111
  ## Limits and discovery
96
112
 
@@ -132,7 +148,7 @@ Normally Pi restarts through `process.execPath process.argv[1]`. No package-mana
132
148
 
133
149
  ## Forwarded CLI arguments
134
150
 
135
- Children inherit the parent's CLI settings except arguments managed by the extension. Without smart-decision selection, every new launch explicitly selects the parent's active model, so `/model` changes affect subsequent launches.
151
+ Children inherit the parent's CLI settings except arguments managed by the extension. Without an intelligence preset, every new launch explicitly selects the parent's active model, so `/model` changes affect subsequent launches.
136
152
 
137
153
  Forwarded unchanged:
138
154
 
@@ -28,6 +28,7 @@ export async function executeSingle(
28
28
  topLevelBaseId: number,
29
29
  subagentName?: string,
30
30
  budget?: SubagentBudget,
31
+ intelligence?: string,
31
32
  ) {
32
33
  if (previousResult && isFinishedResult(previousResult)) {
33
34
  return {
@@ -65,7 +66,8 @@ export async function executeSingle(
65
66
  resumeSession: resumeExistingSession,
66
67
  initialResult: previousResult,
67
68
  fallbackModel,
68
- smartDecision: state.smartDecision,
69
+ intelligence,
70
+ intelligencePresets: state.intelligencePresets,
69
71
  onHandle: (handle) => {
70
72
  activeId = topLevelBaseId;
71
73
  state.activeSubagents.set(activeId, { agent: agentName, task, handle, name: subagentName });
@@ -106,7 +108,7 @@ export async function executeSingle(
106
108
 
107
109
  export async function executeParallel(
108
110
  state: ExtensionState,
109
- tasks: Array<{ agent: string; task: string }>,
111
+ tasks: Array<{ agent: string; task: string; intelligence?: string }>,
110
112
  agents: AgentConfig[],
111
113
  defaultCwd: string,
112
114
  signal: AbortSignal | undefined,
@@ -153,7 +155,7 @@ export async function executeParallel(
153
155
  {
154
156
  ...extras,
155
157
  namesFile: state.currentNamesFile || undefined,
156
- smartDecision: state.smartDecision,
158
+ intelligencePresets: state.intelligencePresets,
157
159
  projectTrusted: state.latestSessionCtx?.cwd === defaultCwd && state.latestSessionCtx.isProjectTrusted(),
158
160
  },
159
161
  );
@@ -1,4 +1,5 @@
1
- import { validatePreparedArguments } from "./schemas.js";
1
+ import { createIntelligenceSchemas, validatePreparedArguments } from "./schemas.js";
2
+ import { selectIntelligence } from "../intelligence.js";
2
3
  import * as path from "node:path";
3
4
  import { discoverAgents } from "../agents.js";
4
5
  import {
@@ -10,7 +11,7 @@ import {
10
11
  } from "../budget.js";
11
12
  import { allocateSubagentNames } from "../names.js";
12
13
  import { recordToolCallStart, renderCall, renderResult } from "../render.js";
13
- import { getTaskBranchSize, sameTasks } from "../resume.js";
14
+ import { getTaskBranchSize } from "../resume.js";
14
15
  import { buildSubagentDetails, DEFAULT_DELEGATION_MODE, SUBAGENT_TOOL_NAME } from "../types.js";
15
16
  import { updateLatestBroadcastTargets } from "./broadcast.js";
16
17
  import { makeDetailsFactory } from "./details.js";
@@ -29,17 +30,25 @@ import {
29
30
  import { trackProgress } from "./progress.js";
30
31
  import { getSubagentsToolDescription } from "./prompts.js";
31
32
  import { ensureBudget, getParentModelForSubagent, getSessionDirForTask } from "./runtime.js";
32
- import { prepareRecoveryArguments, SubagentParams } from "./schemas.js";
33
+ import { findRecoveryPlanIndex, prepareIntelligenceArguments, prepareRecoveryArguments } from "./schemas.js";
33
34
  import type { ExtensionState } from "./state.js";
34
35
 
35
36
  export function registerSubagentsTool(state: ExtensionState) {
37
+ const parameters = createIntelligenceSchemas(state.intelligencePresets).subagents;
36
38
  state.pi.registerTool({
37
39
  name: SUBAGENT_TOOL_NAME,
38
40
  label: "Subagents",
39
41
  description: state.configuredToolPrompts[SUBAGENT_TOOL_NAME] ?? getSubagentsToolDescription(),
40
- parameters: SubagentParams,
42
+ parameters,
41
43
  prepareArguments(args) {
42
- return validatePreparedArguments(SubagentParams, prepareRecoveryArguments(args, state.pendingResumePlans));
44
+ return validatePreparedArguments(
45
+ parameters,
46
+ prepareRecoveryArguments(
47
+ prepareIntelligenceArguments(args, "tasks"),
48
+ state.pendingResumePlans,
49
+ state.intelligencePresets,
50
+ ),
51
+ );
43
52
  },
44
53
 
45
54
  async execute(toolCallId, params, signal, onUpdate, ctx) {
@@ -67,6 +76,7 @@ export function registerSubagentsTool(state: ExtensionState) {
67
76
  }
68
77
 
69
78
  for (const [index, task] of tasks.entries()) {
79
+ selectIntelligence(state.intelligencePresets, task.intelligence);
70
80
  if (!isBranchBudgetAmount(task.max_subagents_allowed)) {
71
81
  throw new SubagentBudgetError(
72
82
  `tasks[${index}].max_subagents_allowed is required. Use a non-negative safe integer below Number.MAX_SAFE_INTEGER, excluding the assigned agent. Use 0 for a direct worker.`,
@@ -144,7 +154,7 @@ export function registerSubagentsTool(state: ExtensionState) {
144
154
  }
145
155
  }
146
156
 
147
- const resumePlanIndex = state.pendingResumePlans.findIndex((plan) => sameTasks(plan.tasks, tasks));
157
+ const resumePlanIndex = findRecoveryPlanIndex(tasks, state.pendingResumePlans, state.intelligencePresets);
148
158
  const resumePlan = resumePlanIndex >= 0 ? state.pendingResumePlans[resumePlanIndex] : null;
149
159
  if (launchGeneration !== state.lifecycleGeneration || signal?.aborted)
150
160
  throw new SubagentBudgetError("Launch canceled or session changed. No slots were reserved.");
@@ -203,11 +213,15 @@ export function registerSubagentsTool(state: ExtensionState) {
203
213
  state.currentOwnerId,
204
214
  pendingAllocation.map(({ task, index }) => {
205
215
  const agentConfig = agents.find((agent) => agent.name === task.agent);
216
+ const preset = selectIntelligence(state.intelligencePresets, task.intelligence);
206
217
  return {
207
218
  agent: task.agent,
208
219
  task: task.task,
209
220
  budget: budgets[index],
210
- model: formatModelFlag(getParentModelForSubagent(state, ctx)) ?? agentConfig?.model,
221
+ model: preset
222
+ ? `${preset.provider}/${preset.model}`
223
+ : (formatModelFlag(getParentModelForSubagent(state, ctx)) ?? agentConfig?.model),
224
+ intelligence: preset?.name,
211
225
  tools: agentConfig?.tools,
212
226
  sessionDir:
213
227
  resumePlan?.details?.results[index]?.sessionDir ??
@@ -250,6 +264,7 @@ export function registerSubagentsTool(state: ExtensionState) {
250
264
  topLevelBaseId,
251
265
  names[0],
252
266
  budgets[0],
267
+ task.intelligence,
253
268
  );
254
269
  }
255
270
 
@@ -6,6 +6,7 @@ import type { ResumeModel, StreamOptions, ProviderContext } from "./contracts.js
6
6
  import { RESUME_MODEL_DEF, isSyntheticResumePrompt } from "./models.js";
7
7
  import { restoreVisibleModelForResume } from "./runtime.js";
8
8
  import type { ExtensionState } from "./state.js";
9
+ import { normalizeRecoveryIntelligence } from "./schemas.js";
9
10
 
10
11
  export function mergeProviderHeaders(
11
12
  base: Record<string, string | null> | undefined,
@@ -129,7 +130,11 @@ export function registerResumeProvider(state: ExtensionState): void {
129
130
  const toolCalls = plans.map((plan, index) =>
130
131
  fauxToolCall(
131
132
  SUBAGENT_TOOL_NAME,
132
- { tasks: plan.tasks.map((task) => ({ ...task })) },
133
+ {
134
+ tasks: normalizeRecoveryIntelligence(plan.tasks, state.intelligencePresets).map((task) => ({
135
+ ...task,
136
+ })),
137
+ },
133
138
  { id: `resume_subagent_${Date.now()}_${index}` },
134
139
  ),
135
140
  );
@@ -1,4 +1,5 @@
1
- import { validatePreparedArguments } from "./schemas.js";
1
+ import { createIntelligenceSchemas, validatePreparedArguments } from "./schemas.js";
2
+ import { selectIntelligence } from "../intelligence.js";
2
3
  import * as fs from "node:fs";
3
4
  import * as path from "node:path";
4
5
  import { discoverAgents, isAgentEnabledAtLayer, type AgentConfig } from "../agents.js";
@@ -26,11 +27,12 @@ import { formatModelFlag } from "./models.js";
26
27
  import { resumableSubagentsDisabled } from "./policy.js";
27
28
  import { trackProgress } from "./progress.js";
28
29
  import { ensureBudget, getParentModelForSubagent } from "./runtime.js";
29
- import { normalizeResumes, ResumeSubagentsParams } from "./schemas.js";
30
+ import { normalizeResumes, prepareIntelligenceArguments } from "./schemas.js";
30
31
  import type { ExtensionState } from "./state.js";
31
32
 
32
33
  export function registerResumeSubagentsTool(state: ExtensionState) {
33
34
  if (resumableSubagentsDisabled()) return;
35
+ const parameters = createIntelligenceSchemas(state.intelligencePresets).resumes;
34
36
  state.pi.registerTool({
35
37
  name: RESUME_SUBAGENTS_TOOL_NAME,
36
38
  label: "Resume subagents",
@@ -41,9 +43,12 @@ export function registerResumeSubagentsTool(state: ExtensionState) {
41
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.",
42
44
  "Pass { resumes: [{ subagent, task }] }. Resumes in one call run in parallel; wait between dependent tasks.",
43
45
  ].join("\n"),
44
- parameters: ResumeSubagentsParams,
46
+ parameters,
45
47
  prepareArguments(args) {
46
- return validatePreparedArguments(ResumeSubagentsParams, prepareResumeArguments(args));
48
+ return validatePreparedArguments(
49
+ parameters,
50
+ prepareIntelligenceArguments(prepareResumeArguments(args), "resumes"),
51
+ );
47
52
  },
48
53
 
49
54
  async execute(toolCallId, params, signal, onUpdate, ctx) {
@@ -68,6 +73,8 @@ export function registerResumeSubagentsTool(state: ExtensionState) {
68
73
  );
69
74
  }
70
75
 
76
+ for (const resume of resumes) selectIntelligence(state.intelligencePresets, resume.intelligence);
77
+
71
78
  const duplicates = resumes
72
79
  .map((resume) => resume.name)
73
80
  .filter((name, index, all) => all.indexOf(name) !== index);
@@ -117,6 +124,7 @@ export function registerResumeSubagentsTool(state: ExtensionState) {
117
124
  tools?: string[];
118
125
  budget: SubagentBudget;
119
126
  max_subagents_allowed?: number;
127
+ intelligence?: string;
120
128
  }> = [];
121
129
  const hasSessionFiles = (dir: string): boolean => {
122
130
  try {
@@ -166,6 +174,7 @@ export function registerResumeSubagentsTool(state: ExtensionState) {
166
174
  budget:
167
175
  resolution.record.budget ?? createBudget(path.join(resolution.record.sessionDir, "legacy-budget"), 0),
168
176
  max_subagents_allowed: resume.max_subagents_allowed,
177
+ intelligence: resume.intelligence,
169
178
  });
170
179
  }
171
180
  if (errors.length > 0) {
@@ -225,7 +234,11 @@ export function registerResumeSubagentsTool(state: ExtensionState) {
225
234
  }
226
235
  }
227
236
 
228
- const tasks = targets.map((target) => ({ agent: target.agent, task: target.task }));
237
+ const tasks = targets.map((target) => ({
238
+ agent: target.agent,
239
+ task: target.task,
240
+ intelligence: target.intelligence,
241
+ }));
229
242
  const topLevelBaseId = state.nextActiveSubagentId;
230
243
  state.nextActiveSubagentId += tasks.length;
231
244
  const trackedOnUpdate = trackProgress(state, toolCallId, topLevelBaseId, ctx, onUpdate);
@@ -1,9 +1,10 @@
1
1
  import { Assert } from "@sinclair/typebox/value";
2
- import type { Static, TSchema } from "@sinclair/typebox";
2
+ import type { Static, TSchema, TLiteral } from "@sinclair/typebox";
3
3
  import { Type } from "@sinclair/typebox";
4
4
  import { isBranchBudgetAmount, SubagentBudgetError } from "../budget.js";
5
5
  import { getTaskBranchSize, sameTasks, type ResumableSubagentCall, type ResumableTask } from "../resume.js";
6
6
  import { isRecord } from "./contracts.js";
7
+ import { intelligenceEnabled, type IntelligencePreset } from "../intelligence.js";
7
8
 
8
9
  export const TaskItem = Type.Object(
9
10
  {
@@ -64,14 +65,61 @@ export const ResumeSubagentsParams = Type.Object(
64
65
  { additionalProperties: false },
65
66
  );
66
67
 
67
- export function normalizeResumes(raw: unknown): Array<{ name: string; task: string; max_subagents_allowed?: number }> {
68
+ export function createIntelligenceSchemas(presets: IntelligencePreset[] = []) {
69
+ // Literal alternatives enforce validation; enum and descriptions advertise the caller's choices.
70
+ // The tuple is non-empty whenever these dynamic schemas are exposed.
71
+ const intelligence = {
72
+ intelligence: Type.Optional(
73
+ Type.Union(
74
+ presets.map((preset) => Type.Literal(preset.name, { description: preset.description })) as [
75
+ TLiteral<string>,
76
+ ...TLiteral<string>[],
77
+ ],
78
+ {
79
+ enum: presets.map((preset) => preset.name),
80
+ description: [
81
+ "Optional named model/provider/reasoning preset. Omit to use existing defaults.",
82
+ ...presets.map((preset) => `${preset.name}${preset.description ? `: ${preset.description}` : ""}`),
83
+ ].join("\n"),
84
+ },
85
+ ),
86
+ ),
87
+ };
88
+ const task = Type.Object({ ...TaskItem.properties, ...intelligence }, { additionalProperties: false });
89
+ const resume = Type.Object({ ...ResumeItem.properties, ...intelligence }, { additionalProperties: false });
90
+ const subagents = Type.Object(
91
+ { tasks: Type.Array(task, { minItems: 1, description: SubagentParams.properties.tasks.description }) },
92
+ { additionalProperties: false },
93
+ );
94
+ const resumes = Type.Object(
95
+ {
96
+ resumes: Type.Union([Type.Array(resume, { minItems: 1 }), resume], {
97
+ description: ResumeSubagentsParams.properties.resumes.description,
98
+ }),
99
+ },
100
+ { additionalProperties: false },
101
+ );
102
+ return presets.length >= 2 && intelligenceEnabled(presets)
103
+ ? { subagents, resumes }
104
+ : {
105
+ subagents: SubagentParams as typeof subagents,
106
+ resumes: ResumeSubagentsParams as typeof resumes,
107
+ };
108
+ }
109
+
110
+ export function normalizeResumes(
111
+ raw: unknown,
112
+ ): Array<{ name: string; task: string; intelligence?: string; max_subagents_allowed?: number }> {
68
113
  const items = Array.isArray(raw) ? raw : raw && typeof raw === "object" ? [raw] : [];
69
- const normalized: Array<{ name: string; task: string; max_subagents_allowed?: number }> = [];
114
+ const normalized: Array<{ name: string; task: string; intelligence?: string; max_subagents_allowed?: number }> = [];
70
115
  for (const item of items) {
71
116
  if (!isRecord(item)) continue;
72
117
  const name =
73
118
  typeof item.subagent === "string" ? item.subagent : typeof item.name === "string" ? item.name : undefined;
74
119
  const task = typeof item.task === "string" ? item.task : typeof item.prompt === "string" ? item.prompt : undefined;
120
+ if (item.intelligence !== undefined && typeof item.intelligence !== "string") {
121
+ throw new Error("Resume intelligence must be a configured preset name.");
122
+ }
75
123
  if (item.max_subagents_allowed !== undefined && !isBranchBudgetAmount(item.max_subagents_allowed)) {
76
124
  throw new SubagentBudgetError(
77
125
  "Resume max_subagents_allowed must be a non-negative safe integer below Number.MAX_SAFE_INTEGER. Omit it to keep the current allowance.",
@@ -81,14 +129,56 @@ export function normalizeResumes(raw: unknown): Array<{ name: string; task: stri
81
129
  normalized.push({
82
130
  name,
83
131
  task,
132
+ ...(item.intelligence !== undefined ? { intelligence: item.intelligence } : {}),
84
133
  ...(item.max_subagents_allowed !== undefined ? { max_subagents_allowed: item.max_subagents_allowed } : {}),
85
134
  });
86
135
  }
87
136
  return normalized;
88
137
  }
89
138
 
90
- /** Legacy task arguments are accepted only for a matching crash-recovery plan. */
91
- export function prepareRecoveryArguments(args: unknown, plans: ResumableSubagentCall[]): unknown {
139
+ /** Strict provider schemas can send null for omitted optional intelligence. Leave all other fields alone. */
140
+ export function prepareIntelligenceArguments(args: unknown, key: "tasks" | "resumes"): unknown {
141
+ if (!isRecord(args) || !Object.hasOwn(args, key)) return args;
142
+ const omitNull = (item: unknown): unknown => {
143
+ if (!isRecord(item) || item.intelligence !== null) return item;
144
+ const { intelligence: _intelligence, ...rest } = item;
145
+ return rest;
146
+ };
147
+ const items = args[key];
148
+ return { ...args, [key]: Array.isArray(items) ? items.map(omitNull) : omitNull(items) };
149
+ }
150
+
151
+ /** Replay hidden choices through current defaults: a sole preset is automatic, zero/disabled uses no preset. */
152
+ export function normalizeRecoveryIntelligence(
153
+ tasks: ResumableTask[],
154
+ presets: IntelligencePreset[] = [],
155
+ ): ResumableTask[] {
156
+ const exposeChoice = presets.length >= 2 && intelligenceEnabled(presets);
157
+ return tasks.map((task) => {
158
+ if (exposeChoice) return { ...task };
159
+ const { intelligence: _intelligence, ...rest } = task;
160
+ return rest;
161
+ });
162
+ }
163
+
164
+ /** Keep the saved plan intact so recovery reuses its call id, budgets, names, and sessions. */
165
+ export function findRecoveryPlanIndex(
166
+ tasks: ResumableTask[],
167
+ plans: ResumableSubagentCall[],
168
+ presets: IntelligencePreset[] = [],
169
+ ): number {
170
+ const exact = plans.findIndex((plan) => sameTasks(plan.tasks, tasks));
171
+ return exact >= 0
172
+ ? exact
173
+ : plans.findIndex((plan) => sameTasks(normalizeRecoveryIntelligence(plan.tasks, presets), tasks));
174
+ }
175
+
176
+ /** Legacy task arguments and hidden intelligence are accepted only for a matching crash-recovery plan. */
177
+ export function prepareRecoveryArguments(
178
+ args: unknown,
179
+ plans: ResumableSubagentCall[],
180
+ presets: IntelligencePreset[] = [],
181
+ ): unknown {
92
182
  if (!isRecord(args) || !Array.isArray(args.tasks)) return args;
93
183
  const tasks: unknown[] = args.tasks;
94
184
  const isTask = (task: unknown): task is ResumableTask =>
@@ -98,10 +188,10 @@ export function prepareRecoveryArguments(args: unknown, plans: ResumableSubagent
98
188
  ["max_agents_allowed", "max_agents_in_branch", "max_subagents_allowed"].every(
99
189
  (key) => task[key] === undefined || typeof task[key] === "number",
100
190
  );
101
- if (!tasks.every(isTask) || !plans.some((plan) => sameTasks(plan.tasks, tasks))) return args;
191
+ if (!tasks.every(isTask) || findRecoveryPlanIndex(tasks, plans, presets) < 0) return args;
102
192
  return {
103
193
  ...args,
104
- tasks: tasks.map((task) => {
194
+ tasks: normalizeRecoveryIntelligence(tasks, presets).map((task) => {
105
195
  const { max_agents_allowed: _inclusive, max_agents_in_branch: _previous, ...rest } = task;
106
196
  return { ...rest, max_subagents_allowed: (getTaskBranchSize(task) ?? 1) - 1 };
107
197
  }),