@timmyjl12/pi-subagents 0.0.0-stage → 0.20.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.
Files changed (218) hide show
  1. package/CHANGELOG.md +827 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1079 -2
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +18 -0
  9. package/dist/active-agents-prompt.js +34 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +123 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +485 -0
  17. package/dist/agent-manager.js +1380 -0
  18. package/dist/agent-runner.d.ts +319 -0
  19. package/dist/agent-runner.js +1128 -0
  20. package/dist/agent-types.d.ts +119 -0
  21. package/dist/agent-types.js +286 -0
  22. package/dist/child-context.d.ts +15 -0
  23. package/dist/child-context.js +181 -0
  24. package/dist/child-session-shutdown.d.ts +3 -0
  25. package/dist/child-session-shutdown.js +48 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +66 -0
  29. package/dist/cross-extension-rpc.js +138 -0
  30. package/dist/custom-agents.d.ts +54 -0
  31. package/dist/custom-agents.js +386 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +125 -0
  34. package/dist/enabled-models.d.ts +49 -0
  35. package/dist/enabled-models.js +145 -0
  36. package/dist/env.d.ts +6 -0
  37. package/dist/env.js +28 -0
  38. package/dist/error-log.d.ts +58 -0
  39. package/dist/error-log.js +168 -0
  40. package/dist/group-join.d.ts +32 -0
  41. package/dist/group-join.js +116 -0
  42. package/dist/index.d.ts +52 -0
  43. package/dist/index.js +3896 -0
  44. package/dist/invocation-config.d.ts +137 -0
  45. package/dist/invocation-config.js +129 -0
  46. package/dist/memory.d.ts +53 -0
  47. package/dist/memory.js +165 -0
  48. package/dist/mention-clone.d.ts +87 -0
  49. package/dist/mention-clone.js +178 -0
  50. package/dist/mention.d.ts +81 -0
  51. package/dist/mention.js +131 -0
  52. package/dist/model-resolver.d.ts +36 -0
  53. package/dist/model-resolver.js +95 -0
  54. package/dist/model-scope.d.ts +49 -0
  55. package/dist/model-scope.js +48 -0
  56. package/dist/nested-tools.d.ts +55 -0
  57. package/dist/nested-tools.js +299 -0
  58. package/dist/output-diagnostics.d.ts +11 -0
  59. package/dist/output-diagnostics.js +64 -0
  60. package/dist/output-file.d.ts +53 -0
  61. package/dist/output-file.js +248 -0
  62. package/dist/prompts.d.ts +61 -0
  63. package/dist/prompts.js +94 -0
  64. package/dist/recovery.d.ts +56 -0
  65. package/dist/recovery.js +341 -0
  66. package/dist/schedule-store.d.ts +44 -0
  67. package/dist/schedule-store.js +210 -0
  68. package/dist/schedule.d.ts +109 -0
  69. package/dist/schedule.js +359 -0
  70. package/dist/settings.d.ts +360 -0
  71. package/dist/settings.js +251 -0
  72. package/dist/skill-loader.d.ts +24 -0
  73. package/dist/skill-loader.js +93 -0
  74. package/dist/standalone-fallback.d.ts +30 -0
  75. package/dist/standalone-fallback.js +239 -0
  76. package/dist/status-note.d.ts +61 -0
  77. package/dist/status-note.js +85 -0
  78. package/dist/structured-output.d.ts +61 -0
  79. package/dist/structured-output.js +112 -0
  80. package/dist/terminal-progress.d.ts +115 -0
  81. package/dist/terminal-progress.js +206 -0
  82. package/dist/types.d.ts +382 -0
  83. package/dist/types.js +5 -0
  84. package/dist/ui/agent-mention.d.ts +82 -0
  85. package/dist/ui/agent-mention.js +187 -0
  86. package/dist/ui/agent-widget.d.ts +235 -0
  87. package/dist/ui/agent-widget.js +652 -0
  88. package/dist/ui/conversation-viewer.d.ts +105 -0
  89. package/dist/ui/conversation-viewer.js +540 -0
  90. package/dist/ui/fleet-list.d.ts +183 -0
  91. package/dist/ui/fleet-list.js +494 -0
  92. package/dist/ui/fleet-overlay.d.ts +172 -0
  93. package/dist/ui/fleet-overlay.js +691 -0
  94. package/dist/ui/native-transcript.d.ts +33 -0
  95. package/dist/ui/native-transcript.js +230 -0
  96. package/dist/ui/schedule-menu.d.ts +16 -0
  97. package/dist/ui/schedule-menu.js +94 -0
  98. package/dist/ui/select-item.d.ts +27 -0
  99. package/dist/ui/select-item.js +34 -0
  100. package/dist/ui/tool-progress.d.ts +22 -0
  101. package/dist/ui/tool-progress.js +56 -0
  102. package/dist/ui/viewer-keys.d.ts +20 -0
  103. package/dist/ui/viewer-keys.js +17 -0
  104. package/dist/ui/workflow-card.d.ts +175 -0
  105. package/dist/ui/workflow-card.js +332 -0
  106. package/dist/ui/workflow-dialog.d.ts +305 -0
  107. package/dist/ui/workflow-dialog.js +843 -0
  108. package/dist/ui/workflow-menu.d.ts +60 -0
  109. package/dist/ui/workflow-menu.js +147 -0
  110. package/dist/usage.d.ts +135 -0
  111. package/dist/usage.js +120 -0
  112. package/dist/workflow/collisions.d.ts +95 -0
  113. package/dist/workflow/collisions.js +88 -0
  114. package/dist/workflow/entry.d.ts +32 -0
  115. package/dist/workflow/entry.js +29 -0
  116. package/dist/workflow/host.d.ts +62 -0
  117. package/dist/workflow/host.js +363 -0
  118. package/dist/workflow/journal.d.ts +97 -0
  119. package/dist/workflow/journal.js +120 -0
  120. package/dist/workflow/json-schema.d.ts +51 -0
  121. package/dist/workflow/json-schema.js +111 -0
  122. package/dist/workflow/meta.d.ts +67 -0
  123. package/dist/workflow/meta.js +317 -0
  124. package/dist/workflow/progress.d.ts +224 -0
  125. package/dist/workflow/progress.js +361 -0
  126. package/dist/workflow/runtime.d.ts +334 -0
  127. package/dist/workflow/runtime.js +830 -0
  128. package/dist/workflow/saved.d.ts +90 -0
  129. package/dist/workflow/saved.js +203 -0
  130. package/dist/workflow/task.d.ts +136 -0
  131. package/dist/workflow/task.js +207 -0
  132. package/dist/workflow/tool-description.d.ts +38 -0
  133. package/dist/workflow/tool-description.js +199 -0
  134. package/dist/workflow/worker-source.d.ts +47 -0
  135. package/dist/workflow/worker-source.js +778 -0
  136. package/dist/worktree.d.ts +52 -0
  137. package/dist/worktree.js +164 -0
  138. package/dist/xml.d.ts +10 -0
  139. package/dist/xml.js +12 -0
  140. package/docs/FORK.md +40 -0
  141. package/docs/recovery.md +62 -0
  142. package/docs/rpc.md +189 -0
  143. package/docs/workflows.md +437 -0
  144. package/examples/agent-tool-description.md +43 -0
  145. package/examples/workflows/compose.js +51 -0
  146. package/examples/workflows/fan-out-audit.js +47 -0
  147. package/examples/workflows/gated-fix.js +60 -0
  148. package/examples/workflows/lib/count-child.js +27 -0
  149. package/examples/workflows/review-panel.js +63 -0
  150. package/examples/workflows/structured-findings.js +78 -0
  151. package/package.json +75 -6
  152. package/src/abortable.ts +43 -0
  153. package/src/active-agents-prompt.ts +39 -0
  154. package/src/advisor-status.ts +74 -0
  155. package/src/agent-color.ts +161 -0
  156. package/src/agent-file-toggle.ts +273 -0
  157. package/src/agent-manager.ts +1601 -0
  158. package/src/agent-runner.ts +1372 -0
  159. package/src/agent-types.ts +345 -0
  160. package/src/child-context.ts +173 -0
  161. package/src/child-session-shutdown.ts +46 -0
  162. package/src/context.ts +58 -0
  163. package/src/cross-extension-rpc.ts +198 -0
  164. package/src/custom-agents.ts +417 -0
  165. package/src/default-agents.ts +129 -0
  166. package/src/enabled-models.ts +180 -0
  167. package/src/env.ts +33 -0
  168. package/src/error-log.ts +193 -0
  169. package/src/group-join.ts +141 -0
  170. package/src/index.ts +4218 -0
  171. package/src/invocation-config.ts +230 -0
  172. package/src/memory.ts +179 -0
  173. package/src/mention-clone.ts +221 -0
  174. package/src/mention.ts +141 -0
  175. package/src/model-resolver.ts +118 -0
  176. package/src/model-scope.ts +70 -0
  177. package/src/nested-tools.ts +422 -0
  178. package/src/output-diagnostics.ts +68 -0
  179. package/src/output-file.ts +258 -0
  180. package/src/prompts.ts +151 -0
  181. package/src/recovery.ts +320 -0
  182. package/src/schedule-store.ts +201 -0
  183. package/src/schedule.ts +386 -0
  184. package/src/settings.ts +587 -0
  185. package/src/skill-loader.ts +102 -0
  186. package/src/standalone-fallback.ts +195 -0
  187. package/src/status-note.ts +90 -0
  188. package/src/structured-output.ts +130 -0
  189. package/src/terminal-progress.ts +215 -0
  190. package/src/types.ts +394 -0
  191. package/src/ui/agent-mention.ts +216 -0
  192. package/src/ui/agent-widget.ts +732 -0
  193. package/src/ui/conversation-viewer.ts +523 -0
  194. package/src/ui/fleet-list.ts +563 -0
  195. package/src/ui/fleet-overlay.ts +847 -0
  196. package/src/ui/native-transcript.ts +220 -0
  197. package/src/ui/schedule-menu.ts +105 -0
  198. package/src/ui/select-item.ts +45 -0
  199. package/src/ui/tool-progress.ts +67 -0
  200. package/src/ui/viewer-keys.ts +39 -0
  201. package/src/ui/workflow-card.ts +470 -0
  202. package/src/ui/workflow-dialog.ts +1115 -0
  203. package/src/ui/workflow-menu.ts +193 -0
  204. package/src/usage.ts +167 -0
  205. package/src/workflow/collisions.ts +123 -0
  206. package/src/workflow/entry.ts +47 -0
  207. package/src/workflow/host.ts +404 -0
  208. package/src/workflow/journal.ts +164 -0
  209. package/src/workflow/json-schema.ts +128 -0
  210. package/src/workflow/meta.ts +325 -0
  211. package/src/workflow/progress.ts +550 -0
  212. package/src/workflow/runtime.ts +1219 -0
  213. package/src/workflow/saved.ts +217 -0
  214. package/src/workflow/task.ts +302 -0
  215. package/src/workflow/tool-description.ts +200 -0
  216. package/src/workflow/worker-source.ts +781 -0
  217. package/src/worktree.ts +205 -0
  218. package/src/xml.ts +13 -0
