@north-light/cli 0.3.704 → 0.3.705

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 (43) hide show
  1. package/dist/clients/attach/render/chat-view.d.ts +7 -60
  2. package/dist/clients/attach/render/chat-view.js +2 -4
  3. package/dist/clients/attach/viewer.js +537 -539
  4. package/dist/core/canvas/schema-pg/024-conversation-cycle-offset.sql +4 -0
  5. package/dist/core/canvas/schema-version.d.ts +1 -1
  6. package/dist/core/canvas/schema-version.js +1 -1
  7. package/dist/core/config.js +1 -1
  8. package/dist/core/conversation-store/client.js +2 -2
  9. package/dist/core/conversation-store/index.d.ts +3 -3
  10. package/dist/core/conversation-store/patch.js +1 -1
  11. package/dist/core/conversation-store/row-store.js +13 -13
  12. package/dist/core/import/load/prepare.js +4 -4
  13. package/dist/core/runs/operations.js +6 -6
  14. package/dist/core/runtime/broker/tool-groups.js +1 -1
  15. package/dist/core/runtime/broker.js +1 -1
  16. package/dist/core/runtime/node-read.js +3 -3
  17. package/dist/core/runtime/session-cycles.d.ts +5 -22
  18. package/dist/core/runtime/session-cycles.js +1 -1
  19. package/dist/core/user-settings.d.ts +0 -30
  20. package/dist/core/user-settings.js +1 -1
  21. package/dist/daemon/api/handlers/conversations.js +3 -3
  22. package/dist/types.d.ts +0 -23
  23. package/dist/types.js +1 -1
  24. package/package.json +3 -3
  25. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +22 -261
  26. package/packages/crouter-api/dist/clients/attach/viewer.js +6 -5
  27. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  28. package/packages/crouter-api/dist/core/config.js +2 -6
  29. package/packages/crouter-api/dist/core/conversation-store/client.js +1 -1
  30. package/packages/crouter-api/dist/core/conversation-store/patch.js +8 -3
  31. package/packages/crouter-api/dist/core/conversation-store/row-store.js +46 -19
  32. package/packages/crouter-api/dist/core/import/load/prepare.js +1 -1
  33. package/packages/crouter-api/dist/core/runs/operations.js +2 -2
  34. package/packages/crouter-api/dist/core/runtime/session-cycles.js +27 -75
  35. package/packages/crouter-api/dist/core/user-settings.js +1 -43
  36. package/packages/crouter-api/dist/types.js +0 -7
  37. package/packages/crouter-api/package.json +1 -1
  38. package/packages/crouter-identity/package.json +1 -1
  39. package/packages/crouter-plugin/package.json +3 -3
  40. package/runtime.lock.json +14 -14
  41. package/dist/clients/attach/render/condensed-history.d.ts +0 -21
  42. package/dist/clients/attach/render/condensed-history.js +0 -1
  43. package/packages/crouter-api/dist/clients/attach/render/condensed-history.js +0 -60
@@ -5,7 +5,7 @@ import { type AttachPalette } from '../config.js';
5
5
  import { type ToolGroupSummary } from '../../../shared/tool-groups.js';
6
6
  import { type TurnReply } from '../../../shared/turn-replies.js';
7
7
  import { type ViewportSource } from './measured-container.js';
8
- import type { CondensedHistoryMode, Verbosity } from '../../../types.js';
8
+ import type { Verbosity } from '../../../types.js';
9
9
  /** The viewer's level after Ctrl+O or Ctrl+Shift+O. `atEnd` is true when the
10
10
  * level is the last one in that direction: Full for more detail (the next
11
11
  * press wraps to Replies only), Replies only for less detail (presses stop). */
@@ -13,7 +13,7 @@ export type VerbosityChange = {
13
13
  level: Verbosity;
14
14
  atEnd: boolean;
15
15
  };
16
- export type CopyBlockKind = 'user' | 'assistant' | 'tool' | 'condensed';
16
+ export type CopyBlockKind = 'user' | 'assistant' | 'tool';
17
17
  /** One copyable unit, bound to the exact top-level component the viewport addresses. */
