@north-light/cli 0.3.697 → 0.3.699

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.
@@ -32,6 +32,9 @@ export interface InputControllerHooks {
32
32
  isDormant?: () => boolean;
33
33
  onDormantSubmit?: (text: string) => void;
34
34
  onPromptSent?: () => void;
35
+ /** A new message (not a steer) left the editor; the viewer shows it pending
36
+ * until the engine echoes it. */
37
+ onMessageSent?: (text: string) => void;
35
38
  /** Per-user completion frecency store — usage recorded here biases the sort
36
39
  * order the next time `/` completion opens. */
37
40
  frecency?: FrecencyStore;
@@ -1,7 +1,7 @@
1
- var p=Object.defineProperty;var r=(d,e)=>p(d,"name",{value:e,configurable:!0});import{spawn as u}from"node:child_process";import{readFileSync as f,unlinkSync as k,writeFileSync as g}from"node:fs";import{tmpdir as y}from"node:os";import{join as P}from"node:path";import{BROKER_READ_CAPS as v,encodeFrame as w}from"../../../core/runtime/broker-protocol.js";import{classifySubmit as x}from"../../conversation/submit.js";import{findRefTokens as C}from"../../../shared/inline-ref-grammar.js";import{dispatchSlashCommand as S,isSlashCommand as m}from"../slash/dispatch.js";import{viewerOperationForFrame as b}from"./capabilities.js";import{readClipboardImage as T,writeClipboardImageToFile as I}from"./clipboard-image.js";import{InputOverlayOwner as D}from"./overlay-owner.js";import{announceFallbackEditor as E,NO_EDITOR_MESSAGE as A,resolveEditor as M}from"../../../core/editor-resolver.js";const q=500,R=v.maxLineBytes-4*1024*1024;class z{static{r(this,"InputController")}tui;editor;keybindings;hooks;capabilities;overlays;state;lastEscapeAt=0;pastedImages=new Map;pasteSeq=0;constructor(e,t,o,i,s){this.tui=e,this.editor=t,this.keybindings=o,this.hooks=i,this.capabilities=s,this.overlays=new D(e,t,o,{send:r(n=>this.emitCommand(n),"send"),notify:r(n=>this.notify(n),"notify"),onDialogResponse:i.onDialogResponse,onRequest:i.onRequest,onMountPicker:i.onMountPicker,onUnmountPicker:i.onUnmountPicker,state:r(()=>this.state,"state")}),this.wire()}cycleLadder(e){this.emitCommand({type:"cycle_ladder",direction:e})}sendInterrupting(e){return this.emitDrive({type:"prompt",text:e,interrupt:!0})}abortTurn(){return this.state?.isStreaming!==!0?!1:this.emitCommand({type:"abort"})}attachDialog(e){this.overlays.attachDialog(e)}dismissDialog(e){this.overlays.dismissDialog(e)}setState(e){this.state=e}openFileReviewPicker(e,t,o){this.overlays.openFileReviewPicker(e,t,o)}openAuthPicker(e){return this.overlays.openAuthPicker(e)}send=r(e=>{this.emitCommand(e)},"send");emitCommand(e){const t=b(e),o=t===void 0?void 0:this.capabilities.refusal(t);return o===void 0?(this.hooks.onCommand(e),!0):(this.notify(o),!1)}openBrokerPicker(e){const t=this.capabilities.refusal("engine-drive");if(t!==void 0){this.notify(t);return}e()}wire(){this.editor.onSubmit=t=>this.handleSubmit(t),this.editor.onEscape=()=>{if(this.state?.isStreaming){this.emitCommand({type:"abort"});return}if(this.editor.getText().trim())return;const t=Date.now();t-this.lastEscapeAt<q?(this.lastEscapeAt=0,this.openBrokerPicker(()=>{this.overlays.openTreePicker()})):this.lastEscapeAt=t},this.editor.onPasteImage=()=>{this.handlePaste()};const e=this.editor;e.onPasteImagePath=t=>(this.attachImage(t),!0),this.editor.onAction("app.session.new",()=>this.emitCommand({type:"new_session"})),this.editor.onAction("app.model.cycleForward",()=>this.emitCommand({type:"cycle_model",direction:"forward"})),this.editor.onAction("app.model.cycleBackward",()=>this.emitCommand({type:"cycle_model",direction:"backward"})),this.editor.onAction("app.thinking.cycle",()=>this.emitCommand({type:"cycle_thinking"})),this.editor.onAction("app.message.followUp",()=>this.handleFollowUp()),this.editor.onAction("app.message.dequeue",()=>{this.handleDequeue()}),this.editor.onAction("app.tools.expand",()=>this.hooks.onMoreDetail?.()),this.editor.onAction("app.thinking.toggle",()=>this.hooks.onToggleThinking?.()),this.editor.onAction("app.editor.external",()=>{this.openExternalEditor()}),this.editor.onAction("app.model.select",()=>this.openBrokerPicker(()=>{this.overlays.openModelPicker()})),this.editor.onAction("app.session.tree",()=>this.openBrokerPicker(()=>{this.overlays.openTreePicker()})),this.editor.onAction("app.session.fork",()=>this.openBrokerPicker(()=>{this.overlays.openForkPicker()})),this.editor.onAction("app.session.resume",()=>this.openBrokerPicker(()=>{this.overlays.openSessionPicker()}))}slashContext(){return{send:this.send,notify:r(e=>this.notify(e),"notify"),capabilities:this.capabilities,state:this.state,cwd:process.cwd(),onGraph:this.hooks.onGraph,onInbox:this.hooks.onInbox,onHelp:this.hooks.onHelp,onQuit:this.hooks.onQuit,onCopy:this.hooks.onCopy,onCopyTarget:this.hooks.onCopyTarget,onToggleMouse:this.hooks.onToggleMouse,onColor:this.hooks.onColor,onNodeMetadata:this.hooks.onNodeMetadata,onMoreDetail:this.hooks.onMoreDetail,onLessDetail:this.hooks.onLessDetail,openModelPicker:r(()=>this.openBrokerPicker(()=>{this.overlays.openModelPicker()}),"openModelPicker"),openSessionPicker:r(()=>this.openBrokerPicker(()=>{this.overlays.openSessionPicker()}),"openSessionPicker"),openForkPicker:r(()=>this.openBrokerPicker(()=>{this.overlays.openForkPicker()}),"openForkPicker"),openTreePicker:r(()=>this.openBrokerPicker(()=>{this.overlays.openTreePicker()}),"openTreePicker"),openSettingsPicker:r(()=>this.openBrokerPicker(()=>{this.overlays.openSettingsPicker()}),"openSettingsPicker"),openScopedModelsPicker:r(()=>this.openBrokerPicker(()=>{this.overlays.openScopedModelsPicker()}),"openScopedModelsPicker"),openMcpPicker:r(e=>this.overlays.openMcpPicker(e),"openMcpPicker"),openLoginPicker:this.hooks.openLoginPicker,openLogoutPicker:this.hooks.openLogoutPicker}}recordCommandUse(e){const t=this.hooks.frecency;if(!t)return;const o=e.slice(1).split(/\s/,1)[0];o&&t.record(`command:${o}`)}recordCompletionUse(e){const t=this.hooks.frecency;if(!t)return;const o=e.trim();if(m(o)){this.recordCommandUse(o);return}const i=this.hooks.knownRefNames?.();if(!i||i.size===0)return;const s=new Set;for(const n of C(e))i.has(n.candidate)&&!s.has(n.candidate)&&(s.add(n.candidate),t.record(`ref:${n.candidate}`))}handleSubmit(e){const t=e.trim();if(!t)return;if(m(t)&&S(t,this.slashContext())){this.recordCommandUse(t),this.editor.setText("");return}const o=this.hooks.isDormant?.()===!0;if(o&&(t.startsWith("/")||t.startsWith("!"))){this.notify("This node is parked \u2014 submit a message to wake it; broker commands need a live engine");return}const i=x(e,{isDormant:o,canWakeDormant:o&&this.capabilities.permits("wake-dormant")&&this.hooks.onDormantSubmit!==void 0,isStreaming:this.state?.isStreaming===!0});if(i.kind==="empty")return;if(i.kind==="dormant"){const a=this.hooks.onDormantSubmit;if(a===void 0)return;a(this.expandImagePlaceholders(i.text)),this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),this.hooks.onPromptSent?.();return}if(i.kind==="bash"){if(!this.emitDrive({type:"bash",command:i.command,excludeFromContext:i.excludeFromContext}))return;this.editor.addToHistory(i.trimmed),this.editor.setText("");return}const s=i.kind==="slash"?this.state?.isStreaming===!0?"steer":"prompt":i.kind;if(s!=="steer"&&s!=="prompt")return;const n=this.expandImagePlaceholders(i.kind==="slash"?e:i.text);this.emitDrive(s==="steer"?{type:"steer",text:n}:{type:"prompt",text:n})&&(this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),this.hooks.onPromptSent?.())}handleFollowUp(){const e=this.editor.getText(),t=e.trim();t&&this.emitDrive({type:"follow_up",text:this.expandImagePlaceholders(e)})&&(this.editor.addToHistory(t),this.editor.setText(""),this.clearPastedImages())}async handleDequeue(){const e=this.capabilities.refusal("dequeue");if(e!==void 0){this.notify(e);return}const t=this.hooks.onRequest;if(t===void 0){this.notify("Restoring queued messages isn't available in this viewer");return}let o;try{o=await t({type:"dequeue"})}catch(s){this.notify(`Could not restore queued messages: ${s instanceof Error?s.message:String(s)}`);return}if(o.kind!=="dequeue"){this.notify("Unexpected reply restoring queued messages");return}const i=[...o.steering,...o.followUp];if(i.length===0){this.notify("No queued messages to restore");return}this.editor.setText([i.join(`
1
+ var p=Object.defineProperty;var n=(h,e)=>p(h,"name",{value:e,configurable:!0});import{spawn as u}from"node:child_process";import{readFileSync as f,unlinkSync as k,writeFileSync as g}from"node:fs";import{tmpdir as y}from"node:os";import{join as P}from"node:path";import{BROKER_READ_CAPS as v,encodeFrame as x}from"../../../core/runtime/broker-protocol.js";import{classifySubmit as w}from"../../conversation/submit.js";import{findRefTokens as C}from"../../../shared/inline-ref-grammar.js";import{dispatchSlashCommand as S,isSlashCommand as m}from"../slash/dispatch.js";import{viewerOperationForFrame as b}from"./capabilities.js";import{readClipboardImage as T,writeClipboardImageToFile as I}from"./clipboard-image.js";import{InputOverlayOwner as D}from"./overlay-owner.js";import{announceFallbackEditor as E,NO_EDITOR_MESSAGE as M,resolveEditor as A}from"../../../core/editor-resolver.js";const q=500,R=v.maxLineBytes-4*1024*1024;class z{static{n(this,"InputController")}tui;editor;keybindings;hooks;capabilities;overlays;state;lastEscapeAt=0;pastedImages=new Map;pasteSeq=0;constructor(e,t,o,i,s){this.tui=e,this.editor=t,this.keybindings=o,this.hooks=i,this.capabilities=s,this.overlays=new D(e,t,o,{send:n(r=>this.emitCommand(r),"send"),notify:n(r=>this.notify(r),"notify"),onDialogResponse:i.onDialogResponse,onRequest:i.onRequest,onMountPicker:i.onMountPicker,onUnmountPicker:i.onUnmountPicker,state:n(()=>this.state,"state")}),this.wire()}cycleLadder(e){this.emitCommand({type:"cycle_ladder",direction:e})}sendInterrupting(e){return this.emitDrive({type:"prompt",text:e,interrupt:!0})}abortTurn(){return this.state?.isStreaming!==!0?!1:this.emitCommand({type:"abort"})}attachDialog(e){this.overlays.attachDialog(e)}dismissDialog(e){this.overlays.dismissDialog(e)}setState(e){this.state=e}openFileReviewPicker(e,t,o){this.overlays.openFileReviewPicker(e,t,o)}openAuthPicker(e){return this.overlays.openAuthPicker(e)}send=n(e=>{this.emitCommand(e)},"send");emitCommand(e){const t=b(e),o=t===void 0?void 0:this.capabilities.refusal(t);return o===void 0?(this.hooks.onCommand(e),!0):(this.notify(o),!1)}openBrokerPicker(e){const t=this.capabilities.refusal("engine-drive");if(t!==void 0){this.notify(t);return}e()}wire(){this.editor.onSubmit=t=>this.handleSubmit(t),this.editor.onEscape=()=>{if(this.state?.isStreaming){this.emitCommand({type:"abort"});return}if(this.editor.getText().trim())return;const t=Date.now();t-this.lastEscapeAt<q?(this.lastEscapeAt=0,this.openBrokerPicker(()=>{this.overlays.openTreePicker()})):this.lastEscapeAt=t},this.editor.onPasteImage=()=>{this.handlePaste()};const e=this.editor;e.onPasteImagePath=t=>(this.attachImage(t),!0),this.editor.onAction("app.session.new",()=>this.emitCommand({type:"new_session"})),this.editor.onAction("app.model.cycleForward",()=>this.emitCommand({type:"cycle_model",direction:"forward"})),this.editor.onAction("app.model.cycleBackward",()=>this.emitCommand({type:"cycle_model",direction:"backward"})),this.editor.onAction("app.thinking.cycle",()=>this.emitCommand({type:"cycle_thinking"})),this.editor.onAction("app.message.followUp",()=>this.handleFollowUp()),this.editor.onAction("app.message.dequeue",()=>{this.handleDequeue()}),this.editor.onAction("app.tools.expand",()=>this.hooks.onMoreDetail?.()),this.editor.onAction("app.thinking.toggle",()=>this.hooks.onToggleThinking?.()),this.editor.onAction("app.editor.external",()=>{this.openExternalEditor()}),this.editor.onAction("app.model.select",()=>this.openBrokerPicker(()=>{this.overlays.openModelPicker()})),this.editor.onAction("app.session.tree",()=>this.openBrokerPicker(()=>{this.overlays.openTreePicker()})),this.editor.onAction("app.session.fork",()=>this.openBrokerPicker(()=>{this.overlays.openForkPicker()})),this.editor.onAction("app.session.resume",()=>this.openBrokerPicker(()=>{this.overlays.openSessionPicker()}))}slashContext(){return{send:this.send,notify:n(e=>this.notify(e),"notify"),capabilities:this.capabilities,state:this.state,cwd:process.cwd(),onGraph:this.hooks.onGraph,onInbox:this.hooks.onInbox,onHelp:this.hooks.onHelp,onQuit:this.hooks.onQuit,onCopy:this.hooks.onCopy,onCopyTarget:this.hooks.onCopyTarget,onToggleMouse:this.hooks.onToggleMouse,onColor:this.hooks.onColor,onNodeMetadata:this.hooks.onNodeMetadata,onMoreDetail:this.hooks.onMoreDetail,onLessDetail:this.hooks.onLessDetail,openModelPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openModelPicker()}),"openModelPicker"),openSessionPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openSessionPicker()}),"openSessionPicker"),openForkPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openForkPicker()}),"openForkPicker"),openTreePicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openTreePicker()}),"openTreePicker"),openSettingsPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openSettingsPicker()}),"openSettingsPicker"),openScopedModelsPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openScopedModelsPicker()}),"openScopedModelsPicker"),openMcpPicker:n(e=>this.overlays.openMcpPicker(e),"openMcpPicker"),openLoginPicker:this.hooks.openLoginPicker,openLogoutPicker:this.hooks.openLogoutPicker}}recordCommandUse(e){const t=this.hooks.frecency;if(!t)return;const o=e.slice(1).split(/\s/,1)[0];o&&t.record(`command:${o}`)}recordCompletionUse(e){const t=this.hooks.frecency;if(!t)return;const o=e.trim();if(m(o)){this.recordCommandUse(o);return}const i=this.hooks.knownRefNames?.();if(!i||i.size===0)return;const s=new Set;for(const r of C(e))i.has(r.candidate)&&!s.has(r.candidate)&&(s.add(r.candidate),t.record(`ref:${r.candidate}`))}handleSubmit(e){const t=e.trim();if(!t)return;if(m(t)&&S(t,this.slashContext())){this.recordCommandUse(t),this.editor.setText("");return}const o=this.hooks.isDormant?.()===!0;if(o&&(t.startsWith("/")||t.startsWith("!"))){this.notify("This node is parked \u2014 submit a message to wake it; broker commands need a live engine");return}const i=w(e,{isDormant:o,canWakeDormant:o&&this.capabilities.permits("wake-dormant")&&this.hooks.onDormantSubmit!==void 0,isStreaming:this.state?.isStreaming===!0});if(i.kind==="empty")return;if(i.kind==="dormant"){const a=this.hooks.onDormantSubmit;if(a===void 0)return;const d=this.expandImagePlaceholders(i.text);a(d),this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),this.hooks.onMessageSent?.(d),this.hooks.onPromptSent?.();return}if(i.kind==="bash"){if(!this.emitDrive({type:"bash",command:i.command,excludeFromContext:i.excludeFromContext}))return;this.editor.addToHistory(i.trimmed),this.editor.setText("");return}const s=i.kind==="slash"?this.state?.isStreaming===!0?"steer":"prompt":i.kind;if(s!=="steer"&&s!=="prompt")return;const r=this.expandImagePlaceholders(i.kind==="slash"?e:i.text);this.emitDrive(s==="steer"?{type:"steer",text:r}:{type:"prompt",text:r})&&(this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),s==="prompt"&&this.hooks.onMessageSent?.(r),this.hooks.onPromptSent?.())}handleFollowUp(){const e=this.editor.getText(),t=e.trim();t&&this.emitDrive({type:"follow_up",text:this.expandImagePlaceholders(e)})&&(this.editor.addToHistory(t),this.editor.setText(""),this.clearPastedImages())}async handleDequeue(){const e=this.capabilities.refusal("dequeue");if(e!==void 0){this.notify(e);return}const t=this.hooks.onRequest;if(t===void 0){this.notify("Restoring queued messages isn't available in this viewer");return}let o;try{o=await t({type:"dequeue"})}catch(s){this.notify(`Could not restore queued messages: ${s instanceof Error?s.message:String(s)}`);return}if(o.kind!=="dequeue"){this.notify("Unexpected reply restoring queued messages");return}const i=[...o.steering,...o.followUp];if(i.length===0){this.notify("No queued messages to restore");return}this.editor.setText([i.join(`
2
2
 
3
3
  `),this.editor.getText()].filter(s=>s.trim()).join(`
4
4
 
5
- `)),this.tui.requestRender(),this.notify(`Restored ${i.length} queued message${i.length>1?"s":""} to editor`)}emitDrive(e){try{const t=Buffer.byteLength(w(e));if(t>R)return this.notify(`Message too large to send (${Math.round(t/(1024*1024))} MiB) \u2014 shorten the text or remove an attached image`),!1}catch{return this.notify("Message could not be encoded"),!1}return this.emitCommand(e)}async handlePaste(){try{const e=await T();if(!e){this.notify("No image in the clipboard");return}if(!e.image){this.notify(e.note??"Image not pasted");return}this.attachImage(I(e.image),e.note)}catch{this.notify("Could not read the clipboard image")}}attachImage(e,t){const o=++this.pasteSeq;this.pastedImages.set(o,e);const i=this.editor.getText();this.editor.insertTextAtCursor(`${i&&!/\s$/.test(i)?" ":""}[Image #${o}] `),this.notify(t?`Image #${o} attached (${t})`:`Image #${o} attached`),this.tui.requestRender()}expandImagePlaceholders(e){return e.replace(/\[Image #(\d+)\]/g,(t,o)=>this.pastedImages.get(Number(o))??t)}clearPastedImages(){this.pastedImages.clear(),this.pasteSeq=0}async openExternalEditor(){const e=M();if(e===null){this.notify(A);return}const t=e.command,o=this.editor,i=P(y(),`crtr-attach-editor-${Date.now()}.pi.md`);try{g(i,o.getExpandedText?.()??this.editor.getText(),"utf-8"),this.tui.stop();const[s,...n]=t.split(" ");process.stdout.write(`Launching external editor: ${t}
5
+ `)),this.tui.requestRender(),this.notify(`Restored ${i.length} queued message${i.length>1?"s":""} to editor`)}emitDrive(e){try{const t=Buffer.byteLength(x(e));if(t>R)return this.notify(`Message too large to send (${Math.round(t/(1024*1024))} MiB) \u2014 shorten the text or remove an attached image`),!1}catch{return this.notify("Message could not be encoded"),!1}return this.emitCommand(e)}async handlePaste(){try{const e=await T();if(!e){this.notify("No image in the clipboard");return}if(!e.image){this.notify(e.note??"Image not pasted");return}this.attachImage(I(e.image),e.note)}catch{this.notify("Could not read the clipboard image")}}attachImage(e,t){const o=++this.pasteSeq;this.pastedImages.set(o,e);const i=this.editor.getText();this.editor.insertTextAtCursor(`${i&&!/\s$/.test(i)?" ":""}[Image #${o}] `),this.notify(t?`Image #${o} attached (${t})`:`Image #${o} attached`),this.tui.requestRender()}expandImagePlaceholders(e){return e.replace(/\[Image #(\d+)\]/g,(t,o)=>this.pastedImages.get(Number(o))??t)}clearPastedImages(){this.pastedImages.clear(),this.pasteSeq=0}async openExternalEditor(){const e=A();if(e===null){this.notify(M);return}const t=e.command,o=this.editor,i=P(y(),`crtr-attach-editor-${Date.now()}.pi.md`);try{g(i,o.getExpandedText?.()??this.editor.getText(),"utf-8"),this.tui.stop();const[s,...r]=t.split(" ");process.stdout.write(`Launching external editor: ${t}
6
6
  The viewer resumes when it exits.
7
- `),E(e);const a=await new Promise(h=>{const c=u(s,[...n,i],{stdio:"inherit",shell:process.platform==="win32"});c.on("error",()=>h(null)),c.on("close",l=>h(l))});a===null&&e.source==="fallback"&&this.notify(`Could not launch ${t} \u2014 set $EDITOR to an editor you have installed`),a===0&&this.editor.setText(f(i,"utf-8").replace(/\n$/,""))}catch(s){this.notify(`External editor failed: ${s instanceof Error?s.message:String(s)}`)}finally{try{k(i)}catch{}this.tui.start(),this.tui.requestRender(!0)}}notify(e){this.hooks.onNotice?.(e)}}export{z as InputController};
7
+ `),E(e);const a=await new Promise(d=>{const c=u(s,[...r,i],{stdio:"inherit",shell:process.platform==="win32"});c.on("error",()=>d(null)),c.on("close",l=>d(l))});a===null&&e.source==="fallback"&&this.notify(`Could not launch ${t} \u2014 set $EDITOR to an editor you have installed`),a===0&&this.editor.setText(f(i,"utf-8").replace(/\n$/,""))}catch(s){this.notify(`External editor failed: ${s instanceof Error?s.message:String(s)}`)}finally{try{k(i)}catch{}this.tui.start(),this.tui.requestRender(!0)}}notify(e){this.hooks.onNotice?.(e)}}export{z as InputController};
@@ -78,6 +78,11 @@ export declare class ChatView {
78
78
  /** Standalone ChatViews render activity inline; the attach viewer supplies
79
79
  * `onActivityChange`, so its transcript excludes this container. */
80
80
  private readonly statusContainer;
81
+ /** Messages the person sent from this viewer that the engine has not echoed
82
+ * back yet, drawn gray below history. Outside `historyContainer`, so a
83
+ * welcome snapshot rebuild never drops them. */
84
+ private readonly pendingContainer;
85
+ private readonly pendingSends;
81
86
  /** Optional banner, above history and status in the viewport's flat source. */
82
87
  private readonly bannerContainer;
83
88
  private readonly transcript;
@@ -88,6 +93,7 @@ export declare class ChatView {
88
93
  /** Inline page blocks placed in this transcript, by page id — one block per
89
94
  * page, so a `--replace` revision refreshes the block already on screen. */
90
95
  private readonly pageBlocks;
96
+ private pageRefresh;
91
97
  /** The person's inbox answers in the live region, each with its leading
92
98
  * spacer. Summary mode hides them with the settled pages they answer. */
93
99
  private readonly inboxAnswers;
@@ -255,9 +261,8 @@ export declare class ChatView {
255
261
  * flight is never hidden or minimized. Only a settled group with a broker-known
256
262
  * summary collapses; incomplete/failed generation leaves its folded call lines. */
257
263
  private applyToolDisplay;
258
- /** Replies only and Messages + summaries hide the back-and-forth with the
259
- * person: every settled inline page and every answer they gave from their
260
- * inbox. A page still awaiting an answer stays on screen. */
264
+ /** Replies only and Messages + summaries hide every answer the person gave
265
+ * from their inbox. A settled inline page hides in every mode. */
261
266
  private hidesInboxExchange;
262
267
  private applyInboxExchangeDisplay;
263
268
  /** A broker rewrite landed for one turn. Stored first: it may precede the
@@ -360,15 +365,22 @@ export declare class ChatView {
360
365
  * viewer's existing low-rate chrome poll, and cheap because it touches only
361
366
  * in-flight tools — usually one, never the transcript. */
362
367
  refreshInFlightTools(): void;
363
- /** Re-read every placed page through the daemon. Driven by the viewer's
364
- * ticket-activity watcher, so an answer, a cancellation, or a `--replace`
365
- * revision lands on the block already anchored in the transcript. */
368
+ /** Re-read every unsettled page through the daemon. Driven by the viewer's
369
+ * chrome poll, so an answer, a cancellation, or a `--replace` revision lands
370
+ * on the block already anchored in the transcript, from any machine. */
366
371
  refreshPageBlocks(): Promise<void>;
367
372
  private makeLoader;
368
373
  /** Let a self-updating history child invalidate only its own cached lines. */
369
374
  private componentTui;
370
375
  /** Complete and release the live bash component before ChatView gives up ownership. */
371
376
  private settleBashComponent;
377
+ /** Show a message the person just sent as pending: gray text, no background,
378
+ * until the engine echoes it as a user message. */
379
+ addPendingSend(text: string): void;
380
+ /** The engine echoed a user message: the matching pending send landed. */
381
+ private confirmPendingSend;
382
+ /** A snapshot rebuild: drop pending sends whose text the history now holds. */
383
+ private confirmPendingSendsIn;
372
384
  /** Swap the single active activity indicator (working/compaction/retry). */
373
385
  private setActivity;
374
386
  private showStatus;
@@ -1,5 +1,5 @@
1
- var N=Object.defineProperty;var l=(h,t)=>N(h,"name",{value:t,configurable:!0});import{Container as P,Loader as Y,Spacer as u,Text as x}from"@earendil-works/pi-tui";import{AssistantMessageComponent as z,BashExecutionComponent as _,BranchSummaryMessageComponent as K,CompactionSummaryMessageComponent as J,CustomMessageComponent as j,parseSkillBlock as X,SkillInvocationMessageComponent as Q,ToolExecutionComponent as Z,UserMessageComponent as M}from"@earendil-works/pi-coding-agent";import{attachMarkdownTheme as f}from"../config.js";import{ContextMessageComponent as H}from"./context-message.js";import{presentationFor as tt}from"./card-presentation.js";import{detectInlinePageResult as et,PageBlockComponent as st}from"./page-block.js";import{CRTR_OUTPUT_CUSTOM_TYPE as it,CrtrOutputMessageComponent as F,createCrtrBashToolDefinition as nt}from"./crtr-output.js";import{CRTR_CYCLE_DIVIDER_CUSTOM_TYPE as ot,endedByAbort as E}from"../../../core/runtime/session-cycles.js";import{isHumanWordsEntry as L,parseCard as rt}from"../../../shared/generated-context.js";import{assistantVisibleText as c,isGroupBoundaryKind as at,isTrueUserMessage as T}from"../../../shared/tool-groups.js";import{messageKey as S,normalizeTurnReplyRecord as ht,START_TURN_KEY as G,turnReplyText as W}from"../../../shared/turn-replies.js";import{isCycleDivider as lt}from"./condensed-history.js";import{transformDiagramFences as pt}from"./diagram.js";import{styleAttachAgentMarkdown as dt,styleAttachMarkdownSource as $,styleAttachMessageMarkdown as ct,styleAttachSummaryMarkdown as U}from"./markdown-source.js";import{createCrtrEditToolDefinition as ut}from"./edit-diff.js";import{GroupActivityRecorder as ft}from"./group-activity.js";import{GroupRecapComponent as mt}from"./group-recap.js";import{FoldedToolCallController as yt,bashCallBackgroundHintLines as gt,createCrtrPlainBashToolDefinition as Tt,createCrtrReadToolDefinition as Ct,createCrtrWriteToolDefinition as kt}from"./tool-calls.js";import{ringCompletionBell as bt}from"../chrome/completion-bell.js";import{extractFilePaths as xt}from"../../../core/human/visible-paths.js";import{extractDocRefs as wt}from"./doc-links.js";import{keepWhenCondensed as Rt,liveRegionStart as St}from"./condensed-history.js";import{ViewerAssistantMessageComponent as w}from"./assistant-message.js";import{CompositeViewportSource as Bt,MeasuredContainer as v}from"./measured-container.js";import{readConfig as B}from"../../../core/config.js";import{DEFAULT_CONDENSED_HISTORY as At,DEFAULT_LIVE_CYCLES as Mt,DEFAULT_VERBOSITY as Et,VERBOSITY_LEVELS as m}from"../../../types.js";import{applySnapshot as Gt,applyToolGroupSummary as vt,applyWorkingActivity as Ot,bashEnd as It,bashOutput as Dt,bashStart as Pt,initialConvState as _t,reduce as jt}from"../../conversation/projection.js";const V=l(h=>`\x1B[2m${h}\x1B[22m`,"defaultDimStyle"),O=50;function Ht(){try{return B("user").live_cycles}catch{return Mt}}l(Ht,"readLiveCycles");function Ft(){try{return B("user").condensed_history}catch{return At}}l(Ft,"readCondensedHistory");function Lt(){try{return B("user").verbosity}catch{return Et}}l(Lt,"readVerbosity");function Wt(){try{return B("user").detailed_tool_recaps}catch{return!0}}l(Wt,"readDetailedToolRecaps");function $t(h){return typeof h=="object"&&h!==null&&"setExpanded"in h&&typeof h.setExpanded=="function"}l($t,"isExpandable");const Ut=/\x1b\[[0-9;]*m/g,Vt=/\x1b\[([0-9;]*)m/g;function qt(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(qt,"stripBackground");const Nt=/<from\b[^>]*>[\s\S]*?<\/from>/g;class I extends u{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 Yt extends P{static{l(this,"WorkingRow")}label=new x("",1,0);constructor(){super(),this.addChild(new u(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 A extends Z{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),...gt(this.foldController?.callComponent(),t)];const e=this.foldController?.callComponent();return e?e.render(t).filter(s=>s.replace(Ut,"").trim().length>0).map(s=>qt(s).trimEnd()):super.render(t)}}const zt=l(h=>`\x1B[31m${h}\x1B[39m`,"defaultErrorStyle"),Kt={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:V,faint:V,border:l(h=>h,"border"),surface:l(h=>h,"surface"),bold:l(h=>`\x1B[1m${h}\x1B[22m`,"bold"),error:zt,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 v;statusContainer=new v;bannerContainer;transcript;appendTarget=this.historyContainer;pageBlocks=new Map;inboxAnswers=new Set;inlinePageBlocks;pageOpenHint;backgroundBashHint;liveCycles;condensedHistory;cwd;showImages;imageWidthCells;hideThinking;hiddenThinkingLabel;level;detailedToolRecaps=Wt();groups=[];openGroup;turnReplies=new Map;turns=[];openReplyTurn;carriedTurn={key:G,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"?pt(t,s):t,(t,{messageType:e})=>e==="user"?$(t):dt(t)];streamingComponent;streamingToolSeparator;foldedToolSeparatorContents=new Map;pendingTools=new Map;bashComponent;activityLoader;projection=_t();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??Lt(),this.liveCycles=s.liveCycles??Ht(),this.condensedHistory=s.condensedHistory??Ft(),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??Kt,this.spinnerStyle=this.recapPalette.active,this.dimStyle=this.recapPalette.muted,this.errorStyle=this.recapPalette.error,s.banner&&s.banner.length>0){const i=new v;i.addChild(new u(1));for(const n of s.banner)i.addChild(new x(n,1,0));i.addChild(new u(1)),this.bannerContainer=i,this.container.addChild(i)}this.container.addChild(this.historyContainer),this.onActivityChange||this.container.addChild(this.statusContainer),this.transcript=new Bt([...this.bannerContainer?[this.bannerContainer]:[],this.historyContainer,...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=Gt(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(ht(t.turnReplies)))this.turnReplies.set(o,r);const s=new Map,i=this.projection.messages,n=i.length-1,a=St(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=c(r);p.trim()&&(this.lastAssistantText=p,this.pushTranscriptText(p));const d=o===n&&this.projection.isStreaming&&r.stopReason!=="aborted"&&r.stopReason!=="error",C=c(r).trim()!=="",q=this.assistantToolCalls(r),k=r.stopReason==="aborted"||r.stopReason==="error",b=E(r)?"Interrupted":r.errorMessage??"Error";if(k){for(const y of s.values()){const g={content:[{type:"text",text:b}],isError:!0};y.updateResult(g),this.registerCopyBlock(y,"tool",b),this.settleGroupTool(y,g,!0)}s.clear()}(C||k)&&this.closeOpenGroup();let R;d?(this.streamingComponent=new w(void 0,this.hideThinking,f(),this.hiddenThinkingLabel,this.markdownTransformers),this.appendAssistantPart(this.streamingComponent,!C),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingWasGroupMember=!C,this.streamingComponent.updateContent(r),this.registerCopyBlock(this.streamingComponent,"assistant",c(r)),R=this.streamingToolSeparator=this.appendAssistantSeparator(!C)):R=this.appendAssistantMessage(r,!C&&!k),R&&this.setAssistantSeparatorContent(R,r);for(const y of q){this.pushTranscriptValue(y.arguments);const g=this.appendToolComponent(y.name,y.id,y.arguments);r.stopReason==="aborted"||r.stopReason==="error"?(g.updateResult({content:[{type:"text",text:b}],isError:!0}),this.registerCopyBlock(g,"tool",b),this.settleGroupTool(g,{content:[{type:"text",text:b}],isError:!0},!0)):s.set(y.id,g)}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.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:G,prose:[],dividers:[]}];for(const o of t){const r=s.at(-1);if(T(o))s.push({key:S(o)??`local-${s.length}`,user:o,prose:[],dividers:[]});else if(lt(o))r.dividers.push(o);else if(o.role==="assistant"&&o.stopReason!=="aborted"&&o.stopReason!=="error"){const p=c(o).trim(),d=S(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,f(),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=Ot(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 A&&i.setMinimized(this.foldsSettledTools()&&!t.has(i)),$t(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,t&&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,f(),this.hiddenThinkingLabel,this.markdownTransformers),i=new Yt;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=c(t).trim(),i=S(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 A?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 z&&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=jt(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(),bt();break}case"agent_settled":{this.settleRun();break}case"message_start":{if(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=c(t.message).trim()!=="";e&&this.closeOpenGroup(),this.streamingComponent=new w(void 0,this.hideThinking,f(),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",c(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",c(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",c(t.message)),t.message.stopReason!=="aborted"&&t.message.stopReason!=="error"){const s=c(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=Pt(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=Dt(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=It(this.projection,t),this.settleBashComponent(t),this.tui.requestRender())}addMessageToChat(t){const e=rt(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(Nt,"").trim()===""&&e.senders.every(n=>n.entries.every(L)))){const n=tt(e.kind),a=new H(e,n,this.toolOutputExpanded(),this.dimStyle,o=>this.spinnerStyle(this.labelStyle(o)));at(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===it){this.appendGroupMember(new F(this.userMessageText(t),this.toolOutputExpanded(),this.crtrOutputTheme()));break}if(t.customType===ot){this.closeOpenGroup(),this.append(new u(1)),this.append(new x(this.dimStyle(`\u2500\u2500 ${this.userMessageText(t)} \u2500\u2500`),1,0)),this.append(new u(1));break}const s=new j(ct(t),void 0,f());s.setExpanded(this.toolOutputExpanded()),this.appendGroupMember(s)}break}case"compactionSummary":{this.closeOpenGroup(),this.append(new u(1));const s=new J(U(t),f());s.setExpanded(this.toolOutputExpanded()),this.append(s);break}case"branchSummary":{this.closeOpenGroup(),this.append(new u(1));const s=new K(U(t),f());s.setExpanded(this.toolOutputExpanded()),this.append(s),this.registerCopyBlock(s,"assistant",t.summary);break}case"user":{if(T(t)&&this.closeOpenGroup(),T(t)&&this.consolidatingHere()){!this.openReplyTurn&&this.carriedTurn.prose.length>0&&this.currentTurn(),this.outsideTurns++;try{this.appendUserMessage(t)}finally{this.outsideTurns--}this.beginTurn(S(t)??`local-${this.turns.length}`);break}this.appendUserMessage(t);break}case"assistant":{const s=c(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 u(1),!T(t));const s=X(e);if(s){const i=new Q({...s,content:$(s.content)},f());if(i.setExpanded(this.toolOutputExpanded()),this.appendUserPart(i,!T(t)),this.registerCopyBlock(i,"user",e),s.userMessage){const n=new M(s.userMessage,f(),void 0,this.markdownTransformers);this.appendUserPart(n,!T(t)),this.registerCopyBlock(n,"user",s.userMessage)}}else{const i=new M(e,f(),void 0,this.markdownTransformers);this.appendUserPart(i,!T(t)),this.registerCopyBlock(i,"user",e)}}appendAssistantMessage(t,e=!1){const s=new w(void 0,this.hideThinking,f(),this.hiddenThinkingLabel,this.markdownTransformers),i=E(t)?{...t,stopReason:"aborted",errorMessage:"Interrupted"}:t;s.updateContent(i),this.appendAssistantPart(s,e),this.registerCopyBlock(s,"assistant",c(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 u(1);this.append(i),e&&this.trackInboxAnswer(i)}const s=new M(t,f(),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 mt,e={members:[],recap:t,activity:new ft(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&&c(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=vt(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 A&&!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=nt(s,i);r===void 0?a=Tt(this.cwd,i,this.backgroundBashHint):a=r.definition}else if(t==="edit"){const r=ut(this.cwd,i);a=r.definition,n=r.observeResult}else t==="read"?a=Ct(this.cwd,i):t==="write"&&(a=kt(this.cwd,i));let o;return o=new A(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:G,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=et(t);if(e===void 0||this.pageBlocks.has(e.pageId))return;const s=new st(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,this.hidesInboxExchange()&&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(){const t=[...this.pageBlocks.values()];(await Promise.all(t.map(async s=>{const i=await s.refresh();return i&&(this.historyContainer.setHidden(s,this.hidesInboxExchange()&&s.settled),this.historyContainer.markDirty(s)),i}))).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}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 u(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 u(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 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(`
2
2
 
3
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
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(wt(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=xt([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};
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};
@@ -40,6 +40,8 @@ export interface InputWiringHooks {
40
40
  setChipColor: (color: string | null) => void;
41
41
  /** A prompt or steer was accepted from the editor. */
42
42
  onPromptSent: () => void;
43
+ /** A new message left the editor; show it pending until echoed. */
44
+ onMessageSent: (text: string) => void;
43
45
  /** Per-user completion frecency store, shared with the editor inventory. */
44
46
  frecency: FrecencyStore;
45
47
  }
@@ -1 +1 @@
1
- var D=Object.defineProperty;var e=(n,a)=>D(n,"name",{value:a,configurable:!0});import{InputController as b}from"../input/controller.js";import{createViewerCapabilities as I}from"../input/capabilities.js";import{VERBOSITY_LABELS as C}from"../../../core/user-settings.js";import{VERBOSITY_LEVELS as m}from"../../../types.js";import{cliClient as T}from"../../../commands/api-client.js";import{buildLoginPicker as v,buildLogoutPicker as E}from"../overlays/auth.js";import{defaultAgentDir as w}from"../config.js";function q(n,a){return I({nodeId:n.nodeId,profileId:n.meta.profile_id??void 0,remote:n.remote,role:n.role,isBrokerOffline:a})}e(q,"createViewerCapabilitiesForInput");function u({level:n}){return`Verbosity: ${C[n]} (${m.indexOf(n)+1}/${m.length})`}e(u,"verbosityName");function L(n){return n.atEnd?`${u(n)} \u2014 Ctrl+O again goes back to ${C[m[0]]}`:`${u(n)} \u2014 Ctrl+O shows more`}e(L,"moreDetailNotice");function M(n){return n.atEnd?`${u(n)}, the most collapsed level \u2014 Ctrl+O shows more`:`${u(n)} \u2014 Ctrl+O shows more`}e(M,"lessDetailNotice");function A(n,a,d,o){const{nodeId:y,socket:l,tui:s,editor:p,containers:g}=n,{setNotice:i}=o,f=e(()=>l.send({type:"reload_auth"}),"reloadAuth"),P=d.permits("auth")?{openLoginPicker:e(()=>{const t=o.agentDir()??w();c.openAuthPicker(()=>v(s,t,f,r=>i(r)))},"openLoginPicker"),openLogoutPicker:e(()=>{const t=o.agentDir()??w();c.openAuthPicker(()=>E(t,f,r=>i(r)))},"openLogoutPicker")}:{},c=new b(s,p,a,{onCommand:e(t=>l.send(t),"onCommand"),onDialogResponse:e(t=>l.send(t),"onDialogResponse"),onNotice:e(t=>i(t),"onNotice"),onGraph:o.toggleGraph,onInbox:o.toggleInbox,onHelp:o.toggleHelp,onNodeMetadata:o.openNodeMetadata,onQuit:o.quit,onCopy:e(()=>o.copyTarget("last-assistant"),"onCopy"),onCopyTarget:o.copyTarget,onToggleMouse:e(()=>{const t=o.toggleMouse();i(t?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"onToggleMouse"),onColor:o.setChipColor,onPromptSent:o.onPromptSent,frecency:o.frecency,knownRefNames:e(()=>p.getResolvedRefNames(),"knownRefNames"),onMoreDetail:e(()=>i(L(o.moreDetail())),"onMoreDetail"),onLessDetail:e(()=>i(M(o.lessDetail())),"onLessDetail"),onToggleThinking:e(()=>i(o.toggleThinking()?"Thinking blocks: hidden":"Thinking blocks: visible"),"onToggleThinking"),onRequest:e(t=>{const r=d.refusal("engine-drive");return r===void 0?l.request(t):Promise.reject(new Error(r))},"onRequest"),onMountPicker:e(t=>{g.pickerPanel.addChild(t),s.requestRender()},"onMountPicker"),onUnmountPicker:e(()=>{g.pickerPanel.clear(),s.requestRender()},"onUnmountPicker"),isDormant:o.isDormant,onDormantSubmit:d.permits("wake-dormant")?t=>{(async()=>{try{const r=await T().sendMessage(y,{body:t,from:"human"});i(r.revived?"\u21BB waking node\u2026":"\u2709 delivered \u2014 node reads on next wake")}catch(r){i(`Couldn't wake node: ${r instanceof Error?r.message:String(r)}`)}})()}:void 0,...P},d);return c}e(A,"createInputController");export{A as createInputController,q as createViewerCapabilitiesForInput,M as lessDetailNotice,L as moreDetailNotice};
1
+ var D=Object.defineProperty;var e=(n,a)=>D(n,"name",{value:a,configurable:!0});import{InputController as b}from"../input/controller.js";import{createViewerCapabilities as I}from"../input/capabilities.js";import{VERBOSITY_LABELS as C}from"../../../core/user-settings.js";import{VERBOSITY_LEVELS as m}from"../../../types.js";import{cliClient as M}from"../../../commands/api-client.js";import{buildLoginPicker as T,buildLogoutPicker as v}from"../overlays/auth.js";import{defaultAgentDir as w}from"../config.js";function q(n,a){return I({nodeId:n.nodeId,profileId:n.meta.profile_id??void 0,remote:n.remote,role:n.role,isBrokerOffline:a})}e(q,"createViewerCapabilitiesForInput");function u({level:n}){return`Verbosity: ${C[n]} (${m.indexOf(n)+1}/${m.length})`}e(u,"verbosityName");function S(n){return n.atEnd?`${u(n)} \u2014 Ctrl+O again goes back to ${C[m[0]]}`:`${u(n)} \u2014 Ctrl+O shows more`}e(S,"moreDetailNotice");function E(n){return n.atEnd?`${u(n)}, the most collapsed level \u2014 Ctrl+O shows more`:`${u(n)} \u2014 Ctrl+O shows more`}e(E,"lessDetailNotice");function A(n,a,d,t){const{nodeId:y,socket:s,tui:l,editor:p,containers:g}=n,{setNotice:i}=t,f=e(()=>s.send({type:"reload_auth"}),"reloadAuth"),P=d.permits("auth")?{openLoginPicker:e(()=>{const o=t.agentDir()??w();c.openAuthPicker(()=>T(l,o,f,r=>i(r)))},"openLoginPicker"),openLogoutPicker:e(()=>{const o=t.agentDir()??w();c.openAuthPicker(()=>v(o,f,r=>i(r)))},"openLogoutPicker")}:{},c=new b(l,p,a,{onCommand:e(o=>s.send(o),"onCommand"),onDialogResponse:e(o=>s.send(o),"onDialogResponse"),onNotice:e(o=>i(o),"onNotice"),onGraph:t.toggleGraph,onInbox:t.toggleInbox,onHelp:t.toggleHelp,onNodeMetadata:t.openNodeMetadata,onQuit:t.quit,onCopy:e(()=>t.copyTarget("last-assistant"),"onCopy"),onCopyTarget:t.copyTarget,onToggleMouse:e(()=>{const o=t.toggleMouse();i(o?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"onToggleMouse"),onColor:t.setChipColor,onPromptSent:t.onPromptSent,onMessageSent:t.onMessageSent,frecency:t.frecency,knownRefNames:e(()=>p.getResolvedRefNames(),"knownRefNames"),onMoreDetail:e(()=>i(S(t.moreDetail())),"onMoreDetail"),onLessDetail:e(()=>i(E(t.lessDetail())),"onLessDetail"),onToggleThinking:e(()=>i(t.toggleThinking()?"Thinking blocks: hidden":"Thinking blocks: visible"),"onToggleThinking"),onRequest:e(o=>{const r=d.refusal("engine-drive");return r===void 0?s.request(o):Promise.reject(new Error(r))},"onRequest"),onMountPicker:e(o=>{g.pickerPanel.addChild(o),l.requestRender()},"onMountPicker"),onUnmountPicker:e(()=>{g.pickerPanel.clear(),l.requestRender()},"onUnmountPicker"),isDormant:t.isDormant,onDormantSubmit:d.permits("wake-dormant")?o=>{(async()=>{try{const r=await M().sendMessage(y,{body:o,from:"human"});i(r.revived?"\u21BB waking node\u2026":"\u2709 delivered \u2014 node reads on next wake")}catch(r){i(`Couldn't wake node: ${r instanceof Error?r.message:String(r)}`)}})()}:void 0,...P},d);return c}e(A,"createInputController");export{A as createInputController,q as createViewerCapabilitiesForInput,E as lessDetailNotice,S as moreDetailNotice};