@esso0428/pi-subagents 0.15.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 (98) hide show
  1. package/CHANGELOG.md +638 -0
  2. package/CONTRIBUTING.md +68 -0
  3. package/LICENSE +21 -0
  4. package/README.md +745 -0
  5. package/SECURITY.md +95 -0
  6. package/dist/agent-manager.d.ts +144 -0
  7. package/dist/agent-manager.js +542 -0
  8. package/dist/agent-runner.d.ts +212 -0
  9. package/dist/agent-runner.js +850 -0
  10. package/dist/agent-types.d.ts +67 -0
  11. package/dist/agent-types.js +168 -0
  12. package/dist/context.d.ts +12 -0
  13. package/dist/context.js +56 -0
  14. package/dist/cross-extension-rpc.d.ts +46 -0
  15. package/dist/cross-extension-rpc.js +76 -0
  16. package/dist/custom-agents.d.ts +17 -0
  17. package/dist/custom-agents.js +156 -0
  18. package/dist/default-agents.d.ts +7 -0
  19. package/dist/default-agents.js +122 -0
  20. package/dist/enabled-models.d.ts +49 -0
  21. package/dist/enabled-models.js +145 -0
  22. package/dist/env.d.ts +6 -0
  23. package/dist/env.js +28 -0
  24. package/dist/group-join.d.ts +32 -0
  25. package/dist/group-join.js +116 -0
  26. package/dist/index.d.ts +16 -0
  27. package/dist/index.js +2209 -0
  28. package/dist/invocation-config.d.ts +22 -0
  29. package/dist/invocation-config.js +15 -0
  30. package/dist/memory.d.ts +53 -0
  31. package/dist/memory.js +165 -0
  32. package/dist/model-resolver.d.ts +19 -0
  33. package/dist/model-resolver.js +80 -0
  34. package/dist/nico-overrides.d.ts +53 -0
  35. package/dist/nico-overrides.js +169 -0
  36. package/dist/output-file.d.ts +24 -0
  37. package/dist/output-file.js +101 -0
  38. package/dist/prompts.d.ts +32 -0
  39. package/dist/prompts.js +73 -0
  40. package/dist/schedule-store.d.ts +38 -0
  41. package/dist/schedule-store.js +155 -0
  42. package/dist/schedule.d.ts +109 -0
  43. package/dist/schedule.js +338 -0
  44. package/dist/settings.d.ts +141 -0
  45. package/dist/settings.js +162 -0
  46. package/dist/skill-loader.d.ts +24 -0
  47. package/dist/skill-loader.js +93 -0
  48. package/dist/status-note.d.ts +13 -0
  49. package/dist/status-note.js +24 -0
  50. package/dist/types.d.ts +197 -0
  51. package/dist/types.js +5 -0
  52. package/dist/ui/agent-widget.d.ts +160 -0
  53. package/dist/ui/agent-widget.js +484 -0
  54. package/dist/ui/conversation-viewer.d.ts +57 -0
  55. package/dist/ui/conversation-viewer.js +354 -0
  56. package/dist/ui/fleet-list.d.ts +106 -0
  57. package/dist/ui/fleet-list.js +345 -0
  58. package/dist/ui/schedule-menu.d.ts +16 -0
  59. package/dist/ui/schedule-menu.js +95 -0
  60. package/dist/ui/viewer-keys.d.ts +20 -0
  61. package/dist/ui/viewer-keys.js +17 -0
  62. package/dist/usage.d.ts +50 -0
  63. package/dist/usage.js +49 -0
  64. package/dist/worktree.d.ts +45 -0
  65. package/dist/worktree.js +160 -0
  66. package/examples/agent-tool-description.md +42 -0
  67. package/package.json +56 -0
  68. package/src/agent-manager.ts +631 -0
  69. package/src/agent-runner.ts +1014 -0
  70. package/src/agent-types.ts +202 -0
  71. package/src/context.ts +58 -0
  72. package/src/cross-extension-rpc.ts +122 -0
  73. package/src/custom-agents.ts +167 -0
  74. package/src/default-agents.ts +126 -0
  75. package/src/enabled-models.ts +180 -0
  76. package/src/env.ts +33 -0
  77. package/src/group-join.ts +141 -0
  78. package/src/index.ts +2400 -0
  79. package/src/invocation-config.ts +40 -0
  80. package/src/memory.ts +179 -0
  81. package/src/model-resolver.ts +100 -0
  82. package/src/nico-overrides.ts +235 -0
  83. package/src/output-file.ts +110 -0
  84. package/src/prompts.ts +99 -0
  85. package/src/schedule-store.ts +153 -0
  86. package/src/schedule.ts +365 -0
  87. package/src/settings.ts +288 -0
  88. package/src/skill-loader.ts +102 -0
  89. package/src/status-note.ts +25 -0
  90. package/src/types.ts +208 -0
  91. package/src/ui/agent-widget.ts +566 -0
  92. package/src/ui/conversation-viewer.ts +362 -0
  93. package/src/ui/fleet-list.ts +380 -0
  94. package/src/ui/schedule-menu.ts +104 -0
  95. package/src/ui/viewer-keys.ts +39 -0
  96. package/src/usage.ts +60 -0
  97. package/src/worktree.ts +191 -0
  98. package/vitest.config.ts +18 -0
