@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
@@ -2,10 +2,11 @@
2
2
  * custom-agents.ts — Load user-defined agents from project (.pi/agents/, plus the shared .agents/agents/ workspace) and global ($PI_CODING_AGENT_DIR/agents/, default ~/.pi/agent/agents/) locations.
3
3
  */
4
4
  import { existsSync, readdirSync, readFileSync } from "node:fs";
5
+ import { readdir, readFile } from "node:fs/promises";
5
6
  import { basename, join } from "node:path";
6
7
  import { inspect } from "node:util";
7
8
  import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
8
- import { BUILTIN_TOOL_NAMES } from "./agent-types.js";
9
+ import { BUILTIN_TOOL_NAMES, cloneAgentDefinition } from "./agent-types.js";
9
10
  /**
10
11
  * The one thing a declared `name:` may not contain, matching Claude Code
11
12
  * exactly: it reserves `:` for plugin-scoped identifiers (`my-plugin:reviewer`)
@@ -45,124 +46,195 @@ const ADVISOR_FIELDS = ["advisor", "advisors"];
45
46
  * filename clash, and `warnSkippedOverride` reports the substitution.
46
47
  */
47
48
  export function loadCustomAgents(cwd, strict = false) {
48
- const globalDir = join(getAgentDir(), "agents");
49
- const workspaceProjectDir = join(cwd, ".agents", "agents");
50
- const projectDir = join(cwd, ".pi", "agents");
49
+ const { globalDir, workspaceProjectDir, projectDir } = agentDirs(cwd);
50
+ const warnings = beginLoadWarnings();
51
51
  const agents = new Map();
52
- loadFromDir(globalDir, agents, "global", strict); // lowest priority
53
- loadFromDir(workspaceProjectDir, agents, "project", strict); // shared workspace
54
- loadFromDir(projectDir, agents, "project", strict); // highest priority (overwrites)
55
- warnedLastLoad = warnedThisLoad;
56
- warnedThisLoad = new Set();
52
+ loadFromDirSync(globalDir, agents, "global", strict, warnings); // lowest priority
53
+ loadFromDirSync(workspaceProjectDir, agents, "project", strict, warnings); // shared workspace
54
+ loadFromDirSync(projectDir, agents, "project", strict, warnings); // highest priority (overwrites)
55
+ commitLoadWarnings(warnings);
56
+ return agents;
57
+ }
58
+ /**
59
+ * Async twin of {@link loadCustomAgents} for ordinary awaitable admission.
60
+ *
61
+ * Discovery and content reads are fresh every call; only the raw YAML parse is
62
+ * reused, and only when the bytes just read are identical. That distinction is
63
+ * deliberate: caching a size/mtime stamp would let a same-size edit through,
64
+ * and caching a validated AgentConfig would make a lenient load's skipped or
65
+ * coerced field authorize a strict request. Cache entries are bounded by both
66
+ * entry count and retained bytes, so a pathological directory cannot pin
67
+ * arbitrary content for the process lifetime.
68
+ *
69
+ * Concurrent callers for the same three-directory scope and strictness share
70
+ * one refresh. Each gets its own Map so a caller mutating its result cannot
71
+ * rewrite another caller's registry; warnings are collected per load and
72
+ * committed atomically when the shared load finishes.
73
+ */
74
+ export async function loadCustomAgentsAsync(cwd, strict = false) {
75
+ const { globalDir, workspaceProjectDir, projectDir } = agentDirs(cwd);
76
+ const key = [globalDir, workspaceProjectDir, projectDir, strict ? "strict" : "lenient"].join("\0");
77
+ const inflight = inflightAsyncLoads.get(key);
78
+ if (inflight)
79
+ return cloneRegistry(await inflight);
80
+ const warnings = beginLoadWarnings();
81
+ let shared;
82
+ shared = loadAllDirsAsync({ globalDir, workspaceProjectDir, projectDir }, strict, warnings).finally(() => {
83
+ if (inflightAsyncLoads.get(key) === shared)
84
+ inflightAsyncLoads.delete(key);
85
+ });
86
+ inflightAsyncLoads.set(key, shared);
87
+ return cloneRegistry(await shared);
88
+ }
89
+ /** Coalescing shares I/O, never mutable definitions or tool-policy arrays. */
90
+ function cloneRegistry(agents) {
91
+ return new Map([...agents].map(([name, config]) => [name, cloneAgentDefinition(config)]));
92
+ }
93
+ function agentDirs(cwd) {
94
+ return {
95
+ globalDir: join(getAgentDir(), "agents"),
96
+ workspaceProjectDir: join(cwd, ".agents", "agents"),
97
+ projectDir: join(cwd, ".pi", "agents"),
98
+ };
99
+ }
100
+ async function loadAllDirsAsync(dirs, strict, warnings) {
101
+ const agents = new Map();
102
+ await loadFromDirAsync(dirs.globalDir, agents, "global", strict, warnings);
103
+ await loadFromDirAsync(dirs.workspaceProjectDir, agents, "project", strict, warnings);
104
+ await loadFromDirAsync(dirs.projectDir, agents, "project", strict, warnings);
105
+ commitLoadWarnings(warnings);
57
106
  return agents;
58
107
  }
