@abelxiaoxing/cadence 2.0.35 → 2.0.37

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 (40) hide show
  1. package/README.de.md +4 -4
  2. package/README.es.md +4 -4
  3. package/README.fr.md +4 -4
  4. package/README.ja.md +3 -4
  5. package/README.ko.md +4 -4
  6. package/README.md +4 -4
  7. package/README.pt-BR.md +4 -4
  8. package/README.ru.md +5 -4
  9. package/README.zh-CN.md +4 -4
  10. package/THIRD_PARTY_NOTICES.md +9 -1
  11. package/docs/conversation-mode.md +21 -2
  12. package/docs/reuse-and-distribution.md +1 -1
  13. package/docs/service-management.md +35 -9
  14. package/package.json +18 -18
  15. package/src/abort-scope.ts +47 -0
  16. package/src/agent-browser/labeled-rule.ts +74 -0
  17. package/src/agent-browser/session-navigator.ts +187 -0
  18. package/src/agent-browser/source.ts +170 -0
  19. package/src/agent-browser/transcript-content.ts +442 -0
  20. package/src/agent-browser/transcript-pane.ts +324 -0
  21. package/src/agent-panel-model.ts +4 -248
  22. package/src/agent-panel.ts +138 -432
  23. package/src/coordinator-tools.mjs +42 -14
  24. package/src/image-content.mjs +7 -28
  25. package/src/native-build.ts +1 -1
  26. package/src/research-scan.mjs +393 -0
  27. package/src/research-tools.mjs +406 -342
  28. package/src/sdk-worker.mjs +40 -55
  29. package/src/service/contracts/core.ts +0 -1
  30. package/src/service/contracts/workbench.ts +10 -16
  31. package/src/service-cli.mjs +328 -106
  32. package/src/service-host.mjs +545 -404
  33. package/src/service-http-client.ts +55 -50
  34. package/src/worker-public.mjs +1 -2
  35. package/src/worker-toolkit.mjs +110 -0
  36. package/src/worker-workspace.d.mts +13 -0
  37. package/src/worker-workspace.mjs +48 -0
  38. package/web/dist/assets/cadence.css +1 -1
  39. package/web/dist/assets/cadence.js +17 -17
  40. package/web/dist/manifest.json +7 -7