@@ -0,0 +1,288 @@
1
+ // Persistence for pi-subagents operational settings.
2
+ // - Global: ~/.pi/agent/subagents.json (via getAgentDir()) — manual defaults, never written here
3
+ // - Project: <cwd>/.pi/subagents.json — written by /agents → Settings; overrides global on load
4
+
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
7
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
8
+ import type { JoinMode, WidgetMode } from "./types.js";
9
+
10
+ export interface SubagentsSettings {
11
+ maxConcurrent?: number;
12
+ /**
13
+ * 0 = unlimited — the extension's single source of truth for that convention:
14
+ * `normalizeMaxTurns()` in agent-runner.ts treats 0 → `undefined`, and the
15
+ * `/agents` → Settings input prompt explicitly says "0 = unlimited".
16
+ */
17
+ defaultMaxTurns?: number;
18
+ graceTurns?: number;
19
+ defaultJoinMode?: JoinMode;
20
+ /**
21
+ * Master switch for the schedule subagent feature. Defaults to `true`.
22
+ * When `false`: the `Agent` tool's `schedule` param + its guideline are
23
+ * stripped from the tool spec at registration (zero LLM-context cost), the
24
+ * scheduler doesn't bind to the session, and the `/agents → Scheduled jobs`
25
+ * menu entry is hidden. Schema-level removal applies at extension load
26
+ * (next pi session); runtime menu/runtime-fire short-circuit is immediate.
27
+ */
28
+ schedulingEnabled?: boolean;
29
+ /**
30
+ * When true, the effective model of each subagent spawn is validated
31
+ * against `enabledModels` from pi's settings — both global
32
+ * (`<agentDir>/settings.json`) and project-local (`<cwd>/.pi/settings.json`),
33
+ * with project overriding global (mirrors pi's SettingsManager deep-merge).
34
+ *
35
+ * scopeModels guards against runtime LLM choices, not user-level config.
36
+ * Out-of-scope handling reflects this:
37
+ * - Caller-supplied via `Agent({ model: "..." })` (only when frontmatter
38
+ * has no `model:`, since frontmatter is authoritative): hard error
39
+ * returned to the orchestrator, listing the allowed models. The LLM
40
+ * made an explicit out-of-scope choice and gets explicit feedback.
41
+ * - Frontmatter-pinned: warning toast + the pinned model runs. The
42
+ * agent's author/installer chose this; trust it.
43
+ * - Parent-inherited (neither caller nor frontmatter sets a model):
44
+ * warning toast + parent's model runs. The user chose the parent's
45
+ * model when starting the session; trust it.
46
+ *
47
+ * No-op when pi's `enabledModels` is empty or absent — nothing to validate
48
+ * against. Defaults to false: subagents may use any model.
49
+ */
50
+ scopeModels?: boolean;
51
+ /**
52
+ * When true, the three built-in default agents (general-purpose, Explore, Plan)
53
+ * are not registered at startup. User-defined agents from project/global custom
54
+ * agent dirs are completely unaffected — only the hardcoded DEFAULT_AGENTS are suppressed.
55
+ * Defaults to false.
56
+ */
57
+ disableDefaultAgents?: boolean;
58
+ /**
59
+ * Which Agent tool description the LLM sees. "full" (default) is the rich
60
+ * Claude Code-style prompt; "compact" is a ~75% smaller version (one-line
61
+ * agent type list, terse usage notes) for small/local models where tool-spec
62
+ * tokens are expensive; "custom" reads `.pi/agent-tool-description.md`
63
+ * (project, falling back to `<agentDir>/agent-tool-description.md`) with
64
+ * `{{placeholder}}` substitution — a missing/empty file falls back to "full".
65
+ * The mode is read once at tool registration — changing it applies on the
66
+ * next pi session.
67
+ */
68
+ toolDescriptionMode?: ToolDescriptionMode;
69
+ /**
70
+ * Whether the Claude Code-style FleetView (the navigable main+subagents list
71
+ * rendered below the editor) is shown. Defaults to `true`. Pure-UI: when off,
72
+ * the list never registers and the global key handler never captures input.
73
+ */
74
+ fleetView?: boolean;
75
+ /**
76
+ * Display mode for the persistent above-editor agent widget:
77
+ * - `all`: show every agent (foreground + background).
78
+ * - `background`: hide foreground agents — they already render inline as the
79
+ * Agent tool result, so the widget would otherwise double-render them
80
+ * (#118); everything else (background, queued, scheduled, RPC) stays.
81
+ * - `off`: hide the widget entirely.
82
+ * Defaults to `background`. Pure-UI and applied live (toggling refreshes the
83
+ * widget).
84
+ */
85
+ widgetMode?: WidgetMode;
86
+ /**
87
+ * Project/global default for writing each subagent's `.output` transcript
88
+ * (a JSON-lines copy of the run, stored under the OS temp dir).
89
+ * Defaults to `true`. Set `false` to make transcripts opt-in for the whole
90
+ * project (e.g. a repo that shouldn't leave run transcripts on disk for backup
91
+ * or DLP tooling to ingest). A custom agent's `output_transcript` frontmatter
92
+ * overrides this per agent. This governs only the transcript — it does NOT
93
+ * affect the persisted pi session (`persist_session`), worktree commits
94
+ * (`isolation: worktree`), or memory files.
95
+ */
96
+ outputTranscript?: boolean;
97
+ }
98
+
99
+ export type ToolDescriptionMode = "full" | "compact" | "custom";
100
+
101
+ /** Setter hooks used by applySettings to wire persisted values into in-memory state. */
102
+ export interface SettingsAppliers {
103
+ setMaxConcurrent: (n: number) => void;
104
+ setDefaultMaxTurns: (n: number) => void;
105
+ setGraceTurns: (n: number) => void;
106
+ setDefaultJoinMode: (mode: JoinMode) => void;
107
+ setSchedulingEnabled: (b: boolean) => void;
108
+ setScopeModels: (enabled: boolean) => void;
109
+ setDisableDefaultAgents: (b: boolean) => void;
110
+ setToolDescriptionMode: (mode: ToolDescriptionMode) => void;
111
+ setFleetView: (b: boolean) => void;
112
+ setWidgetMode: (mode: WidgetMode) => void;
113
+ setOutputTranscript: (b: boolean) => void;
114
+ }
115
+
116
+ /** Emit callback — a subset of `pi.events.emit` to keep helpers testable. */
117
+ export type SettingsEmit = (event: string, payload: unknown) => void;
118
+
119
+ const VALID_JOIN_MODES: ReadonlySet<string> = new Set<JoinMode>(["async", "group", "smart"]);
120
+ const VALID_TOOL_DESCRIPTION_MODES: ReadonlySet<string> = new Set<ToolDescriptionMode>(["full", "compact", "custom"]);
121
+ const VALID_WIDGET_MODES: ReadonlySet<string> = new Set<WidgetMode>(["all", "background", "off"]);
122
+
123
+ // Sanity ceilings — prevent hand-edited configs from asking for values that
124
+ // make no operational sense (e.g. 1e6 concurrent subagents). Permissive enough
125
+ // that any realistic power-user setting passes through.
126
+ const MAX_CONCURRENT_CEILING = 1024;
127
+ const MAX_TURNS_CEILING = 10_000;
128
+ const GRACE_TURNS_CEILING = 1_000;
129
+
130
+ /** Drop fields that don't match the expected shape. Silent — garbage becomes absent. */
131
+ function sanitize(raw: unknown): SubagentsSettings {
132
+ if (!raw || typeof raw !== "object") return {};
133
+ const r = raw as Record<string, unknown>;
134
+ const out: SubagentsSettings = {};
135
+ if (
136
+ Number.isInteger(r.maxConcurrent) &&
137
+ (r.maxConcurrent as number) >= 1 &&
138
+ (r.maxConcurrent as number) <= MAX_CONCURRENT_CEILING
139
+ ) {
140
+ out.maxConcurrent = r.maxConcurrent as number;
141
+ }
142
+ if (
143
+ Number.isInteger(r.defaultMaxTurns) &&
144
+ (r.defaultMaxTurns as number) >= 0 &&
145
+ (r.defaultMaxTurns as number) <= MAX_TURNS_CEILING
146
+ ) {
147
+ out.defaultMaxTurns = r.defaultMaxTurns as number;
148
+ }
149
+ if (
150
+ Number.isInteger(r.graceTurns) &&
151
+ (r.graceTurns as number) >= 1 &&
152
+ (r.graceTurns as number) <= GRACE_TURNS_CEILING
153
+ ) {
154
+ out.graceTurns = r.graceTurns as number;
155
+ }
156
+ if (typeof r.defaultJoinMode === "string" && VALID_JOIN_MODES.has(r.defaultJoinMode)) {
157
+ out.defaultJoinMode = r.defaultJoinMode as JoinMode;
158
+ }
159
+ if (typeof r.schedulingEnabled === "boolean") {
160
+ out.schedulingEnabled = r.schedulingEnabled;
161
+ }
162
+ if (typeof r.scopeModels === "boolean") {
163
+ out.scopeModels = r.scopeModels;
164
+ }
165
+ if (typeof r.disableDefaultAgents === "boolean") {
166
+ out.disableDefaultAgents = r.disableDefaultAgents;
167
+ }
168
+ if (typeof r.toolDescriptionMode === "string" && VALID_TOOL_DESCRIPTION_MODES.has(r.toolDescriptionMode)) {
169
+ out.toolDescriptionMode = r.toolDescriptionMode as ToolDescriptionMode;
170
+ }
171
+ if (typeof r.fleetView === "boolean") {
172
+ out.fleetView = r.fleetView;
173
+ }
174
+ if (typeof r.widgetMode === "string" && VALID_WIDGET_MODES.has(r.widgetMode)) {
175
+ out.widgetMode = r.widgetMode as WidgetMode;
176
+ }
177
+ if (typeof r.outputTranscript === "boolean") {
178
+ out.outputTranscript = r.outputTranscript;
179
+ }
180
+ return out;
181
+ }
182
+
183
+ function globalPath(): string {
184
+ return join(getAgentDir(), "subagents.json");
185
+ }
186
+
187
+ function projectPath(cwd: string): string {
188
+ return join(cwd, ".pi", "subagents.json");
189
+ }
190
+
191
+ /**
192
+ * Read a settings file. Missing file is silent (returns `{}`). A file that
193
+ * exists but can't be parsed emits a warning to stderr so users aren't
194
+ * silently reverted to defaults — and still returns `{}` so startup proceeds.
195
+ */
196
+ function readSettingsFile(path: string): SubagentsSettings {
197
+ if (!existsSync(path)) return {};
198
+ try {
199
+ return sanitize(JSON.parse(readFileSync(path, "utf-8")));
200
+ } catch (err) {
201
+ const reason = err instanceof Error ? err.message : String(err);
202
+ console.warn(`[pi-subagents] Ignoring malformed settings at ${path}: ${reason}`);
203
+ return {};
204
+ }
205
+ }
206
+
207
+ /** Load merged settings: global provides defaults, project overrides. */
208
+ export function loadSettings(cwd: string = process.cwd()): SubagentsSettings {
209
+ return { ...readSettingsFile(globalPath()), ...readSettingsFile(projectPath(cwd)) };
210
+ }
211
+
212
+ /**
213
+ * Write project-local settings. Global is never touched from code.
214
+ * Returns `true` on success, `false` if the write (or mkdir) failed so the
215
+ * caller can surface a warning — persistence isn't fatal but isn't silent.
216
+ */
217
+ export function saveSettings(s: SubagentsSettings, cwd: string = process.cwd()): boolean {
218
+ const path = projectPath(cwd);
219
+ try {
220
+ mkdirSync(dirname(path), { recursive: true });
221
+ writeFileSync(path, JSON.stringify(s, null, 2), "utf-8");
222
+ return true;
223
+ } catch {
224
+ return false;
225
+ }
226
+ }
227
+
228
+ /** Apply persisted settings to the in-memory state via caller-supplied setters. */
229
+ export function applySettings(s: SubagentsSettings, appliers: SettingsAppliers): void {
230
+ if (typeof s.maxConcurrent === "number") appliers.setMaxConcurrent(s.maxConcurrent);
231
+ if (typeof s.defaultMaxTurns === "number") appliers.setDefaultMaxTurns(s.defaultMaxTurns);
232
+ if (typeof s.graceTurns === "number") appliers.setGraceTurns(s.graceTurns);
233
+ if (s.defaultJoinMode) appliers.setDefaultJoinMode(s.defaultJoinMode);
234
+ if (typeof s.schedulingEnabled === "boolean") appliers.setSchedulingEnabled(s.schedulingEnabled);
235
+ if (typeof s.scopeModels === "boolean") appliers.setScopeModels(s.scopeModels);
236
+ if (typeof s.disableDefaultAgents === "boolean") appliers.setDisableDefaultAgents(s.disableDefaultAgents);
237
+ if (s.toolDescriptionMode) appliers.setToolDescriptionMode(s.toolDescriptionMode);
238
+ if (typeof s.fleetView === "boolean") appliers.setFleetView(s.fleetView);
239
+ if (s.widgetMode) appliers.setWidgetMode(s.widgetMode);
240
+ if (typeof s.outputTranscript === "boolean") appliers.setOutputTranscript(s.outputTranscript);
241
+ }
242
+
243
+ /**
244
+ * Format the user-facing toast for a settings mutation. Pure function —
245
+ * routes the success/failure of `saveSettings` into the right message + level
246
+ * so the UI layer (index.ts) stays a thin wire between input and notification.
247
+ */
248
+ export function persistToastFor(
249
+ successMsg: string,
250
+ persisted: boolean,
251
+ ): { message: string; level: "info" | "warning" } {
252
+ return persisted
253
+ ? { message: successMsg, level: "info" }
254
+ : { message: `${successMsg} (session only; failed to persist)`, level: "warning" };
255
+ }
256
+
257
+ /**
258
+ * Load merged settings, apply them to in-memory state, and emit the
259
+ * `subagents:settings_loaded` lifecycle event. Returns the loaded settings so
260
+ * callers can log/inspect. Extension init wires this once.
261
+ */
262
+ export function applyAndEmitLoaded(
263
+ appliers: SettingsAppliers,
264
+ emit: SettingsEmit,
265
+ cwd: string = process.cwd(),
266
+ ): SubagentsSettings {
267
+ const settings = loadSettings(cwd);
268
+ applySettings(settings, appliers);
269
+ emit("subagents:settings_loaded", { settings });
270
+ return settings;
271
+ }
272
+
273
+ /**
274
+ * Persist a settings snapshot, emit the `subagents:settings_changed` event
275
+ * (regardless of persist outcome so listeners see the in-memory change), and
276
+ * return the toast the UI should display. Event payload carries the `persisted`
277
+ * flag so listeners can react to write failures.
278
+ */
279
+ export function saveAndEmitChanged(
280
+ snapshot: SubagentsSettings,
281
+ successMsg: string,
282
+ emit: SettingsEmit,
283
+ cwd: string = process.cwd(),
284
+ ): { message: string; level: "info" | "warning" } {
285
+ const persisted = saveSettings(snapshot, cwd);
286
+ emit("subagents:settings_changed", { settings: snapshot, persisted });
287
+ return persistToastFor(successMsg, persisted);
288
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * skill-loader.ts — Preload named skills.
3
+ *
4
+ * Roots, in precedence order:
5
+ * - <cwd>/.pi/skills (project, Pi's standard)
6
+ * - <cwd>/.agents/skills (project, cross-tool Agent Skills spec — https://agentskills.io)
7
+ * - getAgentDir()/skills (user, default ~/.pi/agent/skills — Pi's standard)
8
+ * - ~/.agents/skills (user, cross-tool Agent Skills spec)
9
+ * - ~/.pi/skills (legacy global, pre-Pi)
10
+ *
11
+ * Layout per root:
12
+ * - <root>/<name>.md (flat file at the top level)
13
+ * - <root>/.../<name>/SKILL.md (directory skill, may be nested — Pi's standard)
14
+ *
15
+ * Recursion skips dotfile entries and node_modules. A directory that itself contains
16
+ * SKILL.md is a skill — we don't descend into it (Pi: skills don't nest).
17
+ *
18
+ * Symlinks are rejected for security (deviation from Pi, which follows them).
19
+ */
20
+
21
+ import type { Dirent } from "node:fs";
22
+ import { existsSync, readdirSync } from "node:fs";
23
+ import { homedir } from "node:os";
24
+ import { join } from "node:path";
25
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
26
+ import { isSymlink, isUnsafeName, safeReadFile } from "./memory.js";
27
+
28
+ export interface PreloadedSkill {
29
+ name: string;
30
+ content: string;
31
+ }
32
+
33
+ export function preloadSkills(skillNames: string[], cwd: string): PreloadedSkill[] {
34
+ return skillNames.map((name) => ({ name, content: loadSkillContent(name, cwd) }));
35
+ }
36
+
37
+ function loadSkillContent(name: string, cwd: string): string {
38
+ if (isUnsafeName(name)) {
39
+ return `(Skill "${name}" skipped: name contains path traversal characters)`;
40
+ }
41
+ const roots = [
42
+ join(cwd, ".pi", "skills"), // project — Pi standard
43
+ join(cwd, ".agents", "skills"), // project — Agent Skills spec
44
+ join(getAgentDir(), "skills"), // user — Pi standard
45
+ join(homedir(), ".agents", "skills"), // user — Agent Skills spec
46
+ join(homedir(), ".pi", "skills"), // legacy global, pre-Pi
47
+ ];
48
+ for (const root of roots) {
49
+ const content = findInRoot(root, name);
50
+ if (content !== undefined) return content;
51
+ }
52
+ return `(Skill "${name}" not found in .pi/skills/, .agents/skills/, or global skill locations)`;
53
+ }
54
+
55
+ function findInRoot(root: string, name: string): string | undefined {
56
+ if (isSymlink(root)) return undefined; // reject symlinked roots entirely
57
+ const flat = safeReadFile(join(root, `${name}.md`))?.trim();
58
+ if (flat !== undefined) return flat;
59
+ return findSkillDirectory(root, name);
60
+ }
61
+
62
+ /** BFS under `root` for a directory named `name` containing `SKILL.md`. Pi-conforming filters. */
63
+ function findSkillDirectory(root: string, name: string): string | undefined {
64
+ if (!existsSync(root)) return undefined;
65
+ const queue: string[] = [root];
66
+
67
+ while (queue.length > 0) {
68
+ const current = queue.shift();
69
+ if (current === undefined) continue;
70
+
71
+ let entries: Dirent<string>[];
72
+ try {
73
+ entries = readdirSync(current, { withFileTypes: true });
74
+ } catch {
75
+ continue;
76
+ }
77
+
78
+ // Deterministic byte-order traversal — locale-independent.
79
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
80
+
81
+ for (const entry of entries) {
82
+ if (!entry.isDirectory()) continue;
83
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
84
+
85
+ // Symlinked dirs already filtered by entry.isDirectory() — Dirent uses lstat semantics.
86
+ const path = join(current, entry.name);
87
+ const skillMd = join(path, "SKILL.md");
88
+ const isSkillDir = existsSync(skillMd);
89
+
90
+ if (isSkillDir) {
91
+ if (entry.name === name) {
92
+ const content = safeReadFile(skillMd)?.trim();
93
+ if (content !== undefined) return content;
94
+ }
95
+ continue; // Pi rule: skills don't nest — don't descend into a skill dir
96
+ }
97
+
98
+ queue.push(path);
99
+ }
100
+ }
101
+ return undefined;
102
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * status-note.ts — Parenthetical status note appended to agent result text.
3
+ */
4
+
5
+ /**
6
+ * Explicit parenthetical note for a non-normal terminal outcome, so the parent
7
+ * agent can't mistake partial output for a completed result. Empty string for a
8
+ * clean completion (and any unknown/non-terminal status).
9
+ *
10
+ * `stopped` (a human aborted it) is deliberately distinct from `aborted` (the
11
+ * turn limit was hit) — the parent should treat human intervention differently
12
+ * from a budget cutoff.
13
+ */
14
+ export function getStatusNote(status: string): string {
15
+ switch (status) {
16
+ case "stopped":
17
+ return " (STOPPED BY THE USER before completion — output is partial; the task was NOT finished)";
18
+ case "aborted":
19
+ return " (aborted — hit the turn limit before completion; output may be incomplete)";
20
+ case "steered":
21
+ return " (wrapped up at the turn limit — output may be partial)";
22
+ default:
23
+ return "";
24
+ }
25
+ }
package/src/types.ts ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * types.ts — Type definitions for the subagent system.
3
+ */
4
+
5
+ import type { ThinkingLevel } from "@earendil-works/pi-ai";
6
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
7
+ import type { LifetimeUsage } from "./usage.js";
8
+
9
+ export type { ThinkingLevel };
10
+
11
+ /** Agent type: any string name (built-in defaults or user-defined). */
12
+ export type SubagentType = string;
13
+
14
+ /** Names of the three embedded default agents. */
15
+ export const DEFAULT_AGENT_NAMES = ["general-purpose", "Explore", "Plan"] as const;
16
+
17
+ /** Memory scope for persistent agent memory. */
18
+ export type MemoryScope = "user" | "project" | "local";
19
+
20
+ /** Isolation mode for agent execution. */
21
+ export type IsolationMode = "worktree";
22
+
23
+ /** Unified agent configuration — used for both default and user-defined agents. */
24
+ export interface AgentConfig {
25
+ name: string;
26
+ displayName?: string;
27
+ description: string;
28
+ builtinToolNames?: string[];
29
+ /** Raw `ext:` selector entries from the `tools:` CSV, e.g. ["ext:foo", "ext:bar/x"].
30
+ * Presence of any entry flips extension tools to an explicit allowlist. */
31
+ extSelectors?: string[];
32
+ /** Tool denylist — these tools are removed even if `builtinToolNames` or extensions include them. */
33
+ disallowedTools?: string[];
34
+ /** true = inherit all, string[] = only listed, false = none */
35
+ extensions: true | string[] | false;
36
+ /** Extension-name denylist applied after the `extensions:` include set. Exclude wins.
37
+ * Plain canonical names only (case-insensitive); no paths, no wildcard. */
38
+ excludeExtensions?: string[];
39
+ /** true = inherit all, string[] = only listed, false = none */
40
+ skills: true | string[] | false;
41
+ model?: string;
42
+ thinking?: ThinkingLevel;
43
+ maxTurns?: number;
44
+ /** Persist this subagent as a normal pi session instead of keeping it in memory only. */
45
+ persistSession?: boolean;
46
+ /** Write the subagent's .output transcript. Defaults to true; false suppresses only that transcript. */
47
+ outputTranscript?: boolean;
48
+ /** Optional session directory used when persistSession is true. Omitted = pi's normal session location. */
49
+ sessionDir?: string;
50
+ systemPrompt: string;
51
+ promptMode: "replace" | "append";
52
+ /** Default for spawn: fork parent conversation. undefined = caller decides. */
53
+ inheritContext?: boolean;
54
+ /** Default for spawn: run in background. undefined = caller decides. */
55
+ runInBackground?: boolean;
56
+ /** Default for spawn: no extension tools. undefined = caller decides. */
57
+ isolated?: boolean;
58
+ /** Persistent memory scope — agents with memory get a persistent directory and MEMORY.md */
59
+ memory?: MemoryScope;
60
+ /** Isolation mode — "worktree" runs the agent in a temporary git worktree */
61
+ isolation?: IsolationMode;
62
+ /** true = this is an embedded default agent (informational) */
63
+ isDefault?: boolean;
64
+ /** false = agent is hidden from the registry */
65
+ enabled?: boolean;
66
+ /** Where this agent was loaded from */
67
+ source?: "default" | "project" | "global";
68
+ }
69
+
70
+ export type JoinMode = 'async' | 'group' | 'smart';
71
+
72
+ /**
73
+ * Display mode for the persistent above-editor agent widget.
74
+ * - `all`: show every agent (foreground + background).
75
+ * - `background`: hide foreground agents (they already render inline as the
76
+ * Agent tool result, #118); show background/queued/scheduled/RPC.
77
+ * - `off`: hide the widget entirely.
78
+ */
79
+ export type WidgetMode = 'all' | 'background' | 'off';
80
+
81
+ export interface AgentRecord {
82
+ id: string;
83
+ type: SubagentType;
84
+ description: string;
85
+ status: "queued" | "running" | "completed" | "steered" | "aborted" | "stopped" | "error";
86
+ result?: string;
87
+ error?: string;
88
+ toolUses: number;
89
+ startedAt: number;
90
+ completedAt?: number;
91
+ session?: AgentSession;
92
+ abortController?: AbortController;
93
+ promise?: Promise<string>;
94
+ groupId?: string;
95
+ joinMode?: JoinMode;
96
+ /** Set when result was already consumed via get_subagent_result — suppresses completion notification. */
97
+ resultConsumed?: boolean;
98
+ /** Steering messages queued before the session was ready. */
99
+ pendingSteers?: string[];
100
+ /** Worktree info if the agent is running in an isolated worktree. */
101
+ worktree?: { path: string; branch: string; baseSha: string; workPath: string };
102
+ /** Worktree cleanup result after agent completion. */
103
+ worktreeResult?: { hasChanges: boolean; branch?: string };
104
+ /** The tool_use_id from the original Agent tool call. */
105
+ toolCallId?: string;
106
+ /** Path to the streaming output transcript file. */
107
+ outputFile?: string;
108
+ /** Cleanup function for the output file stream subscription. */
109
+ outputCleanup?: () => void;
110
+ /**
111
+ * Lifetime usage breakdown, accumulated via `message_end` events. Survives
112
+ * compaction. Total = input + output + cacheWrite (cacheRead deliberately
113
+ * excluded — see issue #38). Initialized to zeros at spawn.
114
+ */
115
+ lifetimeUsage: LifetimeUsage;
116
+ /** Number of times this agent's session has compacted. Initialized to 0 at spawn. */
117
+ compactionCount: number;
118
+ /**
119
+ * Whether this agent was spawned to run in the background. Tri-state, set at
120
+ * spawn from `SpawnOptions.isBackground`: `true` = background, `false` =
121
+ * foreground (has an inline Agent tool-result surface), `undefined` = the
122
+ * caller never declared it (e.g. a cross-extension RPC spawn, which is detached
123
+ * and has no inline surface). The widget's background-only filter keys off this
124
+ * — and excludes only explicit `false`, so `undefined` agents stay visible.
125
+ * Reliable across ALL spawn paths, unlike the UI-only `invocation` snapshot,
126
+ * which only the Agent-tool path populates.
127
+ */
128
+ isBackground?: boolean;
129
+ /** Resolved spawn params, captured for UI display. Fixed at spawn time. */
130
+ invocation?: AgentInvocation;
131
+ }
132
+
133
+ export interface AgentInvocation {
134
+ /** Short display name, e.g. "haiku" — only set when different from parent. */
135
+ modelName?: string;
136
+ thinking?: ThinkingLevel;
137
+ maxTurns?: number;
138
+ isolated?: boolean;
139
+ inheritContext?: boolean;
140
+ runInBackground?: boolean;
141
+ isolation?: IsolationMode;
142
+ }
143
+
144
+ /** Details attached to custom notification messages for visual rendering. */
145
+ export interface NotificationDetails {
146
+ id: string;
147
+ description: string;
148
+ status: string;
149
+ toolUses: number;
150
+ turnCount: number;
151
+ maxTurns?: number;
152
+ totalTokens: number;
153
+ durationMs: number;
154
+ outputFile?: string;
155
+ error?: string;
156
+ resultPreview: string;
157
+ /** Additional agents in a group notification. */
158
+ others?: NotificationDetails[];
159
+ }
160
+
161
+ export interface EnvInfo {
162
+ isGitRepo: boolean;
163
+ branch: string;
164
+ platform: string;
165
+ }
166
+
167
+ /**
168
+ * A subagent spawn registered to fire on a schedule.
169
+ *
170
+ * Stored at `<cwd>/.pi/subagent-schedules/<sessionId>.json`. Session-scoped:
171
+ * survives `/resume` but resets on `/new`, mirroring pi-chonky-tasks.
172
+ */
173
+ export interface ScheduledSubagent {
174
+ id: string;
175
+ /** Unique within store. Defaults to `description`. */
176
+ name: string;
177
+ description: string;
178
+ /** Raw user input — cron expr | "+10m" | ISO | "5m". */
179
+ schedule: string;
180
+ scheduleType: "cron" | "once" | "interval";
181
+ /** Computed at create time for interval/once. */
182
+ intervalMs?: number;
183
+
184
+ // spawn params (subset of Agent tool params; no inherit_context, no resume)
185
+ subagent_type: SubagentType;
186
+ prompt: string;
187
+ model?: string;
188
+ thinking?: ThinkingLevel;
189
+ max_turns?: number;
190
+ isolated?: boolean;
191
+ isolation?: IsolationMode;
192
+
193
+ // state
194
+ enabled: boolean;
195
+ /** ISO timestamp. */
196
+ createdAt: string;
197
+ lastRun?: string;
198
+ lastStatus?: "success" | "error" | "running";
199
+ /** Refreshed on every fire and on store load. */
200
+ nextRun?: string;
201
+ runCount: number;
202
+ }
203
+
204
+ export interface ScheduleStoreData {
205
+ /** For future migrations. */
206
+ version: 1;
207
+ jobs: ScheduledSubagent[];
208
+ }