@clanker-code/pi-subagents 0.10.5

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 (130) hide show
  1. package/.plans/PLAN-next-changes.md +183 -0
  2. package/.plans/README.md +14 -0
  3. package/AGENTS.md +31 -0
  4. package/CHANGELOG.md +583 -0
  5. package/CLAUDE.md +1 -0
  6. package/LICENSE +21 -0
  7. package/README.md +630 -0
  8. package/RELEASE.md +39 -0
  9. package/dist/abort-resend.d.ts +35 -0
  10. package/dist/abort-resend.js +71 -0
  11. package/dist/agent-details.d.ts +17 -0
  12. package/dist/agent-details.js +22 -0
  13. package/dist/agent-manager.d.ts +132 -0
  14. package/dist/agent-manager.js +493 -0
  15. package/dist/agent-runner.d.ts +165 -0
  16. package/dist/agent-runner.js +732 -0
  17. package/dist/agent-tool-description.d.ts +9 -0
  18. package/dist/agent-tool-description.js +147 -0
  19. package/dist/agent-types.d.ts +60 -0
  20. package/dist/agent-types.js +157 -0
  21. package/dist/context.d.ts +12 -0
  22. package/dist/context.js +56 -0
  23. package/dist/cross-extension-rpc.d.ts +46 -0
  24. package/dist/cross-extension-rpc.js +76 -0
  25. package/dist/custom-agents.d.ts +14 -0
  26. package/dist/custom-agents.js +149 -0
  27. package/dist/default-agents.d.ts +7 -0
  28. package/dist/default-agents.js +119 -0
  29. package/dist/enabled-models.d.ts +49 -0
  30. package/dist/enabled-models.js +145 -0
  31. package/dist/env.d.ts +6 -0
  32. package/dist/env.js +28 -0
  33. package/dist/group-join.d.ts +32 -0
  34. package/dist/group-join.js +116 -0
  35. package/dist/index.d.ts +36 -0
  36. package/dist/index.js +1918 -0
  37. package/dist/invocation-config.d.ts +25 -0
  38. package/dist/invocation-config.js +19 -0
  39. package/dist/memory.d.ts +49 -0
  40. package/dist/memory.js +151 -0
  41. package/dist/model-resolver.d.ts +19 -0
  42. package/dist/model-resolver.js +62 -0
  43. package/dist/notifications.d.ts +6 -0
  44. package/dist/notifications.js +107 -0
  45. package/dist/output-file.d.ts +24 -0
  46. package/dist/output-file.js +86 -0
  47. package/dist/peek.d.ts +37 -0
  48. package/dist/peek.js +121 -0
  49. package/dist/prompts.d.ts +40 -0
  50. package/dist/prompts.js +95 -0
  51. package/dist/schedule-store.d.ts +38 -0
  52. package/dist/schedule-store.js +155 -0
  53. package/dist/schedule.d.ts +109 -0
  54. package/dist/schedule.js +338 -0
  55. package/dist/settings.d.ts +135 -0
  56. package/dist/settings.js +168 -0
  57. package/dist/skill-loader.d.ts +24 -0
  58. package/dist/skill-loader.js +93 -0
  59. package/dist/status-note.d.ts +13 -0
  60. package/dist/status-note.js +24 -0
  61. package/dist/types.d.ts +184 -0
  62. package/dist/types.js +7 -0
  63. package/dist/ui/agent-tool-rendering.d.ts +34 -0
  64. package/dist/ui/agent-tool-rendering.js +154 -0
  65. package/dist/ui/agent-widget-tree.d.ts +33 -0
  66. package/dist/ui/agent-widget-tree.js +130 -0
  67. package/dist/ui/agent-widget.d.ts +156 -0
  68. package/dist/ui/agent-widget.js +408 -0
  69. package/dist/ui/conversation-viewer.d.ts +47 -0
  70. package/dist/ui/conversation-viewer.js +290 -0
  71. package/dist/ui/menu-select.d.ts +20 -0
  72. package/dist/ui/menu-select.js +46 -0
  73. package/dist/ui/schedule-menu.d.ts +16 -0
  74. package/dist/ui/schedule-menu.js +99 -0
  75. package/dist/ui/viewer-keys.d.ts +20 -0
  76. package/dist/ui/viewer-keys.js +17 -0
  77. package/dist/usage.d.ts +50 -0
  78. package/dist/usage.js +49 -0
  79. package/dist/wait.d.ts +10 -0
  80. package/dist/wait.js +37 -0
  81. package/dist/worktree.d.ts +45 -0
  82. package/dist/worktree.js +160 -0
  83. package/docs/design/default-extension-tool-exposure.md +56 -0
  84. package/docs/superpowers/plans/2026-06-19-recursive-subagent-widget.md +600 -0
  85. package/docs/superpowers/specs/2026-06-19-recursive-subagent-widget-design.md +189 -0
  86. package/examples/agent-tool-description.md +45 -0
  87. package/package.json +56 -0
  88. package/reviews/proposal-structured-output-schema.md +135 -0
  89. package/reviews/recursive-subagent-widget-preview-rev2.png +0 -0
  90. package/reviews/recursive-subagent-widget-preview.html +137 -0
  91. package/reviews/recursive-subagent-widget-preview.png +0 -0
  92. package/reviews/subagent-features-comparison.md +350 -0
  93. package/src/abort-resend.ts +75 -0
  94. package/src/agent-details.ts +31 -0
  95. package/src/agent-manager.ts +596 -0
  96. package/src/agent-runner.ts +872 -0
  97. package/src/agent-tool-description.ts +163 -0
  98. package/src/agent-types.ts +189 -0
  99. package/src/context.ts +58 -0
  100. package/src/cross-extension-rpc.ts +122 -0
  101. package/src/custom-agents.ts +160 -0
  102. package/src/default-agents.ts +123 -0
  103. package/src/enabled-models.ts +180 -0
  104. package/src/env.ts +33 -0
  105. package/src/group-join.ts +141 -0
  106. package/src/index.ts +2115 -0
  107. package/src/invocation-config.ts +42 -0
  108. package/src/memory.ts +165 -0
  109. package/src/model-resolver.ts +81 -0
  110. package/src/notifications.ts +120 -0
  111. package/src/output-file.ts +96 -0
  112. package/src/peek.ts +155 -0
  113. package/src/prompts.ts +129 -0
  114. package/src/schedule-store.ts +153 -0
  115. package/src/schedule.ts +365 -0
  116. package/src/settings.ts +289 -0
  117. package/src/skill-loader.ts +102 -0
  118. package/src/status-note.ts +25 -0
  119. package/src/types.ts +195 -0
  120. package/src/ui/agent-tool-rendering.ts +175 -0
  121. package/src/ui/agent-widget-tree.ts +169 -0
  122. package/src/ui/agent-widget.ts +497 -0
  123. package/src/ui/conversation-viewer.ts +297 -0
  124. package/src/ui/menu-select.ts +68 -0
  125. package/src/ui/schedule-menu.ts +105 -0
  126. package/src/ui/viewer-keys.ts +39 -0
  127. package/src/usage.ts +60 -0
  128. package/src/wait.ts +44 -0
  129. package/src/worktree.ts +191 -0
  130. package/vitest.config.ts +25 -0
