@diousk/pi-subagents-fast 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 (183) hide show
  1. package/CHANGELOG.md +808 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1034 -0
  5. package/SECURITY.md +95 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/agent-color.d.ts +35 -0
  9. package/dist/agent-color.js +123 -0
  10. package/dist/agent-file-toggle.d.ts +125 -0
  11. package/dist/agent-file-toggle.js +260 -0
  12. package/dist/agent-manager.d.ts +472 -0
  13. package/dist/agent-manager.js +1338 -0
  14. package/dist/agent-runner.d.ts +312 -0
  15. package/dist/agent-runner.js +1034 -0
  16. package/dist/agent-types.d.ts +119 -0
  17. package/dist/agent-types.js +286 -0
  18. package/dist/child-context.d.ts +2 -0
  19. package/dist/child-context.js +12 -0
  20. package/dist/context.d.ts +12 -0
  21. package/dist/context.js +56 -0
  22. package/dist/cross-extension-rpc.d.ts +66 -0
  23. package/dist/cross-extension-rpc.js +138 -0
  24. package/dist/custom-agents.d.ts +54 -0
  25. package/dist/custom-agents.js +316 -0
  26. package/dist/default-agents.d.ts +7 -0
  27. package/dist/default-agents.js +122 -0
  28. package/dist/enabled-models.d.ts +49 -0
  29. package/dist/enabled-models.js +145 -0
  30. package/dist/env.d.ts +6 -0
  31. package/dist/env.js +28 -0
  32. package/dist/group-join.d.ts +32 -0
  33. package/dist/group-join.js +116 -0
  34. package/dist/index.d.ts +50 -0
  35. package/dist/index.js +3682 -0
  36. package/dist/invocation-config.d.ts +107 -0
  37. package/dist/invocation-config.js +83 -0
  38. package/dist/memory.d.ts +53 -0
  39. package/dist/memory.js +165 -0
  40. package/dist/mention-clone.d.ts +87 -0
  41. package/dist/mention-clone.js +153 -0
  42. package/dist/mention.d.ts +81 -0
  43. package/dist/mention.js +131 -0
  44. package/dist/model-resolver.d.ts +36 -0
  45. package/dist/model-resolver.js +95 -0
  46. package/dist/model-scope.d.ts +49 -0
  47. package/dist/model-scope.js +48 -0
  48. package/dist/nested-tools.d.ts +55 -0
  49. package/dist/nested-tools.js +299 -0
  50. package/dist/output-file.d.ts +43 -0
  51. package/dist/output-file.js +142 -0
  52. package/dist/prompts.d.ts +55 -0
  53. package/dist/prompts.js +91 -0
  54. package/dist/schedule-store.d.ts +38 -0
  55. package/dist/schedule-store.js +155 -0
  56. package/dist/schedule.d.ts +109 -0
  57. package/dist/schedule.js +359 -0
  58. package/dist/settings.d.ts +360 -0
  59. package/dist/settings.js +251 -0
  60. package/dist/skill-loader.d.ts +24 -0
  61. package/dist/skill-loader.js +93 -0
  62. package/dist/status-note.d.ts +61 -0
  63. package/dist/status-note.js +85 -0
  64. package/dist/structured-output.d.ts +61 -0
  65. package/dist/structured-output.js +112 -0
  66. package/dist/types.d.ts +371 -0
  67. package/dist/types.js +5 -0
  68. package/dist/ui/agent-mention.d.ts +82 -0
  69. package/dist/ui/agent-mention.js +187 -0
  70. package/dist/ui/agent-widget.d.ts +219 -0
  71. package/dist/ui/agent-widget.js +592 -0
  72. package/dist/ui/conversation-viewer.d.ts +120 -0
  73. package/dist/ui/conversation-viewer.js +578 -0
  74. package/dist/ui/fleet-list.d.ts +195 -0
  75. package/dist/ui/fleet-list.js +471 -0
  76. package/dist/ui/schedule-menu.d.ts +16 -0
  77. package/dist/ui/schedule-menu.js +94 -0
  78. package/dist/ui/select-item.d.ts +27 -0
  79. package/dist/ui/select-item.js +34 -0
  80. package/dist/ui/viewer-keys.d.ts +20 -0
  81. package/dist/ui/viewer-keys.js +17 -0
  82. package/dist/ui/workflow-card.d.ts +175 -0
  83. package/dist/ui/workflow-card.js +332 -0
  84. package/dist/ui/workflow-dialog.d.ts +305 -0
  85. package/dist/ui/workflow-dialog.js +843 -0
  86. package/dist/ui/workflow-menu.d.ts +60 -0
  87. package/dist/ui/workflow-menu.js +147 -0
  88. package/dist/usage.d.ts +135 -0
  89. package/dist/usage.js +120 -0
  90. package/dist/workflow/collisions.d.ts +95 -0
  91. package/dist/workflow/collisions.js +88 -0
  92. package/dist/workflow/entry.d.ts +32 -0
  93. package/dist/workflow/entry.js +29 -0
  94. package/dist/workflow/host.d.ts +62 -0
  95. package/dist/workflow/host.js +362 -0
  96. package/dist/workflow/journal.d.ts +97 -0
  97. package/dist/workflow/journal.js +120 -0
  98. package/dist/workflow/json-schema.d.ts +51 -0
  99. package/dist/workflow/json-schema.js +111 -0
  100. package/dist/workflow/meta.d.ts +67 -0
  101. package/dist/workflow/meta.js +317 -0
  102. package/dist/workflow/progress.d.ts +224 -0
  103. package/dist/workflow/progress.js +361 -0
  104. package/dist/workflow/runtime.d.ts +334 -0
  105. package/dist/workflow/runtime.js +830 -0
  106. package/dist/workflow/saved.d.ts +90 -0
  107. package/dist/workflow/saved.js +203 -0
  108. package/dist/workflow/task.d.ts +136 -0
  109. package/dist/workflow/task.js +207 -0
  110. package/dist/workflow/tool-description.d.ts +38 -0
  111. package/dist/workflow/tool-description.js +199 -0
  112. package/dist/workflow/worker-source.d.ts +47 -0
  113. package/dist/workflow/worker-source.js +778 -0
  114. package/dist/worktree.d.ts +52 -0
  115. package/dist/worktree.js +164 -0
  116. package/dist/xml.d.ts +10 -0
  117. package/dist/xml.js +12 -0
  118. package/docs/rpc.md +183 -0
  119. package/docs/workflows.md +437 -0
  120. package/examples/agent-tool-description.md +42 -0
  121. package/examples/workflows/compose.js +51 -0
  122. package/examples/workflows/fan-out-audit.js +47 -0
  123. package/examples/workflows/gated-fix.js +60 -0
  124. package/examples/workflows/lib/count-child.js +27 -0
  125. package/examples/workflows/review-panel.js +63 -0
  126. package/examples/workflows/structured-findings.js +78 -0
  127. package/package.json +68 -0
  128. package/src/abortable.ts +43 -0
  129. package/src/agent-color.ts +161 -0
  130. package/src/agent-file-toggle.ts +270 -0
  131. package/src/agent-manager.ts +1581 -0
  132. package/src/agent-runner.ts +1286 -0
  133. package/src/agent-types.ts +346 -0
  134. package/src/child-context.ts +15 -0
  135. package/src/context.ts +58 -0
  136. package/src/cross-extension-rpc.ts +198 -0
  137. package/src/custom-agents.ts +333 -0
  138. package/src/default-agents.ts +126 -0
  139. package/src/enabled-models.ts +180 -0
  140. package/src/env.ts +33 -0
  141. package/src/group-join.ts +141 -0
  142. package/src/index.ts +3991 -0
  143. package/src/invocation-config.ts +155 -0
  144. package/src/memory.ts +179 -0
  145. package/src/mention-clone.ts +196 -0
  146. package/src/mention.ts +141 -0
  147. package/src/model-resolver.ts +118 -0
  148. package/src/model-scope.ts +70 -0
  149. package/src/nested-tools.ts +422 -0
  150. package/src/output-file.ts +155 -0
  151. package/src/prompts.ts +142 -0
  152. package/src/schedule-store.ts +153 -0
  153. package/src/schedule.ts +386 -0
  154. package/src/settings.ts +587 -0
  155. package/src/skill-loader.ts +102 -0
  156. package/src/status-note.ts +90 -0
  157. package/src/structured-output.ts +130 -0
  158. package/src/types.ts +384 -0
  159. package/src/ui/agent-mention.ts +216 -0
  160. package/src/ui/agent-widget.ts +664 -0
  161. package/src/ui/conversation-viewer.ts +589 -0
  162. package/src/ui/fleet-list.ts +543 -0
  163. package/src/ui/schedule-menu.ts +105 -0
  164. package/src/ui/select-item.ts +45 -0
  165. package/src/ui/viewer-keys.ts +39 -0
  166. package/src/ui/workflow-card.ts +470 -0
  167. package/src/ui/workflow-dialog.ts +1115 -0
  168. package/src/ui/workflow-menu.ts +193 -0
  169. package/src/usage.ts +167 -0
  170. package/src/workflow/collisions.ts +123 -0
  171. package/src/workflow/entry.ts +47 -0
  172. package/src/workflow/host.ts +403 -0
  173. package/src/workflow/journal.ts +164 -0
  174. package/src/workflow/json-schema.ts +128 -0
  175. package/src/workflow/meta.ts +325 -0
  176. package/src/workflow/progress.ts +550 -0
  177. package/src/workflow/runtime.ts +1219 -0
  178. package/src/workflow/saved.ts +217 -0
  179. package/src/workflow/task.ts +302 -0
  180. package/src/workflow/tool-description.ts +200 -0
  181. package/src/workflow/worker-source.ts +781 -0
  182. package/src/worktree.ts +205 -0
  183. package/src/xml.ts +13 -0
