@oh-my-pi/pi-coding-agent 12.11.2 → 12.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  import type { AssistantMessage } from "@oh-my-pi/pi-ai";
2
2
  import { Container, Markdown, Spacer, TERMINAL, Text } from "@oh-my-pi/pi-tui";
3
+ import { logger } from "@oh-my-pi/pi-utils";
3
4
  import { hasPendingMermaid, prerenderMermaid } from "../../modes/theme/mermaid-cache";
4
5
  import { getMarkdownTheme, theme } from "../../modes/theme/theme";
5
6
 
@@ -47,15 +48,22 @@ export class AssistantMessageComponent extends Container {
47
48
  this.#prerenderInFlight = true;
48
49
 
49
50
  // Fire off background prerender
50
- (async () => {
51
- for (const content of message.content) {
52
- if (content.type === "text" && content.text.trim() && hasPendingMermaid(content.text)) {
53
- await prerenderMermaid(content.text);
51
+ void (async () => {
52
+ try {
53
+ for (const content of message.content) {
54
+ if (content.type === "text" && content.text.trim() && hasPendingMermaid(content.text)) {
55
+ await prerenderMermaid(content.text);
56
+ }
54
57
  }
58
+ } catch (error) {
59
+ logger.warn("Background mermaid prerender failed", {
60
+ error: error instanceof Error ? error.message : String(error),
61
+ });
62
+ } finally {
63
+ this.#prerenderInFlight = false;
64
+ // Invalidate to re-render with cached images
65
+ this.invalidate();
55
66
  }
56
- this.#prerenderInFlight = false;
57
- // Invalidate to re-render with cached images
58
- this.invalidate();
59
67
  })();
60
68
  }
61
69
 
@@ -161,8 +161,11 @@ export class ModelSelectorComponent extends Container {
161
161
  this.#loadModels().then(() => {
162
162
  this.#buildProviderTabs();
163
163
  this.#updateTabBar();
164
- if (initialSearchInput) {
165
- this.#filterModels(initialSearchInput);
164
+ // Always apply the current search query — the user may have typed
165
+ // while models were loading asynchronously.
166
+ const currentQuery = this.#searchInput.getValue();
167
+ if (currentQuery) {
168
+ this.#filterModels(currentQuery);
166
169
  } else {
167
170
  this.#updateList();
168
171
  }
@@ -7,16 +7,6 @@ import { MODEL_ROLES } from "../../config/model-registry";
7
7
  import { settings } from "../../config/settings";
8
8
  import { DebugSelectorComponent } from "../../debug";
9
9
  import { disableProvider, enableProvider } from "../../discovery";
10
- import { AssistantMessageComponent } from "../../modes/components/assistant-message";
11
- import { ExtensionDashboard } from "../../modes/components/extensions";
12
- import { HistorySearchComponent } from "../../modes/components/history-search";
13
- import { ModelSelectorComponent } from "../../modes/components/model-selector";
14
- import { OAuthSelectorComponent } from "../../modes/components/oauth-selector";
15
- import { SessionSelectorComponent } from "../../modes/components/session-selector";
16
- import { SettingsSelectorComponent } from "../../modes/components/settings-selector";
17
- import { ToolExecutionComponent } from "../../modes/components/tool-execution";
18
- import { TreeSelectorComponent } from "../../modes/components/tree-selector";
19
- import { UserMessageSelectorComponent } from "../../modes/components/user-message-selector";
20
10
  import {
21
11
  getAvailableThemes,
22
12
  getSymbolTheme,
@@ -29,6 +19,17 @@ import {
29
19
  import type { InteractiveModeContext } from "../../modes/types";
30
20
  import { SessionManager } from "../../session/session-manager";
31
21
  import { setPreferredImageProvider, setPreferredSearchProvider } from "../../tools";
22
+ import { AgentDashboard } from "../components/agent-dashboard";
23
+ import { AssistantMessageComponent } from "../components/assistant-message";
24
+ import { ExtensionDashboard } from "../components/extensions";
25
+ import { HistorySearchComponent } from "../components/history-search";
26
+ import { ModelSelectorComponent } from "../components/model-selector";
27
+ import { OAuthSelectorComponent } from "../components/oauth-selector";
28
+ import { SessionSelectorComponent } from "../components/session-selector";
29
+ import { SettingsSelectorComponent } from "../components/settings-selector";
30
+ import { ToolExecutionComponent } from "../components/tool-execution";
31
+ import { TreeSelectorComponent } from "../components/tree-selector";
32
+ import { UserMessageSelectorComponent } from "../components/user-message-selector";
32
33
 
33
34
  export class SelectorController {
34
35
  constructor(private ctx: InteractiveModeContext) {}
@@ -158,6 +159,30 @@ export class SelectorController {
158
159
  });
159
160
  }
160
161
 
162
+ /**
163
+ * Show the Agent Control Center dashboard.
164
+ */
165
+ async showAgentsDashboard(): Promise<void> {
166
+ const activeModel = this.ctx.session.model;
167
+ const activeModelPattern = activeModel ? `${activeModel.provider}/${activeModel.id}` : undefined;
168
+ const defaultModelPattern = this.ctx.settings.getModelRole("default");
169
+ const dashboard = await AgentDashboard.create(getProjectDir(), this.ctx.settings, this.ctx.ui.terminal.rows, {
170
+ modelRegistry: this.ctx.session.modelRegistry,
171
+ activeModelPattern,
172
+ defaultModelPattern,
173
+ });
174
+ this.showSelector(done => {
175
+ dashboard.onClose = () => {
176
+ done();
177
+ this.ctx.ui.requestRender();
178
+ };
179
+ dashboard.onRequestRender = () => {
180
+ this.ctx.ui.requestRender();
181
+ };
182
+ return { component: dashboard, focus: dashboard };
183
+ });
184
+ }
185
+
161
186
  /**
162
187
  * Handle setting changes from the settings selector.
163
188
  * Most settings are saved directly via SettingsManager in the definitions.
@@ -60,6 +60,10 @@ import { UiHelpers } from "./utils/ui-helpers";
60
60
  const debugStartup = $env.PI_DEBUG_STARTUP ? (stage: string) => process.stderr.write(`[startup] ${stage}\n`) : () => {};
61
61
 
62
62
  const TODO_FILE_NAME = "todos.json";
63
+ const EDITOR_MAX_HEIGHT_MIN = 6;
64
+ const EDITOR_MAX_HEIGHT_MAX = 18;
65
+ const EDITOR_RESERVED_ROWS = 12;
66
+ const EDITOR_FALLBACK_ROWS = 24;
63
67
 
64
68
  /** Options for creating an InteractiveMode instance (for future API use) */
65
69
  export interface InteractiveModeOptions {
@@ -158,6 +162,7 @@ export class InteractiveMode implements InteractiveModeContext {
158
162
  #voiceHue = 0;
159
163
  #voicePreviousShowHardwareCursor: boolean | null = null;
160
164
  #voicePreviousUseTerminalCursor: boolean | null = null;
165
+ #resizeHandler?: () => void;
161
166
 
162
167
  constructor(
163
168
  session: AgentSession,
@@ -196,6 +201,11 @@ export class InteractiveMode implements InteractiveModeContext {
196
201
  this.editor.onAutocompleteUpdate = () => {
197
202
  this.ui.requestRender(true);
198
203
  };
204
+ this.#syncEditorMaxHeight();
205
+ this.#resizeHandler = () => {
206
+ this.#syncEditorMaxHeight();
207
+ };
208
+ process.stdout.on("resize", this.#resizeHandler);
199
209
  try {
200
210
  this.historyStorage = HistoryStorage.open();
201
211
  this.editor.setHistoryStorage(this.historyStorage);
@@ -332,6 +342,7 @@ export class InteractiveMode implements InteractiveModeContext {
332
342
 
333
343
  // Start the UI
334
344
  this.ui.start();
345
+ this.#syncEditorMaxHeight();
335
346
  this.isInitialized = true;
336
347
  this.ui.requestRender(true);
337
348
 
@@ -390,6 +401,17 @@ export class InteractiveMode implements InteractiveModeContext {
390
401
  return promise;
391
402
  }
392
403
 
404
+ #computeEditorMaxHeight(): number {
405
+ const rows = this.ui.terminal.rows;
406
+ const terminalRows = Number.isFinite(rows) && rows > 0 ? rows : EDITOR_FALLBACK_ROWS;
407
+ const maxHeight = terminalRows - EDITOR_RESERVED_ROWS;
408
+ return Math.max(EDITOR_MAX_HEIGHT_MIN, Math.min(EDITOR_MAX_HEIGHT_MAX, maxHeight));
409
+ }
410
+
411
+ #syncEditorMaxHeight(): void {
412
+ this.editor.setMaxHeight(this.#computeEditorMaxHeight());
413
+ }
414
+
393
415
  updateEditorBorderColor(): void {
394
416
  if (this.isBashMode) {
395
417
  this.editor.borderColor = theme.getBashModeBorderColor();
@@ -723,6 +745,10 @@ export class InteractiveMode implements InteractiveModeContext {
723
745
  }
724
746
  this.#extensionUiController.clearExtensionTerminalInputListeners();
725
747
  this.statusLine.dispose();
748
+ if (this.#resizeHandler) {
749
+ process.stdout.removeListener("resize", this.#resizeHandler);
750
+ this.#resizeHandler = undefined;
751
+ }
726
752
  if (this.unsubscribe) {
727
753
  this.unsubscribe();
728
754
  }
@@ -1055,6 +1081,10 @@ export class InteractiveMode implements InteractiveModeContext {
1055
1081
  void this.#selectorController.showExtensionsDashboard();
1056
1082
  }
1057
1083
 
1084
+ showAgentsDashboard(): void {
1085
+ void this.#selectorController.showAgentsDashboard();
1086
+ }
1087
+
1058
1088
  showModelSelector(options?: { temporaryOnly?: boolean }): void {
1059
1089
  this.#selectorController.showModelSelector(options);
1060
1090
  }
@@ -4,9 +4,11 @@ import {
4
4
  type MermaidRenderOptions,
5
5
  renderMermaidToPng,
6
6
  } from "@oh-my-pi/pi-tui";
7
+ import { logger } from "@oh-my-pi/pi-utils";
7
8
 
8
9
  const cache = new Map<string, MermaidImage>();
9
10
  const pending = new Map<string, Promise<MermaidImage | null>>();
11
+ const failed = new Set<string>();
10
12
 
11
13
  const defaultOptions: MermaidRenderOptions = {
12
14
  theme: "dark",
@@ -45,7 +47,7 @@ export async function prerenderMermaid(
45
47
  const promises: Promise<boolean>[] = [];
46
48
 
47
49
  for (const { source, hash } of blocks) {
48
- if (cache.has(hash)) continue;
50
+ if (cache.has(hash) || failed.has(hash)) continue;
49
51
 
50
52
  let promise = pending.get(hash);
51
53
  if (!promise) {
@@ -54,14 +56,26 @@ export async function prerenderMermaid(
54
56
  }
55
57
 
56
58
  promises.push(
57
- promise.then(image => {
58
- pending.delete(hash);
59
- if (image) {
60
- cache.set(hash, image);
61
- return true;
62
- }
63
- return false;
64
- }),
59
+ promise
60
+ .then(image => {
61
+ pending.delete(hash);
62
+ if (image) {
63
+ cache.set(hash, image);
64
+ failed.delete(hash);
65
+ return true;
66
+ }
67
+ failed.add(hash);
68
+ return false;
69
+ })
70
+ .catch(error => {
71
+ pending.delete(hash);
72
+ failed.add(hash);
73
+ logger.warn("Mermaid render failed", {
74
+ hash,
75
+ error: error instanceof Error ? error.message : String(error),
76
+ });
77
+ return false;
78
+ }),
65
79
  );
66
80
  }
67
81
 
@@ -69,7 +83,13 @@ export async function prerenderMermaid(
69
83
  const newImages = results.some(added => added);
70
84
 
71
85
  if (newImages && onRenderNeeded) {
72
- onRenderNeeded();
86
+ try {
87
+ onRenderNeeded();
88
+ } catch (error) {
89
+ logger.warn("Mermaid render callback failed", {
90
+ error: error instanceof Error ? error.message : String(error),
91
+ });
92
+ }
73
93
  }
74
94
  }
75
95
 
@@ -78,7 +98,7 @@ export async function prerenderMermaid(
78
98
  */
79
99
  export function hasPendingMermaid(markdown: string): boolean {
80
100
  const blocks = extractMermaidBlocks(markdown);
81
- return blocks.some(({ hash }) => !cache.has(hash));
101
+ return blocks.some(({ hash }) => !cache.has(hash) && !failed.has(hash));
82
102
  }
83
103
 
84
104
  /**
@@ -86,4 +106,6 @@ export function hasPendingMermaid(markdown: string): boolean {
86
106
  */
87
107
  export function clearMermaidCache(): void {
88
108
  cache.clear();
109
+ failed.clear();
110
+ pending.clear();
89
111
  }
@@ -161,6 +161,7 @@ export interface InteractiveModeContext {
161
161
  showSettingsSelector(): void;
162
162
  showHistorySearch(): void;
163
163
  showExtensionsDashboard(): void;
164
+ showAgentsDashboard(): void;
164
165
  showModelSelector(options?: { temporaryOnly?: boolean }): void;
165
166
  showUserMessageSelector(): void;
166
167
  showTreeSelector(): void;
@@ -0,0 +1,65 @@
1
+ You are an elite AI agent architect specializing in crafting high-performance agent configurations. Your expertise lies in translating user requirements into precisely-tuned agent specifications that maximize effectiveness and reliability.
2
+
3
+ Important Context: You may have access to project-specific instructions from CLAUDE.md files and other context that may include coding standards, project structure, and custom requirements. Consider this context when creating agents to ensure they align with the project's established patterns and practices.
4
+
5
+ When a user describes what they want an agent to do, you will:
6
+ 1. Extract Core Intent: Identify the fundamental purpose, key responsibilities, and success criteria for the agent. Look for both explicit requirements and implicit needs. Consider any project-specific context from CLAUDE.md files. For agents that are meant to review code, you should assume that the user is asking to review recently written code and not the whole codebase, unless the user has explicitly instructed you otherwise.
7
+ 2. Design Expert Persona: Create a compelling expert identity that embodies deep domain knowledge relevant to the task. The persona should inspire confidence and guide the agent's decision-making approach.
8
+ 3. Architect Comprehensive Instructions: Develop a system prompt that:
9
+ - Establishes clear behavioral boundaries and operational parameters
10
+ - Provides specific methodologies and best practices for task execution
11
+ - Anticipates edge cases and provides guidance for handling them
12
+ - Incorporates any specific requirements or preferences mentioned by the user
13
+ - Defines output format expectations when relevant
14
+ - Aligns with project-specific coding standards and patterns from CLAUDE.md
15
+ 4. Optimize for Performance: Include:
16
+ - Decision-making frameworks appropriate to the domain
17
+ - Quality control mechanisms and self-verification steps
18
+ - Efficient workflow patterns
19
+ - Clear escalation or fallback strategies
20
+ 5. Create Identifier: Design a concise, descriptive identifier that:
21
+ - Uses lowercase letters, numbers, and hyphens only
22
+ - Is typically 2-4 words joined by hyphens
23
+ - Clearly indicates the agent's primary function
24
+ - Is memorable and easy to type
25
+ - Avoids generic terms like "helper" or "assistant"
26
+ 6. Example agent descriptions:
27
+ - in the 'whenToUse' field of the JSON object, you should include examples of when this agent should be used.
28
+ - examples should be of the form:
29
+ - <example>
30
+ Context: The user is creating a test-runner agent that should be called after a logical chunk of code is written.
31
+ user: "Please write a function that checks if a number is prime"
32
+ assistant: "Here is the relevant function: "
33
+ <function call omitted for brevity only for this example>
34
+ <commentary>
35
+ Since a significant piece of code was written, use the {{TASK_TOOL_NAME}} tool to launch the test-runner agent to run the tests.
36
+ </commentary>
37
+ assistant: "Now let me use the test-runner agent to run the tests"
38
+ </example>
39
+ - <example>
40
+ Context: User is creating an agent to respond to the word "hello" with a friendly jok.
41
+ user: "Hello"
42
+ assistant: "I'm going to use the {{TASK_TOOL_NAME}} tool to launch the greeting-responder agent to respond with a friendly joke"
43
+ <commentary>
44
+ Since the user is greeting, use the greeting-responder agent to respond with a friendly joke.
45
+ </commentary>
46
+ </example>
47
+ - If the user mentioned or implied that the agent should be used proactively, you should include examples of this.
48
+ - NOTE: Ensure that in the examples, you are making the assistant use the Agent tool and not simply respond directly to the task.
49
+
50
+ Your output must be a valid JSON object with exactly these fields:
51
+ {
52
+ "identifier": "A unique, descriptive identifier using lowercase letters, numbers, and hyphens (e.g., 'test-runner', 'api-docs-writer', 'code-formatter')",
53
+ "whenToUse": "A precise, actionable description starting with 'Use this agent when...' that clearly defines the triggering conditions and use cases. Ensure you include examples as described above.",
54
+ "systemPrompt": "The complete system prompt that will govern the agent's behavior, written in second person ('You are...', 'You will...') and structured for maximum clarity and effectiveness"
55
+ }
56
+
57
+ Key principles for your system prompts:
58
+ - Be specific rather than generic - avoid vague instructions
59
+ - Include concrete examples when they would clarify behavior
60
+ - Balance comprehensiveness with clarity - every instruction should add value
61
+ - Ensure the agent has enough context to handle variations of the core task
62
+ - Make the agent proactive in seeking clarification when needed
63
+ - Build in quality assurance and self-correction mechanisms
64
+
65
+ Remember: The agents you create should be autonomous experts capable of handling their designated tasks with minimal additional guidance. Your system prompts are their complete operational manual.
@@ -0,0 +1,6 @@
1
+ Design a custom agent for this request:
2
+
3
+ {{request}}
4
+
5
+ Return only the JSON object required by your system instructions.
6
+ Do not include markdown fences.
@@ -2302,7 +2302,7 @@ export class AgentSession {
2302
2302
  throw new Error(`No API key for ${model.provider}/${model.id}`);
2303
2303
  }
2304
2304
 
2305
- this.agent.setModel(this.#applySessionModelOverrides(model));
2305
+ this.#setModelWithProviderSessionReset(model);
2306
2306
  this.sessionManager.appendModelChange(`${model.provider}/${model.id}`, role);
2307
2307
  this.settings.setModelRole(role, `${model.provider}/${model.id}`);
2308
2308
  this.settings.getStorage()?.recordModelUsage(`${model.provider}/${model.id}`);
@@ -2322,7 +2322,7 @@ export class AgentSession {
2322
2322
  throw new Error(`No API key for ${model.provider}/${model.id}`);
2323
2323
  }
2324
2324
 
2325
- this.agent.setModel(this.#applySessionModelOverrides(model));
2325
+ this.#setModelWithProviderSessionReset(model);
2326
2326
  this.sessionManager.appendModelChange(`${model.provider}/${model.id}`, "temporary");
2327
2327
  this.settings.getStorage()?.recordModelUsage(`${model.provider}/${model.id}`);
2328
2328
 
@@ -2436,7 +2436,7 @@ export class AgentSession {
2436
2436
  const next = scopedModels[nextIndex];
2437
2437
 
2438
2438
  // Apply model
2439
- this.agent.setModel(this.#applySessionModelOverrides(next.model));
2439
+ this.#setModelWithProviderSessionReset(next.model);
2440
2440
  this.sessionManager.appendModelChange(`${next.model.provider}/${next.model.id}`);
2441
2441
  this.settings.setModelRole("default", `${next.model.provider}/${next.model.id}`);
2442
2442
  this.settings.getStorage()?.recordModelUsage(`${next.model.provider}/${next.model.id}`);
@@ -2464,7 +2464,7 @@ export class AgentSession {
2464
2464
  throw new Error(`No API key for ${nextModel.provider}/${nextModel.id}`);
2465
2465
  }
2466
2466
 
2467
- this.agent.setModel(this.#applySessionModelOverrides(nextModel));
2467
+ this.#setModelWithProviderSessionReset(nextModel);
2468
2468
  this.sessionManager.appendModelChange(`${nextModel.provider}/${nextModel.id}`);
2469
2469
  this.settings.setModelRole("default", `${nextModel.provider}/${nextModel.id}`);
2470
2470
  this.settings.getStorage()?.recordModelUsage(`${nextModel.provider}/${nextModel.id}`);
@@ -2610,6 +2610,7 @@ export class AgentSession {
2610
2610
  await this.sessionManager.rewriteEntries();
2611
2611
  const sessionContext = this.sessionManager.buildSessionContext();
2612
2612
  this.agent.replaceMessages(sessionContext.messages);
2613
+ this.#closeCodexProviderSessionsForHistoryRewrite();
2613
2614
  return result;
2614
2615
  }
2615
2616
 
@@ -2733,6 +2734,7 @@ export class AgentSession {
2733
2734
  const newEntries = this.sessionManager.getEntries();
2734
2735
  const sessionContext = this.sessionManager.buildSessionContext();
2735
2736
  this.agent.replaceMessages(sessionContext.messages);
2737
+ this.#closeCodexProviderSessionsForHistoryRewrite();
2736
2738
 
2737
2739
  // Get the saved compaction entry for the hook
2738
2740
  const savedCompactionEntry = newEntries.find(e => e.type === "compaction" && e.summary === summary) as
@@ -3082,7 +3084,6 @@ Be thorough - include exact file paths, function names, error messages, and tech
3082
3084
  if (!targetModel) return false;
3083
3085
 
3084
3086
  try {
3085
- this.#closeProviderSessionsForModelSwitch(currentModel, targetModel);
3086
3087
  await this.setModelTemporary(targetModel);
3087
3088
  logger.debug("Context promotion switched model on overflow", {
3088
3089
  from: `${currentModel.provider}/${currentModel.id}`,
@@ -3132,6 +3133,20 @@ Be thorough - include exact file paths, function names, error messages, and tech
3132
3133
  return undefined;
3133
3134
  }
3134
3135
 
3136
+ #setModelWithProviderSessionReset(model: Model): void {
3137
+ const currentModel = this.model;
3138
+ if (currentModel) {
3139
+ this.#closeProviderSessionsForModelSwitch(currentModel, model);
3140
+ }
3141
+ this.agent.setModel(this.#applySessionModelOverrides(model));
3142
+ }
3143
+
3144
+ #closeCodexProviderSessionsForHistoryRewrite(): void {
3145
+ const currentModel = this.model;
3146
+ if (!currentModel || currentModel.api !== "openai-codex-responses") return;
3147
+ this.#closeProviderSessionsForModelSwitch(currentModel, currentModel);
3148
+ }
3149
+
3135
3150
  #closeProviderSessionsForModelSwitch(currentModel: Model, nextModel: Model): void {
3136
3151
  if (currentModel.api !== "openai-codex-responses" && nextModel.api !== "openai-codex-responses") return;
3137
3152
 
@@ -3431,6 +3446,7 @@ Be thorough - include exact file paths, function names, error messages, and tech
3431
3446
  const newEntries = this.sessionManager.getEntries();
3432
3447
  const sessionContext = this.sessionManager.buildSessionContext();
3433
3448
  this.agent.replaceMessages(sessionContext.messages);
3449
+ this.#closeCodexProviderSessionsForHistoryRewrite();
3434
3450
 
3435
3451
  // Get the saved compaction entry for the hook
3436
3452
  const savedCompactionEntry = newEntries.find(e => e.type === "compaction" && e.summary === summary) as
@@ -4013,7 +4029,7 @@ Be thorough - include exact file paths, function names, error messages, and tech
4013
4029
  const availableModels = this.#modelRegistry.getAvailable();
4014
4030
  const match = availableModels.find(m => m.provider === provider && m.id === modelId);
4015
4031
  if (match) {
4016
- this.agent.setModel(this.#applySessionModelOverrides(match));
4032
+ this.#setModelWithProviderSessionReset(match);
4017
4033
  }
4018
4034
  }
4019
4035
  }
@@ -212,6 +212,14 @@ const BUILTIN_SLASH_COMMAND_REGISTRY: ReadonlyArray<BuiltinSlashCommandSpec> = [
212
212
  runtime.ctx.editor.setText("");
213
213
  },
214
214
  },
215
+ {
216
+ name: "agents",
217
+ description: "Open Agent Control Center dashboard",
218
+ handle: (_command, runtime) => {
219
+ runtime.ctx.showAgentsDashboard();
220
+ runtime.ctx.editor.setText("");
221
+ },
222
+ },
215
223
  {
216
224
  name: "branch",
217
225
  description: "Create a new branch from a previous message",
package/src/task/index.ts CHANGED
@@ -36,6 +36,7 @@ import { mapWithConcurrencyLimit } from "./parallel";
36
36
  import { renderCall, renderResult } from "./render";
37
37
  import { renderTemplate } from "./template";
38
38
  import {
39
+ type AgentDefinition,
39
40
  type AgentProgress,
40
41
  type SingleResult,
41
42
  type TaskParams,
@@ -109,13 +110,17 @@ export type { AgentDefinition, AgentProgress, SingleResult, TaskParams, TaskTool
109
110
  export { taskSchema } from "./types";
110
111
 
111
112
  /**
112
- * Build dynamic tool description listing available agents.
113
+ * Render the tool description from a cached agent list and current settings.
113
114
  */
114
- async function buildDescription(cwd: string, maxConcurrency: number, isolationEnabled: boolean): Promise<string> {
115
- const { agents } = await discoverAgents(cwd);
116
-
115
+ function renderDescription(
116
+ agents: AgentDefinition[],
117
+ maxConcurrency: number,
118
+ isolationEnabled: boolean,
119
+ disabledAgents: string[],
120
+ ): string {
121
+ const filteredAgents = disabledAgents.length > 0 ? agents.filter(a => !disabledAgents.includes(a.name)) : agents;
117
122
  return renderPromptTemplate(taskDescriptionTemplate, {
118
- agents,
123
+ agents: filteredAgents,
119
124
  MAX_CONCURRENCY: maxConcurrency,
120
125
  isolationEnabled,
121
126
  });
@@ -137,26 +142,33 @@ export class TaskTool implements AgentTool<TaskSchema, TaskToolDetails, Theme> {
137
142
  readonly parameters: TaskSchema;
138
143
  readonly renderCall = renderCall;
139
144
  readonly renderResult = renderResult;
140
-
145
+ readonly #discoveredAgents: AgentDefinition[];
141
146
  readonly #blockedAgent: string | undefined;
142
147
 
148
+ /** Dynamic description that reflects current disabled-agent settings */
149
+ get description(): string {
150
+ const disabledAgents = this.session.settings.get("task.disabledAgents") as string[];
151
+ const maxConcurrency = this.session.settings.get("task.maxConcurrency");
152
+ const isolationEnabled = this.session.settings.get("task.isolation.enabled");
153
+ return renderDescription(this.#discoveredAgents, maxConcurrency, isolationEnabled, disabledAgents);
154
+ }
143
155
  private constructor(
144
156
  private readonly session: ToolSession,
145
- public readonly description: string,
157
+ discoveredAgents: AgentDefinition[],
146
158
  isolationEnabled: boolean,
147
159
  ) {
148
160
  this.parameters = isolationEnabled ? taskSchema : taskSchemaNoIsolation;
149
161
  this.#blockedAgent = $env.PI_BLOCKED_AGENT;
162
+ this.#discoveredAgents = discoveredAgents;
150
163
  }
151
164
 
152
165
  /**
153
166
  * Create a TaskTool instance with async agent discovery.
154
167
  */
155
168
  static async create(session: ToolSession): Promise<TaskTool> {
156
- const maxConcurrency = session.settings.get("task.maxConcurrency");
157
169
  const isolationEnabled = session.settings.get("task.isolation.enabled");
158
- const description = await buildDescription(session.cwd, maxConcurrency, isolationEnabled);
159
- return new TaskTool(session, description, isolationEnabled);
170
+ const { agents } = await discoverAgents(session.cwd);
171
+ return new TaskTool(session, agents, isolationEnabled);
160
172
  }
161
173
 
162
174
  async execute(
@@ -209,6 +221,25 @@ export class TaskTool implements AgentTool<TaskSchema, TaskToolDetails, Theme> {
209
221
  };
210
222
  }
211
223
 
224
+ // Check if agent is disabled in settings
225
+ const disabledAgents = this.session.settings.get("task.disabledAgents") as string[];
226
+ if (disabledAgents.length > 0 && disabledAgents.includes(agentName)) {
227
+ const enabled = agents.filter(a => !disabledAgents.includes(a.name)).map(a => a.name);
228
+ return {
229
+ content: [
230
+ {
231
+ type: "text",
232
+ text: `Agent "${agentName}" is disabled in settings. Enable it via /agents, or use a different agent type.${enabled.length > 0 ? ` Available: ${enabled.join(", ")}` : ""}`,
233
+ },
234
+ ],
235
+ details: {
236
+ projectAgentsDir,
237
+ results: [],
238
+ totalDurationMs: 0,
239
+ },
240
+ };
241
+ }
242
+
212
243
  const planModeState = this.session.getPlanModeState?.();
213
244
  const planModeTools = ["read", "grep", "find", "ls", "lsp", "fetch", "web_search"];
214
245
  const effectiveAgent: typeof agent = planModeState?.enabled
@@ -220,9 +251,15 @@ export class TaskTool implements AgentTool<TaskSchema, TaskToolDetails, Theme> {
220
251
  }
221
252
  : agent;
222
253
 
254
+ // Apply per-agent model override from settings (highest priority)
255
+ const agentModelOverrides = this.session.settings.get("task.agentModelOverrides") as Record<string, string>;
256
+ const settingsModelOverride = agentModelOverrides[agentName];
223
257
  const effectiveAgentModel = isDefaultModelAlias(effectiveAgent.model) ? undefined : effectiveAgent.model;
224
258
  const modelOverride =
225
- effectiveAgentModel ?? this.session.getActiveModelString?.() ?? this.session.getModelString?.();
259
+ settingsModelOverride ??
260
+ effectiveAgentModel ??
261
+ this.session.getActiveModelString?.() ??
262
+ this.session.getModelString?.();
226
263
  const thinkingLevelOverride = effectiveAgent.thinkingLevel;
227
264
 
228
265
  // Output schema priority: agent frontmatter > params > inherited from parent session