@@ -0,0 +1,160 @@
1
+ /**
2
+ * custom-agents.ts — Load user-defined agents from project (.pi/agents/) and global ($PI_CODING_AGENT_DIR/agents/, default ~/.pi/agent/agents/) locations.
3
+ */
4
+
5
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
6
+ import { basename, join } from "node:path";
7
+ import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
8
+ import { BUILTIN_TOOL_NAMES } from "./agent-types.js";
9
+ import type { AgentConfig, MemoryScope, ThinkingLevel } from "./types.js";
10
+
11
+ /**
12
+ * Scan for custom agent .md files from multiple locations.
13
+ * Discovery hierarchy (higher priority wins):
14
+ * 1. Project: <cwd>/.pi/agents/*.md
15
+ * 2. Global: $PI_CODING_AGENT_DIR/agents/*.md (default: ~/.pi/agent/agents/*.md)
16
+ *
17
+ * Project-level agents override global ones with the same name.
18
+ * Any name is allowed — names matching defaults (e.g. "Explore") override them.
19
+ */
20
+ export function loadCustomAgents(cwd: string): Map<string, AgentConfig> {
21
+ const globalDir = join(getAgentDir(), "agents");
22
+ const projectDir = join(cwd, ".pi", "agents");
23
+
24
+ const agents = new Map<string, AgentConfig>();
25
+ loadFromDir(globalDir, agents, "global"); // lower priority
26
+ loadFromDir(projectDir, agents, "project"); // higher priority (overwrites)
27
+ return agents;
28
+ }
29
+
30
+ /** Load agent configs from a directory into the map. */
31
+ function loadFromDir(dir: string, agents: Map<string, AgentConfig>, source: "project" | "global"): void {
32
+ if (!existsSync(dir)) return;
33
+
34
+ let files: string[];
35
+ try {
36
+ files = readdirSync(dir).filter(f => f.endsWith(".md"));
37
+ } catch {
38
+ return;
39
+ }
40
+
41
+ for (const file of files) {
42
+ const name = basename(file, ".md");
43
+
44
+ let content: string;
45
+ try {
46
+ content = readFileSync(join(dir, file), "utf-8");
47
+ } catch {
48
+ continue;
49
+ }
50
+
51
+ const { frontmatter: fm, body } = parseFrontmatter<Record<string, unknown>>(content);
52
+
53
+ const { builtinToolNames, extSelectors } = parseToolsField(fm.tools);
54
+
55
+ agents.set(name, {
56
+ name,
57
+ displayName: str(fm.display_name),
58
+ description: str(fm.description) ?? name,
59
+ builtinToolNames,
60
+ extSelectors,
61
+ disallowedTools: csvListOptional(fm.disallowed_tools),
62
+ extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
63
+ excludeExtensions: csvListOptional(fm.exclude_extensions),
64
+ skills: inheritField(fm.skills ?? fm.inherit_skills),
65
+ model: str(fm.model),
66
+ thinking: str(fm.thinking) as ThinkingLevel | undefined,
67
+ maxTurns: nonNegativeInt(fm.max_turns),
68
+ systemPrompt: body.trim(),
69
+ promptMode: fm.prompt_mode === "append" ? "append" : "replace",
70
+ inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
71
+ // Parsed for compatibility, but ignored at spawn time — this fork always runs in the background.
72
+ runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
73
+ isolated: fm.isolated != null ? fm.isolated === true : undefined,
74
+ memory: parseMemory(fm.memory),
75
+ isolation: fm.isolation === "worktree" ? "worktree" : undefined,
76
+ enabled: fm.enabled !== false, // default true; explicitly false disables
77
+ source,
78
+ });
79
+ }
80
+ }
81
+
82
+ // ---- Field parsers ----
83
+ // All follow the same convention: omitted → default, "none"/empty → nothing, value → exact.
84
+
85
+ /** Extract a string or undefined. */
86
+ function str(val: unknown): string | undefined {
87
+ return typeof val === "string" ? val : undefined;
88
+ }
89
+
90
+ /** Extract a non-negative integer or undefined. 0 means unlimited for max_turns. */
91
+ function nonNegativeInt(val: unknown): number | undefined {
92
+ return typeof val === "number" && val >= 0 ? val : undefined;
93
+ }
94
+
95
+ /**
96
+ * Parse a raw CSV field value into items, or undefined if absent/empty/"none".
97
+ */
98
+ function parseCsvField(val: unknown): string[] | undefined {
99
+ if (val === undefined || val === null) return undefined;
100
+ const s = String(val).trim();
101
+ if (!s || s === "none") return undefined;
102
+ const items = s.split(",").map(t => t.trim()).filter(Boolean);
103
+ return items.length > 0 ? items : undefined;
104
+ }
105
+
106
+ /**
107
+ * Parse a comma-separated list field with defaults.
108
+ * omitted → defaults; "none"/empty → []; csv → listed items.
109
+ */
110
+ function csvList(val: unknown, defaults: string[]): string[] {
111
+ if (val === undefined || val === null) return defaults;
112
+ return parseCsvField(val) ?? [];
113
+ }
114
+
115
+ /**
116
+ * Partition the `tools:` CSV into the built-in tool allowlist and raw `ext:` selectors.
117
+ * `*` (and the case-insensitive alias `all`, for `tools: all`) expands to all
118
+ * built-ins; plain entries are built-in names; `ext:` entries are extension-tool
119
+ * selectors parsed later by the runner. omitted → all built-ins, no selectors.
120
+ * `tools:` present with only `ext:` entries → zero built-ins (use `*`).
121
+ */
122
+ function parseToolsField(val: unknown): { builtinToolNames: string[]; extSelectors: string[] | undefined } {
123
+ const entries = csvList(val, BUILTIN_TOOL_NAMES);
124
+ const isWildcard = (e: string) => e === "*" || e.toLowerCase() === "all";
125
+ const hasWildcard = entries.some(isWildcard);
126
+ const plain = entries.filter(e => !isWildcard(e) && !e.startsWith("ext:"));
127
+ const extEntries = entries.filter(e => e.startsWith("ext:"));
128
+ return {
129
+ builtinToolNames: hasWildcard ? [...new Set([...BUILTIN_TOOL_NAMES, ...plain])] : plain,
130
+ extSelectors: extEntries.length > 0 ? extEntries : undefined,
131
+ };
132
+ }
133
+
134
+ /**
135
+ * Parse an optional comma-separated list field.
136
+ * omitted → undefined; "none"/empty → undefined; csv → listed items.
137
+ */
138
+ function csvListOptional(val: unknown): string[] | undefined {
139
+ return parseCsvField(val);
140
+ }
141
+
142
+ /**
143
+ * Parse a memory scope field.
144
+ * omitted → undefined; "user"/"project"/"local" → MemoryScope.
145
+ */
146
+ function parseMemory(val: unknown): MemoryScope | undefined {
147
+ if (val === "user" || val === "project" || val === "local") return val;
148
+ return undefined;
149
+ }
150
+
151
+ /**
152
+ * Parse an inherit field (extensions, skills).
153
+ * omitted/true → true (inherit all); false/"none"/empty → false; csv → listed names.
154
+ */
155
+ function inheritField(val: unknown): true | string[] | false {
156
+ if (val === undefined || val === null || val === true) return true;
157
+ if (val === false || val === "none") return false;
158
+ const items = csvList(val, []);
159
+ return items.length > 0 ? items : false;
160
+ }
@@ -0,0 +1,123 @@
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
+ model: "anthropic/claude-haiku-4-5-20251001",
38
+ systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
39
+ You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
40
+ Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.
41
+
42
+ You are STRICTLY PROHIBITED from:
43
+ - Creating new files
44
+ - Modifying existing files
45
+ - Deleting files
46
+ - Moving or copying files
47
+ - Creating temporary files anywhere, including /tmp
48
+ - Using redirect operators (>, >>, |) or heredocs to write to files
49
+ - Running ANY commands that change system state
50
+
51
+ Use Bash ONLY for read-only operations: ls, git status, git log, git diff, find, cat, head, tail.
52
+
53
+ # Tool Usage
54
+ - Use the find tool for file pattern matching (NOT the bash find command)
55
+ - Use the grep tool for content search (NOT bash grep/rg command)
56
+ - Use the read tool for reading files (NOT bash cat/head/tail)
57
+ - Use Bash ONLY for read-only operations
58
+ - Make independent tool calls in parallel for efficiency
59
+ - Adapt search approach based on thoroughness level specified
60
+
61
+ # Output
62
+ - Use absolute file paths in all references
63
+ - Report findings as regular messages
64
+ - Do not use emojis
65
+ - Be thorough and precise`,
66
+ promptMode: "replace",
67
+ isDefault: true,
68
+ },
69
+ ],
70
+ [
71
+ "Plan",
72
+ {
73
+ name: "Plan",
74
+ displayName: "Plan",
75
+ 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.",
76
+ builtinToolNames: READ_ONLY_TOOLS,
77
+ extensions: true,
78
+ skills: true,
79
+ systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
80
+ You are a software architect and planning specialist.
81
+ Your role is EXCLUSIVELY to explore the codebase and design implementation plans.
82
+ You do NOT have access to file editing tools — attempting to edit files will fail.
83
+
84
+ You are STRICTLY PROHIBITED from:
85
+ - Creating new files
86
+ - Modifying existing files
87
+ - Deleting files
88
+ - Moving or copying files
89
+ - Creating temporary files anywhere, including /tmp
90
+ - Using redirect operators (>, >>, |) or heredocs to write to files
91
+ - Running ANY commands that change system state
92
+
93
+ # Planning Process
94
+ 1. Understand requirements
95
+ 2. Explore thoroughly (read files, find patterns, understand architecture)
96
+ 3. Design solution based on your assigned perspective
97
+ 4. Detail the plan with step-by-step implementation strategy
98
+
99
+ # Requirements
100
+ - Consider trade-offs and architectural decisions
101
+ - Identify dependencies and sequencing
102
+ - Anticipate potential challenges
103
+ - Follow existing patterns where appropriate
104
+
105
+ # Tool Usage
106
+ - Use the find tool for file pattern matching (NOT the bash find command)
107
+ - Use the grep tool for content search (NOT bash grep/rg command)
108
+ - Use the read tool for reading files (NOT bash cat/head/tail)
109
+ - Use Bash ONLY for read-only operations
110
+
111
+ # Output Format
112
+ - Use absolute file paths
113
+ - Do not use emojis
114
+ - End your response with:
115
+
116
+ ### Critical Files for Implementation
117
+ List 3-5 files most critical for implementing this plan:
118
+ - /absolute/path/to/file.ts - [Brief reason]`,
119
+ promptMode: "replace",
120
+ isDefault: true,
121
+ },
122
+ ],
123
+ ]);
@@ -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,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
+ }