package/src/types.ts ADDED
@@ -0,0 +1,384 @@
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
+ /** OpenAI Responses/Codex request processing tier. */
21
+ export type ServiceTier = "auto" | "default" | "flex" | "priority" | "scale";
22
+
23
+ /**
24
+ * Isolation mode for agent execution.
25
+ *
26
+ * `"off"` exists for the caller's benefit, not the runtime's: models that fill
27
+ * every optional parameter had no legal way to decline a single-value
28
+ * `isolation` field and kept spawning worktrees they had just reasoned their
29
+ * way out of (#231, #184). It is an input spelling only —
30
+ * `resolveAgentInvocationConfig` collapses it to `undefined`, so nothing
31
+ * downstream sees a value other than `"worktree"`. In an agent file it is a
32
+ * genuine veto, since agent config outranks tool-call params.
33
+ */
34
+ export type IsolationMode = "worktree" | "off";
35
+
36
+ /** Unified agent configuration — used for both default and user-defined agents. */
37
+ export interface AgentConfig {
38
+ name: string;
39
+ /** UI name. `display_name` wins; Claude Code's `name` is accepted as a fallback. */
40
+ displayName?: string;
41
+ /** Claude Code-compatible name color (named color or #RRGGBB). */
42
+ color?: string;
43
+ description: string;
44
+ builtinToolNames?: string[];
45
+ /** Raw `ext:` selector entries from the `tools:` CSV, e.g. ["ext:foo", "ext:bar/x"].
46
+ * Presence of any entry flips extension tools to an explicit allowlist. */
47
+ extSelectors?: string[];
48
+ /** Tool denylist — these tools are removed even if `builtinToolNames` or extensions include them. */
49
+ disallowedTools?: string[];
50
+ /** true = inherit all, string[] = only listed, false = none */
51
+ extensions: true | string[] | false;
52
+ /** Extension-name denylist applied after the `extensions:` include set. Exclude wins.
53
+ * Plain canonical names only (case-insensitive); no paths, no wildcard. */
54
+ excludeExtensions?: string[];
55
+ /** true = inherit all, string[] = only listed, false = none */
56
+ skills: true | string[] | false;
57
+ model?: string;
58
+ thinking?: ThinkingLevel;
59
+ /** OpenAI Responses/Codex processing tier; ignored by other APIs. */
60
+ serviceTier?: ServiceTier;
61
+ maxTurns?: number;
62
+ /** Persist this subagent as a normal pi session instead of keeping it in memory only. */
63
+ persistSession?: boolean;
64
+ /** Write the subagent's .output transcript. Defaults to true; false suppresses only that transcript. */
65
+ outputTranscript?: boolean;
66
+ /** Optional session directory used when persistSession is true. Omitted = pi's normal session location. */
67
+ sessionDir?: string;
68
+ /**
69
+ * Nested delegation, off by default: undefined = no nested tools;
70
+ * "all" = any enabled agent; string[] = only those agent types.
71
+ */
72
+ allowedSubagents?: "all" | string[];
73
+ systemPrompt: string;
74
+ promptMode: "replace" | "append";
75
+ /** Default for spawn: fork parent conversation. undefined = caller decides. */
76
+ inheritContext?: boolean;
77
+ /** Default for spawn: run in background. undefined = caller decides. */
78
+ runInBackground?: boolean;
79
+ /** Default for spawn: no extension tools. undefined = caller decides. */
80
+ isolated?: boolean;
81
+ /** Persistent memory scope — agents with memory get a persistent directory and MEMORY.md */
82
+ memory?: MemoryScope;
83
+ /**
84
+ * Isolation mode — "worktree" runs the agent in a temporary git worktree,
85
+ * "off" refuses one even when the caller asks (frontmatter outranks params).
86
+ */
87
+ isolation?: IsolationMode;
88
+ /** true = this is an embedded default agent (informational) */
89
+ isDefault?: boolean;
90
+ /** false = agent is hidden from the registry */
91
+ enabled?: boolean;
92
+ /** Where this agent was loaded from */
93
+ source?: "default" | "project" | "global";
94
+ /** Path of the .md it was loaded from. Unset for embedded defaults. */
95
+ sourcePath?: string;
96
+ }
97
+
98
+ export type JoinMode = 'async' | 'group' | 'smart';
99
+
100
+ /**
101
+ * Display mode for the persistent above-editor agent widget.
102
+ * - `all`: show every agent (foreground + background).
103
+ * - `background`: hide foreground agents (they already render inline as the
104
+ * Agent tool result, #118); show background/queued/scheduled/RPC.
105
+ * - `off`: hide the widget entirely.
106
+ */
107
+ export type WidgetMode = 'all' | 'background' | 'off';
108
+
109
+ /**
110
+ * How much of the conversation viewer's transcript is rendered as Markdown.
111
+ * - `off`: every line wraps as literal text, as it did before the mode existed.
112
+ * - `assistant`: assistant text renders as Markdown; tool results stay verbatim
113
+ * and dim. The default, because assistant text *is* Markdown by contract
114
+ * while a tool result is arbitrary bytes — a Markdown pass over a log or a
115
+ * diff eats `#` from shell comments, swallows a `---` line into a setext
116
+ * heading, re-fences indented output and redraws `| a | b |` as a table.
117
+ * (Ordered-list renumbering is the one such rewrite actively suppressed —
118
+ * see `MARKDOWN_OPTIONS` — because it silently changes data, not layout.)
119
+ * - `all`: tool results render as Markdown too, for tools that genuinely emit
120
+ * it (#210's `ctx_execute`), accepting the rewrites above on ones that don't.
121
+ */
122
+ export type ViewerMarkdownMode = 'off' | 'assistant' | 'all';
123
+
124
+ /**
125
+ * How `@handle message` starts an agent that is not already running.
126
+ * - `model`: inject Claude Code's `agent_mention` reminder and let the main
127
+ * model spawn it with the `Agent` tool, which is what Claude Code does.
128
+ * - `direct`: spawn it here, immediately, with the typed message as its prompt
129
+ * and no main-model turn spent.
130
+ * - `off`: `@` means only "attach a file" again.
131
+ *
132
+ * Messaging a running agent and resuming a finished one are direct in every
133
+ * mode — Claude Code only differs from us on the *new* invocation.
134
+ */
135
+ export type AgentMentionMode = 'model' | 'direct' | 'off';
136
+
137
+ /**
138
+ * What survives a record's eviction so `@handle` keeps working. The live record
139
+ * is discarded after ~10 minutes, but the pi session it wrote is still on disk,
140
+ * and this is the little that is needed to find and describe it again.
141
+ */
142
+ export interface AgentTombstone {
143
+ handle: string;
144
+ alias?: string;
145
+ id: string;
146
+ type: SubagentType;
147
+ description: string;
148
+ /** Always set — a record with no session file is never tombstoned. */
149
+ sessionFile: string;
150
+ completedAt: number;
151
+ }
152
+
153
+ /**
154
+ * What `@handle` resolved to: an agent still in memory, or the remains of one
155
+ * whose conversation can be reopened from disk.
156
+ */
157
+ export type MentionResolution =
158
+ | { kind: "live"; record: AgentRecord }
159
+ | { kind: "tombstone"; entry: AgentTombstone };
160
+
161
+ export interface AgentRecord {
162
+ id: string;
163
+ type: SubagentType;
164
+ /**
165
+ * Typeable name for the `@handle message` prompt mention, derived from the
166
+ * agent type and numbered when siblings collide (`explore`, `explore-2`).
167
+ * Top-level agents only — nested children are hidden from every top-level
168
+ * surface, so nothing can address them.
169
+ */
170
+ handle?: string;
171
+ /**
172
+ * A second, memorable handle from the spawner's `name` (`@auth-audit`), drawn
173
+ * from the same namespace as `handle` so the two can never collide. Purely
174
+ * additive: `handle` is assigned regardless, so a named agent stays reachable
175
+ * by its type and `@explore` never comes to mean "start another one".
176
+ */
177
+ alias?: string;
178
+ description: string;
179
+ status: "queued" | "running" | "completed" | "steered" | "aborted" | "stopped" | "error";
180
+ result?: string;
181
+ error?: string;
182
+ toolUses: number;
183
+ startedAt: number;
184
+ completedAt?: number;
185
+ session?: AgentSession;
186
+ abortController?: AbortController;
187
+ promise?: Promise<string>;
188
+ /**
189
+ * A caller is awaiting this agent inline (`spawnAndWait`) — what
190
+ * `maxConcurrentForeground` bounds. Distinct from `isBackground === false`,
191
+ * which says only that the agent has an inline result surface: a detached
192
+ * cross-extension RPC spawn is foreground by that measure and yet blocks
193
+ * nobody, so it takes no slot.
194
+ */
195
+ blocking?: boolean;
196
+ /**
197
+ * Present only while the record is "queued": resolves when it leaves the
198
+ * queue, started or aborted. `spawnAndWait` waits on this because a queued
199
+ * record has no `promise` yet. Always resolves, never rejects — a rejection
200
+ * would escape into the caller's tool `execute` and take down pi's whole
201
+ * Promise.all tool batch.
202
+ */
203
+ startGate?: Promise<void>;
204
+ groupId?: string;
205
+ joinMode?: JoinMode;
206
+ /** Set when result was already consumed via get_subagent_result — suppresses completion notification. */
207
+ resultConsumed?: boolean;
208
+ /** Steering messages queued before the session was ready. */
209
+ pendingSteers?: string[];
210
+ /** Worktree info if the agent is running in an isolated worktree. */
211
+ worktree?: { path: string; branch: string; baseSha: string; workPath: string };
212
+ /** Worktree cleanup result after agent completion. */
213
+ worktreeResult?: { hasChanges: boolean; branch?: string };
214
+ /** The tool_use_id from the original Agent tool call. */
215
+ toolCallId?: string;
216
+ /** Path to the streaming output transcript file. */
217
+ outputFile?: string;
218
+ /**
219
+ * The agent's pi session file, when it was persisted (`persist_session`, or
220
+ * the `rememberAgents` default). Captured so a mention can reopen the
221
+ * conversation after the record itself has been evicted; undefined for an
222
+ * in-memory session, which leaves nothing to reopen.
223
+ */
224
+ sessionFile?: string;
225
+ /** Cleanup function for the output file stream subscription. */
226
+ outputCleanup?: () => void;
227
+ /**
228
+ * Lifetime usage breakdown, accumulated via `message_end` events. Survives
229
+ * compaction. Total = input + output + cacheWrite (cacheRead deliberately
230
+ * excluded — see issue #38). Initialized to zeros at spawn.
231
+ */
232
+ lifetimeUsage: LifetimeUsage;
233
+ /** Number of times this agent's session has compacted. Initialized to 0 at spawn. */
234
+ compactionCount: number;
235
+ /**
236
+ * Whether this agent was spawned to run in the background. Tri-state, set at
237
+ * spawn from `SpawnOptions.isBackground`: `true` = background, `false` =
238
+ * foreground (has an inline Agent tool-result surface), `undefined` = the
239
+ * caller never declared it (e.g. a cross-extension RPC spawn, which is detached
240
+ * and has no inline surface). The widget's background-only filter keys off this
241
+ * — and excludes only explicit `false`, so `undefined` agents stay visible.
242
+ * Reliable across ALL spawn paths, unlike the UI-only `invocation` snapshot,
243
+ * which only the Agent-tool path populates.
244
+ */
245
+ isBackground?: boolean;
246
+ /** Resolved spawn params, captured for UI display. Fixed at spawn time. */
247
+ invocation?: AgentInvocation;
248
+ /** Nesting depth: top-level subagent = 1. */
249
+ depth?: number;
250
+ /**
251
+ * The validated `StructuredOutput` payload, as canonical JSON.
252
+ *
253
+ * Set only when the spawn asked for a schema. Separate from `result` because
254
+ * `result` is prose for a reader — previewed in the widget, written to the
255
+ * transcript, and appended to with the worktree branch note — and JSON that
256
+ * has been appended to no longer parses.
257
+ */
258
+ structuredJson?: string;
259
+ /** Whether the child needed the extra structured-output prompt. */
260
+ structuredRetried?: boolean;
261
+ /** Parent agent ID for ownership-scoped nested controls. */
262
+ parentAgentId?: string;
263
+ /**
264
+ * The workflow run that owns this child, when a workflow spawned it.
265
+ *
266
+ * Owned the same way a nested child is owned by its parent: filtered out of
267
+ * every top-level surface, and outside the `maxConcurrent` pool. See
268
+ * `isTopLevelAgent`.
269
+ */
270
+ workflowId?: string;
271
+ /** Effective inherited nesting cap for this branch. */
272
+ maxSubagentDepth?: number;
273
+ /**
274
+ * Session id of the root (main) session this branch descends from. Nested
275
+ * spawns inherit it so their transcripts file under the same session
276
+ * directory as their ancestors' instead of the child session's own id.
277
+ */
278
+ rootSessionId?: string;
279
+ }
280
+
281
+ /**
282
+ * What a session reports as its level: pi's `ThinkingLevel` plus the `"off"` a
283
+ * model with thinking disabled reports. Display-only — spawning still takes a
284
+ * `ThinkingLevel`, so this widening cannot leak into an invocation.
285
+ */
286
+ export type EffectiveThinkingLevel = ThinkingLevel | "off";
287
+
288
+ export interface AgentInvocation {
289
+ /** Short display name for tight rows, e.g. "haiku 4.5". Always set once known. */
290
+ modelName?: string;
291
+ /** Canonical `provider/id`, for surfaces with room to disambiguate providers. */
292
+ modelId?: string;
293
+ /** The level actually in effect, once a session exists to report one. */
294
+ thinking?: EffectiveThinkingLevel;
295
+ /** Configured OpenAI Responses/Codex processing tier, when applicable. */
296
+ serviceTier?: ServiceTier;
297
+ /**
298
+ * What the caller asked for, kept only when they did not get it — pi clamped
299
+ * the level to the model's capabilities, or an agent file's frontmatter
300
+ * outranked the parameter (#182). The snapshot exists to answer "did the spawn
301
+ * honor my instructions?" (#62), which it cannot do if the request is lost, so
302
+ * neither `requested*` field is overwritten once set.
303
+ */
304
+ requestedThinking?: EffectiveThinkingLevel;
305
+ /** The caller's `model` parameter, as written, when an agent file's pin won. */
306
+ requestedModel?: string;
307
+ maxTurns?: number;
308
+ isolated?: boolean;
309
+ inheritContext?: boolean;
310
+ runInBackground?: boolean;
311
+ isolation?: IsolationMode;
312
+ }
313
+
314
+ /** Details attached to custom notification messages for visual rendering. */
315
+ export interface NotificationDetails {
316
+ id: string;
317
+ description: string;
318
+ status: string;
319
+ toolUses: number;
320
+ turnCount: number;
321
+ maxTurns?: number;
322
+ totalTokens: number;
323
+ /**
324
+ * Estimated cost in USD, from pi's per-message `usage.cost.total`. Always
325
+ * populated (0 when the model has no pricing); the renderer decides whether
326
+ * to show it, per the `showCost` setting.
327
+ */
328
+ totalCost?: number;
329
+ durationMs: number;
330
+ outputFile?: string;
331
+ error?: string;
332
+ resultPreview: string;
333
+ /** Additional agents in a group notification. */
334
+ others?: NotificationDetails[];
335
+ }
336
+
337
+ export interface EnvInfo {
338
+ isGitRepo: boolean;
339
+ branch: string;
340
+ platform: string;
341
+ }
342
+
343
+ /**
344
+ * A subagent spawn registered to fire on a schedule.
345
+ *
346
+ * Stored at `<cwd>/.pi/subagent-schedules/<sessionId>.json`. Session-scoped:
347
+ * survives `/resume` but resets on `/new`, mirroring pi-chonky-tasks.
348
+ */
349
+ export interface ScheduledSubagent {
350
+ id: string;
351
+ /** Unique within store. Defaults to `description`. */
352
+ name: string;
353
+ description: string;
354
+ /** Raw user input — cron expr | "+10m" | ISO | "5m". */
355
+ schedule: string;
356
+ scheduleType: "cron" | "once" | "interval";
357
+ /** Computed at create time for interval/once. */
358
+ intervalMs?: number;
359
+
360
+ // spawn params (subset of Agent tool params; no inherit_context, no resume)
361
+ subagent_type: SubagentType;
362
+ prompt: string;
363
+ model?: string;
364
+ thinking?: ThinkingLevel;
365
+ max_turns?: number;
366
+ isolated?: boolean;
367
+ isolation?: IsolationMode;
368
+
369
+ // state
370
+ enabled: boolean;
371
+ /** ISO timestamp. */
372
+ createdAt: string;
373
+ lastRun?: string;
374
+ lastStatus?: "success" | "error" | "running";
375
+ /** Refreshed on every fire and on store load. */
376
+ nextRun?: string;
377
+ runCount: number;
378
+ }
379
+
380
+ export interface ScheduleStoreData {
381
+ /** For future migrations. */
382
+ version: 1;
383
+ jobs: ScheduledSubagent[];
384
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * agent-mention.ts — what `@` can address, and the suggestions pi renders for it.
3
+ *
4
+ * A subagent is addressable whether or not it is currently running: a live
5
+ * record is messaged or resumed, an evicted one whose session is still on disk
6
+ * is reopened, and an agent *type* with no instance at all is started. That is
7
+ * the point of the handle — `@explore` means the Explore agent, not "the
8
+ * Explore process that happens to exist right now" — so the roster below unions
9
+ * all three, and the dispatcher and the popup read the same list.
10
+ *
11
+ * Rows are per *agent*, not per handle. An agent given a `name` holds two names
12
+ * (its alias and its type-derived handle) and both resolve, but it lists once,
13
+ * under the alias, with its type moved into the description so the row still
14
+ * says what it is.
15
+ *
16
+ * pi's `CombinedAutocompleteProvider` already owns `@`, where it means "attach a
17
+ * file". Extensions can wrap it (`ctx.ui.addAutocompleteProvider`), so this
18
+ * provider adds the `@` tokens that name an agent and delegates everything else
19
+ * — including all of `applyCompletion`, whose `@`-branch already inserts
20
+ * `item.value` plus a trailing space, which is exactly what a handle needs.
21
+ *
22
+ * Matching mirrors Claude Code: case-insensitive prefix, not fuzzy. What it does
23
+ * NOT mirror is Claude Code dropping files whenever an agent matches. Here `@` is
24
+ * pi's file picker first, and the handles are additive, so a token matching both
25
+ * lists both — agents first. Suppressing on any match sounds narrow and is not:
26
+ * an empty token prefix-matches every handle, so a bare `@` — the gesture people
27
+ * use to browse files — would offer no files at all, and a single letter
28
+ * beginning any handle would do the same.
29
+ *
30
+ * Both halves ship under ONE `prefix`, which is sound because wherever BOTH sides
31
+ * produce rows they measured the same span. pi's `extractAtPrefix` takes the
32
+ * token after the last of `{space, tab, ", ', =}` and keeps it only if it starts
33
+ * with `@`; `MENTION_TRIGGER` matches `@[\w-]*` at the cursor, after start-of-line
34
+ * or `[\s。、?!]`. Where those two disagree, exactly one side answers and there
35
+ * is nothing to merge: `@src/index.ts` and `@"my file` are pi's alone (no handle
36
+ * matches), `=@ex` is pi's alone (`=` is a delimiter to pi, not a boundary to us),
37
+ * and `。@ex` is ours alone (the reverse). A merged response therefore never
38
+ * carries a prefix from one side and an item from the other.
39
+ *
40
+ * Offering never-started types is a deliberate step beyond Claude Code, whose
41
+ * registry holds only live tasks, so an agent you had not launched yet was
42
+ * unaddressable.
43
+ */
44
+
45
+ import type { AutocompleteItem, AutocompleteProvider, AutocompleteSuggestions } from "@earendil-works/pi-tui";
46
+ import type { AgentManager } from "../agent-manager.js";
47
+ import { handleBase, MENTION_TRIGGER } from "../mention.js";
48
+ import type { AgentRecord, AgentTombstone } from "../types.js";
49
+
50
+ /**
51
+ * One thing `@` can address, and what sending to it will do. `typeLabel` is the
52
+ * agent's `display_name`, resolved by the caller: this module stays independent
53
+ * of the type registry, but the popup must agree with FleetView and the widget,
54
+ * which both render the label rather than the raw type.
55
+ */
56
+ export type MentionTarget =
57
+ | { kind: "record"; handle: string; record: AgentRecord; typeLabel: string }
58
+ | { kind: "tombstone"; handle: string; entry: AgentTombstone; typeLabel: string }
59
+ | { kind: "type"; handle: string; type: string; description: string };
60
+
61
+ /** The registry facts the roster needs, so it stays independent of agent-types. */
62
+ export type TypeInfo = { name: string; description: string };
63
+
64
+ /**
65
+ * Everything `@` can reach, in the order the popup lists it: steerable agents
66
+ * first, then the other live ones earliest-launched, then agent types with no
67
+ * live instance. A type whose handle a record already holds is omitted — that
68
+ * name addresses the existing agent, which is what makes `@explore` mean
69
+ * "message the one that's running" and only otherwise "start one".
70
+ */
71
+ export function mentionRoster(
72
+ manager: AgentManager,
73
+ types: readonly TypeInfo[],
74
+ // Identity by default: a caller with no registry to consult gets the raw
75
+ // type, which is also what `getConfig` falls back to when no label is set.
76
+ displayNameOf: (type: string) => string = type => type,
77
+ ): MentionTarget[] {
78
+ const live = (r: AgentRecord) => r.status === "running" || r.status === "queued";
79
+ const records = manager.listAgents()
80
+ .filter(r => r.handle !== undefined && r.parentAgentId === undefined)
81
+ .sort((a, b) => (Number(live(b)) - Number(live(a))) || (a.startedAt - b.startedAt));
82
+
83
+ const taken = new Set<string>();
84
+ const targets: MentionTarget[] = [];
85
+
86
+ // One row per agent, not per handle. An aliased agent lists under its alias
87
+ // only — both names resolve, but showing two rows for one agent reads as two
88
+ // agents. The type handle stays addressable whether or not it is listed.
89
+ for (const record of records) {
90
+ const handle = record.alias ?? record.handle!;
91
+ taken.add(handle.toLowerCase());
92
+ if (record.handle) taken.add(record.handle.toLowerCase());
93
+ targets.push({ kind: "record", handle, record, typeLabel: displayNameOf(record.type) });
94
+ }
95
+
96
+ // Then agents that are gone but whose conversation can be reopened. After the
97
+ // live ones: a running agent is the likelier target, and this keeps the
98
+ // ordering "what exists now, then what can be brought back, then what can be
99
+ // started".
100
+ for (const entry of manager.listTombstones()) {
101
+ const handle = entry.alias ?? entry.handle;
102
+ if (taken.has(handle.toLowerCase())) continue;
103
+ taken.add(handle.toLowerCase());
104
+ taken.add(entry.handle.toLowerCase());
105
+ targets.push({ kind: "tombstone", handle, entry, typeLabel: displayNameOf(entry.type) });
106
+ }
107
+
108
+ for (const type of types) {
109
+ const handle = handleBase(type.name);
110
+ if (taken.has(handle)) continue;
111
+ taken.add(handle);
112
+ targets.push({ kind: "type", handle, type: type.name, description: type.description });
113
+ }
114
+ return targets;
115
+ }
116
+
117
+ export function createMentionProvider(
118
+ current: AutocompleteProvider,
119
+ roster: () => MentionTarget[],
120
+ isEnabled: () => boolean,
121
+ ): AutocompleteProvider {
122
+ // One warning per provider, not per keystroke: `getSuggestions` runs on every
123
+ // character typed after `@`, so an unguarded log would bury the terminal in
124
+ // the time it takes to finish a word.
125
+ let warnedInnerFailure = false;
126
+ return {
127
+ // Only `@` — the contract is "characters that should naturally trigger
128
+ // THIS provider", and pi unions each wrapper's own set onto the outermost
129
+ // one itself (interactive-mode.js:432), so re-declaring the wrapped
130
+ // provider's characters here would both misreport us and duplicate that.
131
+ triggerCharacters: ["@"],
132
+
133
+ async getSuggestions(lines, cursorLine, cursorCol, options): Promise<AutocompleteSuggestions | null> {
134
+ const mine = isEnabled() ? mentionItems(roster(), lines[cursorLine] ?? "", cursorCol) : null;
135
+ // Asked unconditionally: pi owns `@` and must keep answering for it even
136
+ // when a handle matches too. That is the same work vanilla pi does on any
137
+ // `@` keystroke — a capped `fd` search, or nothing at all when the host
138
+ // configured no `fd` path — but we now do it on tokens we used to answer
139
+ // alone, so it must not be able to take the popup down with it. The
140
+ // wrapped provider is not always pi's: another extension may sit inside
141
+ // us, and before this it was never called for a token naming an agent.
142
+ // try/catch, not `.catch()`: a provider that throws SYNCHRONOUSLY never
143
+ // returns the promise a `.catch()` would attach to, and the throw escapes
144
+ // this method as a rejection — which pi does not handle either
145
+ // (components/editor.js:1892 awaits with no catch of its own).
146
+ let theirs: AutocompleteSuggestions | null = null;
147
+ try {
148
+ theirs = await current.getSuggestions(lines, cursorLine, cursorCol, options);
149
+ } catch (err) {
150
+ // Safe to treat as "no files": pi discards any response whose request is
151
+ // no longer current, so an aborted search that surfaces as a rejection
152
+ // cannot leave a stale popup behind (`isAutocompleteRequestCurrent`).
153
+ // Warned rather than swallowed outright — the failure is invisible in
154
+ // the popup, and the same `console.warn` channel already carries this
155
+ // extension's other non-fatal failures.
156
+ if (!warnedInnerFailure) {
157
+ warnedInnerFailure = true;
158
+ console.warn("[pi-subagents] the autocomplete provider below us failed; showing agent rows only:", err);
159
+ }
160
+ theirs = null;
161
+ }
162
+ if (!mine) return theirs;
163
+ if (!theirs) return mine;
164
+ // Agents first: there are a handful of them against pi's 20 file rows, and
165
+ // a handle buried under fuzzy path matches is a handle nobody finds. The
166
+ // prefix is ours by the span argument in the header — identical to pi's
167
+ // whenever both sides have something to say.
168
+ return { items: [...mine.items, ...theirs.items], prefix: mine.prefix };
169
+ },
170
+
171
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
172
+ return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
173
+ },
174
+
175
+ shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
176
+ return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
177
+ },
178
+ };
179
+ }
180
+
181
+ /** Suggestions for the `@…` token under the cursor, or null when it names no agent. */
182
+ function mentionItems(roster: MentionTarget[], line: string, cursorCol: number): AutocompleteSuggestions | null {
183
+ const match = MENTION_TRIGGER.exec(line.slice(0, cursorCol));
184
+ if (!match) return null;
185
+
186
+ const typed = match[2].toLowerCase();
187
+ const items: AutocompleteItem[] = [];
188
+ for (const target of roster) {
189
+ if (!target.handle.toLowerCase().startsWith(typed)) continue;
190
+ items.push({ value: `@${target.handle}`, label: `@${target.handle}`, description: describeTarget(target) });
191
+ }
192
+ return items.length > 0 ? { items, prefix: `@${match[2]}` } : null;
193
+ }
194
+
195
+ /** Name the action that will actually happen, so the list never mispromises. */
196
+ function describeTarget(target: MentionTarget): string {
197
+ if (target.kind === "type") return `start agent · ${summarize(target.description)}`;
198
+ if (target.kind === "tombstone") {
199
+ // No status: the record is gone, and "completed" would imply one is still
200
+ // being tracked. The type carries the identity the handle may not.
201
+ return `resume · ${target.typeLabel} · ${target.entry.description}`;
202
+ }
203
+ const { status, description, alias } = target.record;
204
+ const action = status === "running" || status === "queued" ? "send message" : "resume";
205
+ // A row listed under its alias has lost the type its handle would have shown,
206
+ // so name it — `@auth-audit` alone says nothing about what the agent is.
207
+ // A type-derived row already reads as its type and would just repeat itself.
208
+ const identity = alias ? `${target.typeLabel} · ` : "";
209
+ return `${action} · ${identity}${status} · ${description}`;
210
+ }
211
+
212
+ /** First sentence of an agent description, clipped — these run to paragraphs. */
213
+ function summarize(description: string): string {
214
+ const first = (description.match(/^.*?[.!?](?=\s|$)/s)?.[0] ?? description).replace(/\s+/g, " ").trim();
215
+ return first.length > 60 ? `${first.slice(0, 59).trimEnd()}…` : first;
216
+ }