@timmyjl12/pi-subagents 0.20.0 → 0.21.1

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.
Files changed (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3616 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4133 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
@@ -3,11 +3,12 @@
3
3
  */
4
4
 
5
5
  import { existsSync, readdirSync, readFileSync } from "node:fs";
6
+ import { readdir, readFile } from "node:fs/promises";
6
7
  import { basename, join } from "node:path";
7
8
  import { inspect } from "node:util";
8
9
  import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
9
- import { BUILTIN_TOOL_NAMES } from "./agent-types.js";
10
- import type { AgentConfig, IsolationMode, MemoryScope, ThinkingLevel } from "./types.js";
10
+ import { BUILTIN_TOOL_NAMES, cloneAgentDefinition } from "./agent-types.ts";
11
+ import type { AgentConfig, IsolationMode, MemoryScope, ThinkingLevel } from "./types.ts";
11
12
 
12
13
  /**
13
14
  * The one thing a declared `name:` may not contain, matching Claude Code
@@ -49,28 +50,103 @@ const ADVISOR_FIELDS = ["advisor", "advisors"] as const;
49
50
  * filename clash, and `warnSkippedOverride` reports the substitution.
50
51
  */
51
52
  export function loadCustomAgents(cwd: string, strict = false): Map<string, AgentConfig> {
52
- const globalDir = join(getAgentDir(), "agents");
53
- const workspaceProjectDir = join(cwd, ".agents", "agents");
54
- const projectDir = join(cwd, ".pi", "agents");
53
+ const { globalDir, workspaceProjectDir, projectDir } = agentDirs(cwd);
54
+ const warnings = beginLoadWarnings();
55
55
 
56
56
  const agents = new Map<string, AgentConfig>();
57
- loadFromDir(globalDir, agents, "global", strict); // lowest priority
58
- loadFromDir(workspaceProjectDir, agents, "project", strict); // shared workspace
59
- loadFromDir(projectDir, agents, "project", strict); // highest priority (overwrites)
57
+ loadFromDirSync(globalDir, agents, "global", strict, warnings); // lowest priority
58
+ loadFromDirSync(workspaceProjectDir, agents, "project", strict, warnings); // shared workspace
59
+ loadFromDirSync(projectDir, agents, "project", strict, warnings); // highest priority (overwrites)
60
60
 
61
- warnedLastLoad = warnedThisLoad;
62
- warnedThisLoad = new Set();
61
+ commitLoadWarnings(warnings);
62
+ return agents;
63
+ }
64
+
65
+ /**
66
+ * Async twin of {@link loadCustomAgents} for ordinary awaitable admission.
67
+ *
68
+ * Discovery and content reads are fresh every call; only the raw YAML parse is
69
+ * reused, and only when the bytes just read are identical. That distinction is
70
+ * deliberate: caching a size/mtime stamp would let a same-size edit through,
71
+ * and caching a validated AgentConfig would make a lenient load's skipped or
72
+ * coerced field authorize a strict request. Cache entries are bounded by both
73
+ * entry count and retained bytes, so a pathological directory cannot pin
74
+ * arbitrary content for the process lifetime.
75
+ *
76
+ * Concurrent callers for the same three-directory scope and strictness share
77
+ * one refresh. Each gets its own Map so a caller mutating its result cannot
78
+ * rewrite another caller's registry; warnings are collected per load and
79
+ * committed atomically when the shared load finishes.
80
+ */
81
+ export async function loadCustomAgentsAsync(cwd: string, strict = false): Promise<Map<string, AgentConfig>> {
82
+ const { globalDir, workspaceProjectDir, projectDir } = agentDirs(cwd);
83
+ const key = [globalDir, workspaceProjectDir, projectDir, strict ? "strict" : "lenient"].join("\0");
84
+ const inflight = inflightAsyncLoads.get(key);
85
+ if (inflight) return cloneRegistry(await inflight);
86
+
87
+ const warnings = beginLoadWarnings();
88
+ let shared: Promise<Map<string, AgentConfig>>;
89
+ shared = loadAllDirsAsync(
90
+ { globalDir, workspaceProjectDir, projectDir },
91
+ strict,
92
+ warnings,
93
+ ).finally(() => {
94
+ if (inflightAsyncLoads.get(key) === shared) inflightAsyncLoads.delete(key);
95
+ });
96
+ inflightAsyncLoads.set(key, shared);
97
+ return cloneRegistry(await shared);
98
+ }
99
+
100
+ /** Coalescing shares I/O, never mutable definitions or tool-policy arrays. */
101
+ function cloneRegistry(agents: Map<string, AgentConfig>): Map<string, AgentConfig> {
102
+ return new Map([...agents].map(([name, config]) => [name, cloneAgentDefinition(config)]));
103
+ }
104
+
105
+ interface AgentDirs {
106
+ globalDir: string;
107
+ workspaceProjectDir: string;
108
+ projectDir: string;
109
+ }
110
+
111
+ function agentDirs(cwd: string): AgentDirs {
112
+ return {
113
+ globalDir: join(getAgentDir(), "agents"),
114
+ workspaceProjectDir: join(cwd, ".agents", "agents"),
115
+ projectDir: join(cwd, ".pi", "agents"),
116
+ };
117
+ }
118
+
119
+ async function loadAllDirsAsync(
120
+ dirs: AgentDirs,
121
+ strict: boolean,
122
+ warnings: LoadWarnings,
123
+ ): Promise<Map<string, AgentConfig>> {
124
+ const agents = new Map<string, AgentConfig>();
125
+ await loadFromDirAsync(dirs.globalDir, agents, "global", strict, warnings);
126
+ await loadFromDirAsync(dirs.workspaceProjectDir, agents, "project", strict, warnings);
127
+ await loadFromDirAsync(dirs.projectDir, agents, "project", strict, warnings);
128
+ commitLoadWarnings(warnings);
63
129
  return agents;
64
130
  }
65
131
 
66
132
  /** Load agent configs from a directory into the map. */
67
- function loadFromDir(dir: string, agents: Map<string, AgentConfig>, source: "project" | "global", strict: boolean): void {
133
+ function loadFromDirSync(
134
+ dir: string,
135
+ agents: Map<string, AgentConfig>,
136
+ source: "project" | "global",
137
+ strict: boolean,
138
+ warnings: LoadWarnings,
139
+ ): void {
140
+ syncReads++;
68
141
  if (!existsSync(dir)) return;
69
142
 
70
143
  let files: string[];
71
144
  try {
145
+ syncReads++;
72
146
  files = readdirSync(dir).filter(f => f.endsWith(".md"));
73
147
  } catch {
148
+ // Missing/unreadable directory: skip it, as discovery always has. Strict
149
+ // mode is about a READABLE file's contents, not an optional directory.
74
150
  return;
75
151
  }
76
152
 
@@ -79,104 +155,140 @@ function loadFromDir(dir: string, agents: Map<string, AgentConfig>, source: "pro
79
155
 
80
156
  const path = join(dir, file);
81
157
 
82
- const parsed = readAgentFile(path, strict);
158
+ const parsed = readAgentFileSync(path, strict, warnings);
83
159
  if (!parsed) {
84
- warnSkippedOverride(filenameType, agents);
160
+ warnSkippedOverride(filenameType, agents, warnings);
85
161
  continue;
86
162
  }
87
- const { frontmatter: fm, body } = parsed;
88
-
89
- // Claude Code's rule: `name:` IS the agent type, and the filename need not
90
- // match. Absent, the filename stands in — Claude Code requires the field,
91
- // but most files here predate it and must keep loading.
92
- const declared = str(fm.name)?.trim();
93
- if (declared?.includes(RESERVED_IN_TYPE)) {
94
- // Refusing beats silently substituting: the file would otherwise load
95
- // under its filename, so `Agent({subagent_type})` would succeed against
96
- // an agent whose declared identity nothing honoured.
97
- warnIfNew(
98
- `Agent file ${path} declares name "${declared}", which contains "${RESERVED_IN_TYPE}" — reserved for `
99
- + "plugin-scoped identifiers. Rename it, or move the label to `display_name:`. Skipping.",
100
- );
101
- // No `warnSkippedOverride`: this file would have registered under its
102
- // *declared* name, which nothing else can hold (a colon keeps it out of
103
- // the registry), so it shadowed nothing. Passing the filename instead
104
- // would report a substitution of an unrelated agent that never happened.
105
- continue;
106
- }
107
- // `||`, not `??`: a quoted empty or all-whitespace `name:` would otherwise
108
- // register the agent under the empty type — unspawnable, and it takes the
109
- // filename-derived one down with it.
110
- const name = declared || filenameType;
111
-
112
- let thinking: ThinkingLevel | undefined;
113
- let fallbackModel: string | undefined;
114
- let advisor: boolean | undefined;
115
- try {
116
- // AgentConfig uses pi-ai's streaming type (which omits "off"), while
117
- // session settings accept it. Cast only AFTER validating the seven levels.
118
- thinking = parseAliasedString(fm, path, THINKING_FIELDS, THINKING_LEVELS) as ThinkingLevel | undefined;
119
- fallbackModel = parseAliasedString(fm, path, FALLBACK_MODEL_FIELDS);
120
- advisor = parseAliasedBoolean(fm, path, ADVISOR_FIELDS);
121
- } catch (err) {
122
- const reason = err instanceof Error ? err.message : String(err);
123
- if (strict) throw new Error(`${path}: ${reason}`);
124
- warnIfNew(`Skipping agent file ${path}: ${reason}`);
125
- warnSkippedOverride(name, agents);
163
+ addAgent(path, filenameType, parsed, agents, source, strict, warnings);
164
+ }
165
+ }
166
+
167
+ async function loadFromDirAsync(
168
+ dir: string,
169
+ agents: Map<string, AgentConfig>,
170
+ source: "project" | "global",
171
+ strict: boolean,
172
+ warnings: LoadWarnings,
173
+ ): Promise<void> {
174
+ let files: string[];
175
+ try {
176
+ asyncReads++;
177
+ files = (await readdir(dir)).filter(f => f.endsWith(".md"));
178
+ } catch {
179
+ // Same deliberate skip as the synchronous fallback: the three discovery
180
+ // directories are optional, and an absent one is not a load failure.
181
+ return;
182
+ }
183
+
184
+ for (const file of files) {
185
+ const filenameType = basename(file, ".md");
186
+ const path = join(dir, file);
187
+ const parsed = await readAgentFileAsync(path, strict, warnings);
188
+ if (!parsed) {
189
+ warnSkippedOverride(filenameType, agents, warnings);
126
190
  continue;
127
191
  }
128
-
129
- const { builtinToolNames, extSelectors } = parseToolsField(fm.tools);
130
-
131
- agents.set(name, {
132
- name,
133
- // Only `display_name` now: `name` is the type, and `getConfig` already
134
- // falls back to the type when no label is set — so a Claude Code file
135
- // with `name: code-reviewer` still badges as "code-reviewer".
136
- displayName: str(fm.display_name),
137
- color: str(fm.color),
138
- description: str(fm.description) ?? name,
139
- builtinToolNames,
140
- extSelectors,
141
- disallowedTools: csvListOptional(fm.disallowed_tools),
142
- extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
143
- excludeExtensions: csvListOptional(fm.exclude_extensions),
144
- skills: inheritField(fm.skills ?? fm.inherit_skills),
145
- model: str(fm.model),
146
- fallbackModel,
147
- thinking,
148
- advisor,
149
- maxTurns: nonNegativeInt(fm.max_turns),
150
- persistSession: fm.persist_session != null ? fm.persist_session === true : undefined,
151
- outputTranscript: fm.output_transcript != null ? fm.output_transcript !== false : undefined,
152
- sessionDir: str(fm.session_dir),
153
- allowedSubagents: parseAllowedSubagents(fm.allowed_subagents),
154
- systemPrompt: body.trim(),
155
- promptMode: fm.prompt_mode === "append" ? "append" : "replace",
156
- inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
157
- runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
158
- isolated: fm.isolated != null ? fm.isolated === true : undefined,
159
- memory: parseMemory(fm.memory),
160
- isolation: parseIsolation(fm.isolation),
161
- enabled: fm.enabled !== false, // default true; explicitly false disables
162
- source,
163
- sourcePath: path,
164
- });
192
+ addAgent(path, filenameType, parsed, agents, source, strict, warnings);
165
193
  }
166
194
  }
167
195
 
168
196
  /**
169
- * Read and parse one agent file, or warn and return undefined for the caller to
170
- * skip. One bad file must not take the whole extension down with it — an
171
- * unparseable `.md` used to abort activation, so pi exited before the TUI.
172
- *
173
- * The path is as much of the fix as the recovery: a bare YAML error ("line 2,
174
- * column 14") is unactionable when agents come from three directories at once,
175
- * and the only other symptom is `Unknown agent type`, which reads like a typo.
176
- *
177
- * Under `strict` the same failure rethrows, still naming the path, so callers
178
- * that opted into failing closed stop rather than run a substituted agent.
197
+ * Turn one freshly parsed file into an AgentConfig, applying the current
198
+ * strictness and precedence policy. The parsed frontmatter is raw cache data;
199
+ * every validation, alias conflict and skip decision is rerun here so a strict
200
+ * request never inherits a lenient load's decision.
179
201
  */
202
+ function addAgent(
203
+ path: string,
204
+ filenameType: string,
205
+ parsed: ParsedAgentFile,
206
+ agents: Map<string, AgentConfig>,
207
+ source: "project" | "global",
208
+ strict: boolean,
209
+ warnings: LoadWarnings,
210
+ ): void {
211
+ const { frontmatter: fm, body } = parsed;
212
+
213
+ // Claude Code's rule: `name:` IS the agent type, and the filename need not
214
+ // match. Absent, the filename stands in — Claude Code requires the field,
215
+ // but most files here predate it and must keep loading.
216
+ const declared = str(fm.name)?.trim();
217
+ if (declared?.includes(RESERVED_IN_TYPE)) {
218
+ // Refusing beats silently substituting: the file would otherwise load
219
+ // under its filename, so `Agent({subagent_type})` would succeed against
220
+ // an agent whose declared identity nothing honoured.
221
+ warnIfNew(
222
+ warnings,
223
+ `Agent file ${path} declares name "${declared}", which contains "${RESERVED_IN_TYPE}" — reserved for `
224
+ + "plugin-scoped identifiers. Rename it, or move the label to `display_name:`. Skipping.",
225
+ );
226
+ // No `warnSkippedOverride`: this file would have registered under its
227
+ // *declared* name, which nothing else can hold (a colon keeps it out of
228
+ // the registry), so it shadowed nothing. Passing the filename instead
229
+ // would report a substitution of an unrelated agent that never happened.
230
+ return;
231
+ }
232
+ // `||`, not `??`: a quoted empty or all-whitespace `name:` would otherwise
233
+ // register the agent under the empty type — unspawnable, and it takes the
234
+ // filename-derived one down with it.
235
+ const name = declared || filenameType;
236
+
237
+ let thinking: ThinkingLevel | undefined;
238
+ let fallbackModel: string | undefined;
239
+ let advisor: boolean | undefined;
240
+ try {
241
+ // AgentConfig uses pi-ai's streaming type (which omits "off"), while
242
+ // session settings accept it. Cast only AFTER validating the seven levels.
243
+ thinking = parseAliasedString(fm, path, THINKING_FIELDS, THINKING_LEVELS, warnings) as ThinkingLevel | undefined;
244
+ fallbackModel = parseAliasedString(fm, path, FALLBACK_MODEL_FIELDS, undefined, warnings);
245
+ advisor = parseAliasedBoolean(fm, path, ADVISOR_FIELDS, warnings);
246
+ } catch (err) {
247
+ const reason = err instanceof Error ? err.message : String(err);
248
+ if (strict) throw new Error(`${path}: ${reason}`);
249
+ warnIfNew(warnings, `Skipping agent file ${path}: ${reason}`);
250
+ warnSkippedOverride(name, agents, warnings);
251
+ return;
252
+ }
253
+
254
+ const { builtinToolNames, extSelectors } = parseToolsField(fm.tools);
255
+
256
+ agents.set(name, {
257
+ name,
258
+ // Only `display_name` now: `name` is the type, and `getConfig` already
259
+ // falls back to the type when no label is set — so a Claude Code file
260
+ // with `name: code-reviewer` still badges as "code-reviewer".
261
+ displayName: str(fm.display_name),
262
+ color: str(fm.color),
263
+ description: str(fm.description) ?? name,
264
+ builtinToolNames,
265
+ extSelectors,
266
+ disallowedTools: csvListOptional(fm.disallowed_tools),
267
+ extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
268
+ excludeExtensions: csvListOptional(fm.exclude_extensions),
269
+ skills: inheritField(fm.skills ?? fm.inherit_skills),
270
+ model: str(fm.model),
271
+ fallbackModel,
272
+ thinking,
273
+ advisor,
274
+ maxTurns: nonNegativeInt(fm.max_turns),
275
+ persistSession: fm.persist_session != null ? fm.persist_session === true : undefined,
276
+ outputTranscript: fm.output_transcript != null ? fm.output_transcript !== false : undefined,
277
+ sessionDir: str(fm.session_dir),
278
+ allowedSubagents: parseAllowedSubagents(fm.allowed_subagents),
279
+ systemPrompt: body.trim(),
280
+ promptMode: fm.prompt_mode === "append" ? "append" : "replace",
281
+ inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
282
+ runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
283
+ isolated: fm.isolated != null ? fm.isolated === true : undefined,
284
+ memory: parseMemory(fm.memory),
285
+ isolation: parseIsolation(fm.isolation),
286
+ enabled: fm.enabled !== false, // default true; explicitly false disables
287
+ source,
288
+ sourcePath: path,
289
+ });
290
+ }
291
+
180
292
  /**
181
293
  * Parse an agent file's frontmatter, tolerating a leading UTF-8 BOM.
182
294
  *
@@ -196,14 +308,154 @@ export function parseAgentFrontmatter<T extends Record<string, unknown>>(content
196
308
  return parseFrontmatter<T>(content.startsWith("\uFEFF") ? content.slice(1) : content);
197
309
  }
198
310
 
199
- function readAgentFile(path: string, strict: boolean): { frontmatter: Record<string, unknown>; body: string } | undefined {
311
+ interface ParsedAgentFile {
312
+ frontmatter: Record<string, unknown>;
313
+ body: string;
314
+ }
315
+
316
+ interface ParseCacheEntry extends ParsedAgentFile {
317
+ content: string;
318
+ bytes: number;
319
+ }
320
+
321
+ /**
322
+ * Bounds for the raw parse cache. `bytes` counts both the content used for
323
+ * exact equality and the parsed body retained beside it; it is a storage bound,
324
+ * not a limit on file size (a file larger than the cap simply is not cached).
325
+ */
326
+ export const AGENT_PARSE_CACHE_MAX_ENTRIES = 64;
327
+ export const AGENT_PARSE_CACHE_MAX_BYTES = 2 * 1024 * 1024;
328
+
329
+ const parseCache = new Map<string, ParseCacheEntry>();
330
+ let parseCacheBytes = 0;
331
+ let parseCount = 0;
332
+ let parseCacheHits = 0;
333
+ let parseEvictions = 0;
334
+ let syncReads = 0;
335
+ let asyncReads = 0;
336
+ const inflightAsyncLoads = new Map<string, Promise<Map<string, AgentConfig>>>();
337
+
338
+ export interface AgentParseCacheStats {
339
+ entries: number;
340
+ bytes: number;
341
+ parses: number;
342
+ hits: number;
343
+ evictions: number;
344
+ syncReads: number;
345
+ asyncReads: number;
346
+ }
347
+
348
+ /** Operation counts used by the definition-refresh tests. */
349
+ export function getAgentParseCacheStats(): AgentParseCacheStats {
350
+ return {
351
+ entries: parseCache.size,
352
+ bytes: parseCacheBytes,
353
+ parses: parseCount,
354
+ hits: parseCacheHits,
355
+ evictions: parseEvictions,
356
+ syncReads,
357
+ asyncReads,
358
+ };
359
+ }
360
+
361
+ /** Drop retained parses and counters so tests start from a known cache. */
362
+ export function resetAgentParseCache(): void {
363
+ parseCache.clear();
364
+ parseCacheBytes = 0;
365
+ parseCount = 0;
366
+ parseCacheHits = 0;
367
+ parseEvictions = 0;
368
+ syncReads = 0;
369
+ asyncReads = 0;
370
+ }
371
+
372
+ function dropCachedParse(path: string): void {
373
+ const existing = parseCache.get(path);
374
+ if (existing === undefined) return;
375
+ parseCache.delete(path);
376
+ parseCacheBytes -= existing.bytes;
377
+ }
378
+
379
+ /**
380
+ * Reuse the parse for `content` only when those exact bytes were parsed
381
+ * before. A hit returns a fresh frontmatter object: all later validation reads
382
+ * it, and a shared mutable object would let one load's decisions leak into the
383
+ * next.
384
+ */
385
+ function parseCached(path: string, content: string): ParsedAgentFile {
386
+ const cached = parseCache.get(path);
387
+ if (cached !== undefined && cached.content === content) {
388
+ parseCacheHits++;
389
+ // Refresh LRU position without changing retained bytes.
390
+ parseCache.delete(path);
391
+ parseCache.set(path, cached);
392
+ return { frontmatter: structuredClone(cached.frontmatter), body: cached.body };
393
+ }
394
+ if (cached !== undefined) dropCachedParse(path);
395
+
396
+ parseCount++;
397
+ const parsed = parseAgentFrontmatter<Record<string, unknown>>(content);
398
+ rememberParsed(path, content, parsed);
399
+ return parsed;
400
+ }
401
+
402
+ function rememberParsed(path: string, content: string, parsed: ParsedAgentFile): void {
403
+ dropCachedParse(path);
404
+ const bytes = Buffer.byteLength(content, "utf8") + Buffer.byteLength(parsed.body, "utf8");
405
+ if (bytes > AGENT_PARSE_CACHE_MAX_BYTES) return;
406
+
407
+ parseCache.set(path, {
408
+ content,
409
+ // The cache owns its own object; the parse returned to this load never
410
+ // aliases it, so no later load can observe a mutation made on the other.
411
+ frontmatter: structuredClone(parsed.frontmatter),
412
+ body: parsed.body,
413
+ bytes,
414
+ });
415
+ parseCacheBytes += bytes;
416
+ while (parseCache.size > AGENT_PARSE_CACHE_MAX_ENTRIES || parseCacheBytes > AGENT_PARSE_CACHE_MAX_BYTES) {
417
+ const oldest = parseCache.keys().next();
418
+ if (oldest.done) break;
419
+ parseEvictions++;
420
+ dropCachedParse(oldest.value);
421
+ }
422
+ }
423
+
424
+ /** Shared warn/skip outcome for read and parse failures. */
425
+ function agentFileFailure(path: string, err: unknown, strict: boolean, warnings: LoadWarnings): undefined {
426
+ const reason = err instanceof Error ? err.message : String(err);
427
+ if (strict) throw new Error(`${path}: ${reason}`);
428
+ warnIfNew(warnings, `Skipping agent file ${path}: ${reason}`);
429
+ return undefined;
430
+ }
431
+
432
+ function readAgentFileSync(path: string, strict: boolean, warnings: LoadWarnings): ParsedAgentFile | undefined {
433
+ let content: string;
200
434
  try {
201
- return parseAgentFrontmatter<Record<string, unknown>>(readFileSync(path, "utf-8"));
435
+ syncReads++;
436
+ content = readFileSync(path, "utf-8");
202
437
  } catch (err) {
203
- const reason = err instanceof Error ? err.message : String(err);
204
- if (strict) throw new Error(`${path}: ${reason}`);
205
- warnIfNew(`Skipping agent file ${path}: ${reason}`);
206
- return undefined;
438
+ return agentFileFailure(path, err, strict, warnings);
439
+ }
440
+ try {
441
+ return parseCached(path, content);
442
+ } catch (err) {
443
+ return agentFileFailure(path, err, strict, warnings);
444
+ }
445
+ }
446
+
447
+ async function readAgentFileAsync(path: string, strict: boolean, warnings: LoadWarnings): Promise<ParsedAgentFile | undefined> {
448
+ let content: string;
449
+ try {
450
+ asyncReads++;
451
+ content = await readFile(path, "utf-8");
452
+ } catch (err) {
453
+ return agentFileFailure(path, err, strict, warnings);
454
+ }
455
+ try {
456
+ return parseCached(path, content);
457
+ } catch (err) {
458
+ return agentFileFailure(path, err, strict, warnings);
207
459
  }
208
460
  }
209
461
 
@@ -212,26 +464,42 @@ function readAgentFile(path: string, strict: boolean): { frontmatter: Record<str
212
464
  * pointing at a *different* file — its own prompt, model and tools. Nothing
213
465
  * downstream can flag that: unlike an unknown type, the `Agent` call succeeds.
214
466
  */
215
- function warnSkippedOverride(name: string, agents: Map<string, AgentConfig>): void {
467
+ function warnSkippedOverride(name: string, agents: Map<string, AgentConfig>, warnings: LoadWarnings): void {
216
468
  const surviving = agents.get(name);
217
469
  // Nothing shadowed, or what it shadowed is disabled: dispatch refuses the type
218
470
  // either way (see resolveEnabledTypeIn), so there is no substitution to report.
219
471
  if (!surviving?.sourcePath || surviving.enabled === false) return;
220
- warnIfNew(`Agent "${name}" now loads from ${surviving.sourcePath} instead`);
472
+ warnIfNew(warnings, `Agent "${name}" now loads from ${surviving.sourcePath} instead`);
473
+ }
474
+
475
+ interface LoadWarnings {
476
+ previous: ReadonlySet<string>;
477
+ current: Set<string>;
221
478
  }
222
479
 
223
480
  let warnedLastLoad = new Set<string>();
224
- let warnedThisLoad = new Set<string>();
481
+
482
+ function beginLoadWarnings(): LoadWarnings {
483
+ return { previous: warnedLastLoad, current: new Set() };
484
+ }
485
+
486
+ function commitLoadWarnings(warnings: LoadWarnings): void {
487
+ warnedLastLoad = warnings.current;
488
+ }
225
489
 
226
490
  /**
227
491
  * Agents reload on activation and again on every `Agent` call, so an unchanged
228
492
  * problem would re-warn all session — over a painted TUI, since pi does not
229
493
  * redirect console output. Compare against the previous load rather than every
230
494
  * load ever, so a file that is fixed and then broken again still reports.
495
+ *
496
+ * The set is per load, not module-wide: an async load may interleave with
497
+ * another refresh or with a synchronous fallback between reads, and sharing
498
+ * one accumulator would let one load suppress another's diagnostics.
231
499
  */
232
- function warnIfNew(message: string): void {
233
- warnedThisLoad.add(message);
234
- if (warnedLastLoad.has(message)) return;
500
+ function warnIfNew(warnings: LoadWarnings, message: string): void {
501
+ warnings.current.add(message);
502
+ if (warnings.previous.has(message)) return;
235
503
  console.warn(`[pi-subagents] ${message}`);
236
504
  }
237
505
 
@@ -242,7 +510,8 @@ function parseAliasedString(
242
510
  fm: Record<string, unknown>,
243
511
  path: string,
244
512
  fields: readonly string[],
245
- allowedValues?: readonly string[],
513
+ allowedValues: readonly string[] | undefined,
514
+ warnings: LoadWarnings,
246
515
  ): string | undefined {
247
516
  const entries = fields.filter(field => Object.hasOwn(fm, field)).map(field => {
248
517
  const value = fm[field];
@@ -258,6 +527,7 @@ function parseAliasedString(
258
527
  if (!selected) return undefined;
259
528
  if (entries.some(entry => entry.value !== selected.value)) {
260
529
  warnIfNew(
530
+ warnings,
261
531
  `Agent file ${path} has conflicting ${fields[0]} aliases: `
262
532
  + `${entries.map(entry => `${entry.field}: ${entry.value}`).join(", ")}. `
263
533
  + `Using ${selected.field}: ${selected.value}; precedence: ${fields.join(" > ")}.`,
@@ -280,6 +550,7 @@ function parseAliasedBoolean(
280
550
  fm: Record<string, unknown>,
281
551
  path: string,
282
552
  fields: readonly string[],
553
+ warnings: LoadWarnings,
283
554
  ): boolean | undefined {
284
555
  const entries = fields.filter(field => Object.hasOwn(fm, field)).map(field => {
285
556
  const value = fm[field];
@@ -295,6 +566,7 @@ function parseAliasedBoolean(
295
566
  if (!selected) return undefined;
296
567
  if (entries.some(entry => entry.value !== selected.value)) {
297
568
  warnIfNew(
569
+ warnings,
298
570
  `Agent file ${path} has conflicting ${fields[0]} aliases: `
299
571
  + `${entries.map(entry => `${entry.field}: ${entry.value}`).join(", ")}. `
300
572
  + `Using ${selected.field}: ${selected.value}; precedence: ${fields.join(" > ")}.`,
@@ -4,7 +4,7 @@
4
4
  * These are always available but can be overridden by user .md files with the same name.
5
5
  */
6
6
 
7
- import type { AgentConfig } from "./types.js";
7
+ import type { AgentConfig } from "./types.ts";
8
8
 
9
9
  const READ_ONLY_TOOLS = ["read", "bash", "grep", "find", "ls"];
10
10
 
@@ -29,7 +29,7 @@
29
29
  import { existsSync, readFileSync, statSync } from "node:fs";
30
30
  import { join } from "node:path";
31
31
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
32
- import type { ModelEntry } from "./model-resolver.js";
32
+ import type { ModelEntry } from "./model-resolver.ts";
33
33
 
34
34
  /** Minimal registry shape — only the methods resolveEnabledModels actually calls. */
35
35
  export interface ModelRegistryRef {
package/src/env.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
- import type { EnvInfo } from "./types.js";
6
+ import type { EnvInfo } from "./types.ts";
7
7
 
8
8
  export async function detectEnv(pi: ExtensionAPI, cwd: string): Promise<EnvInfo> {
9
9
  let isGitRepo = false;
package/src/error-log.ts CHANGED
@@ -24,7 +24,7 @@ import { chmodSync, mkdirSync } from "node:fs";
24
24
  import { appendFile, open, rename, stat, unlink, writeFile } from "node:fs/promises";
25
25
  import { join } from "node:path";
26
26
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
27
- import { sanitizeDiagnosticText } from "./output-diagnostics.js";
27
+ import { sanitizeDiagnosticText } from "./output-diagnostics.ts";
28
28
 
29
29
  export type SubagentIssueKind =
30
30
  | "attempt_error" // assistant message finalized with stopReason error/aborted
@@ -191,3 +191,12 @@ export function logSubagentIssue(record: SubagentIssueRecord): Promise<void> {
191
191
  writeChain = writeChain.then(() => appendIssueLine(path, line));
192
192
  return writeChain;
193
193
  }
194
+
195
+ /**
196
+ * Await every queued diagnostic append. Used by cleanup before it may remove the
197
+ * shared aggregate: an unresolved write would otherwise recreate the file after
198
+ * the unlink. Best-effort like the log itself; never rejects.
199
+ */
200
+ export function flushIssueLog(): Promise<void> {
201
+ return writeChain;
202
+ }