@herbertgao/pi-subagents 0.17.1 → 0.18.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 (50) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +427 -120
  3. package/docs/rpc.md +184 -0
  4. package/docs/workflows.md +466 -0
  5. package/examples/agent-tool-description.md +6 -6
  6. package/examples/workflows/compose.js +52 -0
  7. package/examples/workflows/fan-out-audit.js +56 -0
  8. package/examples/workflows/gated-fix.js +60 -0
  9. package/examples/workflows/lib/count-child.js +30 -0
  10. package/examples/workflows/review-panel.js +68 -0
  11. package/examples/workflows/structured-findings.js +81 -0
  12. package/package.json +11 -9
  13. package/src/agent-file-toggle.ts +52 -12
  14. package/src/agent-manager.ts +837 -146
  15. package/src/agent-runner.ts +213 -39
  16. package/src/cross-extension-rpc.ts +73 -14
  17. package/src/custom-agents.ts +101 -47
  18. package/src/index.ts +2249 -914
  19. package/src/invocation-config.ts +13 -0
  20. package/src/mention-clone.ts +215 -0
  21. package/src/mention.ts +147 -0
  22. package/src/model-resolver.ts +9 -1
  23. package/src/nested-tools.ts +40 -26
  24. package/src/output-file.ts +18 -8
  25. package/src/prompts.ts +46 -9
  26. package/src/schedule.ts +21 -16
  27. package/src/settings.ts +137 -7
  28. package/src/structured-output.ts +136 -0
  29. package/src/types.ts +126 -8
  30. package/src/ui/agent-mention.ts +274 -0
  31. package/src/ui/agent-widget.ts +20 -5
  32. package/src/ui/conversation-viewer.ts +10 -4
  33. package/src/ui/fleet-list.ts +167 -22
  34. package/src/ui/workflow-card.ts +555 -0
  35. package/src/ui/workflow-dialog.ts +1304 -0
  36. package/src/ui/workflow-menu.ts +226 -0
  37. package/src/workflow/collisions.ts +122 -0
  38. package/src/workflow/entry.ts +47 -0
  39. package/src/workflow/host.ts +463 -0
  40. package/src/workflow/journal.ts +164 -0
  41. package/src/workflow/json-schema.ts +142 -0
  42. package/src/workflow/meta.ts +401 -0
  43. package/src/workflow/progress.ts +622 -0
  44. package/src/workflow/runtime.ts +1399 -0
  45. package/src/workflow/saved.ts +230 -0
  46. package/src/workflow/task.ts +333 -0
  47. package/src/workflow/tool-description.ts +200 -0
  48. package/src/workflow/worker-source.ts +781 -0
  49. package/src/worktree.ts +97 -95
  50. package/src/xml.ts +13 -0
