@timmyjl12/pi-subagents 0.0.0-stage → 0.21.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 (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  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 +40 -0
  9. package/dist/active-agents-prompt.js +98 -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 +131 -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 +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,187 @@
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
+ import { handleBase, MENTION_TRIGGER } from "../mention.js";
45
+ /**
46
+ * Everything `@` can reach, in the order the popup lists it: steerable agents
47
+ * first, then the other live ones earliest-launched, then agent types with no
48
+ * live instance. A type whose handle a record already holds is omitted — that
49
+ * name addresses the existing agent, which is what makes `@explore` mean
50
+ * "message the one that's running" and only otherwise "start one".
51
+ */
52
+ export function mentionRoster(manager, types,
53
+ // Identity by default: a caller with no registry to consult gets the raw
54
+ // type, which is also what `getConfig` falls back to when no label is set.
55
+ displayNameOf = type => type) {
56
+ const live = (r) => r.status === "running" || r.status === "queued";
57
+ const records = manager.listAgents()
58
+ .filter(r => r.handle !== undefined && r.parentAgentId === undefined)
59
+ .sort((a, b) => (Number(live(b)) - Number(live(a))) || (a.startedAt - b.startedAt));
60
+ const taken = new Set();
61
+ const targets = [];
62
+ // One row per agent, not per handle. An aliased agent lists under its alias
63
+ // only — both names resolve, but showing two rows for one agent reads as two
64
+ // agents. The type handle stays addressable whether or not it is listed.
65
+ for (const record of records) {
66
+ const handle = record.alias ?? record.handle;
67
+ taken.add(handle.toLowerCase());
68
+ if (record.handle)
69
+ taken.add(record.handle.toLowerCase());
70
+ targets.push({ kind: "record", handle, record, typeLabel: displayNameOf(record.type) });
71
+ }
72
+ // Then agents that are gone but whose conversation can be reopened. After the
73
+ // live ones: a running agent is the likelier target, and this keeps the
74
+ // ordering "what exists now, then what can be brought back, then what can be
75
+ // started".
76
+ for (const entry of manager.listTombstones()) {
77
+ const handle = entry.alias ?? entry.handle;
78
+ if (taken.has(handle.toLowerCase()))
79
+ continue;
80
+ taken.add(handle.toLowerCase());
81
+ taken.add(entry.handle.toLowerCase());
82
+ targets.push({ kind: "tombstone", handle, entry, typeLabel: displayNameOf(entry.type) });
83
+ }
84
+ for (const type of types) {
85
+ const handle = handleBase(type.name);
86
+ if (taken.has(handle))
87
+ continue;
88
+ taken.add(handle);
89
+ targets.push({ kind: "type", handle, type: type.name, description: type.description });
90
+ }
91
+ return targets;
92
+ }
93
+ export function createMentionProvider(current, roster, isEnabled) {
94
+ // One warning per provider, not per keystroke: `getSuggestions` runs on every
95
+ // character typed after `@`, so an unguarded log would bury the terminal in
96
+ // the time it takes to finish a word.
97
+ let warnedInnerFailure = false;
98
+ return {
99
+ // Only `@` — the contract is "characters that should naturally trigger
100
+ // THIS provider", and pi unions each wrapper's own set onto the outermost
101
+ // one itself (interactive-mode.js:432), so re-declaring the wrapped
102
+ // provider's characters here would both misreport us and duplicate that.
103
+ triggerCharacters: ["@"],
104
+ async getSuggestions(lines, cursorLine, cursorCol, options) {
105
+ const mine = isEnabled() ? mentionItems(roster(), lines[cursorLine] ?? "", cursorCol) : null;
106
+ // Asked unconditionally: pi owns `@` and must keep answering for it even
107
+ // when a handle matches too. That is the same work vanilla pi does on any
108
+ // `@` keystroke — a capped `fd` search, or nothing at all when the host
109
+ // configured no `fd` path — but we now do it on tokens we used to answer
110
+ // alone, so it must not be able to take the popup down with it. The
111
+ // wrapped provider is not always pi's: another extension may sit inside
112
+ // us, and before this it was never called for a token naming an agent.
113
+ // try/catch, not `.catch()`: a provider that throws SYNCHRONOUSLY never
114
+ // returns the promise a `.catch()` would attach to, and the throw escapes
115
+ // this method as a rejection — which pi does not handle either
116
+ // (components/editor.js:1892 awaits with no catch of its own).
117
+ let theirs = null;
118
+ try {
119
+ theirs = await current.getSuggestions(lines, cursorLine, cursorCol, options);
120
+ }
121
+ catch (err) {
122
+ // Safe to treat as "no files": pi discards any response whose request is
123
+ // no longer current, so an aborted search that surfaces as a rejection
124
+ // cannot leave a stale popup behind (`isAutocompleteRequestCurrent`).
125
+ // Warned rather than swallowed outright — the failure is invisible in
126
+ // the popup, and the same `console.warn` channel already carries this
127
+ // extension's other non-fatal failures.
128
+ if (!warnedInnerFailure) {
129
+ warnedInnerFailure = true;
130
+ console.warn("[pi-subagents] the autocomplete provider below us failed; showing agent rows only:", err);
131
+ }
132
+ theirs = null;
133
+ }
134
+ if (!mine)
135
+ return theirs;
136
+ if (!theirs)
137
+ return mine;
138
+ // Agents first: there are a handful of them against pi's 20 file rows, and
139
+ // a handle buried under fuzzy path matches is a handle nobody finds. The
140
+ // prefix is ours by the span argument in the header — identical to pi's
141
+ // whenever both sides have something to say.
142
+ return { items: [...mine.items, ...theirs.items], prefix: mine.prefix };
143
+ },
144
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
145
+ return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
146
+ },
147
+ shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
148
+ return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
149
+ },
150
+ };
151
+ }
152
+ /** Suggestions for the `@…` token under the cursor, or null when it names no agent. */
153
+ function mentionItems(roster, line, cursorCol) {
154
+ const match = MENTION_TRIGGER.exec(line.slice(0, cursorCol));
155
+ if (!match)
156
+ return null;
157
+ const typed = match[2].toLowerCase();
158
+ const items = [];
159
+ for (const target of roster) {
160
+ if (!target.handle.toLowerCase().startsWith(typed))
161
+ continue;
162
+ items.push({ value: `@${target.handle}`, label: `@${target.handle}`, description: describeTarget(target) });
163
+ }
164
+ return items.length > 0 ? { items, prefix: `@${match[2]}` } : null;
165
+ }
166
+ /** Name the action that will actually happen, so the list never mispromises. */
167
+ function describeTarget(target) {
168
+ if (target.kind === "type")
169
+ return `start agent · ${summarize(target.description)}`;
170
+ if (target.kind === "tombstone") {
171
+ // No status: the record is gone, and "completed" would imply one is still
172
+ // being tracked. The type carries the identity the handle may not.
173
+ return `resume · ${target.typeLabel} · ${target.entry.description}`;
174
+ }
175
+ const { status, description, alias } = target.record;
176
+ const action = status === "running" || status === "queued" ? "send message" : "resume";
177
+ // A row listed under its alias has lost the type its handle would have shown,
178
+ // so name it — `@auth-audit` alone says nothing about what the agent is.
179
+ // A type-derived row already reads as its type and would just repeat itself.
180
+ const identity = alias ? `${target.typeLabel} · ` : "";
181
+ return `${action} · ${identity}${status} · ${description}`;
182
+ }
183
+ /** First sentence of an agent description, clipped — these run to paragraphs. */
184
+ function summarize(description) {
185
+ const first = (description.match(/^.*?[.!?](?=\s|$)/s)?.[0] ?? description).replace(/\s+/g, " ").trim();
186
+ return first.length > 60 ? `${first.slice(0, 59).trimEnd()}…` : first;
187
+ }
@@ -0,0 +1,304 @@
1
+ /**
2
+ * agent-widget.ts — Compact running/completed agent list above or below the editor.
3
+ *
4
+ * Displays a tree of agents with animated spinners, live stats, and activity descriptions.
5
+ * Uses the callback form of setWidget for themed rendering.
6
+ */
7
+ import { type AdvisorStatus } from "../advisor-status.ts";
8
+ import { type AgentManager } from "../agent-manager.ts";
9
+ import type { AgentInvocation, SubagentType, WidgetMode, WidgetPlacement } from "../types.ts";
10
+ import { type SessionLike } from "../usage.ts";
11
+ /** Braille spinner frames for animated running indicator. */
12
+ export declare const SPINNER: string[];
13
+ /** Statuses that indicate an error/non-success outcome (used for linger behavior and icon rendering). */
14
+ export declare const ERROR_STATUSES: Set<string>;
15
+ export type Theme = {
16
+ fg(color: string, text: string): string;
17
+ bold(text: string): string;
18
+ };
19
+ type WidgetTUI = {
20
+ terminal: {
21
+ columns: number;
22
+ };
23
+ requestRender(): void;
24
+ getFocusedComponent?(): unknown;
25
+ focusedComponent?: unknown;
26
+ };
27
+ export type UICtx = {
28
+ setStatus(key: string, text: string | undefined): void;
29
+ setWidget(key: string, content: undefined | ((tui: WidgetTUI, theme: Theme) => {
30
+ render(width?: number): string[];
31
+ invalidate(): void;
32
+ }), options?: {
33
+ placement?: "aboveEditor" | "belowEditor";
34
+ }): void;
35
+ onTerminalInput?(handler: (data: string) => {
36
+ consume?: boolean;
37
+ } | undefined): () => void;
38
+ getEditorText?(): string;
39
+ };
40
+ /** The host's side of the ← → Agent Hub shortcut; every field is read live. */
41
+ export interface AgentHubWiring {
42
+ /** Open the Hub overlay. */
43
+ open(): void;
44
+ /**
45
+ * Whether the Hub would have rows: the Hub's content, not the compact list's
46
+ * visibility — a foreground-only roster (filtered out by `widgetMode`) or
47
+ * settled history past the linger must still open. Defaults to the
48
+ * unfiltered top-level roster.
49
+ */
50
+ hasContent?(): boolean;
51
+ /** True while the Hub overlay is open; ← then belongs to it, not this handler. */
52
+ isOpen?(): boolean;
53
+ }
54
+ /** Per-agent live activity state. */
55
+ export interface AgentActivity {
56
+ activeTools: Map<string, string>;
57
+ toolUses: number;
58
+ responseText: string;
59
+ session?: SessionLike;
60
+ /** Current turn count. */
61
+ turnCount: number;
62
+ /** Effective max turns for this agent (undefined = unlimited). */
63
+ maxTurns?: number;
64
+ }
65
+ /** Metadata attached to Agent tool results for custom rendering. */
66
+ export interface AgentDetails {
67
+ displayName: string;
68
+ description: string;
69
+ subagentType: string;
70
+ toolUses: number;
71
+ tokens: string;
72
+ durationMs: number;
73
+ status: "queued" | "running" | "completed" | "steered" | "aborted" | "stopped" | "error" | "background";
74
+ /** Human-readable description of what the agent is currently doing. */
75
+ activity?: string;
76
+ /** Current spinner frame index (for animated running indicator). */
77
+ spinnerFrame?: number;
78
+ /** Short label for the model the run used, e.g. "haiku 4.5". */
79
+ modelName?: string;
80
+ /** Notable config tags (e.g. ["thinking: high", "isolated"]). */
81
+ tags?: string[];
82
+ /** Current turn count. */
83
+ turnCount?: number;
84
+ /** Effective max turns (undefined = unlimited). */
85
+ maxTurns?: number;
86
+ /** Estimated cost in USD; 0 when the model has no pricing data. */
87
+ cost?: number;
88
+ agentId?: string;
89
+ advisorStatus?: AdvisorStatus;
90
+ error?: string;
91
+ }
92
+ /** Apply foreground styling while restoring it after nested foreground/full ANSI resets. */
93
+ export declare function fgPreservingNestedStyles(theme: Theme, color: string, text: string): string;
94
+ /** Format a token count compactly: "33.8k token", "1.2M token". */
95
+ export declare function formatTokens(count: number): string;
96
+ /**
97
+ * Format a cost as `~$0.0042`, or "" when there is nothing to show.
98
+ *
99
+ * The tilde is load-bearing: this is pi's own estimate from the model's listed
100
+ * rates, not a billed figure, and the surfaces that print it sit next to token
101
+ * counts that ARE exact.
102
+ *
103
+ * Nothing is printed for zero, which is also what a model with no pricing data
104
+ * reports: `$0.00` beside a local model's tokens would claim its cost was
105
+ * measured and found to be nothing, rather than never measured at all. For the
106
+ * same reason a real cost too small for four decimals reads `<$0.0001` — it was
107
+ * measured, and rounding it to `~$0.0000` would say the opposite.
108
+ */
109
+ export declare function formatCost(cost: number): string;
110
+ /**
111
+ * Token count with optional context-fill % and compaction-count annotations.
112
+ * Thresholds for percent: <70% dim, 70–85% warning, ≥85% error.
113
+ * Compaction count rendered as `⇊N` in dim.
114
+ *
115
+ * "12.3k token" — no annotations
116
+ * "12.3k token (45%)" — percent only
117
+ * "12.3k token (⇊2)" — compactions only (e.g. right after compact)
118
+ * "12.3k token (45% · ⇊2)" — both
119
+ */
120
+ export declare function formatSessionTokens(tokens: number, percent: number | null, theme: Theme, compactions?: number): string;
121
+ /** Format turn count with optional max limit: "↻5≤30" or "↻5". */
122
+ export declare function formatTurns(turnCount: number, maxTurns?: number | null): string;
123
+ /** Format milliseconds as human-readable duration. */
124
+ export declare function formatMs(ms: number): string;
125
+ /** Format duration from start/completed timestamps. */
126
+ export declare function formatDuration(startedAt: number, completedAt?: number): string;
127
+ /** Get display name for any agent type (built-in or custom). */
128
+ export declare function getDisplayName(type: SubagentType): string;
129
+ /** Short label for prompt mode: "twin" for append, nothing for replace (the default). */
130
+ export declare function getPromptModeLabel(type: SubagentType): string | undefined;
131
+ /**
132
+ * Mode label is not included — callers add it where they want it.
133
+ *
134
+ * Both model forms come back so each surface can pick by width; the
135
+ * "(asked X)" annotation is applied here rather than by callers, so a value the
136
+ * spawn did not honor cannot be rendered as though it had been (#182).
137
+ */
138
+ export declare function buildInvocationTags(invocation: AgentInvocation | undefined): {
139
+ modelName?: string;
140
+ modelId?: string;
141
+ tags: string[];
142
+ };
143
+ /**
144
+ * Make externally supplied text safe to place in ONE terminal row.
145
+ *
146
+ * Every entry an extension returns from `render()` is ONE terminal row: pi's
147
+ * TUI pushes each array element verbatim (`tui.js` `lines.push(line)`) and
148
+ * measures the block's height as `childLines.length`. A literal `\n` — or `\t`,
149
+ * or any other control byte — inside an entry makes the terminal advance a row
150
+ * the renderer never counted, permanently desynchronising its line diff. The
151
+ * visible symptom is a frozen duplicate row left on screen above and rows
152
+ * clipped below (the footer/statusline among them). Truncation cannot rescue
153
+ * it either: pi-tui's `visibleWidth` counts control characters as zero-width,
154
+ * so such a line passes the width check and still wraps in the terminal.
155
+ *
156
+ * Agent descriptions and error messages are the realistic carriers — both are
157
+ * free text (a model-supplied tool argument; a raw `Error.message`, which is
158
+ * frequently multi-line). ANSI styling is applied AFTER this runs, so stripping
159
+ * ESC here doubles as a terminal-injection guard for the plain fragments.
160
+ *
161
+ * Internal whitespace is preserved; see {@link sanitizeRowText} to collapse it.
162
+ */
163
+ export declare function flattenRow(text: string): string;
164
+ /**
165
+ * {@link flattenRow} plus whitespace collapsing, for short single-line labels
166
+ * (descriptions, names, error heads) where runs of spaces carry nothing.
167
+ * Use {@link flattenRow} instead where indentation is meaningful.
168
+ */
169
+ export declare function sanitizeRowText(text: string): string;
170
+ /** Build a human-readable activity string from currently-running tools or response text. */
171
+ export declare function describeActivity(activeTools: Map<string, string>, responseText?: string): string;
172
+ export declare class AgentWidget {
173
+ private manager;
174
+ private agentActivity;
175
+ /**
176
+ * Read live at render time. Selects which agents the widget shows — see
177
+ * `WidgetMode`. Defaults to `"all"`, matching the extension's own default.
178
+ */
179
+ private mode;
180
+ /**
181
+ * Read live at render time, like `mode`. Whether running agents show an
182
+ * estimated cost beside their token count. Defaults to off — the extension
183
+ * supplies the user's `showCost` setting.
184
+ */
185
+ private showCost;
186
+ /**
187
+ * Read live at render time, like `mode`. Whether running agents name the
188
+ * model driving them and the thinking level it is running at. Defaults to
189
+ * off — the extension supplies the user's `showModel` setting — because the
190
+ * row is already dense and the same pair is on the tool result and in the
191
+ * conversation viewer unconditionally.
192
+ */
193
+ private showModel;
194
+ /** Read live; changing placement remounts the same widget key once. */
195
+ private placement;
196
+ private uiCtx;
197
+ private widgetFrame;
198
+ private widgetInterval;
199
+ /** One-shot timer that re-runs update() when the earliest finished row expires. */
200
+ private expiryTimer;
201
+ /** Wall-clock time each finished agent was first seen finished. */
202
+ private finishedAt;
203
+ /** How long a completed row lingers without any turn activity. */
204
+ static readonly FINISHED_LINGER_MS = 5000;
205
+ /** Errors/aborts linger longer so they are not missed. */
206
+ static readonly ERROR_LINGER_MS = 10000;
207
+ /** Tracks how many turns each finished agent has survived. Key: agent ID, Value: turns since finished. */
208
+ private finishedTurnAge;
209
+ /** How many extra turns errors/aborted agents linger (completed agents clear after 1 turn). */
210
+ private static readonly ERROR_LINGER_TURNS;
211
+ /** Whether the widget callback is currently registered with the TUI. */
212
+ private widgetRegistered;
213
+ private registeredPlacement;
214
+ private inputUnsub;
215
+ private hub;
216
+ /** Cached TUI reference from widget factory callback, used for repaint and focus checks. */
217
+ private tui;
218
+ /** Last status bar text, used to avoid redundant setStatus calls. */
219
+ private lastStatusText;
220
+ constructor(manager: AgentManager, agentActivity: Map<string, AgentActivity>,
221
+ /**
222
+ * Read live at render time. Selects which agents the widget shows — see
223
+ * `WidgetMode`. Defaults to `"all"`, matching the extension's own default.
224
+ */
225
+ mode?: () => WidgetMode,
226
+ /**
227
+ * Read live at render time, like `mode`. Whether running agents show an
228
+ * estimated cost beside their token count. Defaults to off — the extension
229
+ * supplies the user's `showCost` setting.
230
+ */
231
+ showCost?: () => boolean,
232
+ /**
233
+ * Read live at render time, like `mode`. Whether running agents name the
234
+ * model driving them and the thinking level it is running at. Defaults to
235
+ * off — the extension supplies the user's `showModel` setting — because the
236
+ * row is already dense and the same pair is on the tool result and in the
237
+ * conversation viewer unconditionally.
238
+ */
239
+ showModel?: () => boolean,
240
+ /** Read live; changing placement remounts the same widget key once. */
241
+ placement?: () => WidgetPlacement);
242
+ /** Reuse the extension's canonical Agent Hub, without an inline navigation mode. */
243
+ setHubOpener(hub: AgentHubWiring): void;
244
+ /**
245
+ * Agents eligible for the widget, per the current `WidgetMode`:
246
+ * - `off`: none (the widget's existing empty-state path hides it entirely).
247
+ * - `background`: drop only agents *known* to be foreground
248
+ * (`isBackground === false`); keep everything else — background, queued,
249
+ * scheduled, or RPC-spawned (`undefined`). Keying off the `isBackground`
250
+ * record flag rather than the UI-only `invocation` snapshot (which only the
251
+ * Agent-tool path sets), and excluding rather than allow-listing, means
252
+ * only proven-foreground runs drop out — nothing else silently vanishes.
253
+ * - `all`: every agent.
254
+ */
255
+ private widgetAgents;
256
+ /** Set the UI context (grabbed from first tool execution). */
257
+ setUICtx(ctx: UICtx): void;
258
+ /**
259
+ * Called on each new turn (tool_execution_start).
260
+ * Ages finished agents and clears those that have lingered long enough.
261
+ */
262
+ onTurnStart(): void;
263
+ /** Ensure the widget update timer is running. */
264
+ ensureTimer(): void;
265
+ /** Check if a finished agent should still be shown in the widget. */
266
+ private shouldShowFinished;
267
+ /** Wall-clock expiry of a finished row (seeds the finish time on first sight). */
268
+ private finishedExpiry;
269
+ /** Record an agent as finished (call when agent completes). */
270
+ markFinished(agentId: string): void;
271
+ private stopInterval;
272
+ private clearExpiryTimer;
273
+ /** Schedule one unref'd update() at the given wall-clock time. */
274
+ private scheduleExpiry;
275
+ /** True while the widget holds a repaint timer (interval or expiry). */
276
+ hasPendingTimers(): boolean;
277
+ /**
278
+ * Drop an agent's finished-age (call when a settled agent starts running
279
+ * again, i.e. a background resume). markFinished only seeds an age it has not
280
+ * seen before, so a resumed agent would otherwise keep the age from its
281
+ * previous run — already past the linger limit, hiding the new run's
282
+ * completion line entirely.
283
+ */
284
+ markRunning(agentId: string): void;
285
+ /** Render a finished agent line. */
286
+ private renderFinishedLine;
287
+ /**
288
+ * Render the widget content. Called from the registered widget's render() callback,
289
+ * reading live state each time instead of capturing it in a closure.
290
+ */
291
+ private renderWidget;
292
+ /**
293
+ * Acquire the TUI reference without a visible list. Pi invokes the factory
294
+ * synchronously inside setWidget but paints on the next render tick, so a
295
+ * register immediately followed by an unregister captures the reference and
296
+ * never draws a frame. A separate key from the real widget, so the
297
+ * registration state machine never notices.
298
+ */
299
+ private probeTui;
300
+ /** Force an immediate widget update. */
301
+ update(): void;
302
+ dispose(): void;
303
+ }
304
+ export {};