18
18
  export interface CopyBlock {
19
19
  block: Component;
@@ -44,14 +44,6 @@ export interface ChatViewOptions {
44
44
  /** Viewer-owned fixed activity slot. When supplied, activity stays outside
45
45
  * the scrolling transcript and this callback swaps its sole loader. */
46
46
  onActivityChange?: (loader: Loader | undefined) => void;
47
- /** Trailing refresh-yield cycles rendered at full fidelity; older cycles are
48
- * condensed to lightweight, reflowing content (see condensed-history.ts).
49
- * Absent → the user's `live_cycles` config setting, itself defaulting to 2. */
50
- liveCycles?: number;
51
- /** Which messages of a condensed cycle survive into the condensed region.
52
- * Absent → the user's `condensed_history` config setting, itself defaulting
53
- * to `none` (cycle dividers only). */
54
- condensedHistory?: CondensedHistoryMode;
55
47
  /** Render an inline page sent by THIS node as a durable transcript block,
56
48
  * anchored after the `human send` that raised it. Local attach only: a remote
57
49
  * viewer cannot read the ticket directory the block renders from. */
@@ -86,10 +78,6 @@ export declare class ChatView {
86
78
  /** Optional banner, above history and status in the viewport's flat source. */
87
79
  private readonly bannerContainer;
88
80
  private readonly transcript;
89
- /** Where `append()` puts a component. Normally `historyContainer`; retargeted to
90
- * a nested container while condensed history is being built, so the same
91
- * message-rendering path serves both regions. */
92
- private appendTarget;
93
81
  /** Inline page blocks placed in this transcript, by page id — one block per
94
82
  * page, so a `--replace` revision refreshes the block already on screen. */
95
83
  private readonly pageBlocks;
@@ -100,10 +88,6 @@ export declare class ChatView {
100
88
  private readonly inlinePageBlocks;
101
89
  private readonly pageOpenHint;
102
90
  private readonly backgroundBashHint;
103
- /** Trailing cycles kept at full fidelity (config `live_cycles`). */
104
- private readonly liveCycles;
105
- /** Messages kept from a condensed cycle (config `condensed_history`). */
106
- private readonly condensedHistory;
107
91
  private readonly cwd;
108
92
  private readonly showImages;
109
93
  private readonly imageWidthCells;
@@ -121,16 +105,11 @@ export declare class ChatView {
121
105
  private readonly turnReplies;
122
106
  private readonly turns;
123
107
  private openReplyTurn;
124
- /** The turn the live region opens in when it begins mid-turn (the condensed
125
- * region held its person's message), else the pre-message `start` turn. */
126
- private carriedTurn;
127
108
  /** >0 while appending components that never join a turn (the person's
128
- * message, turn chrome, errors, condensed history). */
109
+ * message, turn chrome, errors). */
129
110
  private outsideTurns;
130
111
  /** Components the turn fold currently hides. */
131
112
  private turnHidden;
132
- /** Both forms of condensed history, when it exists; one is hidden per level. */
133
- private condensedBlocks;
134
113
  /** The newest turn's reply text, which `/copy` takes at Replies only. */
135
114
  private lastReplyText;
136
115
  private readonly groupSummaries;
@@ -199,9 +178,6 @@ export declare class ChatView {
199
178
  /** Canonical copyable transcript blocks, in their rendered visual order. */
200
179
  private readonly copyBlockRecords;
201
180
  private readonly copyIndex;
202
- /** Registrations made while building condensed history are collapsed onto its
203
- * outer container once that container becomes a top-level viewport block. */
204
- private readonly condensedCopyBlocks;
205
181
  constructor(tui: TUI, container: Container, opts?: ChatViewOptions);
206
182
  /** The transcript as one flat ordered block list for the viewport. */
207
183
  transcriptSource(): ViewportSource;
@@ -211,23 +187,6 @@ export declare class ChatView {
211
187
  * else routes through `addMessageToChat`. The TUI's differential renderer +
212
188
  * reflow-on-resize is automatic — no scrollback reconstruction needed. */
213
189
  applySnapshot(snapshot: BrokerSnapshot): Promise<void>;
214
- /**
215
- * Build the condensed form of the already-finished cycles as a nested component
216
- * container, or return undefined when nothing survives condensation.
217
- *
218
- * Reuses `addMessageToChat` by retargeting `append()` at the nested container, so
219
- * condensed history uses the same renderer as live history with tool traffic
220
- * filtered out. The outer history cache keeps stable-width frames cheap, while
221
- * preserving the components lets pane-width changes reflow their content. The
222
- * build yields on the live cadence and abandons itself when a newer welcome
223
- * supersedes this generation.
224
- */
225
- private buildCondensedBlock;
226
- /** Replies only in condensed history: each finished turn renders as
227
- * the person's message, its reply, then any cycle dividers it spanned. A turn
228
- * still open at the end continues into the live region, so it is carried there
229
- * instead of rendered. Returns false when a newer welcome superseded the build. */
230
- private buildCondensedTurns;
231
190
  /** Defer a live broker frame when a snapshot build is in flight. Returns true
232
191
  * (and enqueues the replay closure) while building so the caller returns
233
192
  * without mutating the half-rebuilt view; false when the caller may proceed.
@@ -273,9 +232,6 @@ export declare class ChatView {
273
232
  * below its working row. */
274
233
  private turnFoldedComponents;
275
234
  private beginTurn;
276
- /** Whether an append in progress lands in the live region, where every
277
- * component joins a turn. */
278
- private consolidatingHere;
279
235
  private currentTurn;
280
236
  /** A settled assistant message with prose becomes part of its turn's reply. */
281
237
  private recordTurnProse;
@@ -313,10 +269,6 @@ export declare class ChatView {
313
269
  private appendHumanAnswer;
314
270
  private appendHumanAnswerParts;
315
271
  private trackInboxAnswer;
316
- /** Only the full-fidelity trailing region gets summary groups. Condensed
317
- * history intentionally drops tool traffic, so grouping there would create
318
- * phantom summary rows and cross the live/condensed boundary. */
319
- private isLiveGroupRegion;
320
272
  private ensureGroup;
321
273
  private closeOpenGroup;
322
274
  private appendGroupMember;
@@ -344,19 +296,16 @@ export declare class ChatView {
344
296
  private setAssistantSeparatorContent;
345
297
  /** Tool component with native viewer renderers for crouter-owned tool output. */
346
298
  private makeToolComponent;
347
- /** Append conversation content above the independent live status area — or into
348
- * the nested container while condensed history is under construction. */
299
+ /** Append conversation content above the independent live status area. */
349
300
  private append;
350
- /** Number of rendered conversation components in the container currently being
351
- * appended to (live history or the nested condensed region). */
301
+ /** Number of rendered conversation components. */
352
302
  private chatChildCount;
353
303
  /** Clear all chat content. */
354
304
  private resetChat;
355
305
  /** Place the transcript block for an inline page a `human send` just raised.
356
306
  * The block is a plain history child, NOT a tool-group member: collapsing the
357
307
  * tool group folds the command away and leaves the page itself on screen, the
358
- * way assistant prose stays. Condensed history is skipped deliberately — old
359
- * cycles keep only prose and cycle seams. */
308
+ * way assistant prose stays. */
360
309
  private maybeAppendPageBlock;
361
310
  private loadPageBlock;
362
311
  /** Re-measure the tool calls still in flight. A silent long-running command
@@ -410,12 +359,10 @@ export declare class ChatView {
410
359
  /** Every copyable block's text, oldest → newest, joined by blank lines. */
411
360
  getTranscriptPlainText(): string;
412
361
  /** Blocks built for the other side of the Replies-only boundary: the turn
413
- * replies and reply-form condensed history at every other level, and the
414
- * message-form condensed history at Replies only. */
362
+ * replies at every other level. */
415
363
  private inactiveFormBlocks;
416
364
  private registerCopyBlock;
417
365
  private unregisterCopyBlock;
418
- private appendCondensedBlock;
419
366
  /** Flatten arbitrary tool result payloads into the visible text copy target. */
420
367
  private toolResultText;
421
368
  private pushTranscriptText;
@@ -1,5 +1,3 @@
1
- var N=Object.defineProperty;var l=(h,t)=>N(h,"name",{value:t,configurable:!0});import{Container as P,Loader as Y,Markdown as z,Spacer as c,Text as x}from"@earendil-works/pi-tui";import{AssistantMessageComponent as K,BashExecutionComponent as _,BranchSummaryMessageComponent as J,CompactionSummaryMessageComponent as X,CustomMessageComponent as j,parseSkillBlock as Q,SkillInvocationMessageComponent as Z,ToolExecutionComponent as tt,UserMessageComponent as G}from"@earendil-works/pi-coding-agent";import{attachMarkdownTheme as u}from"../config.js";import{ContextMessageComponent as H}from"./context-message.js";import{presentationFor as et}from"./card-presentation.js";import{detectInlinePageResult as st,PageBlockComponent as it}from"./page-block.js";import{CRTR_OUTPUT_CUSTOM_TYPE as nt,CrtrOutputMessageComponent as F,createCrtrBashToolDefinition as ot}from"./crtr-output.js";import{CRTR_CYCLE_DIVIDER_CUSTOM_TYPE as rt,endedByAbort as E}from"../../../core/runtime/session-cycles.js";import{isHumanWordsEntry as L,parseCard as at}from"../../../shared/generated-context.js";import{assistantVisibleText as f,isGroupBoundaryKind as ht,isTrueUserMessage as y}from"../../../shared/tool-groups.js";import{messageKey as R,normalizeTurnReplyRecord as lt,START_TURN_KEY as v,turnReplyText as W}from"../../../shared/turn-replies.js";import{isCycleDivider as pt}from"./condensed-history.js";import{transformDiagramFences as dt}from"./diagram.js";import{styleAttachAgentMarkdown as ct,styleAttachMarkdownSource as $,styleAttachMessageMarkdown as ut,styleAttachSummaryMarkdown as q}from"./markdown-source.js";import{createCrtrEditToolDefinition as ft}from"./edit-diff.js";import{GroupActivityRecorder as mt}from"./group-activity.js";import{GroupRecapComponent as gt}from"./group-recap.js";import{FoldedToolCallController as yt,bashCallBackgroundHintLines as Ct,createCrtrPlainBashToolDefinition as Tt,createCrtrReadToolDefinition as kt,createCrtrWriteToolDefinition as bt}from"./tool-calls.js";import{ringCompletionBell as xt}from"../chrome/completion-bell.js";import{extractFilePaths as wt}from"../../../core/human/visible-paths.js";import{extractDocRefs as St}from"./doc-links.js";import{keepWhenCondensed as Rt,liveRegionStart as Bt}from"./condensed-history.js";import{ViewerAssistantMessageComponent as w}from"./assistant-message.js";import{CompositeViewportSource as At,MeasuredContainer as B}from"./measured-container.js";import{readConfig as A}from"../../../core/config.js";import{DEFAULT_CONDENSED_HISTORY as Mt,DEFAULT_LIVE_CYCLES as Gt,DEFAULT_VERBOSITY as Et,VERBOSITY_LEVELS as m}from"../../../types.js";import{applySnapshot as vt,applyToolGroupSummary as Ot,applyWorkingActivity as It,bashEnd as Dt,bashOutput as Pt,bashStart as _t,initialConvState as jt,reduce as Ht}from"../../conversation/projection.js";const U=l(h=>`\x1B[2m${h}\x1B[22m`,"defaultDimStyle"),O=50;function Ft(){try{return A("user").live_cycles}catch{return Gt}}l(Ft,"readLiveCycles");function Lt(){try{return A("user").condensed_history}catch{return Mt}}l(Lt,"readCondensedHistory");function Wt(){try{return A("user").verbosity}catch{return Et}}l(Wt,"readVerbosity");function $t(){try{return A("user").detailed_tool_recaps}catch{return!0}}l($t,"readDetailedToolRecaps");function qt(h){return typeof h=="object"&&h!==null&&"setExpanded"in h&&typeof h.setExpanded=="function"}l(qt,"isExpandable");const Ut=/\x1b\[[0-9;]*m/g,Vt=/\x1b\[([0-9;]*)m/g;function Nt(h){return h.replace(Vt,(t,e)=>{const s=e.split(";"),i=[];for(let n=0;n<s.length;n++){const a=Number(s[n]===""?0:s[n]);if(a===38||a===48||a===58){const o=Number(s[n+1]),r=n+(o===5?2:o===2?4:1);a!==48&&i.push(...s.slice(n,r+1)),n=r;continue}a>=40&&a<=47||a>=100&&a<=107||i.push(String(a))}return i.length>0?`\x1B[${i.join(";")}m`:""})}l(Nt,"stripBackground");const Yt=/<from\b[^>]*>[\s\S]*?<\/from>/g;class I extends c{static{l(this,"FoldedToolSeparator")}folded=!1;separatesToolGroup=!1;setFolded(t){this.folded=t,this.refresh()}setSeparatesToolGroup(t){this.separatesToolGroup=t,this.refresh()}refresh(){this.setLines(this.folded&&this.separatesToolGroup?1:0)}}class zt extends P{static{l(this,"WorkingRow")}label=new x("",1,0);constructor(){super(),this.addChild(new c(1)),this.addChild(this.label)}setLabel(t){this.label.setText(t)}}function D(h,t,e){return`${h} ${h===1?t:e}`}l(D,"plural");class M extends tt{static{l(this,"MinimizableToolComponent")}activityCallId;minimized=!1;expandedState=!1;foldController;resultObserver;setToolView(t,e){this.foldController=t,this.resultObserver=e}updateResult(...t){this.resultObserver?.(t[0],t[1]??!1);const e=t[0],s=e.content;Array.isArray(s)&&/^elapsed \d+(?:h \d+)?m \d+s(?:\n|$)/.test(s.at(-1)?.text??"")?super.updateResult({...e,content:s.slice(0,-1)},t[1]):super.updateResult(...t)}setExpanded(t){this.expandedState=t,super.setExpanded(t)}setMinimized(t){!this.foldController||this.minimized===t||(this.minimized=t,this.foldController.setFolded(t),super.setExpanded(this.expandedState))}render(t){if(!this.minimized)return[...super.render(t),...Ct(this.foldController?.callComponent(),t)];const e=this.foldController?.callComponent();return e?e.render(t).filter(s=>s.replace(Ut,"").trim().length>0).map(s=>Nt(s).trimEnd()):super.render(t)}}const Kt=l(h=>`\x1B[31m${h}\x1B[39m`,"defaultErrorStyle"),Jt={accent:l(h=>`\x1B[33m${h}\x1B[39m`,"accent"),active:l(h=>`\x1B[36m${h}\x1B[39m`,"active"),info:l(h=>`\x1B[34m${h}\x1B[39m`,"info"),muted:U,faint:U,border:l(h=>h,"border"),surface:l(h=>h,"surface"),bold:l(h=>`\x1B[1m${h}\x1B[22m`,"bold"),error:Kt,warning:l(h=>`\x1B[33m${h}\x1B[39m`,"warning"),diffAdded:l(h=>`\x1B[32m${h}\x1B[39m`,"diffAdded"),diffRemoved:l(h=>`\x1B[91m${h}\x1B[39m`,"diffRemoved"),bashMode:l(h=>`\x1B[32m${h}\x1B[39m`,"bashMode"),bashModeAlt:l(h=>`\x1B[92m${h}\x1B[39m`,"bashModeAlt")};class Re{static{l(this,"ChatView")}tui;container;historyContainer=new B;statusContainer=new B;pendingContainer=new B;pendingSends=[];bannerContainer;transcript;appendTarget=this.historyContainer;pageBlocks=new Map;pageRefresh=!1;inboxAnswers=new Set;inlinePageBlocks;pageOpenHint;backgroundBashHint;liveCycles;condensedHistory;cwd;showImages;imageWidthCells;hideThinking;hiddenThinkingLabel;level;detailedToolRecaps=$t();groups=[];openGroup;turnReplies=new Map;turns=[];openReplyTurn;carriedTurn={key:v,prose:[]};outsideTurns=0;turnHidden=new Set;condensedBlocks={};lastReplyText;groupSummaries=new Map;nodeRoster=new Map;streamingWasGroupMember=!1;onFooterEvent;onActivityChange;spinnerStyle;dimStyle;errorStyle;recapPalette;labelStyle=l(t=>`\x1B[1m${t}\x1B[22m`,"labelStyle");markdownTransformers=[(t,{messageType:e,availableWidth:s})=>e==="assistant"?dt(t,s):t,(t,{messageType:e})=>e==="user"?$(t):ct(t)];streamingComponent;streamingToolSeparator;foldedToolSeparatorContents=new Map;pendingTools=new Map;bashComponent;activityLoader;projection=jt();workingActivity=this.projection.workingActivity;runActive=!1;applyingSnapshot=!1;snapshotGeneration=0;deferredFrames=[];lastAssistantText;transcriptFilePaths=[];transcriptDocRefs=[];copyBlockRecords=[];copyIndex=new Map;condensedCopyBlocks=new WeakMap;constructor(t,e,s={}){if(this.tui=t,this.container=e,this.cwd=s.cwd??process.cwd(),this.showImages=s.showImages??!0,this.imageWidthCells=s.imageWidthCells??60,this.hideThinking=s.hideThinking??!1,this.hiddenThinkingLabel=s.hiddenThinkingLabel??"Thinking...",this.level=s.verbosity??Wt(),this.liveCycles=s.liveCycles??Ft(),this.condensedHistory=s.condensedHistory??Lt(),this.onFooterEvent=s.onFooterEvent,this.onActivityChange=s.onActivityChange,this.inlinePageBlocks=s.inlinePageBlocks??!1,this.pageOpenHint=s.pageOpenHint??(()=>"crtr human list"),this.backgroundBashHint=s.backgroundBashHint??(()=>null),this.recapPalette=s.palette??Jt,this.spinnerStyle=this.recapPalette.active,this.dimStyle=this.recapPalette.muted,this.errorStyle=this.recapPalette.error,s.banner&&s.banner.length>0){const i=new B;i.addChild(new c(1));for(const n of s.banner)i.addChild(new x(n,1,0));i.addChild(new c(1)),this.bannerContainer=i,this.container.addChild(i)}this.container.addChild(this.historyContainer),this.container.addChild(this.pendingContainer),this.onActivityChange||this.container.addChild(this.statusContainer),this.transcript=new At([...this.bannerContainer?[this.bannerContainer]:[],this.historyContainer,this.pendingContainer,...this.onActivityChange?[]:[this.statusContainer]])}transcriptSource(){return this.transcript}async applySnapshot(t){const e=++this.snapshotGeneration;this.applyingSnapshot=!0,this.deferredFrames.length=0,this.resetChat(),this.projection=vt(t,this.projection),this.workingActivity=this.projection.workingActivity,this.runActive=this.projection.isStreaming,this.seedToolGroupSummaries(this.projection.toolGroupSummaryDetails),this.turnReplies.clear();for(const[o,r]of Object.entries(lt(t.turnReplies)))this.turnReplies.set(o,r);const s=new Map,i=this.projection.messages,n=i.length-1,a=Bt(i,this.liveCycles);if(a>0)for(const o of["turns","messages"]){const r=await this.buildCondensedBlock(i.slice(0,a),e,o);if(e!==this.snapshotGeneration)return;r&&this.appendCondensedBlock(r,o)}for(let o=a;o<i.length;o++){if(!this.projection.isStreaming&&o>a&&(o-a)%O===0&&(await new Promise(p=>setImmediate(p)),e!==this.snapshotGeneration))return;const r=i[o];if(r.role==="assistant"){const p=f(r);p.trim()&&(this.lastAssistantText=p,this.pushTranscriptText(p));const d=o===n&&this.projection.isStreaming&&r.stopReason!=="aborted"&&r.stopReason!=="error",T=f(r).trim()!=="",V=this.assistantToolCalls(r),k=r.stopReason==="aborted"||r.stopReason==="error",b=E(r)?"Interrupted":r.errorMessage??"Error";if(k){for(const g of s.values()){const C={content:[{type:"text",text:b}],isError:!0};g.updateResult(C),this.registerCopyBlock(g,"tool",b),this.settleGroupTool(g,C,!0)}s.clear()}(T||k)&&this.closeOpenGroup();let S;d?(this.streamingComponent=new w(void 0,this.hideThinking,u(),this.hiddenThinkingLabel,this.markdownTransformers),this.appendAssistantPart(this.streamingComponent,!T),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingWasGroupMember=!T,this.streamingComponent.updateContent(r),this.registerCopyBlock(this.streamingComponent,"assistant",f(r)),S=this.streamingToolSeparator=this.appendAssistantSeparator(!T)):S=this.appendAssistantMessage(r,!T&&!k),S&&this.setAssistantSeparatorContent(S,r);for(const g of V){this.pushTranscriptValue(g.arguments);const C=this.appendToolComponent(g.name,g.id,g.arguments);r.stopReason==="aborted"||r.stopReason==="error"?(C.updateResult({content:[{type:"text",text:b}],isError:!0}),this.registerCopyBlock(C,"tool",b),this.settleGroupTool(C,{content:[{type:"text",text:b}],isError:!0},!0)):s.set(g.id,C)}k&&this.closeOpenGroup(),!d&&!k&&this.recordTurnProse(r,!1)}else if(r.role==="toolResult"){this.pushTranscriptText(this.userMessageText(r));const p=s.get(r.toolCallId);p&&(p.updateResult(r),this.registerCopyBlock(p,"tool",this.toolResultText(r)),this.historyContainer.markDirty(p),this.settleGroupTool(p,r,r.isError===!0),s.delete(r.toolCallId),this.maybeAppendPageBlock(r))}else this.addMessageToChat(r)}for(const[o,r]of s)this.pendingTools.set(o,r);for(const o of this.turns)this.refreshTurn(o);this.confirmPendingSendsIn(i),this.applyToolDisplay(),this.projection.isStreaming&&this.setActivity(this.makeLoader(this.workingActivity)),this.tui.requestRender(),this.applyingSnapshot=!1,this.replayDeferredFrames()}async buildCondensedBlock(t,e,s){const i=new P,n=this.appendTarget,a=[];this.appendTarget=i,this.condensedCopyBlocks.set(i,a);try{if(s==="turns")return await this.buildCondensedTurns(t,e)&&i.children.length>0?{component:i,copyBlocks:a}:void 0;let o=0;for(const r of t)if(Rt(r,this.condensedHistory)){if(o>0&&o%O===0&&(await new Promise(p=>setImmediate(p)),e!==this.snapshotGeneration))return;o++,this.pushTranscriptText(this.userMessageText(r)),this.addMessageToChat(r)}}finally{this.appendTarget=n,this.condensedCopyBlocks.delete(i)}return i.children.length>0?{component:i,copyBlocks:a}:void 0}async buildCondensedTurns(t,e){const s=[{key:v,prose:[],dividers:[]}];for(const o of t){const r=s.at(-1);if(y(o))s.push({key:R(o)??`local-${s.length}`,user:o,prose:[],dividers:[]});else if(pt(o))r.dividers.push(o);else if(o.role==="assistant"&&o.stopReason!=="aborted"&&o.stopReason!=="error"){const p=f(o).trim(),d=R(o);p!==""&&d!==void 0&&r.prose.push({key:d,text:p})}}const i=s.pop();let n=0;const a=l(async(o,r)=>{if(n>0&&n%O===0&&(await new Promise(d=>setImmediate(d)),e!==this.snapshotGeneration))return!1;n++,o.user!==void 0&&(this.pushTranscriptText(this.userMessageText(o.user)),this.addMessageToChat(o.user));const p=r?W(o.prose,this.turnReplies.get(o.key)):"";if(p!==""){const d=new w(void 0,this.hideThinking,u(),this.hiddenThinkingLabel,this.markdownTransformers);d.updateContent(this.replyMessage(p)),this.append(d),this.registerCopyBlock(d,"assistant",p)}for(const d of o.dividers)this.addMessageToChat(d);return!0},"render");for(const o of s)if(!await a(o,!0))return!1;return await a(i,!1)?(this.carriedTurn={key:i.key,prose:i.prose},!0):!1}deferIfBuilding(t){return this.applyingSnapshot?(this.deferredFrames.push(t),!0):!1}replayDeferredFrames(){const t=this.deferredFrames.splice(0);for(const e of t)e()}setWorkingActivity(t){if(this.deferIfBuilding(()=>this.setWorkingActivity(t)))return;const e=this.projection.activity===this.workingActivity;this.projection=It(this.projection,t),this.workingActivity=this.projection.workingActivity,this.runActive&&e&&this.setActivity(this.makeLoader(this.workingActivity))}settleRun(){this.runActive=!1;for(const t of this.pendingTools.values())this.settleGroupTool(t);if(this.streamingComponent){this.historyContainer.removeChild(this.streamingComponent);for(const t of this.turns)t.members.delete(this.streamingComponent);this.turnHidden.delete(this.streamingComponent),this.unregisterCopyBlock(this.streamingComponent),this.streamingComponent=void 0}this.streamingToolSeparator=void 0,this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay(),this.setActivity(void 0),this.settleBashComponent()}dispose(){this.settleRun()}moreDetail(){const t=m.indexOf(this.level);return this.setLevel(m[(t+1)%m.length]),{level:this.level,atEnd:this.level===m.at(-1)}}lessDetail(){const t=m.indexOf(this.level);return this.setLevel(m[Math.max(0,t-1)]),{level:this.level,atEnd:this.level===m[0]}}setLevel(t){this.level=t;for(const e of this.turns)this.refreshTurn(e);this.applyToolDisplay()}repliesOnly(){return this.level==="replies"}foldsSettledTools(){return m.indexOf(this.level)<=m.indexOf("tools")}showsGroupSummaries(){return m.indexOf(this.level)<=m.indexOf("summaries")}toolOutputExpanded(){return this.level==="full"}applyToolDisplay(){const t=new Set(this.pendingTools.values());for(const i of this.groups)for(const n of i.inFlight)t.add(n);for(const i of this.historyContainer.children)i instanceof M&&i.setMinimized(this.foldsSettledTools()&&!t.has(i)),qt(i)&&i.setExpanded(this.toolOutputExpanded());const e=this.turnFoldedComponents(t),s=new Set;for(const i of this.groups){this.applyGroupDisplay(i,e),s.add(i.recap);for(const n of i.members)s.add(n)}for(const i of this.turnHidden)!e.has(i)&&!s.has(i)&&this.historyContainer.setHidden(i,!1);for(const i of e)!s.has(i)&&!this.historyContainer.hiddenChildren.has(i)&&this.historyContainer.setHidden(i,!0);this.turnHidden=e;for(const i of["turns","messages"]){const n=this.condensedBlocks[i];n&&this.historyContainer.setHidden(n,i==="turns"!==this.repliesOnly())}this.applyInboxExchangeDisplay(),this.updateFoldedToolSeparators(t),this.historyContainer.markDirty(),this.tui.requestRender()}hidesInboxExchange(){return this.showsGroupSummaries()}applyInboxExchangeDisplay(){const t=this.hidesInboxExchange();for(const e of this.inboxAnswers)this.historyContainer.setHidden(e,t);for(const e of this.pageBlocks.values())this.historyContainer.setHidden(e,e.settled)}applyTurnReply(t,e){if(!this.deferIfBuilding(()=>this.applyTurnReply(t,e))){this.turnReplies.set(t,e);for(const s of this.turns)s.key===t&&this.refreshTurn(s);this.tui.requestRender()}}turnFoldedComponents(t){const e=new Set;if(!this.repliesOnly())return e;for(const s of this.turns){const i=s===this.openReplyTurn;for(const n of s.members)i&&(n===this.streamingComponent||n===this.streamingToolSeparator||n===this.bashComponent||t.has(n))||e.add(n)}return e}beginTurn(t,e=[]){const s=new w(void 0,this.hideThinking,u(),this.hiddenThinkingLabel,this.markdownTransformers),i=new zt;this.outsideTurns++;try{this.append(i),this.append(s)}finally{this.outsideTurns--}this.registerCopyBlock(s,"assistant","");const n={key:t,reply:s,working:i,members:new Set,prose:e};return this.turns.push(n),this.openReplyTurn=n,this.refreshTurn(n),n}consolidatingHere(){return this.appendTarget===this.historyContainer}currentTurn(){return this.openReplyTurn??this.beginTurn(this.carriedTurn.key,[...this.carriedTurn.prose])}recordTurnProse(t,e){if(!this.consolidatingHere()||t.role!=="assistant"||t.stopReason==="aborted"||t.stopReason==="error")return;const s=f(t).trim(),i=R(t);if(s===""||i===void 0)return;const n=this.currentTurn();n.prose.some(a=>a.key===i)||(n.prose.push({key:i,text:s}),e&&this.refreshTurn(n))}refreshTurn(t){const e=W(t.prose,this.turnReplies.get(t.key));t.reply.updateContent(this.replyMessage(e)),this.historyContainer.setHidden(t.reply,e===""||!this.repliesOnly()),this.historyContainer.markDirty(t.reply),this.registerCopyBlock(t.reply,"assistant",e),e!==""&&t===this.turns.at(-1)&&(this.lastReplyText=e),this.refreshWorkingRow(t)}refreshWorkingRow(t){let e=0,s=0;for(const r of t.members)r instanceof M?e++:(r instanceof H||r instanceof j||r instanceof F)&&s++;const i=t.prose.length,n=e>0||s>0||i>1,a=[i>0?D(i,"message","messages"):void 0,e>0?D(e,"tool call","tool calls"):void 0,s>0?D(s,"card","cards"):void 0].filter(r=>r!==void 0),o=this.runActive&&t===this.openReplyTurn;t.working.setLabel(this.dimStyle(`\u25B8 ${o?"working \u2014 ":""}${a.join(" \xB7 ")}`)),this.historyContainer.setHidden(t.working,!n||!this.repliesOnly()),this.historyContainer.markDirty(t.working)}replyMessage(t){return{role:"assistant",content:t===""?[]:[{type:"text",text:t}],stopReason:"stop"}}toggleThinking(){this.hideThinking=!this.hideThinking;for(const t of this.historyContainer.children)t instanceof K&&t.setHideThinkingBlock(this.hideThinking);for(const[t,e]of this.foldedToolSeparatorContents)t.setSeparatesToolGroup(e.hasText||!this.hideThinking&&e.hasThinking);return this.historyContainer.markDirty(),this.tui.requestRender(),this.hideThinking}handleEvent(t){if(!this.deferIfBuilding(()=>this.handleEvent(t))){switch(this.projection=Ht(this.projection,t),t.type){case"agent_start":{this.runActive=this.projection.isStreaming;for(const e of this.pendingTools.values())this.settleGroupTool(e);this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.setActivity(this.makeLoader(this.workingActivity));break}case"agent_end":{this.settleRun(),xt();break}case"agent_settled":{this.settleRun();break}case"message_start":{if(t.message.role==="user"&&y(t.message)&&this.confirmPendingSend(this.userMessageText(t.message).trim()),t.message.role==="custom"||t.message.role==="user")this.addMessageToChat(t.message),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();else if(t.message.role==="assistant"){const e=f(t.message).trim()!=="";e&&this.closeOpenGroup(),this.streamingComponent=new w(void 0,this.hideThinking,u(),this.hiddenThinkingLabel,this.markdownTransformers),this.streamingWasGroupMember=!e,this.appendAssistantPart(this.streamingComponent,!e),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingComponent.updateContent(t.message),this.registerCopyBlock(this.streamingComponent,"assistant",f(t.message)),this.streamingToolSeparator=this.appendAssistantSeparator(!e),this.setAssistantSeparatorContent(this.streamingToolSeparator,t.message)}break}case"message_update":{if(this.streamingComponent&&t.message.role==="assistant"){this.promoteStreamingAssistantToBoundary(t.message),this.streamingComponent.updateContent(t.message),this.registerCopyBlock(this.streamingComponent,"assistant",f(t.message)),this.historyContainer.markDirty(this.streamingComponent);const e=this.assistantToolCalls(t.message);this.streamingToolSeparator&&this.setAssistantSeparatorContent(this.streamingToolSeparator,t.message);for(const s of e){this.pushTranscriptValue(s.arguments);const i=this.pendingTools.get(s.id);if(i)i.updateArgs(s.arguments),this.noteGroupTool(i,s.name,s.arguments),this.historyContainer.markDirty(i);else{const n=this.appendToolComponent(s.name,s.id,s.arguments);this.pendingTools.set(s.id,n)}}}break}case"message_end":{if(t.message.role!=="assistant")break;const e=t.message.stopReason==="aborted"||t.message.stopReason==="error";if(this.promoteStreamingAssistantToBoundary(t.message,e),this.streamingComponent&&this.registerCopyBlock(this.streamingComponent,"assistant",f(t.message)),t.message.stopReason!=="aborted"&&t.message.stopReason!=="error"){const s=f(t.message);s.trim()&&(this.lastAssistantText=s,this.pushTranscriptText(s))}if(this.streamingComponent){const s=t.message.stopReason;let i=t.message.errorMessage;if(E(t.message)&&(i="Interrupted",t.message.errorMessage=i,t.message.stopReason="aborted"),this.streamingComponent.updateContent(t.message),s==="aborted"||s==="error"){const n=i??"Error";for(const a of this.pendingTools.values())a.updateResult({content:[{type:"text",text:n}],isError:!0}),this.registerCopyBlock(a,"tool",n),this.settleGroupTool(a,{content:[{type:"text",text:n}],isError:!0},!0),this.historyContainer.markDirty(a);this.pendingTools.clear()}else for(const n of this.pendingTools.values())n.setArgsComplete(),this.historyContainer.markDirty(n);this.historyContainer.markDirty(this.streamingComponent),this.streamingComponent=void 0,this.streamingToolSeparator=void 0}e&&(this.closeOpenGroup(),this.applyToolDisplay()),this.recordTurnProse(t.message,!0),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();break}case"tool_execution_start":{this.pushTranscriptValue(t.args);let e=this.pendingTools.get(t.toolCallId);e?this.noteGroupTool(e,t.toolName,t.args):(e=this.appendToolComponent(t.toolName,t.toolCallId,t.args),this.pendingTools.set(t.toolCallId,e)),e.markExecutionStarted(),this.historyContainer.markDirty(e);break}case"tool_execution_update":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.partialResult;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e,!0),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.historyContainer.markDirty(s));break}case"tool_execution_end":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.result;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.pendingTools.delete(t.toolCallId),this.settleGroupTool(s,e,t.isError),this.applyToolDisplay(),this.historyContainer.markDirty(s),this.maybeAppendPageBlock(e));break}case"compaction_start":{const e=t.reason==="manual"?"Compacting context...":"Auto-compacting...";this.setActivity(this.makeLoader(e));break}case"compaction_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.aborted?this.showStatus(t.reason==="manual"?"Compaction cancelled":"Auto-compaction cancelled"):t.result?this.addMessageToChat({role:"compactionSummary",summary:t.result.summary,tokensBefore:t.result.tokensBefore,timestamp:Date.now()}):t.errorMessage&&this.showError(t.errorMessage);break}case"auto_retry_start":{const e=Math.ceil(t.delayMs/1e3);this.setActivity(this.makeLoader(`Retrying (${t.attempt}/${t.maxAttempts}) in ${e}s...`));break}case"auto_retry_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.success||this.showError(`Retry failed after ${t.attempt} attempts: ${t.finalError??"Unknown error"}`);break}case"queue_update":case"session_info_changed":case"thinking_level_changed":this.onFooterEvent?.(t);break;default:break}this.tui.requestRender()}}bashStart(t,e){if(this.deferIfBuilding(()=>this.bashStart(t,e)))return;this.projection=_t(this.projection,t,e),this.closeOpenGroup(),this.settleBashComponent();let s;s=new _(t,this.componentTui(()=>s),e),this.bashComponent=s,this.append(s),this.tui.requestRender()}bashOutput(t){this.deferIfBuilding(()=>this.bashOutput(t))||(this.projection=Pt(this.projection,t),this.pushTranscriptText(t),this.bashComponent&&(this.bashComponent.appendOutput(t),this.historyContainer.markDirty(this.bashComponent)),this.tui.requestRender())}bashEnd(t){this.deferIfBuilding(()=>this.bashEnd(t))||(this.projection=Dt(this.projection,t),this.settleBashComponent(t),this.tui.requestRender())}addMessageToChat(t){const e=at(t);if(e!==null&&(t.role!=="custom"||t.display===!0)){this.pushTranscriptText(e.body);const s=e.senders.flatMap(n=>n.entries).filter(L).map(n=>n.body.trim()).filter(n=>n!=="");if(!(s.length>0&&e.body.replace(Yt,"").trim()===""&&e.senders.every(n=>n.entries.every(L)))){const n=et(e.kind),a=new H(e,n,this.toolOutputExpanded(),this.dimStyle,o=>this.spinnerStyle(this.labelStyle(o)));ht(e.kind)?(this.closeOpenGroup(),this.append(a)):this.appendGroupMember(a)?.activity.noteCard(e,n)}for(const n of s)this.appendHumanAnswer(n);return}switch(t.role){case"bashExecution":{this.closeOpenGroup(),this.pushTranscriptText(t.output??"");const s=new _(t.command,this.tui,t.excludeFromContext);t.output&&s.appendOutput(t.output),s.setComplete(t.exitCode,t.cancelled,t.truncated?{truncated:!0}:void 0,t.fullOutputPath),this.append(s);break}case"custom":{if(t.display){if(this.pushTranscriptText(this.userMessageText(t)),t.customType===nt){this.appendGroupMember(new F(this.userMessageText(t),this.toolOutputExpanded(),this.crtrOutputTheme()));break}if(t.customType===rt){this.closeOpenGroup(),this.append(new c(1)),this.append(new x(this.dimStyle(`\u2500\u2500 ${this.userMessageText(t)} \u2500\u2500`),1,0)),this.append(new c(1));break}const s=new j(ut(t),void 0,u());s.setExpanded(this.toolOutputExpanded()),this.appendGroupMember(s)}break}case"compactionSummary":{this.closeOpenGroup(),this.append(new c(1));const s=new X(q(t),u());s.setExpanded(this.toolOutputExpanded()),this.append(s);break}case"branchSummary":{this.closeOpenGroup(),this.append(new c(1));const s=new J(q(t),u());s.setExpanded(this.toolOutputExpanded()),this.append(s),this.registerCopyBlock(s,"assistant",t.summary);break}case"user":{if(y(t)&&this.closeOpenGroup(),y(t)&&this.consolidatingHere()){!this.openReplyTurn&&this.carriedTurn.prose.length>0&&this.currentTurn(),this.outsideTurns++;try{this.appendUserMessage(t)}finally{this.outsideTurns--}this.beginTurn(R(t)??`local-${this.turns.length}`);break}this.appendUserMessage(t);break}case"assistant":{const s=f(t).trim()!=="";s&&this.closeOpenGroup(),this.appendAssistantMessage(t,!s);break}default:break}}appendUserMessage(t){const e=this.userMessageText(t);if(!e)return;this.pushTranscriptText(e),this.chatChildCount()>0&&this.appendUserPart(new c(1),!y(t));const s=Q(e);if(s){const i=new Z({...s,content:$(s.content)},u());if(i.setExpanded(this.toolOutputExpanded()),this.appendUserPart(i,!y(t)),this.registerCopyBlock(i,"user",e),s.userMessage){const n=new G(s.userMessage,u(),void 0,this.markdownTransformers);this.appendUserPart(n,!y(t)),this.registerCopyBlock(n,"user",s.userMessage)}}else{const i=new G(e,u(),void 0,this.markdownTransformers);this.appendUserPart(i,!y(t)),this.registerCopyBlock(i,"user",e)}}appendAssistantMessage(t,e=!1){const s=new w(void 0,this.hideThinking,u(),this.hiddenThinkingLabel,this.markdownTransformers),i=E(t)?{...t,stopReason:"aborted",errorMessage:"Interrupted"}:t;s.updateContent(i),this.appendAssistantPart(s,e),this.registerCopyBlock(s,"assistant",f(t));const n=this.appendAssistantSeparator(e);return this.setAssistantSeparatorContent(n,t),n}appendAssistantSeparator(t=!1){const e=new I;return t?this.appendGroupMember(e):this.append(e),e}appendAssistantPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendUserPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendHumanAnswer(t){this.outsideTurns++;try{this.appendHumanAnswerParts(t)}finally{this.outsideTurns--}}appendHumanAnswerParts(t){this.closeOpenGroup();const e=this.appendTarget===this.historyContainer;if(this.chatChildCount()>0){const i=new c(1);this.append(i),e&&this.trackInboxAnswer(i)}const s=new G(t,u(),void 0,this.markdownTransformers);this.append(s),e&&this.trackInboxAnswer(s),this.registerCopyBlock(s,"user",t)}trackInboxAnswer(t){this.inboxAnswers.add(t),this.hidesInboxExchange()&&this.historyContainer.setHidden(t,!0)}isLiveGroupRegion(){return this.appendTarget===this.historyContainer}ensureGroup(){if(!this.isLiveGroupRegion())return;if(this.openGroup)return this.openGroup;const t=new gt,e={members:[],recap:t,activity:new mt(this.cwd,this.nodeRoster),toolCount:0,inFlight:new Set};return this.append(t),this.historyContainer.setHidden(t,!0),this.groups.push(e),this.openGroup=e,e}closeOpenGroup(){this.openGroup=void 0}appendGroupMember(t){const e=this.ensureGroup();return this.append(t),e&&e.members.push(t),e}removeGroupMember(t){for(const e of this.groups){const s=e.members.indexOf(t);s!==-1&&e.members.splice(s,1)}this.historyContainer.setHidden(t,!1)}appendToolComponent(t,e,s){const i=this.isLiveGroupRegion()&&!this.openGroup&&this.historyContainer.children.at(-1)instanceof I?this.historyContainer.children.at(-1):void 0;i&&this.historyContainer.removeChild(i);const n=this.ensureGroup();i&&(this.append(i),n?.members.push(i));const a=this.makeToolComponent(t,e,s);return a.activityCallId=e,this.appendGroupMember(a),this.registerCopyBlock(a,"tool",""),n&&(n.key??=e,n.toolCount++,n.inFlight.add(a),n.activity.noteCall(e,t,s)),a}noteGroupTool(t,e,s){if(t.activityCallId)for(const i of this.groups)i.members.includes(t)&&i.activity.noteCall(t.activityCallId,e,s)}settleGroupTool(t,e,s=!1){for(const i of this.groups)i.inFlight.delete(t),!(!t.activityCallId||!i.members.includes(t))&&(e===void 0?i.activity.resolveWithoutResult(t.activityCallId):i.activity.settle(t.activityCallId,e,s))}promoteStreamingAssistantToBoundary(t,e=!1){!this.streamingWasGroupMember||!e&&f(t).trim()===""||(this.streamingComponent&&this.removeGroupMember(this.streamingComponent),this.streamingToolSeparator&&this.removeGroupMember(this.streamingToolSeparator),this.streamingWasGroupMember=!1,this.closeOpenGroup())}seedToolGroupSummaries(t){this.groupSummaries.clear();for(const[e,s]of Object.entries(t))this.groupSummaries.set(e,s)}applyToolGroupSummary(t,e){if(this.deferIfBuilding(()=>this.applyToolGroupSummary(t,e)))return;this.projection=Ot(this.projection,t,e);const s=this.projection.toolGroupSummaryDetails[t];s!==void 0&&(this.groupSummaries.set(t,s),this.applyToolDisplay())}applyGroupDisplay(t,e){const s=t.key===void 0?void 0:this.groupSummaries.get(t.key),i=this.showsGroupSummaries()&&t.toolCount>0&&t.inFlight.size===0&&s!==void 0;t.recap.setRecap(i?s:void 0,t.toolCount,t.activity.activity(),this.detailedToolRecaps,this.recapPalette),this.historyContainer.setHidden(t.recap,!i||e.has(t.recap));for(const n of t.members)this.historyContainer.setHidden(n,i||e.has(n))}updateFoldedToolSeparators(t=new Set(this.pendingTools.values())){const e=this.historyContainer.children;for(let s=0;s<e.length;s++){const i=e[s];if(!(i instanceof I))continue;const n=e[s+1];i.setFolded(this.foldsSettledTools()&&!this.historyContainer.hiddenChildren.has(i)&&n instanceof M&&!this.historyContainer.hiddenChildren.has(n)&&!t.has(n)),this.historyContainer.markDirty(i)}}setAssistantSeparatorContent(t,e){const s=e.content,i=Array.isArray(s)?s:[],n=i.some(o=>typeof o=="object"&&o!==null&&o.type==="text"&&typeof o.text=="string"&&o.text.trim()!==""),a=i.some(o=>typeof o=="object"&&o!==null&&o.type==="thinking"&&typeof o.thinking=="string"&&o.thinking.trim()!=="");this.foldedToolSeparatorContents.set(t,{hasText:n,hasThinking:a}),t.setSeparatesToolGroup(n||!this.hideThinking&&a)}makeToolComponent(t,e,s){const i=new yt;let n,a;if(t==="bash"){const r=ot(s,i);r===void 0?a=Tt(this.cwd,i,this.backgroundBashHint):a=r.definition}else if(t==="edit"){const r=ft(this.cwd,i);a=r.definition,n=r.observeResult}else t==="read"?a=kt(this.cwd,i):t==="write"&&(a=bt(this.cwd,i));let o;return o=new M(t,e,s,{showImages:this.showImages,imageWidthCells:this.imageWidthCells},a,this.componentTui(()=>o),this.cwd),o.setToolView(a===void 0?void 0:i,n),o.setExpanded(this.toolOutputExpanded()),o}append(t){if(this.outsideTurns===0&&this.consolidatingHere()){const e=this.currentTurn();this.appendTarget.addChild(t),e.members.add(t);return}this.appendTarget.addChild(t)}chatChildCount(){return this.appendTarget.children.length}resetChat(){this.setActivity(void 0),this.settleBashComponent(),this.streamingComponent=void 0,this.streamingToolSeparator=void 0,this.streamingWasGroupMember=!1,this.foldedToolSeparatorContents.clear(),this.groups.length=0,this.openGroup=void 0,this.turns.length=0,this.openReplyTurn=void 0,this.carriedTurn={key:v,prose:[]},this.turnHidden=new Set,this.condensedBlocks={},this.lastReplyText=void 0,this.groupSummaries.clear(),this.nodeRoster.clear(),this.pendingTools.clear(),this.lastAssistantText=void 0,this.copyBlockRecords.length=0,this.copyIndex.clear(),this.transcriptFilePaths.length=0,this.transcriptDocRefs.length=0,this.pageBlocks.clear(),this.inboxAnswers.clear(),this.historyContainer.clear()}maybeAppendPageBlock(t){if(!this.inlinePageBlocks||this.appendTarget!==this.historyContainer)return;const e=st(t);if(e===void 0||this.pageBlocks.has(e.pageId))return;const s=new it(e.pageId,this.pageOpenHint);this.pageBlocks.set(e.pageId,s),this.outsideTurns++;try{this.append(s)}finally{this.outsideTurns--}this.loadPageBlock(s)}async loadPageBlock(t){await t.refresh()&&(this.historyContainer.setHidden(t,t.settled),this.historyContainer.markDirty(t),this.tui.requestRender())}refreshInFlightTools(){if(this.pendingTools.size!==0){for(const t of this.pendingTools.values())this.historyContainer.markDirty(t);this.tui.requestRender()}}async refreshPageBlocks(){if(this.pageRefresh)return;const t=[...this.pageBlocks.values()].filter(s=>!s.settled);this.pageRefresh=!0,(await Promise.all(t.map(async s=>{const i=await s.refresh();return i&&(this.historyContainer.setHidden(s,s.settled),this.historyContainer.markDirty(s)),i})).finally(()=>{this.pageRefresh=!1})).some(Boolean)&&this.tui.requestRender()}makeLoader(t){let e;const s={requestRender:l(i=>{e&&!this.onActivityChange&&this.statusContainer.markDirty(e),this.tui.requestRender(i)},"requestRender"),terminal:this.tui.terminal};return e=new Y(s,this.spinnerStyle,this.dimStyle,t),e}componentTui(t){return{requestRender:l(e=>{this.historyContainer.markDirty(t()),this.tui.requestRender(e)},"requestRender"),terminal:this.tui.terminal}}settleBashComponent(t){if(!this.bashComponent)return;const e=this.bashComponent;e.setComplete(t?.exitCode,t?.cancelled??!0,t?.truncated?{truncated:!0}:void 0,t?.fullOutputPath),this.historyContainer.markDirty(e),this.bashComponent=void 0}addPendingSend(t){const e=t.trim();if(!e)return;const s=[new c(1),new z(e,1,1,u(),{color:this.dimStyle})];for(const i of s)this.pendingContainer.addChild(i);this.pendingSends.push({text:e,parts:s}),this.tui.requestRender()}confirmPendingSend(t){const e=this.pendingSends.findIndex(n=>n.text===t),s=e>=0?e:0;if(this.pendingSends.length===0)return;const[i]=this.pendingSends.splice(s,1);for(const n of i.parts)this.pendingContainer.removeChild(n)}confirmPendingSendsIn(t){if(this.pendingSends.length===0)return;const e=new Set;for(const s of t.slice(-50))s.role==="user"&&e.add(this.userMessageText(s).trim());for(const s of[...this.pendingSends])if(e.has(s.text)){this.pendingSends.splice(this.pendingSends.indexOf(s),1);for(const i of s.parts)this.pendingContainer.removeChild(i)}}setActivity(t){if(this.activityLoader?.stop(),this.activityLoader=t,this.onActivityChange){this.onActivityChange(t);return}this.statusContainer.clear(),t&&this.statusContainer.addChild(t)}showStatus(t){this.closeOpenGroup(),this.append(new c(1)),this.append(new x(this.dimStyle(t),1,0))}showError(t){if(!this.deferIfBuilding(()=>this.showError(t))){this.closeOpenGroup(),this.outsideTurns++;try{this.append(new c(1)),this.append(new x(this.errorStyle(t),1,0))}finally{this.outsideTurns--}this.tui.requestRender()}}crtrOutputTheme(){return{fg:l((t,e)=>t==="error"?this.errorStyle(e):t==="warning"||t==="accent"||t==="toolTitle"||t==="success"?this.spinnerStyle(e):t==="muted"?this.dimStyle(e):e,"fg"),bg:l((t,e)=>e,"bg"),bold:l(t=>this.labelStyle(t),"bold")}}assistantToolCalls(t){const e=t.content;return Array.isArray(e)?e.filter(s=>typeof s=="object"&&s!==null&&s.type==="toolCall"):[]}getTranscriptFilePathsNewestFirst(){return[...this.transcriptFilePaths]}getTranscriptDocRefsNewestFirst(){return[...this.transcriptDocRefs]}refreshMarkdown(){this.historyContainer.invalidate(),this.tui.requestRender()}getLastAssistantText(){const t=(this.repliesOnly()?this.lastReplyText??this.lastAssistantText:this.lastAssistantText)?.trim();return t||void 0}blockText(t){const e=this.copyIndex.get(t);return e===void 0?void 0:this.copyBlockRecords[e]?.text}copyBlocks(){return this.copyBlockRecords}getLastToolOutputText(){for(let t=this.copyBlockRecords.length-1;t>=0;t--){const e=this.copyBlockRecords[t];if(e.kind==="tool")return e.text.trim()===""?void 0:e.text}}getTranscriptPlainText(){const t=this.inactiveFormBlocks();return this.copyBlockRecords.filter(e=>!t.has(e.block)).map(e=>e.text).filter(e=>e.trim()!=="").join(`
1
+ var W=Object.defineProperty;var h=(a,t)=>W(a,"name",{value:t,configurable:!0});import{Container as $,Loader as q,Markdown as V,Spacer as c,Text as b}from"@earendil-works/pi-tui";import{AssistantMessageComponent as U,BashExecutionComponent as E,BranchSummaryMessageComponent as N,CompactionSummaryMessageComponent as z,CustomMessageComponent as O,parseSkillBlock as Y,SkillInvocationMessageComponent as K,ToolExecutionComponent as J,UserMessageComponent as R}from"@earendil-works/pi-coding-agent";import{attachMarkdownTheme as p}from"../config.js";import{ContextMessageComponent as I}from"./context-message.js";import{presentationFor as X}from"./card-presentation.js";import{detectInlinePageResult as Q,PageBlockComponent as Z}from"./page-block.js";import{CRTR_OUTPUT_CUSTOM_TYPE as tt,CrtrOutputMessageComponent as v,createCrtrBashToolDefinition as et}from"./crtr-output.js";import{endedByAbort as A}from"../../../core/runtime/session-cycles.js";import{isHumanWordsEntry as D,parseCard as st}from"../../../shared/generated-context.js";import{assistantVisibleText as d,isGroupBoundaryKind as it,isTrueUserMessage as g}from"../../../shared/tool-groups.js";import{messageKey as P,normalizeTurnReplyRecord as nt,START_TURN_KEY as ot,turnReplyText as rt}from"../../../shared/turn-replies.js";import{transformDiagramFences as at}from"./diagram.js";import{styleAttachAgentMarkdown as ht,styleAttachMarkdownSource as j,styleAttachMessageMarkdown as lt,styleAttachSummaryMarkdown as F}from"./markdown-source.js";import{createCrtrEditToolDefinition as pt}from"./edit-diff.js";import{GroupActivityRecorder as dt}from"./group-activity.js";import{GroupRecapComponent as ct}from"./group-recap.js";import{FoldedToolCallController as ut,bashCallBackgroundHintLines as mt,createCrtrPlainBashToolDefinition as ft,createCrtrReadToolDefinition as gt,createCrtrWriteToolDefinition as yt}from"./tool-calls.js";import{ringCompletionBell as Ct}from"../chrome/completion-bell.js";import{extractFilePaths as Tt}from"../../../core/human/visible-paths.js";import{extractDocRefs as kt}from"./doc-links.js";import{ViewerAssistantMessageComponent as x}from"./assistant-message.js";import{CompositeViewportSource as bt,MeasuredContainer as w}from"./measured-container.js";import{readConfig as _}from"../../../core/config.js";import{DEFAULT_VERBOSITY as xt,VERBOSITY_LEVELS as u}from"../../../types.js";import{applySnapshot as wt,applyToolGroupSummary as St,applyWorkingActivity as Rt,bashEnd as At,bashOutput as Bt,bashStart as Mt,initialConvState as Gt,reduce as Et}from"../../conversation/projection.js";const H=h(a=>`\x1B[2m${a}\x1B[22m`,"defaultDimStyle"),Ot=50;function It(){try{return _("user").verbosity}catch{return xt}}h(It,"readVerbosity");function vt(){try{return _("user").detailed_tool_recaps}catch{return!0}}h(vt,"readDetailedToolRecaps");function Dt(a){return typeof a=="object"&&a!==null&&"setExpanded"in a&&typeof a.setExpanded=="function"}h(Dt,"isExpandable");const Pt=/\x1b\[[0-9;]*m/g,jt=/\x1b\[([0-9;]*)m/g;function Ft(a){return a.replace(jt,(t,e)=>{const s=e.split(";"),i=[];for(let n=0;n<s.length;n++){const r=Number(s[n]===""?0:s[n]);if(r===38||r===48||r===58){const o=Number(s[n+1]),l=n+(o===5?2:o===2?4:1);r!==48&&i.push(...s.slice(n,l+1)),n=l;continue}r>=40&&r<=47||r>=100&&r<=107||i.push(String(r))}return i.length>0?`\x1B[${i.join(";")}m`:""})}h(Ft,"stripBackground");const _t=/<from\b[^>]*>[\s\S]*?<\/from>/g;class B extends c{static{h(this,"FoldedToolSeparator")}folded=!1;separatesToolGroup=!1;setFolded(t){this.folded=t,this.refresh()}setSeparatesToolGroup(t){this.separatesToolGroup=t,this.refresh()}refresh(){this.setLines(this.folded&&this.separatesToolGroup?1:0)}}class Ht extends ${static{h(this,"WorkingRow")}label=new b("",1,0);constructor(){super(),this.addChild(new c(1)),this.addChild(this.label)}setLabel(t){this.label.setText(t)}}function M(a,t,e){return`${a} ${a===1?t:e}`}h(M,"plural");class S extends J{static{h(this,"MinimizableToolComponent")}activityCallId;minimized=!1;expandedState=!1;foldController;resultObserver;setToolView(t,e){this.foldController=t,this.resultObserver=e}updateResult(...t){this.resultObserver?.(t[0],t[1]??!1);const e=t[0],s=e.content;Array.isArray(s)&&/^elapsed \d+(?:h \d+)?m \d+s(?:\n|$)/.test(s.at(-1)?.text??"")?super.updateResult({...e,content:s.slice(0,-1)},t[1]):super.updateResult(...t)}setExpanded(t){this.expandedState=t,super.setExpanded(t)}setMinimized(t){!this.foldController||this.minimized===t||(this.minimized=t,this.foldController.setFolded(t),super.setExpanded(this.expandedState))}render(t){if(!this.minimized)return[...super.render(t),...mt(this.foldController?.callComponent(),t)];const e=this.foldController?.callComponent();return e?e.render(t).filter(s=>s.replace(Pt,"").trim().length>0).map(s=>Ft(s).trimEnd()):super.render(t)}}const Lt=h(a=>`\x1B[31m${a}\x1B[39m`,"defaultErrorStyle"),Wt={accent:h(a=>`\x1B[33m${a}\x1B[39m`,"accent"),active:h(a=>`\x1B[36m${a}\x1B[39m`,"active"),info:h(a=>`\x1B[34m${a}\x1B[39m`,"info"),muted:H,faint:H,border:h(a=>a,"border"),surface:h(a=>a,"surface"),bold:h(a=>`\x1B[1m${a}\x1B[22m`,"bold"),error:Lt,warning:h(a=>`\x1B[33m${a}\x1B[39m`,"warning"),diffAdded:h(a=>`\x1B[32m${a}\x1B[39m`,"diffAdded"),diffRemoved:h(a=>`\x1B[91m${a}\x1B[39m`,"diffRemoved"),bashMode:h(a=>`\x1B[32m${a}\x1B[39m`,"bashMode"),bashModeAlt:h(a=>`\x1B[92m${a}\x1B[39m`,"bashModeAlt")};class me{static{h(this,"ChatView")}tui;container;historyContainer=new w;statusContainer=new w;pendingContainer=new w;pendingSends=[];bannerContainer;transcript;pageBlocks=new Map;pageRefresh=!1;inboxAnswers=new Set;inlinePageBlocks;pageOpenHint;backgroundBashHint;cwd;showImages;imageWidthCells;hideThinking;hiddenThinkingLabel;level;detailedToolRecaps=vt();groups=[];openGroup;turnReplies=new Map;turns=[];openReplyTurn;outsideTurns=0;turnHidden=new Set;lastReplyText;groupSummaries=new Map;nodeRoster=new Map;streamingWasGroupMember=!1;onFooterEvent;onActivityChange;spinnerStyle;dimStyle;errorStyle;recapPalette;labelStyle=h(t=>`\x1B[1m${t}\x1B[22m`,"labelStyle");markdownTransformers=[(t,{messageType:e,availableWidth:s})=>e==="assistant"?at(t,s):t,(t,{messageType:e})=>e==="user"?j(t):ht(t)];streamingComponent;streamingToolSeparator;foldedToolSeparatorContents=new Map;pendingTools=new Map;bashComponent;activityLoader;projection=Gt();workingActivity=this.projection.workingActivity;runActive=!1;applyingSnapshot=!1;snapshotGeneration=0;deferredFrames=[];lastAssistantText;transcriptFilePaths=[];transcriptDocRefs=[];copyBlockRecords=[];copyIndex=new Map;constructor(t,e,s={}){if(this.tui=t,this.container=e,this.cwd=s.cwd??process.cwd(),this.showImages=s.showImages??!0,this.imageWidthCells=s.imageWidthCells??60,this.hideThinking=s.hideThinking??!1,this.hiddenThinkingLabel=s.hiddenThinkingLabel??"Thinking...",this.level=s.verbosity??It(),this.onFooterEvent=s.onFooterEvent,this.onActivityChange=s.onActivityChange,this.inlinePageBlocks=s.inlinePageBlocks??!1,this.pageOpenHint=s.pageOpenHint??(()=>"crtr human list"),this.backgroundBashHint=s.backgroundBashHint??(()=>null),this.recapPalette=s.palette??Wt,this.spinnerStyle=this.recapPalette.active,this.dimStyle=this.recapPalette.muted,this.errorStyle=this.recapPalette.error,s.banner&&s.banner.length>0){const i=new w;i.addChild(new c(1));for(const n of s.banner)i.addChild(new b(n,1,0));i.addChild(new c(1)),this.bannerContainer=i,this.container.addChild(i)}this.container.addChild(this.historyContainer),this.container.addChild(this.pendingContainer),this.onActivityChange||this.container.addChild(this.statusContainer),this.transcript=new bt([...this.bannerContainer?[this.bannerContainer]:[],this.historyContainer,this.pendingContainer,...this.onActivityChange?[]:[this.statusContainer]])}transcriptSource(){return this.transcript}async applySnapshot(t){const e=++this.snapshotGeneration;this.applyingSnapshot=!0,this.deferredFrames.length=0,this.resetChat(),this.projection=wt(t,this.projection),this.workingActivity=this.projection.workingActivity,this.runActive=this.projection.isStreaming,this.seedToolGroupSummaries(this.projection.toolGroupSummaryDetails),this.turnReplies.clear();for(const[r,o]of Object.entries(nt(t.turnReplies)))this.turnReplies.set(r,o);const s=new Map,i=this.projection.messages,n=i.length-1;for(let r=0;r<i.length;r++){if(!this.projection.isStreaming&&r>0&&r%Ot===0&&(await new Promise(l=>setImmediate(l)),e!==this.snapshotGeneration))return;const o=i[r];if(o.role==="assistant"){const l=d(o);l.trim()&&(this.lastAssistantText=l,this.pushTranscriptText(l));const G=r===n&&this.projection.isStreaming&&o.stopReason!=="aborted"&&o.stopReason!=="error",y=d(o).trim()!=="",L=this.assistantToolCalls(o),C=o.stopReason==="aborted"||o.stopReason==="error",T=A(o)?"Interrupted":o.errorMessage??"Error";if(C){for(const m of s.values()){const f={content:[{type:"text",text:T}],isError:!0};m.updateResult(f),this.registerCopyBlock(m,"tool",T),this.settleGroupTool(m,f,!0)}s.clear()}(y||C)&&this.closeOpenGroup();let k;G?(this.streamingComponent=new x(void 0,this.hideThinking,p(),this.hiddenThinkingLabel,this.markdownTransformers),this.appendAssistantPart(this.streamingComponent,!y),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingWasGroupMember=!y,this.streamingComponent.updateContent(o),this.registerCopyBlock(this.streamingComponent,"assistant",d(o)),k=this.streamingToolSeparator=this.appendAssistantSeparator(!y)):k=this.appendAssistantMessage(o,!y&&!C),k&&this.setAssistantSeparatorContent(k,o);for(const m of L){this.pushTranscriptValue(m.arguments);const f=this.appendToolComponent(m.name,m.id,m.arguments);o.stopReason==="aborted"||o.stopReason==="error"?(f.updateResult({content:[{type:"text",text:T}],isError:!0}),this.registerCopyBlock(f,"tool",T),this.settleGroupTool(f,{content:[{type:"text",text:T}],isError:!0},!0)):s.set(m.id,f)}C&&this.closeOpenGroup(),!G&&!C&&this.recordTurnProse(o,!1)}else if(o.role==="toolResult"){this.pushTranscriptText(this.userMessageText(o));const l=s.get(o.toolCallId);l&&(l.updateResult(o),this.registerCopyBlock(l,"tool",this.toolResultText(o)),this.historyContainer.markDirty(l),this.settleGroupTool(l,o,o.isError===!0),s.delete(o.toolCallId),this.maybeAppendPageBlock(o))}else this.addMessageToChat(o)}for(const[r,o]of s)this.pendingTools.set(r,o);for(const r of this.turns)this.refreshTurn(r);this.confirmPendingSendsIn(i),this.applyToolDisplay(),this.projection.isStreaming&&this.setActivity(this.makeLoader(this.workingActivity)),this.tui.requestRender(),this.applyingSnapshot=!1,this.replayDeferredFrames()}deferIfBuilding(t){return this.applyingSnapshot?(this.deferredFrames.push(t),!0):!1}replayDeferredFrames(){const t=this.deferredFrames.splice(0);for(const e of t)e()}setWorkingActivity(t){if(this.deferIfBuilding(()=>this.setWorkingActivity(t)))return;const e=this.projection.activity===this.workingActivity;this.projection=Rt(this.projection,t),this.workingActivity=this.projection.workingActivity,this.runActive&&e&&this.setActivity(this.makeLoader(this.workingActivity))}settleRun(){this.runActive=!1;for(const t of this.pendingTools.values())this.settleGroupTool(t);if(this.streamingComponent){this.historyContainer.removeChild(this.streamingComponent);for(const t of this.turns)t.members.delete(this.streamingComponent);this.turnHidden.delete(this.streamingComponent),this.unregisterCopyBlock(this.streamingComponent),this.streamingComponent=void 0}this.streamingToolSeparator=void 0,this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay(),this.setActivity(void 0),this.settleBashComponent()}dispose(){this.settleRun()}moreDetail(){const t=u.indexOf(this.level);return this.setLevel(u[(t+1)%u.length]),{level:this.level,atEnd:this.level===u.at(-1)}}lessDetail(){const t=u.indexOf(this.level);return this.setLevel(u[Math.max(0,t-1)]),{level:this.level,atEnd:this.level===u[0]}}setLevel(t){this.level=t;for(const e of this.turns)this.refreshTurn(e);this.applyToolDisplay()}repliesOnly(){return this.level==="replies"}foldsSettledTools(){return u.indexOf(this.level)<=u.indexOf("tools")}showsGroupSummaries(){return u.indexOf(this.level)<=u.indexOf("summaries")}toolOutputExpanded(){return this.level==="full"}applyToolDisplay(){const t=new Set(this.pendingTools.values());for(const i of this.groups)for(const n of i.inFlight)t.add(n);for(const i of this.historyContainer.children)i instanceof S&&i.setMinimized(this.foldsSettledTools()&&!t.has(i)),Dt(i)&&i.setExpanded(this.toolOutputExpanded());const e=this.turnFoldedComponents(t),s=new Set;for(const i of this.groups){this.applyGroupDisplay(i,e),s.add(i.recap);for(const n of i.members)s.add(n)}for(const i of this.turnHidden)!e.has(i)&&!s.has(i)&&this.historyContainer.setHidden(i,!1);for(const i of e)!s.has(i)&&!this.historyContainer.hiddenChildren.has(i)&&this.historyContainer.setHidden(i,!0);this.turnHidden=e,this.applyInboxExchangeDisplay(),this.updateFoldedToolSeparators(t),this.historyContainer.markDirty(),this.tui.requestRender()}hidesInboxExchange(){return this.showsGroupSummaries()}applyInboxExchangeDisplay(){const t=this.hidesInboxExchange();for(const e of this.inboxAnswers)this.historyContainer.setHidden(e,t);for(const e of this.pageBlocks.values())this.historyContainer.setHidden(e,e.settled)}applyTurnReply(t,e){if(!this.deferIfBuilding(()=>this.applyTurnReply(t,e))){this.turnReplies.set(t,e);for(const s of this.turns)s.key===t&&this.refreshTurn(s);this.tui.requestRender()}}turnFoldedComponents(t){const e=new Set;if(!this.repliesOnly())return e;for(const s of this.turns){const i=s===this.openReplyTurn;for(const n of s.members)i&&(n===this.streamingComponent||n===this.streamingToolSeparator||n===this.bashComponent||t.has(n))||e.add(n)}return e}beginTurn(t,e=[]){const s=new x(void 0,this.hideThinking,p(),this.hiddenThinkingLabel,this.markdownTransformers),i=new Ht;this.outsideTurns++;try{this.append(i),this.append(s)}finally{this.outsideTurns--}this.registerCopyBlock(s,"assistant","");const n={key:t,reply:s,working:i,members:new Set,prose:e};return this.turns.push(n),this.openReplyTurn=n,this.refreshTurn(n),n}currentTurn(){return this.openReplyTurn??this.beginTurn(ot)}recordTurnProse(t,e){if(t.role!=="assistant"||t.stopReason==="aborted"||t.stopReason==="error")return;const s=d(t).trim(),i=P(t);if(s===""||i===void 0)return;const n=this.currentTurn();n.prose.some(r=>r.key===i)||(n.prose.push({key:i,text:s}),e&&this.refreshTurn(n))}refreshTurn(t){const e=rt(t.prose,this.turnReplies.get(t.key));t.reply.updateContent(this.replyMessage(e)),this.historyContainer.setHidden(t.reply,e===""||!this.repliesOnly()),this.historyContainer.markDirty(t.reply),this.registerCopyBlock(t.reply,"assistant",e),e!==""&&t===this.turns.at(-1)&&(this.lastReplyText=e),this.refreshWorkingRow(t)}refreshWorkingRow(t){let e=0,s=0;for(const l of t.members)l instanceof S?e++:(l instanceof I||l instanceof O||l instanceof v)&&s++;const i=t.prose.length,n=e>0||s>0||i>1,r=[i>0?M(i,"message","messages"):void 0,e>0?M(e,"tool call","tool calls"):void 0,s>0?M(s,"card","cards"):void 0].filter(l=>l!==void 0),o=this.runActive&&t===this.openReplyTurn;t.working.setLabel(this.dimStyle(`\u25B8 ${o?"working \u2014 ":""}${r.join(" \xB7 ")}`)),this.historyContainer.setHidden(t.working,!n||!this.repliesOnly()),this.historyContainer.markDirty(t.working)}replyMessage(t){return{role:"assistant",content:t===""?[]:[{type:"text",text:t}],stopReason:"stop"}}toggleThinking(){this.hideThinking=!this.hideThinking;for(const t of this.historyContainer.children)t instanceof U&&t.setHideThinkingBlock(this.hideThinking);for(const[t,e]of this.foldedToolSeparatorContents)t.setSeparatesToolGroup(e.hasText||!this.hideThinking&&e.hasThinking);return this.historyContainer.markDirty(),this.tui.requestRender(),this.hideThinking}handleEvent(t){if(!this.deferIfBuilding(()=>this.handleEvent(t))){switch(this.projection=Et(this.projection,t),t.type){case"agent_start":{this.runActive=this.projection.isStreaming;for(const e of this.pendingTools.values())this.settleGroupTool(e);this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.setActivity(this.makeLoader(this.workingActivity));break}case"agent_end":{this.settleRun(),Ct();break}case"agent_settled":{this.settleRun();break}case"message_start":{if(t.message.role==="user"&&g(t.message)&&this.confirmPendingSend(this.userMessageText(t.message).trim()),t.message.role==="custom"||t.message.role==="user")this.addMessageToChat(t.message),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();else if(t.message.role==="assistant"){const e=d(t.message).trim()!=="";e&&this.closeOpenGroup(),this.streamingComponent=new x(void 0,this.hideThinking,p(),this.hiddenThinkingLabel,this.markdownTransformers),this.streamingWasGroupMember=!e,this.appendAssistantPart(this.streamingComponent,!e),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingComponent.updateContent(t.message),this.registerCopyBlock(this.streamingComponent,"assistant",d(t.message)),this.streamingToolSeparator=this.appendAssistantSeparator(!e),this.setAssistantSeparatorContent(this.streamingToolSeparator,t.message)}break}case"message_update":{if(this.streamingComponent&&t.message.role==="assistant"){this.promoteStreamingAssistantToBoundary(t.message),this.streamingComponent.updateContent(t.message),this.registerCopyBlock(this.streamingComponent,"assistant",d(t.message)),this.historyContainer.markDirty(this.streamingComponent);const e=this.assistantToolCalls(t.message);this.streamingToolSeparator&&this.setAssistantSeparatorContent(this.streamingToolSeparator,t.message);for(const s of e){this.pushTranscriptValue(s.arguments);const i=this.pendingTools.get(s.id);if(i)i.updateArgs(s.arguments),this.noteGroupTool(i,s.name,s.arguments),this.historyContainer.markDirty(i);else{const n=this.appendToolComponent(s.name,s.id,s.arguments);this.pendingTools.set(s.id,n)}}}break}case"message_end":{if(t.message.role!=="assistant")break;const e=t.message.stopReason==="aborted"||t.message.stopReason==="error";if(this.promoteStreamingAssistantToBoundary(t.message,e),this.streamingComponent&&this.registerCopyBlock(this.streamingComponent,"assistant",d(t.message)),t.message.stopReason!=="aborted"&&t.message.stopReason!=="error"){const s=d(t.message);s.trim()&&(this.lastAssistantText=s,this.pushTranscriptText(s))}if(this.streamingComponent){const s=t.message.stopReason;let i=t.message.errorMessage;if(A(t.message)&&(i="Interrupted",t.message.errorMessage=i,t.message.stopReason="aborted"),this.streamingComponent.updateContent(t.message),s==="aborted"||s==="error"){const n=i??"Error";for(const r of this.pendingTools.values())r.updateResult({content:[{type:"text",text:n}],isError:!0}),this.registerCopyBlock(r,"tool",n),this.settleGroupTool(r,{content:[{type:"text",text:n}],isError:!0},!0),this.historyContainer.markDirty(r);this.pendingTools.clear()}else for(const n of this.pendingTools.values())n.setArgsComplete(),this.historyContainer.markDirty(n);this.historyContainer.markDirty(this.streamingComponent),this.streamingComponent=void 0,this.streamingToolSeparator=void 0}e&&(this.closeOpenGroup(),this.applyToolDisplay()),this.recordTurnProse(t.message,!0),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();break}case"tool_execution_start":{this.pushTranscriptValue(t.args);let e=this.pendingTools.get(t.toolCallId);e?this.noteGroupTool(e,t.toolName,t.args):(e=this.appendToolComponent(t.toolName,t.toolCallId,t.args),this.pendingTools.set(t.toolCallId,e)),e.markExecutionStarted(),this.historyContainer.markDirty(e);break}case"tool_execution_update":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.partialResult;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e,!0),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.historyContainer.markDirty(s));break}case"tool_execution_end":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.result;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.pendingTools.delete(t.toolCallId),this.settleGroupTool(s,e,t.isError),this.applyToolDisplay(),this.historyContainer.markDirty(s),this.maybeAppendPageBlock(e));break}case"compaction_start":{const e=t.reason==="manual"?"Compacting context...":"Auto-compacting...";this.setActivity(this.makeLoader(e));break}case"compaction_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.aborted?this.showStatus(t.reason==="manual"?"Compaction cancelled":"Auto-compaction cancelled"):t.result?this.addMessageToChat({role:"compactionSummary",summary:t.result.summary,tokensBefore:t.result.tokensBefore,timestamp:Date.now()}):t.errorMessage&&this.showError(t.errorMessage);break}case"auto_retry_start":{const e=Math.ceil(t.delayMs/1e3);this.setActivity(this.makeLoader(`Retrying (${t.attempt}/${t.maxAttempts}) in ${e}s...`));break}case"auto_retry_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.success||this.showError(`Retry failed after ${t.attempt} attempts: ${t.finalError??"Unknown error"}`);break}case"queue_update":case"session_info_changed":case"thinking_level_changed":this.onFooterEvent?.(t);break;default:break}this.tui.requestRender()}}bashStart(t,e){if(this.deferIfBuilding(()=>this.bashStart(t,e)))return;this.projection=Mt(this.projection,t,e),this.closeOpenGroup(),this.settleBashComponent();let s;s=new E(t,this.componentTui(()=>s),e),this.bashComponent=s,this.append(s),this.tui.requestRender()}bashOutput(t){this.deferIfBuilding(()=>this.bashOutput(t))||(this.projection=Bt(this.projection,t),this.pushTranscriptText(t),this.bashComponent&&(this.bashComponent.appendOutput(t),this.historyContainer.markDirty(this.bashComponent)),this.tui.requestRender())}bashEnd(t){this.deferIfBuilding(()=>this.bashEnd(t))||(this.projection=At(this.projection,t),this.settleBashComponent(t),this.tui.requestRender())}addMessageToChat(t){const e=st(t);if(e!==null&&(t.role!=="custom"||t.display===!0)){this.pushTranscriptText(e.body);const s=e.senders.flatMap(n=>n.entries).filter(D).map(n=>n.body.trim()).filter(n=>n!=="");if(!(s.length>0&&e.body.replace(_t,"").trim()===""&&e.senders.every(n=>n.entries.every(D)))){const n=X(e.kind),r=new I(e,n,this.toolOutputExpanded(),this.dimStyle,o=>this.spinnerStyle(this.labelStyle(o)));it(e.kind)?(this.closeOpenGroup(),this.append(r)):this.appendGroupMember(r)?.activity.noteCard(e,n)}for(const n of s)this.appendHumanAnswer(n);return}switch(t.role){case"bashExecution":{this.closeOpenGroup(),this.pushTranscriptText(t.output??"");const s=new E(t.command,this.tui,t.excludeFromContext);t.output&&s.appendOutput(t.output),s.setComplete(t.exitCode,t.cancelled,t.truncated?{truncated:!0}:void 0,t.fullOutputPath),this.append(s);break}case"custom":{if(t.display){if(this.pushTranscriptText(this.userMessageText(t)),t.customType===tt){this.appendGroupMember(new v(this.userMessageText(t),this.toolOutputExpanded(),this.crtrOutputTheme()));break}const s=new O(lt(t),void 0,p());s.setExpanded(this.toolOutputExpanded()),this.appendGroupMember(s)}break}case"compactionSummary":{this.closeOpenGroup(),this.append(new c(1));const s=new z(F(t),p());s.setExpanded(this.toolOutputExpanded()),this.append(s);break}case"branchSummary":{this.closeOpenGroup(),this.append(new c(1));const s=new N(F(t),p());s.setExpanded(this.toolOutputExpanded()),this.append(s),this.registerCopyBlock(s,"assistant",t.summary);break}case"user":{if(g(t)&&this.closeOpenGroup(),g(t)){this.outsideTurns++;try{this.appendUserMessage(t)}finally{this.outsideTurns--}this.beginTurn(P(t)??`local-${this.turns.length}`);break}this.appendUserMessage(t);break}case"assistant":{const s=d(t).trim()!=="";s&&this.closeOpenGroup(),this.appendAssistantMessage(t,!s);break}default:break}}appendUserMessage(t){const e=this.userMessageText(t);if(!e)return;this.pushTranscriptText(e),this.chatChildCount()>0&&this.appendUserPart(new c(1),!g(t));const s=Y(e);if(s){const i=new K({...s,content:j(s.content)},p());if(i.setExpanded(this.toolOutputExpanded()),this.appendUserPart(i,!g(t)),this.registerCopyBlock(i,"user",e),s.userMessage){const n=new R(s.userMessage,p(),void 0,this.markdownTransformers);this.appendUserPart(n,!g(t)),this.registerCopyBlock(n,"user",s.userMessage)}}else{const i=new R(e,p(),void 0,this.markdownTransformers);this.appendUserPart(i,!g(t)),this.registerCopyBlock(i,"user",e)}}appendAssistantMessage(t,e=!1){const s=new x(void 0,this.hideThinking,p(),this.hiddenThinkingLabel,this.markdownTransformers),i=A(t)?{...t,stopReason:"aborted",errorMessage:"Interrupted"}:t;s.updateContent(i),this.appendAssistantPart(s,e),this.registerCopyBlock(s,"assistant",d(t));const n=this.appendAssistantSeparator(e);return this.setAssistantSeparatorContent(n,t),n}appendAssistantSeparator(t=!1){const e=new B;return t?this.appendGroupMember(e):this.append(e),e}appendAssistantPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendUserPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendHumanAnswer(t){this.outsideTurns++;try{this.appendHumanAnswerParts(t)}finally{this.outsideTurns--}}appendHumanAnswerParts(t){if(this.closeOpenGroup(),this.chatChildCount()>0){const s=new c(1);this.append(s),this.trackInboxAnswer(s)}const e=new R(t,p(),void 0,this.markdownTransformers);this.append(e),this.trackInboxAnswer(e),this.registerCopyBlock(e,"user",t)}trackInboxAnswer(t){this.inboxAnswers.add(t),this.hidesInboxExchange()&&this.historyContainer.setHidden(t,!0)}ensureGroup(){if(this.openGroup)return this.openGroup;const t=new ct,e={members:[],recap:t,activity:new dt(this.cwd,this.nodeRoster),toolCount:0,inFlight:new Set};return this.append(t),this.historyContainer.setHidden(t,!0),this.groups.push(e),this.openGroup=e,e}closeOpenGroup(){this.openGroup=void 0}appendGroupMember(t){const e=this.ensureGroup();return this.append(t),e&&e.members.push(t),e}removeGroupMember(t){for(const e of this.groups){const s=e.members.indexOf(t);s!==-1&&e.members.splice(s,1)}this.historyContainer.setHidden(t,!1)}appendToolComponent(t,e,s){const i=!this.openGroup&&this.historyContainer.children.at(-1)instanceof B?this.historyContainer.children.at(-1):void 0;i&&this.historyContainer.removeChild(i);const n=this.ensureGroup();i&&(this.append(i),n?.members.push(i));const r=this.makeToolComponent(t,e,s);return r.activityCallId=e,this.appendGroupMember(r),this.registerCopyBlock(r,"tool",""),n&&(n.key??=e,n.toolCount++,n.inFlight.add(r),n.activity.noteCall(e,t,s)),r}noteGroupTool(t,e,s){if(t.activityCallId)for(const i of this.groups)i.members.includes(t)&&i.activity.noteCall(t.activityCallId,e,s)}settleGroupTool(t,e,s=!1){for(const i of this.groups)i.inFlight.delete(t),!(!t.activityCallId||!i.members.includes(t))&&(e===void 0?i.activity.resolveWithoutResult(t.activityCallId):i.activity.settle(t.activityCallId,e,s))}promoteStreamingAssistantToBoundary(t,e=!1){!this.streamingWasGroupMember||!e&&d(t).trim()===""||(this.streamingComponent&&this.removeGroupMember(this.streamingComponent),this.streamingToolSeparator&&this.removeGroupMember(this.streamingToolSeparator),this.streamingWasGroupMember=!1,this.closeOpenGroup())}seedToolGroupSummaries(t){this.groupSummaries.clear();for(const[e,s]of Object.entries(t))this.groupSummaries.set(e,s)}applyToolGroupSummary(t,e){if(this.deferIfBuilding(()=>this.applyToolGroupSummary(t,e)))return;this.projection=St(this.projection,t,e);const s=this.projection.toolGroupSummaryDetails[t];s!==void 0&&(this.groupSummaries.set(t,s),this.applyToolDisplay())}applyGroupDisplay(t,e){const s=t.key===void 0?void 0:this.groupSummaries.get(t.key),i=this.showsGroupSummaries()&&t.toolCount>0&&t.inFlight.size===0&&s!==void 0;t.recap.setRecap(i?s:void 0,t.toolCount,t.activity.activity(),this.detailedToolRecaps,this.recapPalette),this.historyContainer.setHidden(t.recap,!i||e.has(t.recap));for(const n of t.members)this.historyContainer.setHidden(n,i||e.has(n))}updateFoldedToolSeparators(t=new Set(this.pendingTools.values())){const e=this.historyContainer.children;for(let s=0;s<e.length;s++){const i=e[s];if(!(i instanceof B))continue;const n=e[s+1];i.setFolded(this.foldsSettledTools()&&!this.historyContainer.hiddenChildren.has(i)&&n instanceof S&&!this.historyContainer.hiddenChildren.has(n)&&!t.has(n)),this.historyContainer.markDirty(i)}}setAssistantSeparatorContent(t,e){const s=e.content,i=Array.isArray(s)?s:[],n=i.some(o=>typeof o=="object"&&o!==null&&o.type==="text"&&typeof o.text=="string"&&o.text.trim()!==""),r=i.some(o=>typeof o=="object"&&o!==null&&o.type==="thinking"&&typeof o.thinking=="string"&&o.thinking.trim()!=="");this.foldedToolSeparatorContents.set(t,{hasText:n,hasThinking:r}),t.setSeparatesToolGroup(n||!this.hideThinking&&r)}makeToolComponent(t,e,s){const i=new ut;let n,r;if(t==="bash"){const l=et(s,i);l===void 0?r=ft(this.cwd,i,this.backgroundBashHint):r=l.definition}else if(t==="edit"){const l=pt(this.cwd,i);r=l.definition,n=l.observeResult}else t==="read"?r=gt(this.cwd,i):t==="write"&&(r=yt(this.cwd,i));let o;return o=new S(t,e,s,{showImages:this.showImages,imageWidthCells:this.imageWidthCells},r,this.componentTui(()=>o),this.cwd),o.setToolView(r===void 0?void 0:i,n),o.setExpanded(this.toolOutputExpanded()),o}append(t){if(this.outsideTurns===0){const e=this.currentTurn();this.historyContainer.addChild(t),e.members.add(t);return}this.historyContainer.addChild(t)}chatChildCount(){return this.historyContainer.children.length}resetChat(){this.setActivity(void 0),this.settleBashComponent(),this.streamingComponent=void 0,this.streamingToolSeparator=void 0,this.streamingWasGroupMember=!1,this.foldedToolSeparatorContents.clear(),this.groups.length=0,this.openGroup=void 0,this.turns.length=0,this.openReplyTurn=void 0,this.turnHidden=new Set,this.lastReplyText=void 0,this.groupSummaries.clear(),this.nodeRoster.clear(),this.pendingTools.clear(),this.lastAssistantText=void 0,this.copyBlockRecords.length=0,this.copyIndex.clear(),this.transcriptFilePaths.length=0,this.transcriptDocRefs.length=0,this.pageBlocks.clear(),this.inboxAnswers.clear(),this.historyContainer.clear()}maybeAppendPageBlock(t){if(!this.inlinePageBlocks)return;const e=Q(t);if(e===void 0||this.pageBlocks.has(e.pageId))return;const s=new Z(e.pageId,this.pageOpenHint);this.pageBlocks.set(e.pageId,s),this.outsideTurns++;try{this.append(s)}finally{this.outsideTurns--}this.loadPageBlock(s)}async loadPageBlock(t){await t.refresh()&&(this.historyContainer.setHidden(t,t.settled),this.historyContainer.markDirty(t),this.tui.requestRender())}refreshInFlightTools(){if(this.pendingTools.size!==0){for(const t of this.pendingTools.values())this.historyContainer.markDirty(t);this.tui.requestRender()}}async refreshPageBlocks(){if(this.pageRefresh)return;const t=[...this.pageBlocks.values()].filter(s=>!s.settled);this.pageRefresh=!0,(await Promise.all(t.map(async s=>{const i=await s.refresh();return i&&(this.historyContainer.setHidden(s,s.settled),this.historyContainer.markDirty(s)),i})).finally(()=>{this.pageRefresh=!1})).some(Boolean)&&this.tui.requestRender()}makeLoader(t){let e;const s={requestRender:h(i=>{e&&!this.onActivityChange&&this.statusContainer.markDirty(e),this.tui.requestRender(i)},"requestRender"),terminal:this.tui.terminal};return e=new q(s,this.spinnerStyle,this.dimStyle,t),e}componentTui(t){return{requestRender:h(e=>{this.historyContainer.markDirty(t()),this.tui.requestRender(e)},"requestRender"),terminal:this.tui.terminal}}settleBashComponent(t){if(!this.bashComponent)return;const e=this.bashComponent;e.setComplete(t?.exitCode,t?.cancelled??!0,t?.truncated?{truncated:!0}:void 0,t?.fullOutputPath),this.historyContainer.markDirty(e),this.bashComponent=void 0}addPendingSend(t){const e=t.trim();if(!e)return;const s=[new c(1),new V(e,1,1,p(),{color:this.dimStyle})];for(const i of s)this.pendingContainer.addChild(i);this.pendingSends.push({text:e,parts:s}),this.tui.requestRender()}confirmPendingSend(t){const e=this.pendingSends.findIndex(n=>n.text===t),s=e>=0?e:0;if(this.pendingSends.length===0)return;const[i]=this.pendingSends.splice(s,1);for(const n of i.parts)this.pendingContainer.removeChild(n)}confirmPendingSendsIn(t){if(this.pendingSends.length===0)return;const e=new Set;for(const s of t.slice(-50))s.role==="user"&&e.add(this.userMessageText(s).trim());for(const s of[...this.pendingSends])if(e.has(s.text)){this.pendingSends.splice(this.pendingSends.indexOf(s),1);for(const i of s.parts)this.pendingContainer.removeChild(i)}}setActivity(t){if(this.activityLoader?.stop(),this.activityLoader=t,this.onActivityChange){this.onActivityChange(t);return}this.statusContainer.clear(),t&&this.statusContainer.addChild(t)}showStatus(t){this.closeOpenGroup(),this.append(new c(1)),this.append(new b(this.dimStyle(t),1,0))}showError(t){if(!this.deferIfBuilding(()=>this.showError(t))){this.closeOpenGroup(),this.outsideTurns++;try{this.append(new c(1)),this.append(new b(this.errorStyle(t),1,0))}finally{this.outsideTurns--}this.tui.requestRender()}}crtrOutputTheme(){return{fg:h((t,e)=>t==="error"?this.errorStyle(e):t==="warning"||t==="accent"||t==="toolTitle"||t==="success"?this.spinnerStyle(e):t==="muted"?this.dimStyle(e):e,"fg"),bg:h((t,e)=>e,"bg"),bold:h(t=>this.labelStyle(t),"bold")}}assistantToolCalls(t){const e=t.content;return Array.isArray(e)?e.filter(s=>typeof s=="object"&&s!==null&&s.type==="toolCall"):[]}getTranscriptFilePathsNewestFirst(){return[...this.transcriptFilePaths]}getTranscriptDocRefsNewestFirst(){return[...this.transcriptDocRefs]}refreshMarkdown(){this.historyContainer.invalidate(),this.tui.requestRender()}getLastAssistantText(){const t=(this.repliesOnly()?this.lastReplyText??this.lastAssistantText:this.lastAssistantText)?.trim();return t||void 0}blockText(t){const e=this.copyIndex.get(t);return e===void 0?void 0:this.copyBlockRecords[e]?.text}copyBlocks(){return this.copyBlockRecords}getLastToolOutputText(){for(let t=this.copyBlockRecords.length-1;t>=0;t--){const e=this.copyBlockRecords[t];if(e.kind==="tool")return e.text.trim()===""?void 0:e.text}}getTranscriptPlainText(){const t=this.inactiveFormBlocks();return this.copyBlockRecords.filter(e=>!t.has(e.block)).map(e=>e.text).filter(e=>e.trim()!=="").join(`
2
2
 
3
- `)}inactiveFormBlocks(){const t=new Set;if(this.repliesOnly())this.condensedBlocks.messages&&t.add(this.condensedBlocks.messages);else{this.condensedBlocks.turns&&t.add(this.condensedBlocks.turns);for(const e of this.turns)t.add(e.reply)}return t}registerCopyBlock(t,e,s){const i=this.condensedCopyBlocks.get(this.appendTarget);if(i){const a=i.findIndex(o=>o.block===t);a===-1?i.push({block:t,kind:e,text:s}):i[a].text=s;return}const n=this.copyIndex.get(t);n===void 0?(this.copyIndex.set(t,this.copyBlockRecords.length),this.copyBlockRecords.push({block:t,kind:e,text:s})):this.copyBlockRecords[n].text=s}unregisterCopyBlock(t){const e=this.condensedCopyBlocks.get(this.appendTarget);if(e){const i=e.findIndex(n=>n.block===t);i!==-1&&e.splice(i,1);return}const s=this.copyIndex.get(t);if(s!==void 0){this.copyBlockRecords.splice(s,1),this.copyIndex.delete(t);for(let i=s;i<this.copyBlockRecords.length;i++)this.copyIndex.set(this.copyBlockRecords[i].block,i)}}appendCondensedBlock({component:t,copyBlocks:e},s){this.outsideTurns++;try{this.append(t)}finally{this.outsideTurns--}this.condensedBlocks[s]=t,this.historyContainer.setHidden(t,s==="turns"!==this.repliesOnly()),this.registerCopyBlock(t,"condensed",e.map(i=>i.text).filter(i=>i.trim()!=="").join(`
4
-
5
- `))}toolResultText(t){if(typeof t=="string")return t;if(typeof t=="object"&&t!==null&&"content"in t){const e=t.content;if(typeof e=="string")return e;if(Array.isArray(e))return e.filter(s=>typeof s=="object"&&s!==null&&s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}try{const e=JSON.stringify(t);return typeof e=="string"?e:""}catch{return""}}pushTranscriptText(t){const e=t.trim();if(e==="")return;const s=[...new Set(St(e).reverse())];if(s.length>0){const a=[...s,...this.transcriptDocRefs.filter(o=>!s.includes(o))].slice(0,50);this.transcriptDocRefs.splice(0,this.transcriptDocRefs.length,...a)}const i=wt([e],this.cwd);if(i.length===0)return;const n=[...i,...this.transcriptFilePaths.filter(a=>!i.includes(a))].slice(0,50);this.transcriptFilePaths.splice(0,this.transcriptFilePaths.length,...n)}pushTranscriptValue(t){try{const e=typeof t=="string"?t:JSON.stringify(t);typeof e=="string"&&this.pushTranscriptText(e)}catch{}}userMessageText(t){const e=t.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(s=>typeof s=="object"&&s!==null&&s.type==="text").map(s=>s.text).join(""):""}}export{Re as ChatView};
3
+ `)}inactiveFormBlocks(){const t=new Set;if(!this.repliesOnly())for(const e of this.turns)t.add(e.reply);return t}registerCopyBlock(t,e,s){const i=this.copyIndex.get(t);i===void 0?(this.copyIndex.set(t,this.copyBlockRecords.length),this.copyBlockRecords.push({block:t,kind:e,text:s})):this.copyBlockRecords[i].text=s}unregisterCopyBlock(t){const e=this.copyIndex.get(t);if(e!==void 0){this.copyBlockRecords.splice(e,1),this.copyIndex.delete(t);for(let s=e;s<this.copyBlockRecords.length;s++)this.copyIndex.set(this.copyBlockRecords[s].block,s)}}toolResultText(t){if(typeof t=="string")return t;if(typeof t=="object"&&t!==null&&"content"in t){const e=t.content;if(typeof e=="string")return e;if(Array.isArray(e))return e.filter(s=>typeof s=="object"&&s!==null&&s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}try{const e=JSON.stringify(t);return typeof e=="string"?e:""}catch{return""}}pushTranscriptText(t){const e=t.trim();if(e==="")return;const s=[...new Set(kt(e).reverse())];if(s.length>0){const r=[...s,...this.transcriptDocRefs.filter(o=>!s.includes(o))].slice(0,50);this.transcriptDocRefs.splice(0,this.transcriptDocRefs.length,...r)}const i=Tt([e],this.cwd);if(i.length===0)return;const n=[...i,...this.transcriptFilePaths.filter(r=>!i.includes(r))].slice(0,50);this.transcriptFilePaths.splice(0,this.transcriptFilePaths.length,...n)}pushTranscriptValue(t){try{const e=typeof t=="string"?t:JSON.stringify(t);typeof e=="string"&&this.pushTranscriptText(e)}catch{}}userMessageText(t){const e=t.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(s=>typeof s=="object"&&s!==null&&s.type==="text").map(s=>s.text).join(""):""}}export{me as ChatView};