@@ -0,0 +1,555 @@
1
+ /**
2
+ * workflow-card.ts — the inline transcript card for a running workflow.
3
+ *
4
+ * ```
5
+ * ▸ Workflow review-changes 3/7 agents · 1m12s
6
+ * Review changed files across dimensions, verify each finding
7
+ * ╭─ Review
8
+ * │ ├─ ✔ review:bugs · Explore · haiku · 18.4k · 12 tool calls · 42s
9
+ * │ ├─ ⟳ review:perf · Explore · 8 tool calls · 21s
10
+ * │ └─ ⟳ review:security
11
+ * ╰─ Verify
12
+ * └─ ⟳ verify:auth.ts · Plan · 3 tool calls · 9s
13
+ * ⎿ scanned 41 changed files
14
+ * ```
15
+ *
16
+ * Two things about this file are easy to get wrong.
17
+ *
18
+ * **The glyphs are not the dialog's glyphs.** The inline row keys off the *raw*
19
+ * entry `state` (start | progress | done | error), not the derived display
20
+ * state, so a skipped or blocked agent renders as a plain ✘ here while the
21
+ * workflows dialog distinguishes them. `displayState` is deliberately not
22
+ * consulted below.
23
+ *
24
+ * **The layout is pure.** `layoutWorkflowCard` returns coloured segments and
25
+ * never touches a theme or a terminal, so the same layout drives the `Workflow`
26
+ * tool's `renderResult` and a standalone session entry (a workflow launched from
27
+ * a CLI flag has no tool call to attach to). Theme application is the thin
28
+ * `styleWorkflowCardLines` wrapper on top.
29
+ *
30
+ * All state derivation lives in `src/workflow/progress.ts`; this file only
31
+ * arranges what that module returns.
32
+ */
33
+
34
+ import {
35
+ stripTerminalSequences,
36
+ Text,
37
+ truncateToWidth,
38
+ visibleWidth,
39
+ } from "@earendil-works/pi-tui"
40
+ import type { WorkflowEntryData } from "../workflow/entry.js"
41
+ import type { WorkflowMeta } from "../workflow/meta.js"
42
+ import {
43
+ buildPhaseGroups,
44
+ collapse,
45
+ formatDuration,
46
+ header,
47
+ sizeWarning,
48
+ stats,
49
+ type WorkflowAgentEntry,
50
+ type WorkflowEntry,
51
+ type WorkflowRunStatus,
52
+ } from "../workflow/progress.js"
53
+ import type { Theme } from "./agent-widget.js"
54
+
55
+ /**
56
+ * Header re-render cadence. Claude Code ticks the workflow clock once a second,
57
+ * not at the 80ms spinner cadence — the running glyph is static, so there is
58
+ * nothing to animate faster than the elapsed time changes.
59
+ */
60
+ export const WORKFLOW_TICK_MS = 1000
61
+
62
+ /** Widest label column before stats stop being aligned and just follow the label. */
63
+ const LABEL_COLUMN_MAX = 28
64
+
65
+ /** Fallback width when the caller does not know the terminal's. */
66
+ const DEFAULT_WIDTH = 80
67
+
68
+ /* ------------------------------------------------------------------------- *
69
+ * Glyphs
70
+ * ------------------------------------------------------------------------- */
71
+
72
+ export interface WorkflowGlyphs {
73
+ /** Tool-title pointer, matching the Agent tool's `▸`. */
74
+ pointer: string
75
+ tick: string
76
+ cross: string
77
+ /** Running/queued. A static glyph, hence no spinner inline. */
78
+ running: string
79
+ /** First and subsequent phase groups. */
80
+ groupTop: string
81
+ /** A group that is neither the first nor the last. */
82
+ groupMid: string
83
+ /** The last phase group. */
84
+ groupBottom: string
85
+ /** Continuation rail under a non-final group. */
86
+ vertical: string
87
+ branch: string
88
+ lastBranch: string
89
+ /** Log-line prefix, matching the Agent tool's result lines. */
90
+ log: string
91
+ warning: string
92
+ }
93
+
94
+ export const UNICODE_GLYPHS: WorkflowGlyphs = {
95
+ pointer: "▸",
96
+ tick: "✔",
97
+ cross: "✘",
98
+ running: "⟳",
99
+ groupTop: "╭─",
100
+ groupMid: "├─",
101
+ groupBottom: "╰─",
102
+ vertical: "│",
103
+ branch: "├─",
104
+ lastBranch: "└─",
105
+ log: "⎿",
106
+ warning: "⚠",
107
+ }
108
+
109
+ /**
110
+ * The `figures` ASCII tier, for terminals that cannot draw the box set. Every
111
+ * glyph keeps its unicode counterpart's column width so the tree stays aligned
112
+ * either way.
113
+ */
114
+ export const ASCII_GLYPHS: WorkflowGlyphs = {
115
+ pointer: ">",
116
+ tick: "√",
117
+ cross: "×",
118
+ running: "*",
119
+ groupTop: ",-",
120
+ groupMid: "|-",
121
+ groupBottom: "`-",
122
+ vertical: "|",
123
+ branch: "|-",
124
+ lastBranch: "`-",
125
+ log: "\\",
126
+ warning: "!",
127
+ }
128
+
129
+ /* ------------------------------------------------------------------------- *
130
+ * Lines
131
+ * ------------------------------------------------------------------------- */
132
+
133
+ /**
134
+ * pi theme keys. Claude Code's palette maps as success→success, error→error,
135
+ * subtle→dim, permission→warning for a blocked row and accent for selection;
136
+ * an undefined colour means "leave it at the terminal default", which is what
137
+ * the recovered inline mapping asks for on a running row.
138
+ *
139
+ * `accent` is unused by the card and exists for the workflows dialog, which
140
+ * shares these segment types.
141
+ */
142
+ export type WorkflowCardColor =
143
+ | "success"
144
+ | "error"
145
+ | "warning"
146
+ | "dim"
147
+ | "muted"
148
+ | "toolTitle"
149
+ | "accent"
150
+
151
+ export interface WorkflowCardSegment {
152
+ text: string
153
+ color?: WorkflowCardColor
154
+ bold?: boolean
155
+ }
156
+
157
+ export type WorkflowCardLine = WorkflowCardSegment[]
158
+
159
+ /** The subset of the task record the card reads. */
160
+ export interface WorkflowCardTask {
161
+ status: WorkflowRunStatus
162
+ workflowName?: string
163
+ summary?: string
164
+ description?: string
165
+ startTime: number
166
+ endTime?: number
167
+ totalPausedMs?: number
168
+ }
169
+
170
+ export interface WorkflowCardInput {
171
+ progress: readonly WorkflowEntry[]
172
+ task: WorkflowCardTask
173
+ meta?: WorkflowMeta
174
+ /** Agents the runtime has scheduled, which can exceed those that have reported. */
175
+ agentCount?: number
176
+ /** Total tokens for the size warning; summed from the entries when omitted. */
177
+ totalTokens?: number
178
+ agentCap?: number
179
+ tokenCap?: number
180
+ now?: number
181
+ width?: number
182
+ /** Swap in the ASCII glyph tier for terminals without unicode. */
183
+ ascii?: boolean
184
+ /**
185
+ * Lead with `▸ SubagentWorkflow`.
186
+ *
187
+ * True where the card stands alone — the session entry a flag-launched run
188
+ * writes, which has no tool call above it to say what it is. False as a tool
189
+ * result, where the call line directly above already does.
190
+ */
191
+ showToolTitle?: boolean
192
+ }
193
+
194
+ /* ------------------------------------------------------------------------- *
195
+ * Formatting
196
+ * ------------------------------------------------------------------------- */
197
+
198
+ /** `18.4k` / `1.2M` — bare magnitude, since the row already reads as a stat. */
199
+ export function formatCompactTokens(count: number): string {
200
+ if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`
201
+ if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`
202
+ return `${count}`
203
+ }
204
+
205
+ /**
206
+ * One label for the model pair. A fallback that never differed from the primary
207
+ * would just be noise, so it only shows when the run actually has two models in
208
+ * play.
209
+ */
210
+ export function formatModel(
211
+ entry: WorkflowAgentEntry,
212
+ opts?: { canonical?: boolean },
213
+ ): string | undefined {
214
+ const { fallbackModel, requestedModel } = entry
215
+ // `canonical` is for surfaces with the width for `provider/model-id`; the
216
+ // tight rows take the short label. Chosen here rather than by the caller
217
+ // swapping fields, which would leave `fallbackModel` in the other spelling.
218
+ const model = opts?.canonical ? (entry.modelId ?? entry.model) : entry.model
219
+ const primary =
220
+ model && fallbackModel && model !== fallbackModel
221
+ ? `${model}→${fallbackModel}`
222
+ : (model ?? fallbackModel)
223
+ if (primary === undefined) return undefined
224
+ // Disclosed rather than substituted: a model an agent file pinned over the
225
+ // script's is still a model the script did not get (#182). Same rule as
226
+ // `buildInvocationTags`' `asked()` — only when the two actually differ, so a
227
+ // request that was honoured says nothing.
228
+ return requestedModel !== undefined && requestedModel !== primary
229
+ ? `${primary} (asked ${requestedModel})`
230
+ : primary
231
+ }
232
+
233
+ /**
234
+ * The thinking level, and what was asked for when it was not honoured.
235
+ *
236
+ * Separate from {@link formatModel} because a row can have one without the
237
+ * other: an `agent()` that named no model still runs at some level, and a level
238
+ * pi clamped is worth saying so about even when the model is unremarkable.
239
+ */
240
+ export function formatThinking(entry: WorkflowAgentEntry): string | undefined {
241
+ const { thinking, requestedThinking } = entry
242
+ if (!thinking) return undefined
243
+ return requestedThinking !== undefined && requestedThinking !== thinking
244
+ ? `thinking: ${thinking} (asked ${requestedThinking})`
245
+ : `thinking: ${thinking}`
246
+ }
247
+
248
+ /**
249
+ * What a row replayed from a resume journal says instead of a duration.
250
+ *
251
+ * Shared with the dialog so both views name the same thing the same way — the
252
+ * card shows it inline while the run happens, the dialog on the agent's row.
253
+ */
254
+ export const REPLAYED_ANNOTATION = "from resume journal"
255
+
256
+ /**
257
+ * The `·`-separated tail of an agent row, in the recovered order: agentType,
258
+ * model, tokens, toolCalls, durationMs. Absent values drop out entirely rather
259
+ * than rendering a placeholder.
260
+ */
261
+ export function agentStatSegments(entry: WorkflowAgentEntry): string[] {
262
+ const parts: string[] = []
263
+ if (entry.agentType) parts.push(entry.agentType)
264
+ const model = formatModel(entry)
265
+ if (model) parts.push(model)
266
+ if (entry.tokens) parts.push(formatCompactTokens(entry.tokens))
267
+ if (entry.toolCalls)
268
+ parts.push(
269
+ `${entry.toolCalls} tool call${entry.toolCalls === 1 ? "" : "s"}`,
270
+ )
271
+ if (entry.durationMs) parts.push(formatDuration(entry.durationMs))
272
+ return parts
273
+ }
274
+
275
+ /**
276
+ * The recovered inline mapping — keyed on the raw entry state. `skipped` and
277
+ * `blocked` are not distinguished here; that is the dialog's job.
278
+ */
279
+ function rowGlyph(
280
+ entry: WorkflowAgentEntry,
281
+ glyphs: WorkflowGlyphs,
282
+ ): WorkflowCardSegment {
283
+ if (entry.state === "done") return { text: glyphs.tick, color: "success" }
284
+ if (entry.state === "error") return { text: glyphs.cross, color: "error" }
285
+ return { text: glyphs.running }
286
+ }
287
+
288
+ /* ------------------------------------------------------------------------- *
289
+ * Layout
290
+ * ------------------------------------------------------------------------- */
291
+
292
+ /** Trim a line to `width`, cutting inside whichever segment crosses the edge. */
293
+ export function clampLine(
294
+ line: WorkflowCardLine,
295
+ width: number,
296
+ ): WorkflowCardLine {
297
+ const clamped: WorkflowCardLine = []
298
+ let used = 0
299
+ for (const segment of line) {
300
+ const segmentWidth = visibleWidth(segment.text)
301
+ if (used + segmentWidth <= width) {
302
+ clamped.push(segment)
303
+ used += segmentWidth
304
+ continue
305
+ }
306
+ const room = width - used
307
+ // truncateToWidth wraps its ellipsis in resets, which would leak escape
308
+ // codes into a layout that is supposed to be plain text until it is themed.
309
+ if (room > 0) {
310
+ clamped.push({
311
+ ...segment,
312
+ text: stripTerminalSequences(truncateToWidth(segment.text, room, "…")),
313
+ })
314
+ }
315
+ return clamped
316
+ }
317
+ return clamped
318
+ }
319
+
320
+ const lineWidth = (line: WorkflowCardLine) =>
321
+ line.reduce((sum, s) => sum + visibleWidth(s.text), 0)
322
+
323
+ /**
324
+ * Build the card.
325
+ *
326
+ * Everything derived — the phase tree, the header counts, the logs, the size
327
+ * warning — comes from `progress.ts`; what happens here is purely arrangement.
328
+ */
329
+ export function layoutWorkflowCard(
330
+ input: WorkflowCardInput,
331
+ ): WorkflowCardLine[] {
332
+ const glyphs = input.ascii ? ASCII_GLYPHS : UNICODE_GLYPHS
333
+ const width = Math.max(1, input.width ?? DEFAULT_WIDTH)
334
+ const now = input.now ?? Date.now()
335
+
336
+ const groups = buildPhaseGroups(input.progress, input.meta?.phases)
337
+ const { agents, logs } = collapse(input.progress)
338
+ const totals = stats(input.progress, input.agentCount ?? 0)
339
+ const head = header(
340
+ input.task,
341
+ input.meta,
342
+ groups,
343
+ input.agentCount ?? 0,
344
+ now,
345
+ )
346
+
347
+ const lines: WorkflowCardLine[] = []
348
+
349
+ // ---- Header: `<name>` with the stats flush right ----
350
+ // The tool name appears only when nothing above the card already carries it.
351
+ // As a tool result there is a `▸ SubagentWorkflow …` call line directly above,
352
+ // and repeating it put two near-identical pointer lines back to back.
353
+ const left: WorkflowCardLine = input.showToolTitle
354
+ ? [
355
+ { text: `${glyphs.pointer} `, color: "toolTitle" },
356
+ { text: "SubagentWorkflow", color: "toolTitle", bold: true },
357
+ { text: " " },
358
+ { text: head.name, color: "muted" },
359
+ ]
360
+ : [{ text: " " }, { text: head.name, color: "toolTitle", bold: true }]
361
+ const statsWidth = visibleWidth(head.stats)
362
+ const clampedLeft = clampLine(left, Math.max(0, width - statsWidth - 1))
363
+ const gap = Math.max(1, width - lineWidth(clampedLeft) - statsWidth)
364
+ lines.push([
365
+ ...clampedLeft,
366
+ { text: " ".repeat(gap) },
367
+ { text: head.stats, color: "dim" },
368
+ ])
369
+
370
+ if (head.subtext)
371
+ lines.push(clampLine([{ text: ` ${head.subtext}`, color: "dim" }], width))
372
+
373
+ // ---- Phase tree ----
374
+ // Stats line up in one column across the whole card, not per group, so the
375
+ // eye can scan them; a label past the cap just pushes its own stats along.
376
+ const labelColumn = Math.min(
377
+ LABEL_COLUMN_MAX,
378
+ Math.max(
379
+ 0,
380
+ ...groups.flatMap((group) =>
381
+ group.agents.map((a) => visibleWidth(a.label)),
382
+ ),
383
+ ),
384
+ )
385
+
386
+ groups.forEach((group, groupIndex) => {
387
+ const lastGroup = groupIndex === groups.length - 1
388
+ lines.push(
389
+ clampLine(
390
+ [
391
+ { text: " " },
392
+ // One box, not a stack of them: only the first group opens it and
393
+ // only the last closes it. Everything between branches off the side,
394
+ // or three phases read as three half-drawn boxes.
395
+ {
396
+ text: `${
397
+ lastGroup
398
+ ? glyphs.groupBottom
399
+ : groupIndex === 0
400
+ ? glyphs.groupTop
401
+ : glyphs.groupMid
402
+ } `,
403
+ color: "dim",
404
+ },
405
+ { text: group.title },
406
+ ],
407
+ width,
408
+ ),
409
+ )
410
+
411
+ const rail = lastGroup ? " " : `${glyphs.vertical} `
412
+ group.agents.forEach((entry, agentIndex) => {
413
+ const lastAgent = agentIndex === group.agents.length - 1
414
+ const segments: WorkflowCardLine = [
415
+ { text: " " },
416
+ { text: rail, color: "dim" },
417
+ {
418
+ text: `${lastAgent ? glyphs.lastBranch : glyphs.branch} `,
419
+ color: "dim",
420
+ },
421
+ rowGlyph(entry, glyphs),
422
+ { text: " " },
423
+ ]
424
+
425
+ // Prepended rather than folded into `agentStatSegments`, which is the
426
+ // ported stat tail in its recovered order. A replayed agent otherwise
427
+ // renders as a tick with no tokens and no duration — indistinguishable
428
+ // from one that somehow did the work for free.
429
+ const statParts = entry.cached
430
+ ? [REPLAYED_ANNOTATION, ...agentStatSegments(entry)]
431
+ : agentStatSegments(entry)
432
+ const pad = Math.max(0, labelColumn - visibleWidth(entry.label))
433
+ segments.push({
434
+ text:
435
+ statParts.length > 0 ? entry.label + " ".repeat(pad) : entry.label,
436
+ })
437
+ for (const part of statParts) {
438
+ segments.push(
439
+ { text: " · ", color: "dim" },
440
+ { text: part, color: "dim" },
441
+ )
442
+ }
443
+ lines.push(clampLine(segments, width))
444
+ })
445
+ })
446
+
447
+ // ---- log() output, below the tree ----
448
+ for (const message of logs) {
449
+ const [first, ...rest] = message.split("\n")
450
+ lines.push(
451
+ clampLine([{ text: ` ${glyphs.log} ${first}`, color: "dim" }], width),
452
+ )
453
+ for (const continuation of rest) {
454
+ lines.push(
455
+ clampLine([{ text: ` ${continuation}`, color: "dim" }], width),
456
+ )
457
+ }
458
+ }
459
+
460
+ // ---- Size warning ----
461
+ const totalTokens =
462
+ input.totalTokens ??
463
+ agents.reduce((sum, entry) => sum + (entry.tokens ?? 0), 0)
464
+ const warning = sizeWarning({
465
+ scheduledAgents: Math.max(input.agentCount ?? 0, totals.total),
466
+ startedAgents: totals.started,
467
+ totalTokens,
468
+ agentCap: input.agentCap,
469
+ tokenCap: input.tokenCap,
470
+ })
471
+ if (warning) {
472
+ lines.push(
473
+ clampLine(
474
+ [
475
+ {
476
+ text: ` ${glyphs.warning} Large workflow · /agents → Workflows to stop`,
477
+ color: "warning",
478
+ },
479
+ ],
480
+ width,
481
+ ),
482
+ )
483
+ }
484
+
485
+ return lines
486
+ }
487
+
488
+ /* ------------------------------------------------------------------------- *
489
+ * Rendering
490
+ * ------------------------------------------------------------------------- */
491
+
492
+ /** The card as plain text — what the layout tests assert against. */
493
+ export function plainWorkflowCardLines(
494
+ lines: readonly WorkflowCardLine[],
495
+ ): string[] {
496
+ return lines.map((line) => line.map((segment) => segment.text).join(""))
497
+ }
498
+
499
+ /** Apply the theme. Nothing here changes the layout, only its colours. */
500
+ export function styleWorkflowCardLines(
501
+ lines: readonly WorkflowCardLine[],
502
+ theme: Theme,
503
+ ): string[] {
504
+ return lines.map((line) =>
505
+ line
506
+ .map((segment) => {
507
+ const text = segment.bold ? theme.bold(segment.text) : segment.text
508
+ return segment.color ? theme.fg(segment.color, text) : text
509
+ })
510
+ .join(""),
511
+ )
512
+ }
513
+
514
+ /** The card as a component, for a tool result or a session entry renderer. */
515
+ export function renderWorkflowCard(
516
+ input: WorkflowCardInput,
517
+ theme: Theme,
518
+ ): Text {
519
+ return new Text(
520
+ styleWorkflowCardLines(layoutWorkflowCard(input), theme).join("\n"),
521
+ 0,
522
+ 0,
523
+ )
524
+ }
525
+
526
+ /**
527
+ * The card for a session entry, from the JSON a flag-launched run persisted.
528
+ *
529
+ * The same layout the tool result uses, not a second one — the only difference
530
+ * is `showToolTitle`, because a session entry stands alone and nothing above it
531
+ * says what it is. Returns undefined for an entry with no data, which is what
532
+ * pi's renderer contract wants for "nothing to draw".
533
+ */
534
+ export function renderWorkflowEntryCard(
535
+ data: WorkflowEntryData | undefined,
536
+ theme: Theme,
537
+ ): Text | undefined {
538
+ if (!data) return undefined
539
+ return renderWorkflowCard(
540
+ {
541
+ progress: data.progress,
542
+ task: {
543
+ status: data.status,
544
+ workflowName: data.name,
545
+ startTime: data.startTime,
546
+ endTime: data.endTime,
547
+ },
548
+ meta: data.meta,
549
+ agentCount: data.agentCount,
550
+ totalTokens: data.totalTokens,
551
+ showToolTitle: true,
552
+ },
553
+ theme,
554
+ )
555
+ }