@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,179 @@
1
+ /**
2
+ * hub-feed.ts — pure data for the fleet overlay's live panes (omp Agent Hub parity).
3
+ *
4
+ * - `transcriptTail`: the last few events of one agent's child session — prompts,
5
+ * replies, tool calls and failed results — for the right pane under the detail card.
6
+ * - `activityFeed`: the same events across every agent, newest first, for the
7
+ * Activity tab, with All / Errors / Responses / Tools filters.
8
+ * - `treeOrder`: parent → child ordering for the tree view.
9
+ *
10
+ * Everything is derived from `session.messages` on render; no extra state is
11
+ * recorded, so the feed can never disagree with the conversation viewer.
12
+ */
13
+
14
+ import type { AgentRecord } from "../types.ts";
15
+
16
+ export type FeedKind = "prompt" | "response" | "tool" | "error";
17
+ export type ActivityFilter = "all" | "errors" | "responses" | "tools";
18
+ export const ACTIVITY_FILTERS: readonly ActivityFilter[] = ["all", "errors", "responses", "tools"];
19
+
20
+ export interface FeedEvent {
21
+ readonly kind: FeedKind;
22
+ readonly text: string;
23
+ readonly at?: number;
24
+ }
25
+
26
+ export interface ActivityEntry extends FeedEvent {
27
+ readonly agentId: string;
28
+ readonly agent: string;
29
+ }
30
+
31
+ interface MessageLike {
32
+ role?: unknown;
33
+ content?: unknown;
34
+ timestamp?: unknown;
35
+ toolName?: unknown;
36
+ isError?: unknown;
37
+ stopReason?: unknown;
38
+ errorMessage?: unknown;
39
+ }
40
+
41
+ function oneLine(text: string, max = 240): string {
42
+ const flat = text.replace(/\s+/g, " ").trim();
43
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
44
+ }
45
+
46
+ function textOf(content: unknown): string {
47
+ if (typeof content === "string") return content;
48
+ if (!Array.isArray(content)) return "";
49
+ return content
50
+ .map(part => (part && typeof part === "object" && (part as { type?: unknown }).type === "text" ? String((part as { text?: unknown }).text ?? "") : ""))
51
+ .filter(Boolean)
52
+ .join(" ");
53
+ }
54
+
55
+ /** Compact `name(arg)` label: the first string argument says the most (path, pattern, command). */
56
+ function toolLabel(part: { name?: unknown; arguments?: unknown }): string {
57
+ const name = typeof part.name === "string" ? part.name : "tool";
58
+ const args = part.arguments && typeof part.arguments === "object" ? Object.values(part.arguments as Record<string, unknown>) : [];
59
+ const first = args.find(value => typeof value === "string") as string | undefined;
60
+ return first ? `${name}(${oneLine(first, 80)})` : `${name}()`;
61
+ }
62
+
63
+ /** Events of one message, in order. */
64
+ export function eventsOf(message: unknown): FeedEvent[] {
65
+ const m = (message ?? {}) as MessageLike;
66
+ const at = typeof m.timestamp === "number" ? m.timestamp : undefined;
67
+ const events: FeedEvent[] = [];
68
+ if (m.role === "user") {
69
+ const text = oneLine(textOf(m.content));
70
+ if (text) events.push({ kind: "prompt", text, at });
71
+ } else if (m.role === "assistant") {
72
+ if (Array.isArray(m.content)) {
73
+ for (const part of m.content as Array<{ type?: unknown; text?: unknown; name?: unknown; arguments?: unknown }>) {
74
+ if (part?.type === "text" && typeof part.text === "string" && part.text.trim()) {
75
+ events.push({ kind: "response", text: oneLine(part.text), at });
76
+ } else if (part?.type === "toolCall") {
77
+ events.push({ kind: "tool", text: toolLabel(part), at });
78
+ }
79
+ }
80
+ }
81
+ if (m.stopReason === "error" && typeof m.errorMessage === "string") {
82
+ events.push({ kind: "error", text: oneLine(m.errorMessage), at });
83
+ }
84
+ } else if (m.role === "toolResult" && m.isError === true) {
85
+ const name = typeof m.toolName === "string" ? m.toolName : "tool";
86
+ events.push({ kind: "error", text: `${name} failed: ${oneLine(textOf(m.content), 160)}`, at });
87
+ }
88
+ return events;
89
+ }
90
+
91
+ function messagesOf(record: AgentRecord): readonly unknown[] {
92
+ const messages = (record.session as { messages?: unknown } | undefined)?.messages;
93
+ return Array.isArray(messages) ? messages : [];
94
+ }
95
+
96
+ /** The last `max` events of an agent's session, oldest → newest (bottom is live). */
97
+ export function transcriptTail(record: AgentRecord, max: number): FeedEvent[] {
98
+ if (max <= 0) return [];
99
+ const messages = messagesOf(record);
100
+ const out: FeedEvent[] = [];
101
+ // Walk backwards and stop early: a long session never pays for its whole history.
102
+ for (let i = messages.length - 1; i >= 0 && out.length < max; i -= 1) {
103
+ const events = eventsOf(messages[i]);
104
+ for (let j = events.length - 1; j >= 0 && out.length < max; j -= 1) out.push(events[j] as FeedEvent);
105
+ }
106
+ return out.reverse();
107
+ }
108
+
109
+ function matchesFilter(kind: FeedKind, filter: ActivityFilter): boolean {
110
+ if (filter === "all") return true;
111
+ if (filter === "errors") return kind === "error";
112
+ if (filter === "responses") return kind === "response";
113
+ return kind === "tool";
114
+ }
115
+
116
+ /**
117
+ * Combined log across agents, newest first. Each agent contributes at most
118
+ * `perAgent` recent events so one chatty agent cannot crowd out the rest.
119
+ */
120
+ export function activityFeed(
121
+ records: readonly AgentRecord[],
122
+ options: { filter: ActivityFilter; limit: number; perAgent?: number },
123
+ ): ActivityEntry[] {
124
+ const perAgent = options.perAgent ?? 60;
125
+ const entries: Array<ActivityEntry & { order: number }> = [];
126
+ let order = 0;
127
+ for (const record of records) {
128
+ const agent = record.alias ?? record.handle ?? record.type;
129
+ for (const event of transcriptTail(record, perAgent)) {
130
+ if (!matchesFilter(event.kind, options.filter)) continue;
131
+ entries.push({ ...event, agentId: record.id, agent, order: order++ });
132
+ }
133
+ }
134
+ entries.sort((a, b) => (b.at ?? 0) - (a.at ?? 0) || b.order - a.order);
135
+ return entries.slice(0, options.limit).map(({ order: _order, ...entry }) => entry);
136
+ }
137
+
138
+ export interface TreeRow {
139
+ readonly record: AgentRecord;
140
+ readonly depth: number;
141
+ }
142
+
143
+ /**
144
+ * Parent → child order. Roots are the given top-level records in their given
145
+ * order; each child follows its parent, oldest first. Orphans (parent swept)
146
+ * surface as roots so nothing disappears.
147
+ *
148
+ * `hidden` drops a row from the output without dropping what is under it: the
149
+ * subtree is still traversed, one level up, so a view filter (a dismissed row)
150
+ * can never re-insert the row it removed or hide its descendants.
151
+ */
152
+ export function treeOrder(
153
+ roots: readonly AgentRecord[],
154
+ all: readonly AgentRecord[],
155
+ hidden?: (record: AgentRecord) => boolean,
156
+ ): TreeRow[] {
157
+ const children = new Map<string, AgentRecord[]>();
158
+ const ids = new Set(all.map(record => record.id));
159
+ for (const record of all) {
160
+ const parent = record.parentAgentId;
161
+ if (!parent || !ids.has(parent)) continue;
162
+ const list = children.get(parent) ?? [];
163
+ list.push(record);
164
+ children.set(parent, list);
165
+ }
166
+ const out: TreeRow[] = [];
167
+ const seen = new Set<string>();
168
+ const visit = (record: AgentRecord, depth: number) => {
169
+ if (seen.has(record.id)) return;
170
+ seen.add(record.id);
171
+ const hiddenHere = hidden?.(record) ?? false;
172
+ if (!hiddenHere) out.push({ record, depth });
173
+ for (const child of (children.get(record.id) ?? []).sort((a, b) => a.startedAt - b.startedAt)) {
174
+ visit(child, hiddenHere ? depth : depth + 1);
175
+ }
176
+ };
177
+ for (const root of roots) visit(root, 0);
178
+ return out;
179
+ }
@@ -0,0 +1,224 @@
1
+ /** Native Pi cards without a second InteractiveMode or ownership of the child session. */
2
+ import type { AssistantMessage, ToolResultMessage } from "@earendil-works/pi-ai";
3
+ import {
4
+ type AgentSession, type AgentSessionEvent, AssistantMessageComponent, CustomMessageComponent,
5
+ createBashToolDefinition, createEditToolDefinition, createFindToolDefinition,
6
+ createGrepToolDefinition, createLsToolDefinition, createPowerShellToolDefinition,
7
+ createReadToolDefinition, createWriteToolDefinition, ToolExecutionComponent, UserMessageComponent,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import { type Component, type MarkdownTheme, Text, type TUI, type TuiMouseEvent, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
10
+ import { extractText } from "../context.ts";
11
+ import { boundToolResult, getToolProgress, RESULT_MAX_CHARS, type ToolDisplayResult, truncationNote } from "./tool-progress.ts";
12
+
13
+ type AgentMessage = AgentSession["messages"][number];
14
+ type Renderers = NonNullable<ConstructorParameters<typeof ToolExecutionComponent>[4]>;
15
+ type Entry = { component: Component; raw: () => string; failed?: boolean; failedPrefix?: string; elided?: number; top: number; height: number };
16
+ type ToolEntry = Entry & { component: ToolExecutionComponent; name: string; args: unknown; result?: ToolDisplayResult };
17
+ const factories = {
18
+ read: createReadToolDefinition, bash: createBashToolDefinition, powershell: createPowerShellToolDefinition,
19
+ edit: createEditToolDefinition, write: createWriteToolDefinition, grep: createGrepToolDefinition,
20
+ find: createFindToolDefinition, ls: createLsToolDefinition,
21
+ };
22
+
23
+ export class NativeTranscript implements Component {
24
+ private entries: Entry[] = [];
25
+ private tools = new Map<string, ToolEntry>();
26
+ private seen = new WeakSet<AgentMessage>();
27
+ private streaming: { message: AssistantMessage; entry: Entry; component: AssistantMessageComponent } | undefined;
28
+ private readonly builtIns = new Map<string, Renderers>();
29
+ private expanded = false;
30
+
31
+ constructor(private session: AgentSession, private tui: TUI, private markdownTheme: MarkdownTheme) {}
32
+
33
+ /** Synchronous replay, called after subscribing. No await/gap between snapshot and event delivery. */
34
+ hydrate(): void {
35
+ this.entries = [];
36
+ this.tools.clear();
37
+ this.seen = new WeakSet();
38
+ this.streaming = undefined;
39
+ for (const message of this.session.messages) this.addMessage(message);
40
+ const partial = this.session.agent?.state.streamingMessage;
41
+ if (partial?.role === "assistant" && !this.seen.has(partial)) this.updateAssistant(partial, true);
42
+ for (const progress of getToolProgress(this.session)) {
43
+ const entry = this.ensureTool(progress.toolCallId, progress.toolName, progress.args);
44
+ entry.component.markExecutionStarted();
45
+ entry.component.setArgsComplete();
46
+ if (progress.result) this.updateTool(progress.toolCallId, progress.result, true, progress.elided);
47
+ }
48
+ }
49
+
50
+ handleEvent(event: AgentSessionEvent): void {
51
+ if (event.type === "message_start" || event.type === "message_end") {
52
+ if (event.message.role === "assistant") {
53
+ this.updateAssistant(event.message, event.type === "message_start");
54
+ } else if (event.type === "message_end" || event.message.role === "user") {
55
+ this.addMessage(event.message);
56
+ }
57
+ } else if (event.type === "message_update" && event.message.role === "assistant") {
58
+ this.updateAssistant(event.message, true);
59
+ } else if (event.type === "tool_execution_start" || event.type === "tool_execution_update") {
60
+ const entry = this.ensureTool(event.toolCallId, event.toolName, event.args);
61
+ entry.component.markExecutionStarted();
62
+ entry.component.setArgsComplete();
63
+ if (event.type === "tool_execution_update") this.updateTool(event.toolCallId, { ...event.partialResult, isError: false }, true);
64
+ } else if (event.type === "tool_execution_end") {
65
+ this.ensureTool(event.toolCallId, event.toolName, {});
66
+ // Same shape pi's own transcript hands the card: renderers read durationMs.
67
+ this.updateTool(event.toolCallId, {
68
+ ...event.result, isError: event.isError, ...(event.durationMs === undefined ? {} : { durationMs: event.durationMs }),
69
+ }, false);
70
+ } else if (event.type === "compaction_end" && event.result && !event.aborted) {
71
+ this.hydrate();
72
+ }
73
+ }
74
+
75
+ private renderers(name: string): Renderers | undefined {
76
+ const definition = this.session.getToolDefinition?.(name);
77
+ if (!this.builtIns.has(name) && Object.hasOwn(factories, name)) {
78
+ // Public factories provide the callbacks missing from session built-ins. Never execute them.
79
+ this.builtIns.set(name, factories[name as keyof typeof factories](this.cwd));
80
+ }
81
+ const fallback = this.builtIns.get(name);
82
+ return definition ? {
83
+ ...definition,
84
+ renderCall: definition.renderCall ?? fallback?.renderCall,
85
+ renderResult: definition.renderResult ?? fallback?.renderResult,
86
+ } : fallback;
87
+ }
88
+
89
+ private get cwd(): string { return this.session.sessionManager?.getCwd() ?? process.cwd(); }
90
+
91
+ private ensureTool(id: string, name: string, args: unknown): ToolEntry {
92
+ const existing = this.tools.get(id);
93
+ if (existing) return existing;
94
+ const component = new ToolExecutionComponent(name, id, args, {
95
+ showImages: this.session.settingsManager?.getShowImages() ?? true,
96
+ outputPad: this.session.settingsManager?.getOutputPad() ?? 1,
97
+ }, this.renderers(name), this.tui, this.cwd);
98
+ component.setExpanded(this.expanded);
99
+ const entry: ToolEntry = {
100
+ component, name, args, top: 0, height: 0,
101
+ raw: () => `${name} ${JSON.stringify(entry.args)}\n${entry.result?.content.filter(p => p.type === "text").map(p => p.text ?? "").join("\n") ?? ""}`,
102
+ };
103
+ this.entries.push(entry);
104
+ this.tools.set(id, entry);
105
+ return entry;
106
+ }
107
+
108
+ private updateTool(id: string, result: ToolDisplayResult, partial: boolean, alreadyElided = 0): void {
109
+ const entry = this.tools.get(id);
110
+ if (!entry) return;
111
+ const bounded = boundToolResult(result);
112
+ entry.result = bounded.result;
113
+ entry.elided = bounded.elided + alreadyElided;
114
+ entry.component.updateResult(bounded.result, partial);
115
+ }
116
+
117
+ private updateAssistant(message: AssistantMessage, partial: boolean): void {
118
+ if (!this.streaming && this.seen.has(message)) return;
119
+ if (!this.streaming) {
120
+ const component = new AssistantMessageComponent(undefined,
121
+ this.session.settingsManager?.getHideThinkingBlock() ?? false, this.markdownTheme, undefined,
122
+ this.session.settingsManager?.getOutputPad() ?? 1, this.session.extensionRunner?.getMarkdownTransformers());
123
+ const entry: Entry = { component, raw: () => extractText(message.content), top: 0, height: 0 };
124
+ this.streaming = { message, entry, component };
125
+ this.entries.push(entry);
126
+ }
127
+ const current = this.streaming;
128
+ current.message = message;
129
+ current.entry.raw = () => message.content.map(p => p.type === "thinking" ? p.thinking : p.type === "text" ? p.text : "").join("\n");
130
+ current.component.updateContent(message, partial);
131
+ for (const part of message.content) {
132
+ if (part.type !== "toolCall") continue;
133
+ const entry = this.ensureTool(part.id, part.name, part.arguments);
134
+ entry.args = part.arguments;
135
+ entry.component.updateArgs(part.arguments);
136
+ if (!partial) entry.component.setArgsComplete();
137
+ }
138
+ if (!partial) {
139
+ this.seen.add(message);
140
+ this.streaming = undefined;
141
+ }
142
+ }
143
+
144
+ private addMessage(message: AgentMessage): void {
145
+ if (this.seen.has(message)) return;
146
+ if (message.role === "assistant") { this.updateAssistant(message, false); return; }
147
+ this.seen.add(message);
148
+ if (message.role === "toolResult") {
149
+ const entry = this.ensureTool(message.toolCallId, message.toolName, {});
150
+ entry.component.setArgsComplete();
151
+ this.updateTool(message.toolCallId, message, false);
152
+ return;
153
+ }
154
+ let component: Component;
155
+ let raw: () => string;
156
+ if (message.role === "user") {
157
+ const text = typeof message.content === "string" ? message.content : extractText(message.content);
158
+ raw = () => text;
159
+ component = new UserMessageComponent(text, this.markdownTheme, this.session.settingsManager?.getOutputPad() ?? 1,
160
+ this.session.extensionRunner?.getMarkdownTransformers());
161
+ } else if (message.role === "custom") {
162
+ if (!message.display) return;
163
+ raw = () => typeof message.content === "string" ? message.content : extractText(message.content);
164
+ component = new CustomMessageComponent(message, this.session.extensionRunner?.getMessageRenderer(message.customType),
165
+ this.markdownTheme, this.session.settingsManager?.getOutputPad() ?? 1);
166
+ } else if (message.role === "bashExecution") {
167
+ raw = () => `$ ${message.command}\n${message.output.slice(0, RESULT_MAX_CHARS)}`;
168
+ component = new Text(raw(), 0, 0);
169
+ this.entries.push({ component, raw, top: 0, height: 0, elided: Math.max(0, message.output.length - RESULT_MAX_CHARS) });
170
+ return;
171
+ } else if (message.role === "compactionSummary" || message.role === "branchSummary") {
172
+ raw = () => message.summary;
173
+ component = new Text(raw(), 0, 0);
174
+ } else { return; }
175
+ this.entries.push({ component, raw, top: 0, height: 0 });
176
+ }
177
+
178
+ /** Inspection uses the same live source, not only committed history. */
179
+ inspectionMessages(): (AgentMessage & { viewerElided?: number })[] {
180
+ const messages: (AgentMessage & { viewerElided?: number })[] = [...this.session.messages];
181
+ if (this.streaming && !messages.includes(this.streaming.message)) messages.push(this.streaming.message);
182
+ const committed = new Set(messages.filter(m => m.role === "toolResult").map(m => m.toolCallId));
183
+ for (const [id, entry] of this.tools) {
184
+ if (!entry.result || committed.has(id)) continue;
185
+ messages.push({ role: "toolResult", toolCallId: id, toolName: entry.name,
186
+ content: entry.result.content as ToolResultMessage["content"], details: entry.result.details,
187
+ isError: entry.result.isError, timestamp: 0, viewerElided: entry.elided });
188
+ }
189
+ return messages;
190
+ }
191
+
192
+ toggleExpanded(): void {
193
+ this.expanded = !this.expanded;
194
+ for (const entry of this.tools.values()) entry.component.setExpanded(this.expanded);
195
+ }
196
+
197
+ render(width: number): string[] {
198
+ const lines: string[] = [];
199
+ for (const entry of this.entries) {
200
+ entry.top = lines.length;
201
+ if (entry.failed && !entry.raw().startsWith(entry.failedPrefix ?? "")) entry.failed = false;
202
+ try {
203
+ lines.push(...(entry.failed ? wrapTextWithAnsi(entry.raw(), width) : entry.component.render(width)));
204
+ } catch {
205
+ // Arbitrary extension renderers/Markdown must not take down the parent TUI.
206
+ entry.failed = true;
207
+ entry.failedPrefix = entry.raw();
208
+ lines.push(...wrapTextWithAnsi(entry.failedPrefix, width));
209
+ }
210
+ if (entry.elided) lines.push(truncationNote(entry.elided));
211
+ entry.height = lines.length - entry.top;
212
+ }
213
+ return lines.map(line => truncateToWidth(line, width));
214
+ }
215
+
216
+ handleMouse(event: TuiMouseEvent) {
217
+ const entry = this.entries.find(item => event.y >= item.top && event.y < item.top + item.height);
218
+ return entry?.component.handleMouse?.({ ...event, y: event.y - entry.top, height: entry.height });
219
+ }
220
+
221
+ invalidate(): void {
222
+ for (const entry of this.entries) { entry.failed = false; entry.component.invalidate(); }
223
+ }
224
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * schedule-menu.ts — `/agents → Scheduled jobs` submenu.
3
+ *
4
+ * Minimal v1 surface: list scheduled jobs, select one to inspect details +
5
+ * confirm cancellation. No create wizard (the `Agent` tool's `schedule` param
6
+ * is the canonical creation path), no toggle/cleanup (cancel is enough for
7
+ * "I scheduled something dumb, get rid of it"). Add management surfaces here
8
+ * if real demand emerges.
9
+ */
10
+
11
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
12
+ import type { SubagentScheduler } from "../schedule.ts";
13
+ import type { ScheduledSubagent } from "../types.ts";
14
+ import { selectItem } from "./select-item.ts";
15
+
16
+ /** Format an ISO timestamp as relative time ("in 4h", "2d ago", "—"). */
17
+ function relTime(iso: string | undefined, now = Date.now()): string {
18
+ if (!iso) return "—";
19
+ const t = new Date(iso).getTime();
20
+ if (Number.isNaN(t)) return "—";
21
+ const diff = t - now;
22
+ const abs = Math.abs(diff);
23
+ const future = diff > 0;
24
+ if (abs < 60_000) return future ? "in <1m" : "<1m ago";
25
+ const m = Math.round(abs / 60_000);
26
+ if (m < 60) return future ? `in ${m}m` : `${m}m ago`;
27
+ const h = Math.round(abs / 3_600_000);
28
+ if (h < 24) return future ? `in ${h}h` : `${h}h ago`;
29
+ const d = Math.round(abs / 86_400_000);
30
+ return future ? `in ${d}d` : `${d}d ago`;
31
+ }
32
+
33
+ /** One-line status icon. */
34
+ function statusIcon(j: ScheduledSubagent): string {
35
+ if (!j.enabled) return "✗";
36
+ if (j.lastStatus === "error") return "!";
37
+ if (j.lastStatus === "running") return "⋯";
38
+ return "✓";
39
+ }
40
+
41
+ /** Compact selectable row — name, schedule, agent type, next/last run, count. */
42
+ function formatJob(j: ScheduledSubagent, scheduler: SubagentScheduler): string {
43
+ const next = scheduler.getNextRun(j.id);
44
+ return [
45
+ statusIcon(j),
46
+ j.name.padEnd(18).slice(0, 18),
47
+ j.schedule.padEnd(14).slice(0, 14),
48
+ `[${j.subagent_type}]`,
49
+ `next ${relTime(next)}`,
50
+ `last ${relTime(j.lastRun)}`,
51
+ `runs ${j.runCount}`,
52
+ ].join(" ");
53
+ }
54
+
55
+ /** Multi-line details block for the cancel confirm. */
56
+ function formatDetails(j: ScheduledSubagent, scheduler: SubagentScheduler): string {
57
+ const next = scheduler.getNextRun(j.id) ?? "—";
58
+ return [
59
+ `name: ${j.name}`,
60
+ `schedule: ${j.schedule} (${j.scheduleType})`,
61
+ `agent: ${j.subagent_type}`,
62
+ `prompt: ${j.prompt.slice(0, 200)}${j.prompt.length > 200 ? "…" : ""}`,
63
+ `created: ${j.createdAt}`,
64
+ `last run: ${j.lastRun ?? "—"} (${j.lastStatus ?? "—"})`,
65
+ `next run: ${next}`,
66
+ `runs: ${j.runCount}`,
67
+ ].join("\n");
68
+ }
69
+
70
+ /**
71
+ * List scheduled jobs; selecting one opens a cancel-confirm with details.
72
+ * Returns when the user backs out or after a cancellation.
73
+ */
74
+ export async function showSchedulesMenu(
75
+ ctx: ExtensionCommandContext,
76
+ scheduler: SubagentScheduler,
77
+ ): Promise<void> {
78
+ if (!scheduler.isActive()) {
79
+ ctx.ui.notify("Scheduler is not active in this session.", "warning");
80
+ return;
81
+ }
82
+
83
+ const jobs = scheduler.list();
84
+ if (jobs.length === 0) {
85
+ ctx.ui.notify("No scheduled jobs.", "info");
86
+ return;
87
+ }
88
+
89
+ // Numbered + item-paired: two jobs whose names agree in the first 18
90
+ // characters format identically, and matching the returned string back
91
+ // against a parallel label array cancelled whichever came first.
92
+ const job = await selectItem(
93
+ ctx.ui,
94
+ `Scheduled jobs (${jobs.length}) — select to cancel`,
95
+ jobs,
96
+ j => formatJob(j, scheduler),
97
+ );
98
+ if (!job) return;
99
+
100
+ const ok = await ctx.ui.confirm(`Cancel "${job.name}"?`, formatDetails(job, scheduler));
101
+ if (!ok) return;
102
+
103
+ await scheduler.removeJob(job.id);
104
+ ctx.ui.notify(`Cancelled "${job.name}".`, "info");
105
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * select-item.ts — pick an item from a list via `ctx.ui.select`, safely.
3
+ *
4
+ * Pi's dialog API is `select(title, options: string[]) => Promise<string | undefined>`:
5
+ * strings in, string out, with no index or value form. Callers therefore have to
6
+ * map the returned string back to the item it came from, and the obvious way —
7
+ * `labels.indexOf(choice)` over a parallel array — silently resolves to the
8
+ * FIRST match whenever two rows format identically. Row formatters here truncate
9
+ * (job names to 18 chars, agent descriptions to whatever fits), and the text they
10
+ * truncate is LLM-authored, so collisions are ordinary rather than exotic.
11
+ *
12
+ * This numbers every row, which makes the labels unique by construction — no
13
+ * data-dependent branch that only executes in the case nobody exercises — and
14
+ * keeps each label paired with its item so a later edit that sorts or filters
15
+ * between building and resolving cannot desync them.
16
+ */
17
+
18
+ /** Minimal shape of the `ctx.ui` surface this needs. */
19
+ export interface SelectUI {
20
+ select(title: string, options: string[]): Promise<string | undefined>;
21
+ }
22
+
23
+ /**
24
+ * Show a numbered picker and return the chosen item (not its label).
25
+ *
26
+ * Returns undefined when the user escapes, or when the returned string is not
27
+ * one we offered.
28
+ */
29
+ export async function selectItem<T>(
30
+ ui: SelectUI,
31
+ title: string,
32
+ items: readonly T[],
33
+ format: (item: T, index: number) => string,
34
+ ): Promise<T | undefined> {
35
+ // Pad the number so a 10+ item list keeps its columns aligned.
36
+ const width = String(items.length).length;
37
+ const rows = items.map((item, i) => ({
38
+ item,
39
+ label: `${String(i + 1).padStart(width)}. ${format(item, i)}`,
40
+ }));
41
+
42
+ const choice = await ui.select(title, rows.map(r => r.label));
43
+ if (!choice) return undefined;
44
+ return rows.find(r => r.label === choice)?.item;
45
+ }
@@ -0,0 +1,67 @@
1
+ /** Transient, session-owned tool progress. Attach before the child starts, not when a viewer opens. */
2
+ import type { AgentSession, ToolExecutionComponent } from "@earendil-works/pi-coding-agent";
3
+
4
+ export const RESULT_MAX_CHARS = 16_000;
5
+ export function truncationNote(elided: number): string {
6
+ const thousands = elided < 999_950;
7
+ const value = thousands ? elided / 1_000 : elided / 1_000_000;
8
+ const count = elided < 1_000 ? `${elided}` : `${value.toFixed(1).replace(/\.0$/, "")}${thousands ? "k" : "M"}`;
9
+ return `... (truncated, ${count} more character${elided === 1 ? "" : "s"})`;
10
+ }
11
+
12
+ export type ToolDisplayResult = Parameters<ToolExecutionComponent["updateResult"]>[0];
13
+ export interface ToolProgress {
14
+ toolCallId: string;
15
+ toolName: string;
16
+ args: unknown;
17
+ result?: ToolDisplayResult;
18
+ elided: number;
19
+ }
20
+
21
+ /** Bound text before retaining it or handing it to a renderer; never change the session's result. */
22
+ export function boundToolResult(result: ToolDisplayResult): { result: ToolDisplayResult; elided: number } {
23
+ let remaining = RESULT_MAX_CHARS;
24
+ let elided = 0;
25
+ const content = result.content.map(part => {
26
+ if (part.type !== "text" || part.text === undefined) return part;
27
+ const text = part.text.slice(0, remaining);
28
+ remaining -= text.length;
29
+ elided += part.text.length - text.length;
30
+ return { ...part, text };
31
+ });
32
+ return { result: { ...result, content }, elided };
33
+ }
34
+
35
+ const caches = new WeakMap<AgentSession, { active: Map<string, ToolProgress>; unsubscribe: () => void }>();
36
+
37
+ /** Idempotent across resumes. The manager owns this subscription until session eviction/disposal. */
38
+ export function attachToolProgress(session: AgentSession): void {
39
+ if (caches.has(session)) return;
40
+ const active = new Map<string, ToolProgress>();
41
+ const unsubscribe = session.subscribe(event => {
42
+ if (event.type === "tool_execution_start") {
43
+ active.set(event.toolCallId, { toolCallId: event.toolCallId, toolName: event.toolName, args: event.args, elided: 0 });
44
+ } else if (event.type === "tool_execution_update") {
45
+ const bounded = boundToolResult({ ...event.partialResult, isError: false });
46
+ active.set(event.toolCallId, { toolCallId: event.toolCallId, toolName: event.toolName, args: event.args, ...bounded });
47
+ } else if (event.type === "tool_execution_end") {
48
+ active.delete(event.toolCallId);
49
+ } else if (event.type === "agent_end") {
50
+ active.clear();
51
+ }
52
+ });
53
+ caches.set(session, { active, unsubscribe });
54
+ }
55
+
56
+ export function getToolProgress(session: AgentSession): readonly ToolProgress[] {
57
+ return [...(caches.get(session)?.active.values() ?? [])];
58
+ }
59
+
60
+ /** Never called by the viewer: closing a view must not stop collecting the child's progress. */
61
+ export function releaseToolProgress(session: AgentSession): void {
62
+ const cache = caches.get(session);
63
+ if (!cache) return;
64
+ cache.unsubscribe();
65
+ cache.active.clear();
66
+ caches.delete(session);
67
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * viewer-keys.ts — Scroll key matchers for the conversation viewer.
3
+ *
4
+ * Resolves `tui.select.*` through the user's keybindings when pi provides a
5
+ * manager, falling back to the previous hardcoded keys otherwise. The viewer's
6
+ * k/j and shift+arrow aliases always work alongside whatever is bound.
7
+ */
8
+
9
+ import { type KeyId, matchesKey } from "@earendil-works/pi-tui";
10
+
11
+ /** The `tui.select.*` keybinding ids the viewer resolves. */
12
+ export type ViewerScrollKeybinding =
13
+ | "tui.select.up"
14
+ | "tui.select.down"
15
+ | "tui.select.pageUp"
16
+ | "tui.select.pageDown";
17
+
18
+ /** Structural subset of pi-tui's `KeybindingsManager` (which satisfies it). */
19
+ export interface ViewerKeybindings {
20
+ matches(data: string, keybinding: ViewerScrollKeybinding): boolean;
21
+ }
22
+
23
+ export interface ViewerKeys {
24
+ scrollUp(data: string): boolean;
25
+ scrollDown(data: string): boolean;
26
+ pageUp(data: string): boolean;
27
+ pageDown(data: string): boolean;
28
+ }
29
+
30
+ export function createViewerKeys(keybindings?: ViewerKeybindings): ViewerKeys {
31
+ const matches = (data: string, id: ViewerScrollKeybinding, fallback: KeyId): boolean =>
32
+ keybindings ? keybindings.matches(data, id) : matchesKey(data, fallback);
33
+ return {
34
+ scrollUp: (data) => matches(data, "tui.select.up", "up") || matchesKey(data, "k"),
35
+ scrollDown: (data) => matches(data, "tui.select.down", "down") || matchesKey(data, "j"),
36
+ pageUp: (data) => matches(data, "tui.select.pageUp", "pageUp") || matchesKey(data, "shift+up"),
37
+ pageDown: (data) => matches(data, "tui.select.pageDown", "pageDown") || matchesKey(data, "shift+down"),
38
+ };
39
+ }