@@ -1,93 +1,44 @@
1
- /** Background-agent panel for Pi's TUI. Observation only: it subscribes to
2
- * the `subagent:*` events on Pi's shared extension bus and renders them; it
3
- * never starts, cancels or keeps an agent or the Pi process alive.
4
- *
5
- * Nothing shows while no agent runs. A batch of agents is live above the
6
- * input; once all of them ended it collapses into a card in the transcript
7
- * (a display-only session entry) and the live view goes away. The list below
8
- * the input appears only while it is being used. */
9
- import {
10
- AssistantMessageComponent,
11
- type ExtensionAPI,
12
- type ExtensionContext,
13
- getMarkdownTheme,
14
- type Theme,
15
- ToolExecutionComponent,
16
- UserMessageComponent,
1
+ /** Readonly bus binding and compact batch summary. Agent browsing is delegated
2
+ * to the adapted upstream session navigator, not a second panel/focus model. */
3
+ import type {
4
+ ExtensionAPI,
5
+ ExtensionContext,
6
+ Theme,
17
7
  } from "@earendil-works/pi-coding-agent";
18
8
  import {
19
- type Component,
20
- Container,
21
9
  Editor,
22
10
  isKeyRelease,
23
- Key,
24
- type KeyId,
25
11
  matchesKey,
26
- Spacer,
27
- Text,
28
12
  type TUI,
29
- truncateToWidth,
13
+ type TuiMainScreen,
30
14
  } from "@earendil-works/pi-tui";
15
+ import { SessionNavigator } from "./agent-browser/session-navigator.ts";
16
+ import { cadenceBrowserSource } from "./agent-browser/source.ts";
17
+ import type { ReadingPosition } from "./agent-browser/transcript-pane.ts";
31
18
  import {
32
19
  type AgentCard,
33
20
  CARD_ENTRY,
34
21
  cardLines,
35
22
  cardOf,
36
23
  decodeCard,
37
- factsText,
38
24
  liveLines,
39
25
  MAX_ENDED,
40
26
  type Paint,
41
- type PanelAction,
42
- PanelFocus,
43
- type PanelKey,
44
- panelLines,
45
27
  SUBAGENT_EVENTS,
46
28
  SUBAGENT_VIEW,
47
29
  type SubagentState,
48
30
  SubagentStore,
49
- statusSymbol,
50
31
  } from "./agent-panel-model.ts";
51
32
 
52
33
  export interface AgentPanelOptions {
53
- /** Agent rows shown at once; more collapse into `+K more`. */
54
- maxRows?: number;
55
- /** Keep a finished batch live instead of collapsing it into a card
56
- * (CADENCE_AGENT_PANEL=always). */
34
+ /** Keep a settled summary instead of appending a session card. */
57
35
  keep?: boolean;
58
36
  now?: () => number;
59
37
  }
60
- const LIVE = "cadence-agents",
61
- LIST = "cadence-agents-list",
62
- SPIN_MS = 100;
63
- /** A batch whose agents all ended stays live this long before it collapses
64
- * into its card, so the outcome is seen and a start that follows at once
65
- * (the next workflow step) joins the same batch. */
38
+ const LIVE = "cadence-agents";
39
+ const SPIN_MS = 100;
40
+ /** Adjacent workflow steps join the same batch during this settle window. */
66
41
  export const SETTLE_MS = 1500;
67
-
68
- /** Rows kept for Pi's footer/status lines while an agent view is shown. */
69
- const RESERVED = 5;
70
- const KEYS: [KeyId, PanelKey][] = [
71
- [Key.down, "down"],
72
- [Key.up, "up"],
73
- [Key.ctrl("n"), "next"],
74
- [Key.ctrl("p"), "previous"],
75
- [Key.enter, "enter"],
76
- [Key.escape, "escape"],
77
- [Key.ctrl("c"), "interrupt"],
78
- [Key.pageUp, "pageUp"],
79
- [Key.pageDown, "pageDown"],
80
- [Key.ctrl("u"), "halfUp"],
81
- [Key.ctrl("d"), "halfDown"],
82
- [Key.home, "home"],
83
- [Key.end, "end"],
84
- ];
85
- /** Key releases (Kitty protocol) stay Pi's. */
86
- export function panelKey(data: string): PanelKey | undefined {
87
- if (isKeyRelease(data)) return undefined;
88
- return KEYS.find(([id]) => matchesKey(data, id))?.[1] ?? "other";
89
- }
90
-
91
42
  const themePaint =
92
43
  (theme: Theme): Paint =>
93
44
  (role, text) =>
@@ -102,17 +53,17 @@ export function registerAgentPanel(
102
53
  pi.events.on(channel, (data) => {
103
54
  store.apply(channel, data);
104
55
  });
105
- // Pi renders the card where it was appended and again on resume; Ctrl+O
106
- // (Pi's tool-output expansion) lists every member.
107
56
  pi.registerEntryRenderer(CARD_ENTRY, (entry, { expanded }, theme) => {
108
57
  const card = decodeCard(entry.data);
109
58
  if (!card) return undefined;
110
- const paint = themePaint(theme);
111
59
  return {
112
60
  render: (width) =>
113
- cardLines(card, expanded, Math.max(1, width - 1), paint).map(
114
- (line) => ` ${line}`,
115
- ),
61
+ cardLines(
62
+ card,
63
+ expanded,
64
+ Math.max(1, width - 1),
65
+ themePaint(theme),
66
+ ).map((line) => ` ${line}`),
116
67
  invalidate() {},
117
68
  };
118
69
  });
@@ -144,111 +95,81 @@ function attachPanel(
144
95
  commit: (card: AgentCard) => void,
145
96
  ): () => void {
146
97
  const now = options.now ?? Date.now;
147
- const maxRows = Math.max(1, options.maxRows ?? 6);
148
98
  const keep = options.keep ?? process.env.CADENCE_AGENT_PANEL === "always";
149
- const focus = new PanelFocus(store, maxRows);
150
- // A batch that ended while no session showed it has no card to give, and a
151
- // new session lists only its own agents; ones still running carry over.
152
99
  if (store.settled()) store.closeBatch();
153
100
  store.prune(0);
154
- let tui: TUI | undefined,
155
- paint: Paint = (_role, text) => text,
156
- frame = 0,
157
- spinner: ReturnType<typeof setInterval> | undefined,
158
- settling: ReturnType<typeof setTimeout> | undefined,
159
- view: { component: Component; done: () => void } | undefined,
160
- // Mounted widgets: the batch above the input while one is live, and the
161
- // list's slot below it while any agent is kept for review.
162
- live = false,
163
- list = false,
164
- // The last batch, kept live after it ended (CADENCE_AGENT_PANEL=always).
165
- kept: SubagentState[] = [],
166
- // The agent last announced on `subagent:view`, so producers load only it.
167
- announced: string | undefined;
168
- const announceView = () => {
169
- if (focus.view === announced) return;
170
- announced = focus.view;
171
- announce(announced ?? null);
172
- };
173
- const transcripts = new Map<string, Transcript>();
101
+ let tui: TUI | undefined;
102
+ let frame = 0;
103
+ let spinner: ReturnType<typeof setInterval> | undefined;
104
+ let settling: ReturnType<typeof setTimeout> | undefined;
105
+ let mounted = false;
106
+ let detached = false;
107
+ let opening = false;
108
+ let kept: SubagentState[] = [];
109
+ let browser: SessionNavigator | undefined;
110
+ let closeBrowser: (() => void) | undefined;
111
+ const positions = new Map<string, ReadingPosition>();
112
+ const liveAgents = () => (store.batch().length ? store.batch() : kept);
174
113
  const stopSpinner = () => {
175
114
  clearInterval(spinner);
176
115
  spinner = undefined;
177
116
  };
178
- const liveAgents = () => {
179
- const open = store.batch();
180
- return open.length ? open : kept;
181
- };
182
- const widget =
183
- (lines: (width: number) => string[]) => (t: TUI, theme: Theme) => {
184
- tui = t;
185
- paint = themePaint(theme);
186
- return { render: lines, invalidate() {} };
187
- };
188
- const liveWidget = widget((width) =>
189
- // The agent view takes this place; a summary above it would be noise.
190
- view
191
- ? []
192
- : liveLines(
193
- {
194
- agents: liveAgents(),
195
- now: now(),
196
- frame,
197
- maxRows,
198
- hint: focus.focus === "input",
199
- },
200
- width,
201
- paint,
202
- ),
203
- );
204
- const listWidget = widget((width) => panelLines(panelFrame(), width, paint));
117
+ const source = cadenceBrowserSource(store, announce, now);
205
118
  const mount = () => {
206
- const showLive = liveAgents().length > 0;
207
- // The list renders nothing until used, and Pi gives the slot below the
208
- // input no spacing, so it costs no row; mounting it while agents exist
209
- // is what lets ↓ see whether Pi's input box has focus.
210
- const showList = store.size > 0 || focus.view !== undefined;
211
- if (showLive !== live) {
212
- live = showLive;
213
- ctx.ui.setWidget(LIVE, showLive ? liveWidget : undefined, {
214
- placement: "aboveEditor",
215
- });
216
- }
217
- if (showList !== list) {
218
- list = showList;
219
- ctx.ui.setWidget(LIST, showList ? listWidget : undefined, {
220
- placement: "belowEditor",
221
- });
222
- }
119
+ // An empty mounted summary costs no content rows, and retains the public
120
+ // TUI handle needed to admit ↓ only when Pi's empty editor has focus.
121
+ const show = store.size > 0;
122
+ if (show === mounted) return;
123
+ mounted = show;
124
+ ctx.ui.setWidget(
125
+ LIVE,
126
+ show
127
+ ? (t, theme) => {
128
+ tui = t;
129
+ return {
130
+ render: (width) =>
131
+ browser || opening
132
+ ? []
133
+ : liveLines(
134
+ { agents: liveAgents(), now: now(), frame, hint: true },
135
+ width,
136
+ themePaint(theme),
137
+ ),
138
+ invalidate() {},
139
+ };
140
+ }
141
+ : undefined,
142
+ { placement: "aboveEditor" },
143
+ );
223
144
  };
224
- /** Close the settled batch: its card goes into the session, the live view
225
- * goes away and older ended agents beyond the review bound are dropped. */
226
- const close = () => {
145
+ const closeBatch = () => {
227
146
  clearTimeout(settling);
228
147
  settling = undefined;
229
148
  if (!store.settled()) return;
230
149
  const agents = store.closeBatch();
231
150
  if (keep) kept = agents;
232
- else
151
+ else {
233
152
  try {
234
153
  commit(cardOf(agents));
235
154
  } catch {
236
- // A replaced runtime cannot append; the agents stay reviewable.
155
+ /* A replaced runtime cannot append. */
237
156
  }
238
- const dropped = store.prune(MAX_ENDED, [focus.selected, focus.view]);
239
- for (const id of dropped) transcripts.delete(id);
240
- focus.forget(dropped);
157
+ }
158
+ for (const id of store.prune(MAX_ENDED, [
159
+ browser?.selected,
160
+ browser?.viewing,
161
+ ]))
162
+ positions.delete(id);
241
163
  };
242
- // One redraw per spinner frame while anything runs; Pi's differential
243
- // renderer rewrites only the changed rows.
244
164
  const changed = () => {
165
+ if (detached) return;
245
166
  if (kept.length && store.batch().length) kept = [];
246
167
  if (!store.settled()) {
247
168
  clearTimeout(settling);
248
169
  settling = undefined;
249
170
  } else if (!settling) {
250
171
  settling = setTimeout(() => {
251
- close();
172
+ closeBatch();
252
173
  changed();
253
174
  }, SETTLE_MS);
254
175
  settling.unref?.();
@@ -257,7 +178,7 @@ function attachPanel(
257
178
  else if (!spinner) {
258
179
  spinner = setInterval(() => {
259
180
  frame++;
260
- changed();
181
+ tui?.requestRender();
261
182
  }, SPIN_MS);
262
183
  spinner.unref?.();
263
184
  }
@@ -265,303 +186,88 @@ function attachPanel(
265
186
  tui?.requestRender();
266
187
  };
267
188
  const unsubscribe = store.subscribe(changed);
268
- const focused = () =>
269
- (
270
- tui as { getFocusedComponent?(): Component | null } | undefined
271
- )?.getFocusedComponent?.();
272
- /** Pi's own input box has focus: no dialog, selector or overlay is up. */
273
- const editorFocused = () => focused() instanceof Editor && !tui?.hasOverlay();
274
- const act = (action: PanelAction) => {
275
- if (action === "open") openView();
276
- else if (action === "close") view?.done();
277
- announceView();
278
- mount();
279
- tui?.requestRender();
280
- return action === "pass" ? undefined : { consume: true };
281
- };
282
- const unlisten = ctx.ui.onTerminalInput((data) => {
283
- if (focus.view !== undefined) {
284
- // The view handles its own keys. Pi may have put its editor back in the
285
- // view's slot (another dialog came and went); then the view is gone.
286
- if (!(focused() instanceof Editor)) return undefined;
287
- focus.abandon();
288
- view = undefined;
289
- announceView();
290
- mount();
291
- }
292
- if (focus.focus === "panel" && !editorFocused()) {
293
- // A dialog took focus: its keys are not the panel's.
294
- focus.abandon();
295
- mount();
296
- tui?.requestRender();
297
- return undefined;
298
- }
299
- const key = panelKey(data);
300
- if (!key) return undefined;
301
- const idle = ctx.ui.getEditorText() === "" && editorFocused();
302
- return act(focus.key(key, idle));
303
- });
304
-
305
- const openView = () => {
189
+ const open = () => {
190
+ if (opening || browser || detached || !tui) return;
191
+ opening = true;
192
+ // This is the current renderer's public mode, not a saved setting or a
193
+ // version fallback. Regular mode retains the upstream docked mount to
194
+ // avoid writing overlay pixels into the terminal's scrollback.
195
+ const fullscreen = tui.mode === "fullscreen";
306
196
  void ctx.ui
307
- .custom<void>((_tui, _theme, _keybindings, done) => {
308
- const component: Component = {
309
- render: (width) => viewLines(width),
310
- handleInput(data) {
311
- const key = panelKey(data);
312
- if (key) act(focus.key(key, false));
313
- },
314
- invalidate() {},
315
- };
316
- view = { component, done: () => done() };
317
- return component;
197
+ .custom<void>(
198
+ (t, theme, keys, done) => {
199
+ closeBrowser = () => done();
200
+ browser = new SessionNavigator(
201
+ t,
202
+ theme,
203
+ keys,
204
+ source,
205
+ ctx.cwd,
206
+ positions,
207
+ closeBrowser,
208
+ );
209
+ if (detached) done();
210
+ return browser;
211
+ },
212
+ fullscreen
213
+ ? {
214
+ overlay: true,
215
+ overlayOptions: {
216
+ width: "100%",
217
+ maxHeight: "70%",
218
+ anchor: "center",
219
+ },
220
+ }
221
+ : { overlay: false },
222
+ )
223
+ .catch(() => {
224
+ if (!detached)
225
+ ctx.ui.notify("Could not open the agent browser", "error");
318
226
  })
319
227
  .finally(() => {
320
- view = undefined;
321
- tui?.requestRender();
228
+ browser?.dispose();
229
+ browser = undefined;
230
+ closeBrowser = undefined;
231
+ opening = false;
232
+ if (!detached) changed();
322
233
  });
323
234
  };
324
- const panelFrame = () => ({
325
- agents: store.ordered(),
326
- focus: focus.focus,
327
- selected: focus.selected,
328
- view: focus.view,
329
- now: now(),
330
- frame,
331
- maxRows,
235
+ const unlisten = ctx.ui.onTerminalInput((data) => {
236
+ if (
237
+ detached ||
238
+ opening ||
239
+ browser ||
240
+ isKeyRelease(data) ||
241
+ !matchesKey(data, "down")
242
+ )
243
+ return;
244
+ if (
245
+ !store.size ||
246
+ ctx.ui.getEditorText() !== "" ||
247
+ tui?.hasOverlay() ||
248
+ !(
249
+ (tui as TuiMainScreen | undefined)?.getFocusedComponent() instanceof
250
+ Editor
251
+ )
252
+ )
253
+ return;
254
+ open();
255
+ return { consume: true };
332
256
  });
333
- const viewLines = (width: number): string[] => {
334
- const agent = focus.view === undefined ? undefined : store.get(focus.view);
335
- if (!agent) return [];
336
- const panelHeight = panelLines(panelFrame(), width, paint).length;
337
- const height = Math.max(
338
- 3,
339
- (tui?.terminal.rows ?? 24) - panelHeight - RESERVED,
340
- );
341
- let transcript = transcripts.get(agent.id);
342
- if (!transcript && tui) {
343
- transcript = new Transcript(tui, ctx.cwd, ctx.ui.getToolsExpanded());
344
- transcripts.set(agent.id, transcript);
345
- }
346
- const body = transcript?.render(agent, width, paint) ?? [];
347
- const top = focus.settle(agent.id, body.length, height - 2);
348
- const rows = body.slice(top, top + height - 2);
349
- while (rows.length < height - 2) rows.push("");
350
- return [
351
- truncateToWidth(banner(agent), width, "…"),
352
- ...rows,
353
- truncateToWidth(
354
- paint(
355
- "dim",
356
- "↑↓ select · Enter open · PgUp/PgDn scroll · Esc back to main",
357
- ),
358
- width,
359
- "…",
360
- ),
361
- ];
362
- };
363
- const banner = (agent: SubagentState): string => {
364
- if (agent.status === "running")
365
- return paint(
366
- "dim",
367
- `→ viewing: ${agent.label} (Esc to return to main)`,
368
- );
369
- const [symbol, role] = statusSymbol(agent, frame);
370
- const word = { done: "finished", error: "failed", cancelled: "cancelled" }[
371
- agent.status
372
- ];
373
- const facts = factsText(agent, now());
374
- return `${paint(role, `${symbol} ${word}`)}${paint(
375
- "dim",
376
- ` (${facts}) · ${agent.label} (Esc to return to main)`,
377
- )}`;
378
- };
379
-
380
257
  changed();
381
258
  return () => {
259
+ detached = true;
382
260
  unsubscribe();
383
261
  unlisten();
384
262
  stopSpinner();
385
- // A batch that already ended still gets its card in the session it ran
386
- // in; one still running carries over to the next session.
387
- if (settling) close();
263
+ if (settling) closeBatch();
388
264
  clearTimeout(settling);
389
- if (announced !== undefined) announce(null);
265
+ browser?.dispose();
390
266
  try {
391
- view?.done();
392
- if (live) ctx.ui.setWidget(LIVE, undefined);
393
- if (list) ctx.ui.setWidget(LIST, undefined);
267
+ closeBrowser?.();
268
+ if (mounted) ctx.ui.setWidget(LIVE, undefined);
394
269
  } catch {
395
- // A replaced runtime already cleared its UI.
270
+ /* The old runtime already cleared its UI. */
396
271
  }
397
272
  };
398
273
  }
399
-
400
- // biome-ignore lint/suspicious/noControlCharactersInRegex: match OSC 133 terminal marks
401
- const OSC_133 = /\x1b\]133;[^\x07\x1b]*(?:\x07|\x1b\\)/g;
402
- type Message = Record<string, unknown> & { content?: unknown };
403
- const textOf = (content: unknown): string =>
404
- typeof content === "string"
405
- ? content
406
- : Array.isArray(content)
407
- ? content
408
- .map((block) =>
409
- block?.type === "text"
410
- ? String(block.text ?? "")
411
- : block?.type === "image"
412
- ? "[image]"
413
- : "",
414
- )
415
- .filter(Boolean)
416
- .join("\n")
417
- : "";
418
-
419
- /** One agent's messages as Pi's own transcript components, the way Pi renders
420
- * a resumed session. Only the tail is rebuilt: new messages, a replaced
421
- * streaming snapshot, or everything once older messages were dropped. */
422
- class Transcript {
423
- private readonly root = new Container();
424
- private parts: Component[][] = [];
425
- private tail: object | undefined;
426
- private tailStreaming = false;
427
- private omitted = 0;
428
- private revision = -1;
429
- private readonly tools = new Map<string, ToolExecutionComponent>();
430
- constructor(
431
- private readonly tui: TUI,
432
- private readonly cwd: string,
433
- private readonly expanded: boolean,
434
- ) {}
435
-
436
- render(agent: SubagentState, width: number, paint: Paint): string[] {
437
- this.sync(agent);
438
- // Pi marks its own prompts for terminal shell integration; a sliced view
439
- // of another agent's prompts must not open unmatched marks.
440
- let lines: string[];
441
- try {
442
- lines = this.root.render(width).map((line) => line.replace(OSC_133, ""));
443
- } catch {
444
- // Producer data must never break Pi's own render loop.
445
- lines = [paint("error", " (this transcript could not be rendered)")];
446
- }
447
- if (agent.omitted)
448
- lines.unshift(
449
- paint("dim", `… ${agent.omitted} earlier messages not retained`),
450
- );
451
- if (!agent.messages.length) lines.push(paint("dim", " (no messages yet)"));
452
- return lines;
453
- }
454
- private sync(agent: SubagentState): void {
455
- if (agent.revision === this.revision) return;
456
- this.revision = agent.revision;
457
- const { messages } = agent;
458
- if (agent.omitted !== this.omitted) {
459
- this.root.clear();
460
- this.parts = [];
461
- this.tools.clear();
462
- this.omitted = agent.omitted;
463
- }
464
- let from = this.parts.length;
465
- // A streaming snapshot may be replaced or mutated in place.
466
- if (from > 0 && (this.tailStreaming || messages[from - 1] !== this.tail))
467
- from--;
468
- for (const part of this.parts.splice(from))
469
- for (const component of part) this.root.removeChild(component);
470
- for (let i = from; i < messages.length; i++) {
471
- const last = i === messages.length - 1;
472
- const part = this.build(messages[i] as Message, last && agent.streaming);
473
- for (const component of part) this.root.addChild(component);
474
- this.parts.push(part);
475
- }
476
- this.tail = messages.at(-1);
477
- this.tailStreaming = agent.streaming;
478
- }
479
- private build(message: Message, streaming: boolean): Component[] {
480
- switch (message.role) {
481
- case "user": {
482
- const text = textOf(message.content);
483
- return text
484
- ? [new Spacer(1), new UserMessageComponent(text, getMarkdownTheme())]
485
- : [];
486
- }
487
- case "assistant": {
488
- // Pi's component assumes well-formed blocks; keep only those.
489
- const content = (
490
- Array.isArray(message.content) ? message.content : []
491
- ).filter(
492
- (b) =>
493
- (b?.type === "text" && typeof b.text === "string") ||
494
- (b?.type === "thinking" && typeof b.thinking === "string") ||
495
- b?.type === "toolCall",
496
- );
497
- const parts: Component[] = [
498
- new AssistantMessageComponent(
499
- { ...message, content } as never,
500
- false,
501
- getMarkdownTheme(),
502
- ),
503
- ];
504
- const failed =
505
- message.stopReason === "aborted" || message.stopReason === "error";
506
- for (const block of content) {
507
- if (block.type !== "toolCall") continue;
508
- const tool = this.tool(
509
- String(block.name ?? "tool"),
510
- String(block.id ?? ""),
511
- block.arguments ?? {},
512
- );
513
- // Pi's edit renderer previews complete arguments against the file
514
- // as it is now, where an applied edit no longer matches and would
515
- // read as a failure; a transcript edit shows its call and result only.
516
- if (!streaming && block.name !== "edit") tool.setArgsComplete();
517
- if (failed)
518
- tool.updateResult({
519
- content: [
520
- {
521
- type: "text",
522
- text: String(message.errorMessage ?? "Operation aborted"),
523
- },
524
- ],
525
- isError: true,
526
- });
527
- parts.push(tool);
528
- }
529
- return parts;
530
- }
531
- case "toolResult": {
532
- const result = {
533
- content: Array.isArray(message.content) ? message.content : [],
534
- details: message.details,
535
- isError: message.isError === true,
536
- };
537
- const id = String(message.toolCallId ?? "");
538
- const pending = this.tools.get(id);
539
- if (pending) {
540
- pending.updateResult(result, streaming);
541
- return [];
542
- }
543
- const orphan = this.tool(String(message.toolName ?? "tool"), id, {});
544
- orphan.updateResult(result, streaming);
545
- return [orphan];
546
- }
547
- default: {
548
- const text = textOf(message.content);
549
- return text ? [new Spacer(1), new Text(text, 1, 0)] : [];
550
- }
551
- }
552
- }
553
- private tool(name: string, id: string, args: unknown) {
554
- const tool = new ToolExecutionComponent(
555
- name,
556
- id,
557
- args,
558
- {},
559
- undefined,
560
- this.tui,
561
- this.cwd,
562
- );
563
- tool.setExpanded(this.expanded);
564
- this.tools.set(id, tool);
565
- return tool;
566
- }
567
- }