@@ -0,0 +1,129 @@
1
+ /**
2
+ * default-agents.ts — Embedded default agent configurations.
3
+ *
4
+ * These are always available but can be overridden by user .md files with the same name.
5
+ */
6
+
7
+ import type { AgentConfig } from "./types.js";
8
+
9
+ const READ_ONLY_TOOLS = ["read", "bash", "grep", "find", "ls"];
10
+
11
+ export const DEFAULT_AGENTS: Map<string, AgentConfig> = new Map([
12
+ [
13
+ "general-purpose",
14
+ {
15
+ name: "general-purpose",
16
+ displayName: "Agent",
17
+ description: "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",
18
+ // builtinToolNames omitted — means "all available tools" (resolved at lookup time)
19
+ // inheritContext / runInBackground / isolated omitted — strategy fields, callers decide per-call.
20
+ // Setting them to false would lock callsite intent (see resolveAgentInvocationConfig in invocation-config.ts).
21
+ extensions: true,
22
+ skills: true,
23
+ systemPrompt: "",
24
+ promptMode: "append",
25
+ isDefault: true,
26
+ },
27
+ ],
28
+ [
29
+ "Explore",
30
+ {
31
+ name: "Explore",
32
+ displayName: "Explore",
33
+ description: "Fast read-only search agent for locating code. Use it to find files by pattern (eg. \"src/components/**/*.tsx\"), grep for symbols or keywords (eg. \"API endpoints\"), or answer \"where is X defined / which files reference Y.\" Do NOT use it for code review, design-doc auditing, cross-file consistency checks, or open-ended analysis — it reads excerpts rather than whole files and will miss content past its read window. When calling, specify search breadth: \"quick\" for a single targeted lookup, \"medium\" for moderate exploration, or \"very thorough\" to search across multiple locations and naming conventions.",
34
+ builtinToolNames: READ_ONLY_TOOLS,
35
+ extensions: true,
36
+ skills: true,
37
+ // Fast/cheap model for read-only search. Provider-preferred but resilient:
38
+ // an exact provider/id match wins; otherwise the same model id resolves
39
+ // on another available provider (date-suffix/dot-dash tolerant). Only as
40
+ // a last resort — and only because this is a built-in default, never for
41
+ // a user-authored .md pin — the parent model is used with a visible
42
+ // notice. See resolvePinnedModel in invocation-config.ts.
43
+ model: "anthropic/claude-haiku-4-5",
44
+ systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
45
+ You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
46
+ Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.
47
+
48
+ You are STRICTLY PROHIBITED from:
49
+ - Creating new files
50
+ - Modifying existing files
51
+ - Deleting files
52
+ - Moving or copying files
53
+ - Creating temporary files anywhere, including /tmp
54
+ - Using redirect operators (>, >>, |) or heredocs to write to files
55
+ - Running ANY commands that change system state
56
+
57
+ Use Bash ONLY for read-only operations: ls, git status, git log, git diff, find, cat, head, tail.
58
+
59
+ # Tool Usage
60
+ - Use the find tool for file pattern matching (NOT the bash find command)
61
+ - Use the grep tool for content search (NOT bash grep/rg command)
62
+ - Use the read tool for reading files (NOT bash cat/head/tail)
63
+ - Use Bash ONLY for read-only operations
64
+ - Make independent tool calls in parallel for efficiency
65
+ - Adapt search approach based on thoroughness level specified
66
+
67
+ # Output
68
+ - Use absolute file paths in all references
69
+ - Report findings as regular messages
70
+ - Do not use emojis
71
+ - Be thorough and precise`,
72
+ promptMode: "replace",
73
+ isDefault: true,
74
+ },
75
+ ],
76
+ [
77
+ "Plan",
78
+ {
79
+ name: "Plan",
80
+ displayName: "Plan",
81
+ description: "Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs.",
82
+ builtinToolNames: READ_ONLY_TOOLS,
83
+ extensions: true,
84
+ skills: true,
85
+ systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
86
+ You are a software architect and planning specialist.
87
+ Your role is EXCLUSIVELY to explore the codebase and design implementation plans.
88
+ You do NOT have access to file editing tools — attempting to edit files will fail.
89
+
90
+ You are STRICTLY PROHIBITED from:
91
+ - Creating new files
92
+ - Modifying existing files
93
+ - Deleting files
94
+ - Moving or copying files
95
+ - Creating temporary files anywhere, including /tmp
96
+ - Using redirect operators (>, >>, |) or heredocs to write to files
97
+ - Running ANY commands that change system state
98
+
99
+ # Planning Process
100
+ 1. Understand requirements
101
+ 2. Explore thoroughly (read files, find patterns, understand architecture)
102
+ 3. Design solution based on your assigned perspective
103
+ 4. Detail the plan with step-by-step implementation strategy
104
+
105
+ # Requirements
106
+ - Consider trade-offs and architectural decisions
107
+ - Identify dependencies and sequencing
108
+ - Anticipate potential challenges
109
+ - Follow existing patterns where appropriate
110
+
111
+ # Tool Usage
112
+ - Use the find tool for file pattern matching (NOT the bash find command)
113
+ - Use the grep tool for content search (NOT bash grep/rg command)
114
+ - Use the read tool for reading files (NOT bash cat/head/tail)
115
+ - Use Bash ONLY for read-only operations
116
+
117
+ # Output Format
118
+ - Use absolute file paths
119
+ - Do not use emojis
120
+ - End your response with:
121
+
122
+ ### Critical Files for Implementation
123
+ List 3-5 files most critical for implementing this plan:
124
+ - /absolute/path/to/file.ts - [Brief reason]`,
125
+ promptMode: "replace",
126
+ isDefault: true,
127
+ },
128
+ ],
129
+ ]);
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Reads `enabledModels` from pi's settings (global `<agentDir>/settings.json`
3
+ * + project-local `<cwd>/.pi/settings.json`, project wins) and resolves
4
+ * entries to concrete `provider/modelId` keys for scope validation.
5
+ *
6
+ * **Project overrides global**, mirroring pi's own `SettingsManager`
7
+ * deep-merge behavior and matching the precedence we use for our own
8
+ * `subagents.json` settings (see `src/settings.ts:loadSettings`). If
9
+ * project file has `enabledModels` set, it wholly replaces global's
10
+ * (array fields are replaced, not concatenated).
11
+ *
12
+ * **Limited subset of upstream's resolveModelScope.** We support exact
13
+ * `provider/modelId` matching only. Upstream (pi-coding-agent's
14
+ * `core/model-resolver.ts`) additionally supports glob patterns
15
+ * (`*sonnet*`, `anthropic/*`), bare model IDs without provider, and
16
+ * thinking-level suffixes (`provider/*:high`). Those forms are silently
17
+ * ignored here.
18
+ *
19
+ * In practice, pi's `/scoped-models` picker writes exact `provider/modelId`
20
+ * entries, so the limitation is invisible for users who configure scope
21
+ * through pi's UI. Hand-edited settings using globs or bare IDs will
22
+ * produce an empty allowed set (scope check becomes a no-op).
23
+ *
24
+ * Example:
25
+ * enabledModels = ["anthropic/claude-sonnet-4-6", "anthropic/claude-opus-4-6"]
26
+ * → resolves to { "anthropic/claude-sonnet-4-6", "anthropic/claude-opus-4-6" }
27
+ */
28
+
29
+ import { existsSync, readFileSync, statSync } from "node:fs";
30
+ import { join } from "node:path";
31
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
32
+ import type { ModelEntry } from "./model-resolver.js";
33
+
34
+ /** Minimal registry shape — only the methods resolveEnabledModels actually calls. */
35
+ export interface ModelRegistryRef {
36
+ getAll(): unknown[];
37
+ getAvailable?(): unknown[];
38
+ }
39
+
40
+ /** Paths to pi's settings.json files: [project, global] (project takes precedence). */
41
+ function settingsPaths(cwd: string): [project: string, global: string] {
42
+ return [
43
+ join(cwd, ".pi", "settings.json"),
44
+ join(getAgentDir(), "settings.json"),
45
+ ];
46
+ }
47
+
48
+ /** Read `enabledModels` from a single settings.json file. Undefined when missing or absent. */
49
+ function readField(path: string): string[] | undefined {
50
+ if (!existsSync(path)) return undefined;
51
+ try {
52
+ const raw = JSON.parse(readFileSync(path, "utf-8"));
53
+ if (Array.isArray(raw?.enabledModels)) return raw.enabledModels as string[];
54
+ } catch {
55
+ /* corrupt file — silent */
56
+ }
57
+ return undefined;
58
+ }
59
+
60
+ /**
61
+ * Read enabledModels from pi's settings — project-local overrides global.
62
+ * Mirrors pi's SettingsManager deep-merge for the `enabledModels` field
63
+ * (and matches our own loadSettings precedence in src/settings.ts).
64
+ * Returns undefined when neither file has the field.
65
+ */
66
+ export function readEnabledModels(cwd: string): string[] | undefined {
67
+ const [project, global] = settingsPaths(cwd);
68
+ return readField(project) ?? readField(global);
69
+ }
70
+
71
+ /**
72
+ * Resolve enabledModels patterns → Set<"provider/modelId"> (lowercase keys).
73
+ *
74
+ * Only exact `provider/modelId` patterns are matched (case-insensitive).
75
+ * Patterns without a slash, with glob characters, or with a `:thinking`
76
+ * suffix are silently dropped. See module-level docstring for rationale.
77
+ *
78
+ * Cache: keyed on JSON.stringify(patterns) + mtime/size of *both*
79
+ * project and global settings.json files. Re-resolves when either file
80
+ * changes or the patterns argument differs.
81
+ *
82
+ * Returns undefined when no patterns are provided or no patterns match
83
+ * (scope check becomes a no-op at the call site).
84
+ */
85
+
86
+ // Module-level cache — invalidated when either settings.json changes or patterns differ.
87
+ let cachedAllowed: Set<string> | undefined;
88
+ let cachedHash = "";
89
+ let cachedPatternsKey = "";
90
+
91
+ /** mtime+size hash of one file, or "missing" if absent. */
92
+ function hashOf(path: string): string {
93
+ try {
94
+ const s = statSync(path);
95
+ return `${s.mtimeMs}-${s.size}`;
96
+ } catch {
97
+ return "missing";
98
+ }
99
+ }
100
+
101
+ export function resolveEnabledModels(
102
+ patterns: string[] | undefined,
103
+ registry: ModelRegistryRef,
104
+ cwd: string = process.cwd(),
105
+ ): Set<string> | undefined {
106
+ // Fast path: check cache (stat both project and global settings.json files)
107
+ const patternsKey = JSON.stringify(patterns);
108
+ const [project, global] = settingsPaths(cwd);
109
+ const fileHash = `${hashOf(project)};${hashOf(global)}`;
110
+
111
+ if (fileHash === cachedHash && patternsKey === cachedPatternsKey) {
112
+ return cachedAllowed;
113
+ }
114
+
115
+ // Cache miss — resolve
116
+ if (!patterns || patterns.length === 0) {
117
+ cachedHash = fileHash;
118
+ cachedPatternsKey = patternsKey;
119
+ cachedAllowed = undefined;
120
+ return undefined;
121
+ }
122
+
123
+ const available = (registry.getAvailable?.() ?? registry.getAll()) as ModelEntry[];
124
+ const allowed = new Set<string>();
125
+
126
+ for (const pattern of patterns) {
127
+ const trimmed = pattern.trim();
128
+ if (!trimmed) continue; // skip empty/whitespace
129
+ resolveExact(trimmed, available, allowed);
130
+ }
131
+
132
+ const result = allowed.size > 0 ? allowed : undefined;
133
+ cachedHash = fileHash;
134
+ cachedPatternsKey = patternsKey;
135
+ cachedAllowed = result;
136
+ return result;
137
+ }
138
+
139
+
140
+
141
+ /**
142
+ * True when `model` is in the allowed set. Centralizes the key format
143
+ * (`provider/id` lowercase) so callers don't have to reproduce it —
144
+ * both set-building (resolveExact) and lookup go through `modelKey`.
145
+ */
146
+ export function isModelInScope(
147
+ model: { provider: string; id: string },
148
+ allowed: Set<string>,
149
+ ): boolean {
150
+ return allowed.has(modelKey(model));
151
+ }
152
+
153
+ /** Canonical lowercase `provider/id` key for the allowed set. */
154
+ function modelKey(model: { provider: string; id: string }): string {
155
+ return `${model.provider}/${model.id}`.toLowerCase();
156
+ }
157
+
158
+ /**
159
+ * Resolve exact model pattern. Example: "google/gemma-4-31b-it".
160
+ */
161
+ function resolveExact(
162
+ pattern: string,
163
+ available: ModelEntry[],
164
+ allowed: Set<string>,
165
+ ): void {
166
+ // "provider/modelId" — exact (colon is part of id, not split)
167
+ const slashIdx = pattern.indexOf("/");
168
+ if (slashIdx === -1) return; // bare modelId not supported
169
+
170
+ const provider = pattern.slice(0, slashIdx).toLowerCase();
171
+ const modelId = pattern.slice(slashIdx + 1).toLowerCase();
172
+ const exact = available.find(
173
+ m => m.provider.toLowerCase() === provider && m.id.toLowerCase() === modelId,
174
+ );
175
+ if (exact) {
176
+ allowed.add(modelKey(exact));
177
+ }
178
+ }
179
+
180
+
package/src/env.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * env.ts — Detect environment info (git, platform) for subagent system prompts.
3
+ */
4
+
5
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import type { EnvInfo } from "./types.js";
7
+
8
+ export async function detectEnv(pi: ExtensionAPI, cwd: string): Promise<EnvInfo> {
9
+ let isGitRepo = false;
10
+ let branch = "";
11
+
12
+ try {
13
+ const result = await pi.exec("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 5000 });
14
+ isGitRepo = result.code === 0 && result.stdout.trim() === "true";
15
+ } catch {
16
+ // Not a git repo or git not installed
17
+ }
18
+
19
+ if (isGitRepo) {
20
+ try {
21
+ const result = await pi.exec("git", ["branch", "--show-current"], { cwd, timeout: 5000 });
22
+ branch = result.code === 0 ? result.stdout.trim() : "unknown";
23
+ } catch {
24
+ branch = "unknown";
25
+ }
26
+ }
27
+
28
+ return {
29
+ isGitRepo,
30
+ branch,
31
+ platform: process.platform,
32
+ };
33
+ }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * error-log.ts — Persistent cross-session aggregate log for pi-subagents issues.
3
+ *
4
+ * The per-agent `.output` transcripts (temp dir, cleared on reboot) record
5
+ * per-attempt diagnostics for one session. This module complements them with
6
+ * ONE durable JSONL file that aggregates issue events from every session, so
7
+ * recurring provider failures, spawn rejections, and fallback switches can be
8
+ * tracked over time:
9
+ *
10
+ * <agentDir>/pi-subagents/agent-errors.jsonl
11
+ *
12
+ * The base is the GLOBAL agentDir (getAgentDir(), honoring $PI_CODING_AGENT_DIR),
13
+ * deliberately not configCwd-scoped: sessions span projects, and a per-project
14
+ * log would fragment exactly the cross-session history this file exists for.
15
+ *
16
+ * One JSON object per line, `ts` (ISO 8601) first. Every free-text field is
17
+ * sanitized through sanitizeDiagnosticText (imported, not duplicated — it owns
18
+ * credential/URL/header redaction). Raw prompts are never logged: prompt text
19
+ * belongs to the per-session transcript, not this aggregate.
20
+ */
21
+
22
+ import { randomBytes } from "node:crypto";
23
+ import { chmodSync, mkdirSync } from "node:fs";
24
+ import { appendFile, open, rename, stat, unlink, writeFile } from "node:fs/promises";
25
+ import { join } from "node:path";
26
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
27
+ import { sanitizeDiagnosticText } from "./output-diagnostics.js";
28
+
29
+ export type SubagentIssueKind =
30
+ | "attempt_error" // assistant message finalized with stopReason error/aborted
31
+ | "retry_start" // auto-retry scheduled (attempt, maxAttempts, delayMs)
32
+ | "retry_end" // auto-retry settled (attempt, success, finalError)
33
+ | "standalone_fallback" // child-local fallback switch: success | blocked | failed
34
+ | "spawn_rejected"; // refused before a session existed (bad type, model, scope)
35
+
36
+ export interface SubagentIssueRecord {
37
+ kind: SubagentIssueKind;
38
+ agentId?: string;
39
+ agentType?: string;
40
+ /** Correlation id used where no agentId exists at the call site (recovery layer). */
41
+ sessionId?: string;
42
+ provider?: string;
43
+ model?: string;
44
+ responseModel?: string;
45
+ stopReason?: string;
46
+ messageTimestamp?: number;
47
+ attempt?: number;
48
+ maxAttempts?: number;
49
+ delayMs?: number;
50
+ success?: boolean;
51
+ errorMessage?: string;
52
+ finalError?: string;
53
+ requestedType?: string;
54
+ outcome?: "success" | "blocked" | "failed";
55
+ reason?: string;
56
+ from?: { provider?: string; model?: string };
57
+ to?: { provider?: string; model?: string };
58
+ }
59
+
60
+ /** Prose that can carry prover payloads: full treatment (header/body/URL redaction). */
61
+ const FREE_TEXT = ["errorMessage", "finalError", "reason"] as const;
62
+ /** Short identifiers/labels: bounded but not free prose. */
63
+ const SHORT_TEXT = ["provider", "model", "responseModel", "agentType", "requestedType"] as const;
64
+
65
+ const MAX_BYTES = 10 * 1024 * 1024; // ~10MB: start of the trim check
66
+ const KEEP_BYTES = 5 * 1024 * 1024; // retain the most recent ~5MB on trim
67
+
68
+ // Rename hardening mirrors schedule-store: Windows reports EPERM/EBUSY/EACCES
69
+ // while AV or an indexer holds the target.
70
+ const RENAME_RETRIES = 5;
71
+ const RENAME_RETRY_MS = 20;
72
+
73
+ // Resolved lazily on first use and prepared (mkdir + chmod) once per agentDir.
74
+ // Keyed on the resolved dir — not cached unconditionally — because tests
75
+ // redirect $PI_CODING_AGENT_DIR between cases; a real process never changes it.
76
+ let prepared: { agentDir: string; path: string } | undefined;
77
+
78
+ function errorLogPath(): string {
79
+ const agentDir = getAgentDir();
80
+ if (!agentDir) throw new Error("agent dir unavailable");
81
+ if (prepared?.agentDir === agentDir) return prepared.path;
82
+ const dir = join(agentDir, "pi-subagents");
83
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
84
+ // Same perms pattern as sessionTaskDir in output-file.ts: owner-only past
85
+ // umask; chmod throws on some Windows filesystems and is a no-op there.
86
+ // Failure lands in the swallowed catch of logSubagentIssue either way.
87
+ try {
88
+ chmodSync(dir, 0o700);
89
+ } catch (err) {
90
+ if (process.platform !== "win32") throw err;
91
+ }
92
+ const path = join(dir, "agent-errors.jsonl");
93
+ prepared = { agentDir, path };
94
+ return path;
95
+ }
96
+
97
+ /** Trim an oversized log to its most recent ~5MB, reading only the kept tail. */
98
+ function errorCode(e: unknown): string | undefined {
99
+ const code = (e as { code?: unknown } | null)?.code;
100
+ return typeof code === "string" ? code : undefined;
101
+ }
102
+
103
+ /** rename with a bounded retry: Windows reports EPERM/EBUSY/EACCES while AV or an indexer holds the target. */
104
+ async function renameWithRetry(from: string, to: string): Promise<void> {
105
+ for (let attempt = 0; ; attempt++) {
106
+ try {
107
+ await rename(from, to);
108
+ return;
109
+ } catch (e) {
110
+ const code = errorCode(e);
111
+ const transient = code === "EPERM" || code === "EBUSY" || code === "EACCES";
112
+ if (!transient || attempt >= RENAME_RETRIES) {
113
+ try { await unlink(from); } catch { /* best effort: the rename error below is the one that matters */ }
114
+ throw e;
115
+ }
116
+ await new Promise((resolve) => setTimeout(resolve, RENAME_RETRY_MS * (attempt + 1)));
117
+ }
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Trim an oversized log to its most recent ~5MB. Reads only the tail it keeps
123
+ * — never the whole file — and replaces the log via temp+rename, so a failure
124
+ * leaves the original intact rather than a torn half-rotated file.
125
+ */
126
+ async function trimIfOversized(path: string): Promise<void> {
127
+ let size: number;
128
+ try {
129
+ size = (await stat(path)).size;
130
+ } catch {
131
+ return; // No file yet (first write) — nothing to trim.
132
+ }
133
+ if (size <= MAX_BYTES) return;
134
+ // "~" because the keep window is cut at a byte boundary, mid-line. Drop
135
+ // everything through the first newline of the kept slice so the remainder
136
+ // stays valid JSONL.
137
+ const readLen = Math.min(size, KEEP_BYTES);
138
+ const buffer = Buffer.alloc(readLen);
139
+ const handle = await open(path, "r");
140
+ try {
141
+ await handle.read(buffer, 0, readLen, size - readLen);
142
+ } finally {
143
+ await handle.close();
144
+ }
145
+ const firstBreak = buffer.indexOf(0x0a);
146
+ const tail = firstBreak >= 0 ? buffer.subarray(firstBreak + 1) : buffer;
147
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
148
+ await writeFile(tmp, tail);
149
+ await renameWithRetry(tmp, path);
150
+ }
151
+
152
+ /** Serialized write chain: appends and the (rare) trim never interleave. */
153
+ let writeChain: Promise<void> = Promise.resolve();
154
+
155
+ async function appendIssueLine(path: string, line: string): Promise<void> {
156
+ try {
157
+ await trimIfOversized(path);
158
+ await appendFile(path, line, "utf8");
159
+ } catch { /* diagnostics must never break a session */ }
160
+ }
161
+
162
+ /**
163
+ * Append one issue event. Best-effort and off the event loop: the record is
164
+ * built synchronously, then written through the serialized chain — the trim
165
+ * check never blocks the session, and every failure (unwritable dir, full
166
+ * disk, locked file) is swallowed without even console noise. Resolves once
167
+ * the record is on disk; callers may ignore the promise.
168
+ */
169
+ export function logSubagentIssue(record: SubagentIssueRecord): Promise<void> {
170
+ let line: string;
171
+ let path: string;
172
+ try {
173
+ const entry: Record<string, unknown> = { ts: new Date().toISOString(), ...record };
174
+ for (const key of FREE_TEXT) {
175
+ if (typeof record[key] === "string") entry[key] = sanitizeDiagnosticText(record[key]);
176
+ }
177
+ for (const key of SHORT_TEXT) {
178
+ if (typeof record[key] === "string") entry[key] = sanitizeDiagnosticText(record[key], 256);
179
+ }
180
+ for (const side of ["from", "to"] as const) {
181
+ const model = record[side];
182
+ if (!model) continue;
183
+ entry[side] = {
184
+ ...(typeof model.provider === "string" ? { provider: sanitizeDiagnosticText(model.provider, 256) } : {}),
185
+ ...(typeof model.model === "string" ? { model: sanitizeDiagnosticText(model.model, 256) } : {}),
186
+ };
187
+ }
188
+ path = errorLogPath();
189
+ line = JSON.stringify(entry) + "\n";
190
+ } catch { /* diagnostics must never break a session */ return Promise.resolve(); }
191
+ writeChain = writeChain.then(() => appendIssueLine(path, line));
192
+ return writeChain;
193
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * group-join.ts — Manages grouped background agent completion notifications.
3
+ *
4
+ * Instead of each agent individually nudging the main agent on completion,
5
+ * agents in a group are held until all complete (or a timeout fires),
6
+ * then a single consolidated notification is sent.
7
+ */
8
+
9
+ import type { AgentRecord } from "./types.js";
10
+
11
+ export type DeliveryCallback = (records: AgentRecord[], partial: boolean) => void;
12
+
13
+ interface AgentGroup {
14
+ groupId: string;
15
+ agentIds: Set<string>;
16
+ completedRecords: Map<string, AgentRecord>;
17
+ timeoutHandle?: ReturnType<typeof setTimeout>;
18
+ delivered: boolean;
19
+ /** Shorter timeout for stragglers after a partial delivery. */
20
+ isStraggler: boolean;
21
+ }
22
+
23
+ /** Default timeout: 30s after first completion in a group. */
24
+ const DEFAULT_TIMEOUT = 30_000;
25
+ /** Straggler re-batch timeout: 15s. */
26
+ const STRAGGLER_TIMEOUT = 15_000;
27
+
28
+ export class GroupJoinManager {
29
+ private groups = new Map<string, AgentGroup>();
30
+ private agentToGroup = new Map<string, string>();
31
+
32
+ constructor(
33
+ private deliverCb: DeliveryCallback,
34
+ private groupTimeout = DEFAULT_TIMEOUT,
35
+ ) {}
36
+
37
+ /** Register a group of agent IDs that should be joined. */
38
+ registerGroup(groupId: string, agentIds: string[]): void {
39
+ const group: AgentGroup = {
40
+ groupId,
41
+ agentIds: new Set(agentIds),
42
+ completedRecords: new Map(),
43
+ delivered: false,
44
+ isStraggler: false,
45
+ };
46
+ this.groups.set(groupId, group);
47
+ for (const id of agentIds) {
48
+ this.agentToGroup.set(id, groupId);
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Called when an agent completes.
54
+ * Returns:
55
+ * - 'pass' — agent is not grouped, caller should send individual nudge
56
+ * - 'held' — result held, waiting for group completion
57
+ * - 'delivered' — this completion triggered the group notification
58
+ */
59
+ onAgentComplete(record: AgentRecord): 'delivered' | 'held' | 'pass' {
60
+ const groupId = this.agentToGroup.get(record.id);
61
+ if (!groupId) return 'pass';
62
+
63
+ const group = this.groups.get(groupId);
64
+ if (!group || group.delivered) return 'pass';
65
+
66
+ group.completedRecords.set(record.id, record);
67
+
68
+ // All done — deliver immediately
69
+ if (group.completedRecords.size >= group.agentIds.size) {
70
+ this.deliver(group, false);
71
+ return 'delivered';
72
+ }
73
+
74
+ // First completion in this batch — start timeout
75
+ if (!group.timeoutHandle) {
76
+ const timeout = group.isStraggler ? STRAGGLER_TIMEOUT : this.groupTimeout;
77
+ group.timeoutHandle = setTimeout(() => {
78
+ this.onTimeout(group);
79
+ }, timeout);
80
+ }
81
+
82
+ return 'held';
83
+ }
84
+
85
+ private onTimeout(group: AgentGroup): void {
86
+ if (group.delivered) return;
87
+ group.timeoutHandle = undefined;
88
+
89
+ // Partial delivery — some agents still running
90
+ const remaining = new Set<string>();
91
+ for (const id of group.agentIds) {
92
+ if (!group.completedRecords.has(id)) remaining.add(id);
93
+ }
94
+
95
+ // Clean up agentToGroup for delivered agents (they won't complete again)
96
+ for (const id of group.completedRecords.keys()) {
97
+ this.agentToGroup.delete(id);
98
+ }
99
+
100
+ // Deliver what we have
101
+ this.deliverCb([...group.completedRecords.values()], true);
102
+
103
+ // Set up straggler group for remaining agents
104
+ group.completedRecords.clear();
105
+ group.agentIds = remaining;
106
+ group.isStraggler = true;
107
+ // Timeout will be started when the next straggler completes
108
+ }
109
+
110
+ private deliver(group: AgentGroup, partial: boolean): void {
111
+ if (group.timeoutHandle) {
112
+ clearTimeout(group.timeoutHandle);
113
+ group.timeoutHandle = undefined;
114
+ }
115
+ group.delivered = true;
116
+ this.deliverCb([...group.completedRecords.values()], partial);
117
+ this.cleanupGroup(group.groupId);
118
+ }
119
+
120
+ private cleanupGroup(groupId: string): void {
121
+ const group = this.groups.get(groupId);
122
+ if (!group) return;
123
+ for (const id of group.agentIds) {
124
+ this.agentToGroup.delete(id);
125
+ }
126
+ this.groups.delete(groupId);
127
+ }
128
+
129
+ /** Check if an agent is in a group. */
130
+ isGrouped(agentId: string): boolean {
131
+ return this.agentToGroup.has(agentId);
132
+ }
133
+
134
+ dispose(): void {
135
+ for (const group of this.groups.values()) {
136
+ if (group.timeoutHandle) clearTimeout(group.timeoutHandle);
137
+ }
138
+ this.groups.clear();
139
+ this.agentToGroup.clear();
140
+ }
141
+ }