@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,215 @@
1
+ /**
2
+ * terminal-progress.ts — Keep the terminal's progress spinner alive while subagents run.
3
+ *
4
+ * pi drives the tab/taskbar progress spinner (OSC 9;4, "indeterminate") from
5
+ * the MAIN session only: `turn_start` sets it, `agent_end` clears it. A turn
6
+ * that ends with background agents still running therefore blanks the spinner
7
+ * even though work continues — the session looks finished when it isn't.
8
+ *
9
+ * This module holds the indicator up across exactly that gap, writing the same
10
+ * escape sequences pi itself writes (pi-tui's `ProcessTerminal.setProgress`):
11
+ *
12
+ * active: ESC ] 9 ; 4 ; 3 BEL — indeterminate progress
13
+ * clear: ESC ] 9 ; 4 ; 0 BEL — progress off
14
+ *
15
+ * Two writers share one indicator, so ownership rules keep them from fighting:
16
+ *
17
+ * - While the MAIN session is busy (`ctx.isIdle()` false — an agent run, a
18
+ * queued continuation, a retry, a compaction), pi owns the indicator. We
19
+ * still assert alongside it — the bytes are identical, so the duplicate
20
+ * write is invisible — but we never CLEAR in that window; that would blank
21
+ * pi's own spinner. pi clears at its `agent_end`, and the `agent_end` hook
22
+ * re-asserts right behind it (see onMainAgentEnd).
23
+ * - While the main session is idle and subagent work exists, we own it: assert
24
+ * on every refresh, re-send on a 1s keepalive (same cadence as pi — some
25
+ * terminals, Windows Terminal included, drop the progress state when the
26
+ * title is rewritten, so it must be re-sent), and CLEAR once when the work
27
+ * drains — only ever undoing our own assert.
28
+ * - With no subagent work we never assert: sessions that never spawn agents
29
+ * see pi's indicator behavior untouched.
30
+ *
31
+ * Writes are gated to `ctx.mode === "tui"`: RPC mode's stdout is a JSON
32
+ * channel the sequences would corrupt, and headless child sessions — every
33
+ * subagent re-activates this extension in-process — have no terminal to spin.
34
+ */
35
+
36
+ import { existsSync, readFileSync } from "node:fs";
37
+ import { join } from "node:path";
38
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
39
+
40
+ /** OSC 9;4;3 — indeterminate progress. BEL-terminated, like pi-tui's. */
41
+ const PROGRESS_ACTIVE = "\x1b]9;4;3\x07";
42
+ /** OSC 9;4;0 — progress off. */
43
+ const PROGRESS_CLEAR = "\x1b]9;4;0\x07";
44
+
45
+ /**
46
+ * Keepalive cadence. Mirrors pi-tui's TERMINAL_PROGRESS_KEEPALIVE_MS so the
47
+ * two writers re-assert at the same rate; a faster one would win nothing and
48
+ * a slower one would let the state drop for longer.
49
+ */
50
+ const KEEPALIVE_MS = 1_000;
51
+
52
+ /**
53
+ * Read pi's `terminal.showTerminalProgress` setting (project
54
+ * `<cwd>/.pi/settings.json` over global `<agentDir>/settings.json`, mirroring
55
+ * pi's SettingsManager merge — the same precedence src/enabled-models.ts uses
56
+ * for `enabledModels`).
57
+ *
58
+ * The gate matters because pi's own indicator is opt-in (pi defaults the
59
+ * setting to false): a user who disabled terminal progress should not get a
60
+ * subagent-driven spinner pi would never have shown. Defaults to false on
61
+ * absent field and on unreadable file — the same effective state pi itself
62
+ * degrades to — with a stderr warning on a corrupt file so the miss is
63
+ * diagnosable rather than looking like a dead feature.
64
+ */
65
+ export function readShowTerminalProgress(cwd: string): boolean {
66
+ const read = (path: string): boolean | undefined => {
67
+ if (!existsSync(path)) return undefined;
68
+ try {
69
+ const raw: unknown = JSON.parse(readFileSync(path, "utf-8"));
70
+ const value = (raw as { terminal?: { showTerminalProgress?: unknown } } | null)?.terminal
71
+ ?.showTerminalProgress;
72
+ return typeof value === "boolean" ? value : undefined;
73
+ } catch (err) {
74
+ const reason = err instanceof Error ? err.message : String(err);
75
+ console.warn(`[pi-subagents] Ignoring malformed settings at ${path}: ${reason}`);
76
+ return undefined;
77
+ }
78
+ };
79
+ const project = read(join(cwd, ".pi", "settings.json"));
80
+ if (project !== undefined) return project;
81
+ return read(join(getAgentDir(), "settings.json")) ?? false;
82
+ }
83
+
84
+ /** Live inputs the tracker reads on every decision. All are getters on purpose: state is re-probed, never cached. */
85
+ export interface TerminalProgressInputs {
86
+ /** Whether any subagent work is running or queued (AgentManager.hasRunning). */
87
+ hasWork(): boolean;
88
+ /** Whether the MAIN session owns the indicator: an agent run or compaction in flight (pi shows its own spinner). */
89
+ isMainBusy(): boolean;
90
+ /** Whether writing to the terminal is allowed at all (interactive TUI session). */
91
+ canWrite(): boolean;
92
+ /** Whether the user enabled terminal progress in pi's settings. */
93
+ enabled(): boolean;
94
+ }
95
+
96
+ export class TerminalProgressTracker {
97
+ private interval: ReturnType<typeof setInterval> | undefined;
98
+ /** Last sequence this tracker wrote. ACTIVE re-sends are the keepalive's whole job; CLEAR only ever undoes an assert (see clear()). */
99
+ private lastWrite: "active" | "clear" | undefined;
100
+ private disposed = false;
101
+
102
+ constructor(
103
+ private inputs: TerminalProgressInputs,
104
+ /** Sink for the escape sequences. Injectable so tests can capture writes. */
105
+ private write: (data: string) => void = (data) => { process.stdout.write(data); },
106
+ ) {}
107
+
108
+ /**
109
+ * Re-evaluate and sync the indicator. Called when subagent work starts or
110
+ * settles, and from the keepalive tick — a re-probe, so a missed event
111
+ * self-heals within one keepalive period.
112
+ */
113
+ refresh(): void {
114
+ if (this.disposed) return;
115
+ if (!this.inputs.enabled() || !this.inputs.canWrite()) {
116
+ // Opted out, or nowhere to write. Undo an assert this tracker made —
117
+ // clear() keys off `lastWrite`, which is proof this tracker passed the
118
+ // write gate when it asserted (child/RPC activations can never assert,
119
+ // and the sink never changes), so the clear lands on the same stdout the
120
+ // ACTIVE did; that is also the policy dispose() states. The mid-session
121
+ // opt-out this guards against is unreachable today (the setting is read
122
+ // once per session bind); the branch is the correct undo if that ever
123
+ // becomes live-read, and without it a stranded ACTIVE would have no
124
+ // re-probe left — the keepalive is being stopped here.
125
+ this.clear();
126
+ this.stopKeepalive();
127
+ return;
128
+ }
129
+ if (this.inputs.hasWork()) {
130
+ this.assert();
131
+ } else {
132
+ this.stopKeepalive();
133
+ // No subagent work. Clear only when pi isn't mid-run: pi clears its own
134
+ // indicator at its agent_end, and a clear from us in that window would
135
+ // blank the main session's spinner until pi's 1s keepalive re-sent it.
136
+ if (!this.inputs.isMainBusy()) this.clear();
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Hook for the main session's `agent_end`.
142
+ *
143
+ * pi clears the indicator there AFTER extension handlers run (agent-session
144
+ * emits to extensions before its own listeners), so re-asserting
145
+ * synchronously would be overwritten a moment later. Deferring with
146
+ * setImmediate lands after pi's write in the common case — but that ordering
147
+ * is not guaranteed: another extension's agent_end handler that awaits real
148
+ * I/O lets this callback run first, and the ACTIVE is wiped by pi's clear.
149
+ * That is fine by design: the 1s keepalive re-sends within a second, and the
150
+ * `agent_settled` refresh (which the wiring registers) re-probes the final
151
+ * state. This hook is the fast path, not the only one.
152
+ *
153
+ * Deliberately not gated on `isMainBusy`: agent_end also fires between an
154
+ * intermediate turn and its queued continuation, a window where pi has
155
+ * already cleared but work is still ongoing — the spinner belongs up there
156
+ * too. pi's next turn_start re-asserts over ours harmlessly.
157
+ */
158
+ onMainAgentEnd(): void {
159
+ if (this.disposed) return;
160
+ if (!this.inputs.enabled() || !this.inputs.canWrite()) return;
161
+ setImmediate(() => {
162
+ if (!this.disposed && this.inputs.hasWork()) this.assert();
163
+ });
164
+ }
165
+
166
+ /**
167
+ * Stop the keepalive and clear the indicator. Call on session shutdown, before pi restores the terminal.
168
+ *
169
+ * The clear goes through clear()'s "only undo our own assert" guard, which
170
+ * is the only safe gate here: dispose runs in every activation
171
+ * (session_shutdown fires inside child sessions too, #242), and both a child
172
+ * activation (mode "print") and an RPC-mode root must not put these bytes
173
+ * on stdout — RPC's stdout is a JSON channel, and a child teardown clearing
174
+ * mid-run would blank the root session's spinner. Those activations never
175
+ * pass the write gate, so they never assert, and dispose writes nothing.
176
+ * Reading `canWrite()` here instead would be wrong in the one case dispose
177
+ * exists for: the root TUI session, whose handler has already dropped
178
+ * `currentCtx` by the time dispose runs.
179
+ */
180
+ dispose(): void {
181
+ if (this.disposed) return;
182
+ this.disposed = true;
183
+ this.stopKeepalive();
184
+ this.clear();
185
+ }
186
+
187
+ private assert(): void {
188
+ this.ensureKeepalive();
189
+ this.write(PROGRESS_ACTIVE);
190
+ this.lastWrite = "active";
191
+ }
192
+
193
+ private clear(): void {
194
+ // Only undo an assert this tracker made. A speculative clear would be
195
+ // noise on every no-work refresh (session bind), and worse: it cannot
196
+ // know the terminal's true state — pi drives the indicator too. If our
197
+ // ACTIVE was clobbered by pi's own clear, the keepalive re-asserts; the
198
+ // indicator is only ever cleared by whoever left it up.
199
+ if (this.lastWrite !== "active") return;
200
+ this.write(PROGRESS_CLEAR);
201
+ this.lastWrite = "clear";
202
+ }
203
+
204
+ private ensureKeepalive(): void {
205
+ if (this.interval) return;
206
+ this.interval = setInterval(() => this.refresh(), KEEPALIVE_MS);
207
+ this.interval.unref?.();
208
+ }
209
+
210
+ private stopKeepalive(): void {
211
+ if (!this.interval) return;
212
+ clearInterval(this.interval);
213
+ this.interval = undefined;
214
+ }
215
+ }
package/src/types.ts ADDED
@@ -0,0 +1,394 @@
1
+ /**
2
+ * types.ts — Type definitions for the subagent system.
3
+ */
4
+
5
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
6
+ import type { AdvisorStatus } from "./advisor-status.js";
7
+ import type { LifetimeUsage } from "./usage.js";
8
+
9
+ /** Use the session's full control surface, including the explicit "off" level. */
10
+ export type ThinkingLevel = AgentSession["thinkingLevel"];
11
+
12
+ /** Agent type: any string name (built-in defaults or user-defined). */
13
+ export type SubagentType = string;
14
+
15
+ /** Names of the three embedded default agents. */
16
+ export const DEFAULT_AGENT_NAMES = ["general-purpose", "Explore", "Plan"] as const;
17
+
18
+ /** Memory scope for persistent agent memory. */
19
+ export type MemoryScope = "user" | "project" | "local";
20
+
21
+ /**
22
+ * Isolation mode for agent execution.
23
+ *
24
+ * `"off"` exists for the caller's benefit, not the runtime's: models that fill
25
+ * every optional parameter had no legal way to decline a single-value
26
+ * `isolation` field and kept spawning worktrees they had just reasoned their
27
+ * way out of (#231, #184). It is an input spelling only —
28
+ * `resolveAgentInvocationConfig` collapses it to `undefined`, so nothing
29
+ * downstream sees a value other than `"worktree"`. In an agent file it is a
30
+ * genuine veto, since agent config outranks tool-call params.
31
+ */
32
+ export type IsolationMode = "worktree" | "off";
33
+
34
+ /** Unified agent configuration — used for both default and user-defined agents. */
35
+ export interface AgentConfig {
36
+ name: string;
37
+ /** UI name. `display_name` wins; Claude Code's `name` is accepted as a fallback. */
38
+ displayName?: string;
39
+ /** Claude Code-compatible name color (named color or #RRGGBB). */
40
+ color?: string;
41
+ description: string;
42
+ builtinToolNames?: string[];
43
+ /** Raw `ext:` selector entries from the `tools:` CSV, e.g. ["ext:foo", "ext:bar/x"].
44
+ * Presence of any entry flips extension tools to an explicit allowlist. */
45
+ extSelectors?: string[];
46
+ /** Tool denylist — these tools are removed even if `builtinToolNames` or extensions include them. */
47
+ disallowedTools?: string[];
48
+ /** true = inherit all, string[] = only listed, false = none */
49
+ extensions: true | string[] | false;
50
+ /** Extension-name denylist applied after the `extensions:` include set. Exclude wins.
51
+ * Plain canonical names only (case-insensitive); no paths, no wildcard. */
52
+ excludeExtensions?: string[];
53
+ /** true = inherit all, string[] = only listed, false = none */
54
+ skills: true | string[] | false;
55
+ model?: string;
56
+ /** Standalone recovery target when pi-fallback-chains is absent; runner wiring is separate. */
57
+ fallbackModel?: string;
58
+ /**
59
+ * Per-agent pi-advisor control for this agent's child sessions.
60
+ * `false` excludes the advisor family (pi-advisor, pi-omp-advisor) from the
61
+ * child's loader outright; `true` keeps it loaded and raises
62
+ * `PI_ADVISOR_SUBAGENTS=1` for the child's extension-bind window so the
63
+ * advisor's default-enable gate turns on. Undefined defers to pi-advisor's
64
+ * own precedence (env → WATCHDOG `subagents:` → built-in off) untouched.
65
+ */
66
+ advisor?: boolean;
67
+ thinking?: ThinkingLevel;
68
+ maxTurns?: number;
69
+ /** Persist this subagent as a normal pi session instead of keeping it in memory only. */
70
+ persistSession?: boolean;
71
+ /** Write the subagent's .output transcript. Defaults to true; false suppresses only that transcript. */
72
+ outputTranscript?: boolean;
73
+ /** Optional session directory used when persistSession is true. Omitted = pi's normal session location. */
74
+ sessionDir?: string;
75
+ /**
76
+ * Nested delegation, off by default: undefined = no nested tools;
77
+ * "all" = any enabled agent; string[] = only those agent types.
78
+ */
79
+ allowedSubagents?: "all" | string[];
80
+ systemPrompt: string;
81
+ promptMode: "replace" | "append";
82
+ /** Default for spawn: fork parent conversation. undefined = caller decides. */
83
+ inheritContext?: boolean;
84
+ /** Default for spawn: run in background. undefined = caller decides. */
85
+ runInBackground?: boolean;
86
+ /** Default for spawn: no extension tools. undefined = caller decides. */
87
+ isolated?: boolean;
88
+ /** Persistent memory scope — agents with memory get a persistent directory and MEMORY.md */
89
+ memory?: MemoryScope;
90
+ /**
91
+ * Isolation mode — "worktree" runs the agent in a temporary git worktree,
92
+ * "off" refuses one even when the caller asks (frontmatter outranks params).
93
+ */
94
+ isolation?: IsolationMode;
95
+ /** true = this is an embedded default agent (informational) */
96
+ isDefault?: boolean;
97
+ /** false = agent is hidden from the registry */
98
+ enabled?: boolean;
99
+ /** Where this agent was loaded from */
100
+ source?: "default" | "project" | "global";
101
+ /** Path of the .md it was loaded from. Unset for embedded defaults. */
102
+ sourcePath?: string;
103
+ }
104
+
105
+ export type JoinMode = 'async' | 'group' | 'smart';
106
+
107
+ /**
108
+ * Display mode for the persistent above-editor agent widget.
109
+ * - `all`: show every agent (foreground + background).
110
+ * - `background`: hide foreground agents (they already render inline as the
111
+ * Agent tool result, #118); show background/queued/scheduled/RPC.
112
+ * - `off`: hide the widget entirely.
113
+ */
114
+ export type WidgetMode = 'all' | 'background' | 'off';
115
+
116
+ /**
117
+ * How much of the conversation viewer's transcript is rendered as Markdown.
118
+ * - `off`: every line wraps as literal text, as it did before the mode existed.
119
+ * - `assistant`: assistant text renders as Markdown; tool results stay verbatim
120
+ * and dim. The default, because assistant text *is* Markdown by contract
121
+ * while a tool result is arbitrary bytes — a Markdown pass over a log or a
122
+ * diff eats `#` from shell comments, swallows a `---` line into a setext
123
+ * heading, re-fences indented output and redraws `| a | b |` as a table.
124
+ * (Ordered-list renumbering is the one such rewrite actively suppressed —
125
+ * see `MARKDOWN_OPTIONS` — because it silently changes data, not layout.)
126
+ * - `all`: tool results render as Markdown too, for tools that genuinely emit
127
+ * it (#210's `ctx_execute`), accepting the rewrites above on ones that don't.
128
+ */
129
+ export type ViewerMarkdownMode = 'off' | 'assistant' | 'all';
130
+
131
+ /**
132
+ * How `@handle message` starts an agent that is not already running.
133
+ * - `model`: inject Claude Code's `agent_mention` reminder and let the main
134
+ * model spawn it with the `Agent` tool, which is what Claude Code does.
135
+ * - `direct`: spawn it here, immediately, with the typed message as its prompt
136
+ * and no main-model turn spent.
137
+ * - `off`: `@` means only "attach a file" again.
138
+ *
139
+ * Messaging a running agent and resuming a finished one are direct in every
140
+ * mode — Claude Code only differs from us on the *new* invocation.
141
+ */
142
+ export type AgentMentionMode = 'model' | 'direct' | 'off';
143
+
144
+ /**
145
+ * What survives a record's eviction so `@handle` keeps working. The live record
146
+ * is discarded after ~10 minutes, but the pi session it wrote is still on disk,
147
+ * and this is the little that is needed to find and describe it again.
148
+ */
149
+ export interface AgentTombstone {
150
+ handle: string;
151
+ alias?: string;
152
+ id: string;
153
+ type: SubagentType;
154
+ description: string;
155
+ /** Always set — a record with no session file is never tombstoned. */
156
+ sessionFile: string;
157
+ completedAt: number;
158
+ }
159
+
160
+ /**
161
+ * What `@handle` resolved to: an agent still in memory, or the remains of one
162
+ * whose conversation can be reopened from disk.
163
+ */
164
+ export type MentionResolution =
165
+ | { kind: "live"; record: AgentRecord }
166
+ | { kind: "tombstone"; entry: AgentTombstone };
167
+
168
+ export interface AgentRecord {
169
+ id: string;
170
+ type: SubagentType;
171
+ /**
172
+ * Typeable name for the `@handle message` prompt mention, derived from the
173
+ * agent type and numbered when siblings collide (`explore`, `explore-2`).
174
+ * Top-level agents only — nested children are hidden from every top-level
175
+ * surface, so nothing can address them.
176
+ */
177
+ handle?: string;
178
+ /**
179
+ * A second, memorable handle from the spawner's `name` (`@auth-audit`), drawn
180
+ * from the same namespace as `handle` so the two can never collide. Purely
181
+ * additive: `handle` is assigned regardless, so a named agent stays reachable
182
+ * by its type and `@explore` never comes to mean "start another one".
183
+ */
184
+ alias?: string;
185
+ description: string;
186
+ status: "queued" | "running" | "completed" | "steered" | "aborted" | "stopped" | "error";
187
+ result?: string;
188
+ error?: string;
189
+ toolUses: number;
190
+ startedAt: number;
191
+ completedAt?: number;
192
+ session?: AgentSession;
193
+ abortController?: AbortController;
194
+ promise?: Promise<string>;
195
+ /**
196
+ * A caller is awaiting this agent inline (`spawnAndWait`) — what
197
+ * `maxConcurrentForeground` bounds. Distinct from `isBackground === false`,
198
+ * which says only that the agent has an inline result surface: a detached
199
+ * cross-extension RPC spawn is foreground by that measure and yet blocks
200
+ * nobody, so it takes no slot.
201
+ */
202
+ blocking?: boolean;
203
+ /**
204
+ * Present only while the record is "queued": resolves when it leaves the
205
+ * queue, started or aborted. `spawnAndWait` waits on this because a queued
206
+ * record has no `promise` yet. Always resolves, never rejects — a rejection
207
+ * would escape into the caller's tool `execute` and take down pi's whole
208
+ * Promise.all tool batch.
209
+ */
210
+ startGate?: Promise<void>;
211
+ groupId?: string;
212
+ joinMode?: JoinMode;
213
+ /** Set when result was already consumed via get_subagent_result — suppresses completion notification. */
214
+ resultConsumed?: boolean;
215
+ /** Steering messages queued before the session was ready. */
216
+ pendingSteers?: string[];
217
+ /**
218
+ * Steering messages still queued in the child session when its run ended.
219
+ * They are discarded at completion (so a later resume cannot replay stale
220
+ * instructions) and counted here so the result can say so.
221
+ */
222
+ droppedSteers?: number;
223
+ /** Worktree info if the agent is running in an isolated worktree. */
224
+ worktree?: { path: string; branch: string; baseSha: string; workPath: string };
225
+ /** Worktree cleanup result after agent completion. */
226
+ worktreeResult?: { hasChanges: boolean; branch?: string };
227
+ /** The tool_use_id from the original Agent tool call. */
228
+ toolCallId?: string;
229
+ /** Path to the streaming output transcript file. */
230
+ outputFile?: string;
231
+ /**
232
+ * The agent's pi session file, when it was persisted (`persist_session`, or
233
+ * the `rememberAgents` default). Captured so a mention can reopen the
234
+ * conversation after the record itself has been evicted; undefined for an
235
+ * in-memory session, which leaves nothing to reopen.
236
+ */
237
+ sessionFile?: string;
238
+ /** Cleanup function for the output file stream subscription. */
239
+ /** Detaches the transcript stream; resolves once its final flush is on disk (awaited at settle). */
240
+ outputCleanup?: () => void | Promise<void>;
241
+ /**
242
+ * Lifetime usage breakdown, accumulated via `message_end` events. Survives
243
+ * compaction. Total = input + output + cacheWrite (cacheRead deliberately
244
+ * excluded — see issue #38). Initialized to zeros at spawn.
245
+ */
246
+ lifetimeUsage: LifetimeUsage;
247
+ /** Number of times this agent's session has compacted. Initialized to 0 at spawn. */
248
+ compactionCount: number;
249
+ /** Latest child-local advisor snapshot; absent means telemetry is unavailable. */
250
+ advisorStatus?: AdvisorStatus;
251
+ /**
252
+ * Whether this agent was spawned to run in the background. Tri-state, set at
253
+ * spawn from `SpawnOptions.isBackground`: `true` = background, `false` =
254
+ * foreground (has an inline Agent tool-result surface), `undefined` = the
255
+ * caller never declared it (e.g. a cross-extension RPC spawn, which is detached
256
+ * and has no inline surface). The widget's background-only filter keys off this
257
+ * — and excludes only explicit `false`, so `undefined` agents stay visible.
258
+ * Reliable across ALL spawn paths, unlike the UI-only `invocation` snapshot,
259
+ * which only the Agent-tool path populates.
260
+ */
261
+ isBackground?: boolean;
262
+ /** Resolved spawn params, captured for UI display. Fixed at spawn time. */
263
+ invocation?: AgentInvocation;
264
+ /** Nesting depth: top-level subagent = 1. */
265
+ depth?: number;
266
+ /**
267
+ * The validated `StructuredOutput` payload, as canonical JSON.
268
+ *
269
+ * Set only when the spawn asked for a schema. Separate from `result` because
270
+ * `result` is prose for a reader — previewed in the widget, written to the
271
+ * transcript, and appended to with the worktree branch note — and JSON that
272
+ * has been appended to no longer parses.
273
+ */
274
+ structuredJson?: string;
275
+ /** Whether the child needed the extra structured-output prompt. */
276
+ structuredRetried?: boolean;
277
+ /** Parent agent ID for ownership-scoped nested controls. */
278
+ parentAgentId?: string;
279
+ /**
280
+ * The workflow run that owns this child, when a workflow spawned it.
281
+ *
282
+ * Owned the same way a nested child is owned by its parent: filtered out of
283
+ * every top-level surface, and outside the `maxConcurrent` pool. See
284
+ * `isTopLevelAgent`.
285
+ */
286
+ workflowId?: string;
287
+ /** Effective inherited nesting cap for this branch. */
288
+ maxSubagentDepth?: number;
289
+ /**
290
+ * Session id of the root (main) session this branch descends from. Nested
291
+ * spawns inherit it so their transcripts file under the same session
292
+ * directory as their ancestors' instead of the child session's own id.
293
+ */
294
+ rootSessionId?: string;
295
+ }
296
+
297
+ /** Actual session level after SDK model-capability clamping. */
298
+ export type EffectiveThinkingLevel = ThinkingLevel;
299
+
300
+ export interface AgentInvocation {
301
+ /** Short display name for tight rows, e.g. "haiku 4.5". Always set once known. */
302
+ modelName?: string;
303
+ /** Canonical `provider/id`, for surfaces with room to disambiguate providers. */
304
+ modelId?: string;
305
+ /** The level actually in effect, once a session exists to report one. */
306
+ thinking?: EffectiveThinkingLevel;
307
+ /**
308
+ * What the caller asked for, kept only when they did not get it — pi clamped
309
+ * the level to the model's capabilities, or an agent file's frontmatter
310
+ * outranked the parameter (#182). The snapshot exists to answer "did the spawn
311
+ * honor my instructions?" (#62), which it cannot do if the request is lost, so
312
+ * neither `requested*` field is overwritten once set.
313
+ */
314
+ requestedThinking?: EffectiveThinkingLevel;
315
+ /** The caller's `model` parameter, as written, when an agent file's pin won. */
316
+ requestedModel?: string;
317
+ maxTurns?: number;
318
+ isolated?: boolean;
319
+ inheritContext?: boolean;
320
+ runInBackground?: boolean;
321
+ isolation?: IsolationMode;
322
+ }
323
+
324
+ /** Details attached to custom notification messages for visual rendering. */
325
+ export interface NotificationDetails {
326
+ id: string;
327
+ description: string;
328
+ status: string;
329
+ toolUses: number;
330
+ turnCount: number;
331
+ maxTurns?: number;
332
+ totalTokens: number;
333
+ /**
334
+ * Estimated cost in USD, from pi's per-message `usage.cost.total`. Always
335
+ * populated (0 when the model has no pricing); the renderer decides whether
336
+ * to show it, per the `showCost` setting.
337
+ */
338
+ totalCost?: number;
339
+ durationMs: number;
340
+ outputFile?: string;
341
+ error?: string;
342
+ resultPreview: string;
343
+ /** Additional agents in a group notification. */
344
+ others?: NotificationDetails[];
345
+ }
346
+
347
+ export interface EnvInfo {
348
+ isGitRepo: boolean;
349
+ branch: string;
350
+ platform: string;
351
+ }
352
+
353
+ /**
354
+ * A subagent spawn registered to fire on a schedule.
355
+ *
356
+ * Stored at `<cwd>/.pi/subagent-schedules/<sessionId>.json`. Session-scoped:
357
+ * survives `/resume` but resets on `/new`, mirroring pi-chonky-tasks.
358
+ */
359
+ export interface ScheduledSubagent {
360
+ id: string;
361
+ /** Unique within store. Defaults to `description`. */
362
+ name: string;
363
+ description: string;
364
+ /** Raw user input — cron expr | "+10m" | ISO | "5m". */
365
+ schedule: string;
366
+ scheduleType: "cron" | "once" | "interval";
367
+ /** Computed at create time for interval/once. */
368
+ intervalMs?: number;
369
+
370
+ // spawn params (subset of Agent tool params; no inherit_context, no resume)
371
+ subagent_type: SubagentType;
372
+ prompt: string;
373
+ model?: string;
374
+ thinking?: ThinkingLevel;
375
+ max_turns?: number;
376
+ isolated?: boolean;
377
+ isolation?: IsolationMode;
378
+
379
+ // state
380
+ enabled: boolean;
381
+ /** ISO timestamp. */
382
+ createdAt: string;
383
+ lastRun?: string;
384
+ lastStatus?: "success" | "error" | "running";
385
+ /** Refreshed on every fire and on store load. */
386
+ nextRun?: string;
387
+ runCount: number;
388
+ }
389
+
390
+ export interface ScheduleStoreData {
391
+ /** For future migrations. */
392
+ version: 1;
393
+ jobs: ScheduledSubagent[];
394
+ }