59
108
  /** Load agent configs from a directory into the map. */
60
- function loadFromDir(dir, agents, source, strict) {
109
+ function loadFromDirSync(dir, agents, source, strict, warnings) {
110
+ syncReads++;
61
111
  if (!existsSync(dir))
62
112
  return;
63
113
  let files;
64
114
  try {
115
+ syncReads++;
65
116
  files = readdirSync(dir).filter(f => f.endsWith(".md"));
66
117
  }
67
118
  catch {
119
+ // Missing/unreadable directory: skip it, as discovery always has. Strict
120
+ // mode is about a READABLE file's contents, not an optional directory.
68
121
  return;
69
122
  }
70
123
  for (const file of files) {
71
124
  const filenameType = basename(file, ".md");
72
125
  const path = join(dir, file);
73
- const parsed = readAgentFile(path, strict);
126
+ const parsed = readAgentFileSync(path, strict, warnings);
74
127
  if (!parsed) {
75
- warnSkippedOverride(filenameType, agents);
76
- continue;
77
- }
78
- const { frontmatter: fm, body } = parsed;
79
- // Claude Code's rule: `name:` IS the agent type, and the filename need not
80
- // match. Absent, the filename stands in — Claude Code requires the field,
81
- // but most files here predate it and must keep loading.
82
- const declared = str(fm.name)?.trim();
83
- if (declared?.includes(RESERVED_IN_TYPE)) {
84
- // Refusing beats silently substituting: the file would otherwise load
85
- // under its filename, so `Agent({subagent_type})` would succeed against
86
- // an agent whose declared identity nothing honoured.
87
- warnIfNew(`Agent file ${path} declares name "${declared}", which contains "${RESERVED_IN_TYPE}" — reserved for `
88
- + "plugin-scoped identifiers. Rename it, or move the label to `display_name:`. Skipping.");
89
- // No `warnSkippedOverride`: this file would have registered under its
90
- // *declared* name, which nothing else can hold (a colon keeps it out of
91
- // the registry), so it shadowed nothing. Passing the filename instead
92
- // would report a substitution of an unrelated agent that never happened.
128
+ warnSkippedOverride(filenameType, agents, warnings);
93
129
  continue;
94
130
  }
95
- // `||`, not `??`: a quoted empty or all-whitespace `name:` would otherwise
96
- // register the agent under the empty type — unspawnable, and it takes the
97
- // filename-derived one down with it.
98
- const name = declared || filenameType;
99
- let thinking;
100
- let fallbackModel;
101
- let advisor;
102
- try {
103
- // AgentConfig uses pi-ai's streaming type (which omits "off"), while
104
- // session settings accept it. Cast only AFTER validating the seven levels.
105
- thinking = parseAliasedString(fm, path, THINKING_FIELDS, THINKING_LEVELS);
106
- fallbackModel = parseAliasedString(fm, path, FALLBACK_MODEL_FIELDS);
107
- advisor = parseAliasedBoolean(fm, path, ADVISOR_FIELDS);
108
- }
109
- catch (err) {
110
- const reason = err instanceof Error ? err.message : String(err);
111
- if (strict)
112
- throw new Error(`${path}: ${reason}`);
113
- warnIfNew(`Skipping agent file ${path}: ${reason}`);
114
- warnSkippedOverride(name, agents);
131
+ addAgent(path, filenameType, parsed, agents, source, strict, warnings);
132
+ }
133
+ }
134
+ async function loadFromDirAsync(dir, agents, source, strict, warnings) {
135
+ let files;
136
+ try {
137
+ asyncReads++;
138
+ files = (await readdir(dir)).filter(f => f.endsWith(".md"));
139
+ }
140
+ catch {
141
+ // Same deliberate skip as the synchronous fallback: the three discovery
142
+ // directories are optional, and an absent one is not a load failure.
143
+ return;
144
+ }
145
+ for (const file of files) {
146
+ const filenameType = basename(file, ".md");
147
+ const path = join(dir, file);
148
+ const parsed = await readAgentFileAsync(path, strict, warnings);
149
+ if (!parsed) {
150
+ warnSkippedOverride(filenameType, agents, warnings);
115
151
  continue;
116
152
  }
117
- const { builtinToolNames, extSelectors } = parseToolsField(fm.tools);
118
- agents.set(name, {
119
- name,
120
- // Only `display_name` now: `name` is the type, and `getConfig` already
121
- // falls back to the type when no label is set — so a Claude Code file
122
- // with `name: code-reviewer` still badges as "code-reviewer".
123
- displayName: str(fm.display_name),
124
- color: str(fm.color),
125
- description: str(fm.description) ?? name,
126
- builtinToolNames,
127
- extSelectors,
128
- disallowedTools: csvListOptional(fm.disallowed_tools),
129
- extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
130
- excludeExtensions: csvListOptional(fm.exclude_extensions),
131
- skills: inheritField(fm.skills ?? fm.inherit_skills),
132
- model: str(fm.model),
133
- fallbackModel,
134
- thinking,
135
- advisor,
136
- maxTurns: nonNegativeInt(fm.max_turns),
137
- persistSession: fm.persist_session != null ? fm.persist_session === true : undefined,
138
- outputTranscript: fm.output_transcript != null ? fm.output_transcript !== false : undefined,
139
- sessionDir: str(fm.session_dir),
140
- allowedSubagents: parseAllowedSubagents(fm.allowed_subagents),
141
- systemPrompt: body.trim(),
142
- promptMode: fm.prompt_mode === "append" ? "append" : "replace",
143
- inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
144
- runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
145
- isolated: fm.isolated != null ? fm.isolated === true : undefined,
146
- memory: parseMemory(fm.memory),
147
- isolation: parseIsolation(fm.isolation),
148
- enabled: fm.enabled !== false, // default true; explicitly false disables
149
- source,
150
- sourcePath: path,
151
- });
153
+ addAgent(path, filenameType, parsed, agents, source, strict, warnings);
152
154
  }
153
155
  }
154
156
  /**
155
- * Read and parse one agent file, or warn and return undefined for the caller to
156
- * skip. One bad file must not take the whole extension down with it — an
157
- * unparseable `.md` used to abort activation, so pi exited before the TUI.
158
- *
159
- * The path is as much of the fix as the recovery: a bare YAML error ("line 2,
160
- * column 14") is unactionable when agents come from three directories at once,
161
- * and the only other symptom is `Unknown agent type`, which reads like a typo.
162
- *
163
- * Under `strict` the same failure rethrows, still naming the path, so callers
164
- * that opted into failing closed stop rather than run a substituted agent.
157
+ * Turn one freshly parsed file into an AgentConfig, applying the current
158
+ * strictness and precedence policy. The parsed frontmatter is raw cache data;
159
+ * every validation, alias conflict and skip decision is rerun here so a strict
160
+ * request never inherits a lenient load's decision.
165
161
  */
162
+ function addAgent(path, filenameType, parsed, agents, source, strict, warnings) {
163
+ const { frontmatter: fm, body } = parsed;
164
+ // Claude Code's rule: `name:` IS the agent type, and the filename need not
165
+ // match. Absent, the filename stands in — Claude Code requires the field,
166
+ // but most files here predate it and must keep loading.
167
+ const declared = str(fm.name)?.trim();
168
+ if (declared?.includes(RESERVED_IN_TYPE)) {
169
+ // Refusing beats silently substituting: the file would otherwise load
170
+ // under its filename, so `Agent({subagent_type})` would succeed against
171
+ // an agent whose declared identity nothing honoured.
172
+ warnIfNew(warnings, `Agent file ${path} declares name "${declared}", which contains "${RESERVED_IN_TYPE}" — reserved for `
173
+ + "plugin-scoped identifiers. Rename it, or move the label to `display_name:`. Skipping.");
174
+ // No `warnSkippedOverride`: this file would have registered under its
175
+ // *declared* name, which nothing else can hold (a colon keeps it out of
176
+ // the registry), so it shadowed nothing. Passing the filename instead
177
+ // would report a substitution of an unrelated agent that never happened.
178
+ return;
179
+ }
180
+ // `||`, not `??`: a quoted empty or all-whitespace `name:` would otherwise
181
+ // register the agent under the empty type — unspawnable, and it takes the
182
+ // filename-derived one down with it.
183
+ const name = declared || filenameType;
184
+ let thinking;
185
+ let fallbackModel;
186
+ let advisor;
187
+ try {
188
+ // AgentConfig uses pi-ai's streaming type (which omits "off"), while
189
+ // session settings accept it. Cast only AFTER validating the seven levels.
190
+ thinking = parseAliasedString(fm, path, THINKING_FIELDS, THINKING_LEVELS, warnings);
191
+ fallbackModel = parseAliasedString(fm, path, FALLBACK_MODEL_FIELDS, undefined, warnings);
192
+ advisor = parseAliasedBoolean(fm, path, ADVISOR_FIELDS, warnings);
193
+ }
194
+ catch (err) {
195
+ const reason = err instanceof Error ? err.message : String(err);
196
+ if (strict)
197
+ throw new Error(`${path}: ${reason}`);
198
+ warnIfNew(warnings, `Skipping agent file ${path}: ${reason}`);
199
+ warnSkippedOverride(name, agents, warnings);
200
+ return;
201
+ }
202
+ const { builtinToolNames, extSelectors } = parseToolsField(fm.tools);
203
+ agents.set(name, {
204
+ name,
205
+ // Only `display_name` now: `name` is the type, and `getConfig` already
206
+ // falls back to the type when no label is set — so a Claude Code file
207
+ // with `name: code-reviewer` still badges as "code-reviewer".
208
+ displayName: str(fm.display_name),
209
+ color: str(fm.color),
210
+ description: str(fm.description) ?? name,
211
+ builtinToolNames,
212
+ extSelectors,
213
+ disallowedTools: csvListOptional(fm.disallowed_tools),
214
+ extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
215
+ excludeExtensions: csvListOptional(fm.exclude_extensions),
216
+ skills: inheritField(fm.skills ?? fm.inherit_skills),
217
+ model: str(fm.model),
218
+ fallbackModel,
219
+ thinking,
220
+ advisor,
221
+ maxTurns: nonNegativeInt(fm.max_turns),
222
+ persistSession: fm.persist_session != null ? fm.persist_session === true : undefined,
223
+ outputTranscript: fm.output_transcript != null ? fm.output_transcript !== false : undefined,
224
+ sessionDir: str(fm.session_dir),
225
+ allowedSubagents: parseAllowedSubagents(fm.allowed_subagents),
226
+ systemPrompt: body.trim(),
227
+ promptMode: fm.prompt_mode === "append" ? "append" : "replace",
228
+ inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
229
+ runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
230
+ isolated: fm.isolated != null ? fm.isolated === true : undefined,
231
+ memory: parseMemory(fm.memory),
232
+ isolation: parseIsolation(fm.isolation),
233
+ enabled: fm.enabled !== false, // default true; explicitly false disables
234
+ source,
235
+ sourcePath: path,
236
+ });
237
+ }
166
238
  /**
167
239
  * Parse an agent file's frontmatter, tolerating a leading UTF-8 BOM.
168
240
  *
@@ -181,16 +253,132 @@ function loadFromDir(dir, agents, source, strict) {
181
253
  export function parseAgentFrontmatter(content) {
182
254
  return parseFrontmatter(content.startsWith("\uFEFF") ? content.slice(1) : content);
183
255
  }
184
- function readAgentFile(path, strict) {
256
+ /**
257
+ * Bounds for the raw parse cache. `bytes` counts both the content used for
258
+ * exact equality and the parsed body retained beside it; it is a storage bound,
259
+ * not a limit on file size (a file larger than the cap simply is not cached).
260
+ */
261
+ export const AGENT_PARSE_CACHE_MAX_ENTRIES = 64;
262
+ export const AGENT_PARSE_CACHE_MAX_BYTES = 2 * 1024 * 1024;
263
+ const parseCache = new Map();
264
+ let parseCacheBytes = 0;
265
+ let parseCount = 0;
266
+ let parseCacheHits = 0;
267
+ let parseEvictions = 0;
268
+ let syncReads = 0;
269
+ let asyncReads = 0;
270
+ const inflightAsyncLoads = new Map();
271
+ /** Operation counts used by the definition-refresh tests. */
272
+ export function getAgentParseCacheStats() {
273
+ return {
274
+ entries: parseCache.size,
275
+ bytes: parseCacheBytes,
276
+ parses: parseCount,
277
+ hits: parseCacheHits,
278
+ evictions: parseEvictions,
279
+ syncReads,
280
+ asyncReads,
281
+ };
282
+ }
283
+ /** Drop retained parses and counters so tests start from a known cache. */
284
+ export function resetAgentParseCache() {
285
+ parseCache.clear();
286
+ parseCacheBytes = 0;
287
+ parseCount = 0;
288
+ parseCacheHits = 0;
289
+ parseEvictions = 0;
290
+ syncReads = 0;
291
+ asyncReads = 0;
292
+ }
293
+ function dropCachedParse(path) {
294
+ const existing = parseCache.get(path);
295
+ if (existing === undefined)
296
+ return;
297
+ parseCache.delete(path);
298
+ parseCacheBytes -= existing.bytes;
299
+ }
300
+ /**
301
+ * Reuse the parse for `content` only when those exact bytes were parsed
302
+ * before. A hit returns a fresh frontmatter object: all later validation reads
303
+ * it, and a shared mutable object would let one load's decisions leak into the
304
+ * next.
305
+ */
306
+ function parseCached(path, content) {
307
+ const cached = parseCache.get(path);
308
+ if (cached !== undefined && cached.content === content) {
309
+ parseCacheHits++;
310
+ // Refresh LRU position without changing retained bytes.
311
+ parseCache.delete(path);
312
+ parseCache.set(path, cached);
313
+ return { frontmatter: structuredClone(cached.frontmatter), body: cached.body };
314
+ }
315
+ if (cached !== undefined)
316
+ dropCachedParse(path);
317
+ parseCount++;
318
+ const parsed = parseAgentFrontmatter(content);
319
+ rememberParsed(path, content, parsed);
320
+ return parsed;
321
+ }
322
+ function rememberParsed(path, content, parsed) {
323
+ dropCachedParse(path);
324
+ const bytes = Buffer.byteLength(content, "utf8") + Buffer.byteLength(parsed.body, "utf8");
325
+ if (bytes > AGENT_PARSE_CACHE_MAX_BYTES)
326
+ return;
327
+ parseCache.set(path, {
328
+ content,
329
+ // The cache owns its own object; the parse returned to this load never
330
+ // aliases it, so no later load can observe a mutation made on the other.
331
+ frontmatter: structuredClone(parsed.frontmatter),
332
+ body: parsed.body,
333
+ bytes,
334
+ });
335
+ parseCacheBytes += bytes;
336
+ while (parseCache.size > AGENT_PARSE_CACHE_MAX_ENTRIES || parseCacheBytes > AGENT_PARSE_CACHE_MAX_BYTES) {
337
+ const oldest = parseCache.keys().next();
338
+ if (oldest.done)
339
+ break;
340
+ parseEvictions++;
341
+ dropCachedParse(oldest.value);
342
+ }
343
+ }
344
+ /** Shared warn/skip outcome for read and parse failures. */
345
+ function agentFileFailure(path, err, strict, warnings) {
346
+ const reason = err instanceof Error ? err.message : String(err);
347
+ if (strict)
348
+ throw new Error(`${path}: ${reason}`);
349
+ warnIfNew(warnings, `Skipping agent file ${path}: ${reason}`);
350
+ return undefined;
351
+ }
352
+ function readAgentFileSync(path, strict, warnings) {
353
+ let content;
185
354
  try {
186
- return parseAgentFrontmatter(readFileSync(path, "utf-8"));
355
+ syncReads++;
356
+ content = readFileSync(path, "utf-8");
187
357
  }
188
358
  catch (err) {
189
- const reason = err instanceof Error ? err.message : String(err);
190
- if (strict)
191
- throw new Error(`${path}: ${reason}`);
192
- warnIfNew(`Skipping agent file ${path}: ${reason}`);
193
- return undefined;
359
+ return agentFileFailure(path, err, strict, warnings);
360
+ }
361
+ try {
362
+ return parseCached(path, content);
363
+ }
364
+ catch (err) {
365
+ return agentFileFailure(path, err, strict, warnings);
366
+ }
367
+ }
368
+ async function readAgentFileAsync(path, strict, warnings) {
369
+ let content;
370
+ try {
371
+ asyncReads++;
372
+ content = await readFile(path, "utf-8");
373
+ }
374
+ catch (err) {
375
+ return agentFileFailure(path, err, strict, warnings);
376
+ }
377
+ try {
378
+ return parseCached(path, content);
379
+ }
380
+ catch (err) {
381
+ return agentFileFailure(path, err, strict, warnings);
194
382
  }
195
383
  }
196
384
  /**
@@ -198,31 +386,40 @@ function readAgentFile(path, strict) {
198
386
  * pointing at a *different* file — its own prompt, model and tools. Nothing
199
387
  * downstream can flag that: unlike an unknown type, the `Agent` call succeeds.
200
388
  */
201
- function warnSkippedOverride(name, agents) {
389
+ function warnSkippedOverride(name, agents, warnings) {
202
390
  const surviving = agents.get(name);
203
391
  // Nothing shadowed, or what it shadowed is disabled: dispatch refuses the type
204
392
  // either way (see resolveEnabledTypeIn), so there is no substitution to report.
205
393
  if (!surviving?.sourcePath || surviving.enabled === false)
206
394
  return;
207
- warnIfNew(`Agent "${name}" now loads from ${surviving.sourcePath} instead`);
395
+ warnIfNew(warnings, `Agent "${name}" now loads from ${surviving.sourcePath} instead`);
208
396
  }
209
397
  let warnedLastLoad = new Set();
210
- let warnedThisLoad = new Set();
398
+ function beginLoadWarnings() {
399
+ return { previous: warnedLastLoad, current: new Set() };
400
+ }
401
+ function commitLoadWarnings(warnings) {
402
+ warnedLastLoad = warnings.current;
403
+ }
211
404
  /**
212
405
  * Agents reload on activation and again on every `Agent` call, so an unchanged
213
406
  * problem would re-warn all session — over a painted TUI, since pi does not
214
407
  * redirect console output. Compare against the previous load rather than every
215
408
  * load ever, so a file that is fixed and then broken again still reports.
409
+ *
410
+ * The set is per load, not module-wide: an async load may interleave with
411
+ * another refresh or with a synchronous fallback between reads, and sharing
412
+ * one accumulator would let one load suppress another's diagnostics.
216
413
  */
217
- function warnIfNew(message) {
218
- warnedThisLoad.add(message);
219
- if (warnedLastLoad.has(message))
414
+ function warnIfNew(warnings, message) {
415
+ warnings.current.add(message);
416
+ if (warnings.previous.has(message))
220
417
  return;
221
418
  console.warn(`[pi-subagents] ${message}`);
222
419
  }
223
420
  // ---- Field parsers ----
224
421
  /** Validate every explicit alias before resolving precedence; a bad value must not inherit. */
225
- function parseAliasedString(fm, path, fields, allowedValues) {
422
+ function parseAliasedString(fm, path, fields, allowedValues, warnings) {
226
423
  const entries = fields.filter(field => Object.hasOwn(fm, field)).map(field => {
227
424
  const value = fm[field];
228
425
  if (typeof value !== "string" || !value.trim() || (allowedValues && !allowedValues.includes(value))) {
@@ -237,7 +434,7 @@ function parseAliasedString(fm, path, fields, allowedValues) {
237
434
  if (!selected)
238
435
  return undefined;
239
436
  if (entries.some(entry => entry.value !== selected.value)) {
240
- warnIfNew(`Agent file ${path} has conflicting ${fields[0]} aliases: `
437
+ warnIfNew(warnings, `Agent file ${path} has conflicting ${fields[0]} aliases: `
241
438
  + `${entries.map(entry => `${entry.field}: ${entry.value}`).join(", ")}. `
242
439
  + `Using ${selected.field}: ${selected.value}; precedence: ${fields.join(" > ")}.`);
243
440
  }
@@ -253,7 +450,7 @@ function parseAliasedString(fm, path, fields, allowedValues) {
253
450
  * only real booleans turns those misspellings into a skip-the-file diagnostic
254
451
  * instead of a silently inherited default.
255
452
  */
256
- function parseAliasedBoolean(fm, path, fields) {
453
+ function parseAliasedBoolean(fm, path, fields, warnings) {
257
454
  const entries = fields.filter(field => Object.hasOwn(fm, field)).map(field => {
258
455
  const value = fm[field];
259
456
  if (typeof value !== "boolean") {
@@ -266,7 +463,7 @@ function parseAliasedBoolean(fm, path, fields) {
266
463
  if (!selected)
267
464
  return undefined;
268
465
  if (entries.some(entry => entry.value !== selected.value)) {
269
- warnIfNew(`Agent file ${path} has conflicting ${fields[0]} aliases: `
466
+ warnIfNew(warnings, `Agent file ${path} has conflicting ${fields[0]} aliases: `
270
467
  + `${entries.map(entry => `${entry.field}: ${entry.value}`).join(", ")}. `
271
468
  + `Using ${selected.field}: ${selected.value}; precedence: ${fields.join(" > ")}.`);
272
469
  }
@@ -3,5 +3,5 @@
3
3
  *
4
4
  * These are always available but can be overridden by user .md files with the same name.
5
5
  */
6
- import type { AgentConfig } from "./types.js";
6
+ import type { AgentConfig } from "./types.ts";
7
7
  export declare const DEFAULT_AGENTS: Map<string, AgentConfig>;
package/dist/env.d.ts CHANGED
@@ -2,5 +2,5 @@
2
2
  * env.ts — Detect environment info (git, platform) for subagent system prompts.
3
3
  */
4
4
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
- import type { EnvInfo } from "./types.js";
5
+ import type { EnvInfo } from "./types.ts";
6
6
  export declare function detectEnv(pi: ExtensionAPI, cwd: string): Promise<EnvInfo>;
@@ -56,3 +56,9 @@ export interface SubagentIssueRecord {
56
56
  * the record is on disk; callers may ignore the promise.
57
57
  */
58
58
  export declare function logSubagentIssue(record: SubagentIssueRecord): Promise<void>;
59
+ /**
60
+ * Await every queued diagnostic append. Used by cleanup before it may remove the
61
+ * shared aggregate: an unresolved write would otherwise recreate the file after
62
+ * the unlink. Best-effort like the log itself; never rejects.
63
+ */
64
+ export declare function flushIssueLog(): Promise<void>;
package/dist/error-log.js CHANGED
@@ -166,3 +166,11 @@ export function logSubagentIssue(record) {
166
166
  writeChain = writeChain.then(() => appendIssueLine(path, line));
167
167
  return writeChain;
168
168
  }
169
+ /**
170
+ * Await every queued diagnostic append. Used by cleanup before it may remove the
171
+ * shared aggregate: an unresolved write would otherwise recreate the file after
172
+ * the unlink. Best-effort like the log itself; never rejects.
173
+ */
174
+ export function flushIssueLog() {
175
+ return writeChain;
176
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * force-main-model.ts — Session-only "subagents off" switch behind `/subagents`.
3
+ *
4
+ * When on, every later spawn is a main-model twin: agent-type pins, caller
5
+ * overrides and scheduled-job models all give way to the parent context's model,
6
+ * so delegation never leaves the model the session is actually running.
7
+ *
8
+ * State lives in `process.env` rather than a module variable: subagent sessions
9
+ * bind their own copy of this extension, and only process env reaches a child
10
+ * constructed after the flip (the same channel as `PI_SUBAGENT_CHILD`). Workflow
11
+ * worker threads receive a copy at creation.
12
+ *
13
+ * "Session-only" means the pi process: the flag survives `/new` and `/reload`
14
+ * (same process, new session), reaches anything the bash tool spawns while set,
15
+ * and dies with pi — nothing is ever written to subagents.json.
16
+ */
17
+ export declare const FORCE_MAIN_MODEL_ENV = "PI_SUBAGENTS_FORCE_MAIN_MODEL";
18
+ /** Live read, so a `/subagents` flip applies to the very next spawn — nested included. */
19
+ export declare function isForceMainModel(): boolean;
20
+ /** Set or clear the flag. Session-only: process env never outlives pi. */
21
+ export declare function setForceMainModel(on: boolean): void;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * force-main-model.ts — Session-only "subagents off" switch behind `/subagents`.
3
+ *
4
+ * When on, every later spawn is a main-model twin: agent-type pins, caller
5
+ * overrides and scheduled-job models all give way to the parent context's model,
6
+ * so delegation never leaves the model the session is actually running.
7
+ *
8
+ * State lives in `process.env` rather than a module variable: subagent sessions
9
+ * bind their own copy of this extension, and only process env reaches a child
10
+ * constructed after the flip (the same channel as `PI_SUBAGENT_CHILD`). Workflow
11
+ * worker threads receive a copy at creation.
12
+ *
13
+ * "Session-only" means the pi process: the flag survives `/new` and `/reload`
14
+ * (same process, new session), reaches anything the bash tool spawns while set,
15
+ * and dies with pi — nothing is ever written to subagents.json.
16
+ */
17
+ export const FORCE_MAIN_MODEL_ENV = "PI_SUBAGENTS_FORCE_MAIN_MODEL";
18
+ /** Live read, so a `/subagents` flip applies to the very next spawn — nested included. */
19
+ export function isForceMainModel() {
20
+ return process.env[FORCE_MAIN_MODEL_ENV] === "1";
21
+ }
22
+ /** Set or clear the flag. Session-only: process env never outlives pi. */
23
+ export function setForceMainModel(on) {
24
+ if (on)
25
+ process.env[FORCE_MAIN_MODEL_ENV] = "1";
26
+ else
27
+ delete process.env[FORCE_MAIN_MODEL_ENV];
28
+ }