@north-light/cli 0.3.654 → 0.3.655
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.
- package/dist/clients/attach/config.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +2 -3
- package/dist/clients/attach/input/controller.js +3 -3
- package/dist/clients/attach/render/chat-view.d.ts +41 -37
- package/dist/clients/attach/render/chat-view.js +3 -3
- package/dist/clients/attach/session/bindings.d.ts +1 -1
- package/dist/clients/attach/session/bindings.js +1 -1
- package/dist/clients/attach/session/input-wiring.d.ts +9 -9
- package/dist/clients/attach/session/input-wiring.js +1 -1
- package/dist/clients/attach/slash/dispatch.d.ts +6 -8
- package/dist/clients/attach/slash/dispatch.js +2 -2
- package/dist/clients/attach/viewer.js +514 -514
- package/dist/commands/node/create.js +1 -1
- package/dist/commands/sys/panels/prefs-panel.js +1 -1
- package/dist/core/config.js +1 -1
- package/dist/core/graph/documents.js +13 -11
- package/dist/core/graph/edges.js +4 -3
- package/dist/core/graph/exposures.js +7 -4
- package/dist/core/graph/kinds/document.js +4 -4
- package/dist/core/graph/kinds/dto.d.ts +2 -0
- package/dist/core/graph/kinds/dto.js +1 -1
- package/dist/core/graph/names.d.ts +4 -0
- package/dist/core/graph/names.js +9 -8
- package/dist/core/graph/rules.d.ts +2 -0
- package/dist/core/graph/rules.js +3 -3
- package/dist/core/keybindings/catalog.d.ts +3 -3
- package/dist/core/keybindings/catalog.js +1 -1
- package/dist/core/runtime/broker/tool-groups.js +1 -1
- package/dist/core/runtime/broker/turn-replies.d.ts +1 -4
- package/dist/core/runtime/broker/turn-replies.js +1 -1
- package/dist/core/runtime/broker-protocol.d.ts +2 -2
- package/dist/core/runtime/tmux-bindings.js +3 -3
- package/dist/core/substrate/delivery/corpus.d.ts +3 -0
- package/dist/core/substrate/delivery/corpus.js +2 -3
- package/dist/core/substrate/delivery/render-event.js +4 -4
- package/dist/core/user-settings.d.ts +13 -35
- package/dist/core/user-settings.js +1 -1
- package/dist/types.d.ts +13 -15
- package/dist/types.js +1 -1
- package/docs/cli/the-viewer.md +16 -2
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
var y=Object.defineProperty;var t=(e,o)=>y(e,"name",{value:o,configurable:!0});import{readFileSync as
|
|
1
|
+
var y=Object.defineProperty;var t=(e,o)=>y(e,"name",{value:o,configurable:!0});import{readFileSync as l}from"node:fs";import{createRequire as b}from"node:module";import{piAgentDir as h}from"../../core/runtime/package-health.js";import{join as s}from"node:path";import{pathToFileURL as x}from"node:url";import{KeybindingsManager as K,TUI_KEYBINDINGS as w,setKeybindings as k}from"@earendil-works/pi-tui";import{getMarkdownTheme as p,getSelectListTheme as E}from"@earendil-works/pi-coding-agent";import{initCrtrTheme as T}from"../../core/runtime/crtr-theme.js";import{surfaceBgAnsi as B}from"../../core/runtime/surface-bg.js";function i(){return h()}t(i,"defaultAgentDir");const I={"app.interrupt":{defaultKeys:"escape",description:"Cancel or abort"},"app.clear":{defaultKeys:"ctrl+c",description:"Clear editor"},"app.exit":{defaultKeys:"ctrl+d",description:"Exit when editor is empty"},"app.suspend":{defaultKeys:"ctrl+z",description:"Suspend to background"},"app.thinking.cycle":{defaultKeys:"shift+tab",description:"Cycle thinking level"},"app.model.cycleForward":{defaultKeys:"ctrl+p",description:"Cycle to next model"},"app.model.cycleBackward":{defaultKeys:"shift+ctrl+p",description:"Cycle to previous model"},"app.model.select":{defaultKeys:"ctrl+l",description:"Open model selector"},"app.tools.expand":{defaultKeys:"ctrl+o",description:"Show more detail (verbosity level)"},"app.thinking.toggle":{defaultKeys:"ctrl+t",description:"Toggle thinking blocks"},"app.editor.external":{defaultKeys:"ctrl+g",description:"Open external editor"},"app.message.followUp":{defaultKeys:[],description:"Queue follow-up message"},"app.message.dequeue":{defaultKeys:"alt+up",description:"Restore queued messages"},"app.clipboard.pasteImage":{defaultKeys:["alt+v","ctrl+v"],description:"Paste image from clipboard"},"app.session.new":{defaultKeys:[],description:"Start a new session"},"app.session.tree":{defaultKeys:[],description:"Open session tree"},"app.session.fork":{defaultKeys:[],description:"Fork current session"},"app.session.resume":{defaultKeys:[],description:"Resume a session"}};function R(e=i()){try{const o=JSON.parse(l(s(e,"keybindings.json"),"utf8")),n=o&&typeof o=="object"&&"keybindings"in o?o.keybindings:o;return!n||typeof n!="object"?void 0:n}catch{return}}t(R,"loadUserKeybindings");const $={"tui.input.newLine":{defaultKeys:["shift+enter","alt+enter"],description:"Insert new line"}};function H(e=i()){const o={...w,...I,...$},n=new K(o,R(e));return k(n),n}t(H,"createKeybindingsManager");let a;function u(){return a||(a=(async()=>{try{const e=import.meta.resolve("@earendil-works/pi-coding-agent"),o=b(e).resolve("@earendil-works/pi-tui");return await import(x(o).href)}catch{return}})()),a}t(u,"editorPiTui");async function J(e){(await u())?.setKeybindings(e)}t(J,"mirrorKeybindingsToEditor");async function V(e){(await u())?.setKittyProtocolActive(e)}t(V,"mirrorKittyProtocolToEditor");let c;function z(){return c||(c=(async()=>{try{const e=import.meta.resolve("@earendil-works/pi-coding-agent");return await(await import(new URL("./utils/tools-manager.js",e).href)).ensureTool("fd",!0)??null}catch{return null}})()),c}t(z,"resolveFdPath");function v(e){const o=[s(e?.cwd??process.cwd(),".pi","settings.json"),s(e?.agentDir??i(),"settings.json")];for(const n of o)try{const r=JSON.parse(l(n,"utf8"));if(r&&typeof r=="object"&&typeof r.theme=="string")return r.theme}catch{}}t(v,"loadThemeName");function Q(e){T(v(e),e?.agentDir??i())}t(Q,"applyTheme");const C=t(e=>`\x1B[2m${e}\x1B[22m`,"FAINT"),D=t(e=>`\x1B[31m${e}\x1B[39m`,"RED"),N=t(e=>`\x1B[33m${e}\x1B[39m`,"YELLOW"),f=t(e=>`\x1B[32m${e}\x1B[39m`,"GREEN"),P=t(e=>`\x1B[92m${e}\x1B[39m`,"BRIGHT_GREEN"),O=t(e=>`\x1B[91m${e}\x1B[39m`,"DIFF_REMOVED"),d="\x1B[48;2;36;36;36m";function A(e,o){return`${d}${e(o).replace(/\x1b\[0m/g,`\x1B[0m${d}`)}`}t(A,"codeSurfaceFragment");function W(){const e=p(),o=t((n,r)=>A(n,r),"paint");return{...e,codeBlockIndent:`${d}${e.codeBlockIndent??" "}`,codeBlock:t(n=>o(e.codeBlock,n),"codeBlock"),codeBlockBorder:t(n=>o(e.codeBlockBorder,n),"codeBlockBorder"),highlightCode:e.highlightCode?(n,r)=>e.highlightCode(n,r).map(m=>o(g=>g,m)):void 0}}t(W,"attachMarkdownTheme");function X(){const e=p(),o=E(),n=B();return{accent:e.heading,active:e.code,info:e.link,muted:o.description,faint:C,border:e.hr,bold:e.bold,error:D,warning:N,diffAdded:f,diffRemoved:O,bashMode:f,bashModeAlt:P,surface:t(r=>`${n}${r.replace(/\x1b\[0m/g,`\x1B[0m${n}`)}\x1B[49m`,"surface")}}t(X,"attachPalette");export{Q as applyTheme,W as attachMarkdownTheme,X as attachPalette,H as createKeybindingsManager,i as defaultAgentDir,v as loadThemeName,R as loadUserKeybindings,J as mirrorKeybindingsToEditor,V as mirrorKittyProtocolToEditor,z as resolveFdPath};
|
|
@@ -19,9 +19,8 @@ export interface InputControllerHooks {
|
|
|
19
19
|
onToggleMouse?: () => void;
|
|
20
20
|
onColor?: (color: string | null) => void;
|
|
21
21
|
onNodeMetadata?: () => void;
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
onShowWorking?: () => void;
|
|
22
|
+
onMoreDetail?: () => void;
|
|
23
|
+
onLessDetail?: () => void;
|
|
25
24
|
onToggleThinking?: () => void;
|
|
26
25
|
onRequest?: (frame: ReadOpRequest) => Promise<BrokerDataFrame>;
|
|
27
26
|
onMountPicker?: (component: Component) => void;
|
|
@@ -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
|
|
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(`
|
|
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>
|
|
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}
|
|
6
6
|
The viewer resumes when it exits.
|
|
7
|
-
`),
|
|
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};
|
|
@@ -5,13 +5,13 @@ import { type AttachPalette } from '../config.js';
|
|
|
5
5
|
import { type ToolGroupSummary } from '../../../shared/tool-groups.js';
|
|
6
6
|
import { type TurnReply } from '../../../shared/turn-replies.js';
|
|
7
7
|
import { type ViewportSource } from './measured-container.js';
|
|
8
|
-
import type { CondensedHistoryMode } from '../../../types.js';
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
8
|
+
import type { CondensedHistoryMode, Verbosity } from '../../../types.js';
|
|
9
|
+
/** The viewer's level after Ctrl+O or Ctrl+Shift+O. `atEnd` is true when the
|
|
10
|
+
* level is the last one in that direction: Full for more detail (the next
|
|
11
|
+
* press wraps to Replies only), Replies only for less detail (presses stop). */
|
|
12
|
+
export type VerbosityChange = {
|
|
13
|
+
level: Verbosity;
|
|
14
|
+
atEnd: boolean;
|
|
15
15
|
};
|
|
16
16
|
export type CopyBlockKind = 'user' | 'assistant' | 'tool' | 'condensed';
|
|
17
17
|
/** One copyable unit, bound to the exact top-level component the viewport addresses. */
|
|
@@ -32,8 +32,8 @@ export interface ChatViewOptions {
|
|
|
32
32
|
hideThinking?: boolean;
|
|
33
33
|
/** Label shown for a hidden thinking block. Default "Thinking...". */
|
|
34
34
|
hiddenThinkingLabel?: string;
|
|
35
|
-
/**
|
|
36
|
-
|
|
35
|
+
/** The level this viewer starts at. Absent → the user's `verbosity` setting. */
|
|
36
|
+
verbosity?: Verbosity;
|
|
37
37
|
/** Sink for footer/header-only events ChatView does not itself render
|
|
38
38
|
* (queue_update, session_info_changed, thinking_level_changed). The attach
|
|
39
39
|
* command wires a footer here; absent → these events are no-ops. */
|
|
@@ -103,23 +103,15 @@ export declare class ChatView {
|
|
|
103
103
|
private readonly imageWidthCells;
|
|
104
104
|
private hideThinking;
|
|
105
105
|
private readonly hiddenThinkingLabel;
|
|
106
|
-
/** Ctrl+O
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
* call line. Independent of `toolOutputExpanded` — it survives an expand/collapse
|
|
110
|
-
* and only ever applies to tool calls that are done. */
|
|
111
|
-
private foldSettledTools;
|
|
112
|
-
/** Summary mode only changes Ctrl+O when both persistent settings are on. */
|
|
113
|
-
private readonly summarizeToolCalls;
|
|
106
|
+
/** The viewer's verbosity level (Ctrl+O more, Ctrl+Shift+O less). Every
|
|
107
|
+
* display choice below derives from it. */
|
|
108
|
+
private level;
|
|
114
109
|
private readonly detailedToolRecaps;
|
|
115
|
-
private showGroupSummaries;
|
|
116
110
|
/** Groups exist only while building/rendering the full-fidelity live region. */
|
|
117
111
|
private readonly groups;
|
|
118
112
|
private openGroup;
|
|
119
|
-
/**
|
|
120
|
-
|
|
121
|
-
/** `/show-working`: expand every turn's working. Viewer-local, not persisted. */
|
|
122
|
-
private showWorking;
|
|
113
|
+
/** Turns are always built in the live region, so the viewer can move into
|
|
114
|
+
* and out of Replies only at any time; other levels hide their reply rows. */
|
|
123
115
|
private readonly turnReplies;
|
|
124
116
|
private readonly turns;
|
|
125
117
|
private openReplyTurn;
|
|
@@ -131,6 +123,10 @@ export declare class ChatView {
|
|
|
131
123
|
private outsideTurns;
|
|
132
124
|
/** Components the turn fold currently hides. */
|
|
133
125
|
private turnHidden;
|
|
126
|
+
/** Both forms of condensed history, when it exists; one is hidden per level. */
|
|
127
|
+
private condensedBlocks;
|
|
128
|
+
/** The newest turn's reply text, which `/copy` takes at Replies only. */
|
|
129
|
+
private lastReplyText;
|
|
134
130
|
private readonly groupSummaries;
|
|
135
131
|
/** Node id → display name for every node spawned in this transcript, so a
|
|
136
132
|
* later group's finish notice can name the child rather than its id. */
|
|
@@ -221,7 +217,7 @@ export declare class ChatView {
|
|
|
221
217
|
* supersedes this generation.
|
|
222
218
|
*/
|
|
223
219
|
private buildCondensedBlock;
|
|
224
|
-
/**
|
|
220
|
+
/** Replies only in condensed history: each finished turn renders as
|
|
225
221
|
* the person's message, its reply, then any cycle dividers it spanned. A turn
|
|
226
222
|
* still open at the end continues into the live region, so it is carried there
|
|
227
223
|
* instead of rendered. Returns false when a newer welcome superseded the build. */
|
|
@@ -242,25 +238,28 @@ export declare class ChatView {
|
|
|
242
238
|
* timers die with the process, but if T7 reuses a ChatView across reconnects in
|
|
243
239
|
* one process it should call this on detach to avoid a leaked interval. */
|
|
244
240
|
dispose(): void;
|
|
245
|
-
/** Ctrl+O
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
241
|
+
/** Ctrl+O: one level more detail; from Full it wraps to Replies only. */
|
|
242
|
+
moreDetail(): VerbosityChange;
|
|
243
|
+
/** Ctrl+Shift+O: one level less detail; stops at Replies only. */
|
|
244
|
+
lessDetail(): VerbosityChange;
|
|
245
|
+
private setLevel;
|
|
246
|
+
/** Replies only: one rewritten reply per message the person sends. */
|
|
247
|
+
private repliesOnly;
|
|
248
|
+
/** Every settled tool call folds to its single call line (Replies only through Tool calls). */
|
|
249
|
+
private foldsSettledTools;
|
|
250
|
+
/** A settled tool group collapses onto its broker summary (Replies only and Messages + summaries). */
|
|
251
|
+
private showsGroupSummaries;
|
|
252
|
+
/** pi's tool-output expansion, untruncated at Full only. */
|
|
253
|
+
private toolOutputExpanded;
|
|
251
254
|
/** Push both display settings onto every rendered component. A tool call still in
|
|
252
255
|
* flight is never hidden or minimized. Only a settled group with a broker-known
|
|
253
256
|
* summary collapses; incomplete/failed generation leaves its folded call lines. */
|
|
254
257
|
private applyToolDisplay;
|
|
255
|
-
/**
|
|
256
|
-
* inline page and every answer they gave from their
|
|
257
|
-
* awaiting an answer stays on screen. */
|
|
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. */
|
|
258
261
|
private hidesInboxExchange;
|
|
259
262
|
private applyInboxExchangeDisplay;
|
|
260
|
-
/** `/show-working` (Alt+C → z → w): expand or fold the working behind every
|
|
261
|
-
* consolidated reply. Returns the new state, or null when the
|
|
262
|
-
* `consolidate_replies` experiment is off for this attach. */
|
|
263
|
-
toggleShowWorking(): boolean | null;
|
|
264
263
|
/** A broker rewrite landed for one turn. Stored first: it may precede the
|
|
265
264
|
* turn's events, and snapshot rebuilds defer it through the writer gate. */
|
|
266
265
|
applyTurnReply(key: string, reply: TurnReply): void;
|
|
@@ -269,7 +268,8 @@ export declare class ChatView {
|
|
|
269
268
|
* below its working row. */
|
|
270
269
|
private turnFoldedComponents;
|
|
271
270
|
private beginTurn;
|
|
272
|
-
/** Whether an append in progress lands in the live region
|
|
271
|
+
/** Whether an append in progress lands in the live region, where every
|
|
272
|
+
* component joins a turn. */
|
|
273
273
|
private consolidatingHere;
|
|
274
274
|
private currentTurn;
|
|
275
275
|
/** A settled assistant message with prose becomes part of its turn's reply. */
|
|
@@ -397,6 +397,10 @@ export declare class ChatView {
|
|
|
397
397
|
getLastToolOutputText(): string | undefined;
|
|
398
398
|
/** Every copyable block's text, oldest → newest, joined by blank lines. */
|
|
399
399
|
getTranscriptPlainText(): string;
|
|
400
|
+
/** Blocks built for the other side of the Replies-only boundary: the turn
|
|
401
|
+
* replies and reply-form condensed history at every other level, and the
|
|
402
|
+
* message-form condensed history at Replies only. */
|
|
403
|
+
private inactiveFormBlocks;
|
|
400
404
|
private registerCopyBlock;
|
|
401
405
|
private unregisterCopyBlock;
|
|
402
406
|
private appendCondensedBlock;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var N=Object.defineProperty;var l=(h,t)=>N(h,"name",{value:t,configurable:!0});import{Container as v,Loader as V,Spacer as u,Text as w}from"@earendil-works/pi-tui";import{AssistantMessageComponent as z,BashExecutionComponent as P,BranchSummaryMessageComponent as Y,CompactionSummaryMessageComponent as K,CustomMessageComponent as _,parseSkillBlock as J,SkillInvocationMessageComponent as X,ToolExecutionComponent as Q,UserMessageComponent as B}from"@earendil-works/pi-coding-agent";import{attachMarkdownTheme as f}from"../config.js";import{ContextMessageComponent as j}from"./context-message.js";import{presentationFor as Z}from"./card-presentation.js";import{detectInlinePageResult as tt,PageBlockComponent as et}from"./page-block.js";import{CRTR_OUTPUT_CUSTOM_TYPE as st,CrtrOutputMessageComponent as F,createCrtrBashToolDefinition as it}from"./crtr-output.js";import{CRTR_CYCLE_DIVIDER_CUSTOM_TYPE as nt,endedByAbort as G}from"../../../core/runtime/session-cycles.js";import{isHumanWordsEntry as H,parseCard as ot}from"../../../shared/generated-context.js";import{assistantVisibleText as c,isGroupBoundaryKind as rt,isTrueUserMessage as y}from"../../../shared/tool-groups.js";import{messageKey as R,normalizeTurnReplyRecord as at,START_TURN_KEY as M,turnReplyText as W}from"../../../shared/turn-replies.js";import{isCycleDivider as ht}from"./condensed-history.js";import{transformDiagramFences as lt}from"./diagram.js";import{styleAttachAgentMarkdown as pt,styleAttachMarkdownSource as L,styleAttachMessageMarkdown as dt,styleAttachSummaryMarkdown as $}from"./markdown-source.js";import{createCrtrEditToolDefinition as ct}from"./edit-diff.js";import{GroupActivityRecorder as ut}from"./group-activity.js";import{GroupRecapComponent as ft}from"./group-recap.js";import{FoldedToolCallController as mt,bashCallBackgroundHintLines as gt,createCrtrPlainBashToolDefinition as yt,createCrtrReadToolDefinition as Tt,createCrtrWriteToolDefinition as Ct}from"./tool-calls.js";import{ringCompletionBell as kt}from"../chrome/completion-bell.js";import{extractFilePaths as bt}from"../../../core/human/visible-paths.js";import{extractDocRefs as wt}from"./doc-links.js";import{keepWhenCondensed as xt,liveRegionStart as St}from"./condensed-history.js";import{ViewerAssistantMessageComponent as x}from"./assistant-message.js";import{CompositeViewportSource as Rt,MeasuredContainer as E}from"./measured-container.js";import{readConfig as T,updateRawConfigAtomically as At}from"../../../core/config.js";import{DEFAULT_CONDENSED_HISTORY as Bt,DEFAULT_LIVE_CYCLES as Gt}from"../../../types.js";import{applySnapshot as Mt,applyToolGroupSummary as Et,applyWorkingActivity as It,bashEnd as Dt,bashOutput as Ot,bashStart as vt,initialConvState as Pt,reduce as _t}from"../../conversation/projection.js";const q=l(h=>`\x1B[2m${h}\x1B[22m`,"defaultDimStyle"),I=50;function jt(){try{return T("user").live_cycles}catch{return Gt}}l(jt,"readLiveCycles");function Ft(){try{return T("user").condensed_history}catch{return Bt}}l(Ft,"readCondensedHistory");function Ht(){try{return T("user").fold_finished_tools}catch{return!1}}l(Ht,"readFoldFinishedTools");function Wt(){try{return T("user").summarize_tool_calls}catch{return!1}}l(Wt,"readSummarizeToolCalls");function Lt(){try{return T("user").detailed_tool_recaps}catch{return!0}}l(Lt,"readDetailedToolRecaps");function $t(){try{return T("user").consolidate_replies}catch{return!1}}l($t,"readConsolidateReplies");async function qt(h){try{await At("user",t=>({...t,fold_finished_tools:h}))}catch{}}l(qt,"persistFoldFinishedTools");function Ut(h){return typeof h=="object"&&h!==null&&"setExpanded"in h&&typeof h.setExpanded=="function"}l(Ut,"isExpandable");const Nt=/\x1b\[[0-9;]*m/g,Vt=/\x1b\[([0-9;]*)m/g;function zt(h){return h.replace(Vt,(t,e)=>{const s=e.split(";"),i=[];for(let n=0;n<s.length;n++){const r=Number(s[n]===""?0:s[n]);if(r===38||r===48||r===58){const o=Number(s[n+1]),a=n+(o===5?2:o===2?4:1);r!==48&&i.push(...s.slice(n,a+1)),n=a;continue}r>=40&&r<=47||r>=100&&r<=107||i.push(String(r))}return i.length>0?`\x1B[${i.join(";")}m`:""})}l(zt,"stripBackground");const Yt=/<from\b[^>]*>[\s\S]*?<\/from>/g;class D 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 Kt extends v{static{l(this,"WorkingRow")}label=new w("",1,0);constructor(){super(),this.addChild(new u(1)),this.addChild(this.label)}setLabel(t){this.label.setText(t)}}function O(h,t,e){return`${h} ${h===1?t:e}`}l(O,"plural");class A extends Q{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(Nt,"").trim().length>0).map(s=>zt(s).trimEnd()):super.render(t)}}const Jt=l(h=>`\x1B[31m${h}\x1B[39m`,"defaultErrorStyle"),Xt={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:q,faint:q,border:l(h=>h,"border"),surface:l(h=>h,"surface"),bold:l(h=>`\x1B[1m${h}\x1B[22m`,"bold"),error:Jt,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 Ae{static{l(this,"ChatView")}tui;container;historyContainer=new E;statusContainer=new E;bannerContainer;transcript;appendTarget=this.historyContainer;pageBlocks=new Map;inboxAnswers=new Set;inlinePageBlocks;pageOpenHint;backgroundBashHint;liveCycles;condensedHistory;cwd;showImages;imageWidthCells;hideThinking;hiddenThinkingLabel;toolOutputExpanded;foldSettledTools=Ht();summarizeToolCalls=Wt();detailedToolRecaps=Lt();showGroupSummaries=this.summarizeToolCalls&&this.foldSettledTools;groups=[];openGroup;consolidateReplies=$t();showWorking=!1;turnReplies=new Map;turns=[];openReplyTurn;carriedTurn={key:M,prose:[]};outsideTurns=0;turnHidden=new Set;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"?lt(t,s):t,(t,{messageType:e})=>e==="user"?L(t):pt(t)];streamingComponent;streamingToolSeparator;foldedToolSeparatorContents=new Map;pendingTools=new Map;bashComponent;activityLoader;projection=Pt();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.toolOutputExpanded=s.toolOutputExpanded??!1,this.liveCycles=s.liveCycles??jt(),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??Xt,this.spinnerStyle=this.recapPalette.active,this.dimStyle=this.recapPalette.muted,this.errorStyle=this.recapPalette.error,s.banner&&s.banner.length>0){const i=new E;i.addChild(new u(1));for(const n of s.banner)i.addChild(new w(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 Rt([...this.bannerContainer?[this.bannerContainer]:[],this.historyContainer,...this.onActivityChange?[]:[this.statusContainer]])}transcriptSource(){return this.transcript}async applySnapshot(t){const e=++this.snapshotGeneration;if(this.applyingSnapshot=!0,this.deferredFrames.length=0,this.resetChat(),this.projection=Mt(t,this.projection),this.workingActivity=this.projection.workingActivity,this.runActive=this.projection.isStreaming,this.seedToolGroupSummaries(this.projection.toolGroupSummaryDetails),this.turnReplies.clear(),this.consolidateReplies)for(const[o,a]of Object.entries(at(t.turnReplies)))this.turnReplies.set(o,a);const s=new Map,i=this.projection.messages,n=i.length-1,r=St(i,this.liveCycles);if(r>0){const o=await this.buildCondensedBlock(i.slice(0,r),e);if(e!==this.snapshotGeneration)return;o&&this.appendCondensedBlock(o)}for(let o=r;o<i.length;o++){if(!this.projection.isStreaming&&o>r&&(o-r)%I===0&&(await new Promise(p=>setImmediate(p)),e!==this.snapshotGeneration))return;const a=i[o];if(a.role==="assistant"){const p=c(a);p.trim()&&(this.lastAssistantText=p,this.pushTranscriptText(p));const d=o===n&&this.projection.isStreaming&&a.stopReason!=="aborted"&&a.stopReason!=="error",C=c(a).trim()!=="",U=this.assistantToolCalls(a),k=a.stopReason==="aborted"||a.stopReason==="error",b=G(a)?"Interrupted":a.errorMessage??"Error";if(k){for(const m of s.values()){const g={content:[{type:"text",text:b}],isError:!0};m.updateResult(g),this.registerCopyBlock(m,"tool",b),this.settleGroupTool(m,g,!0)}s.clear()}(C||k)&&this.closeOpenGroup();let S;d?(this.streamingComponent=new x(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(a),this.registerCopyBlock(this.streamingComponent,"assistant",c(a)),S=this.streamingToolSeparator=this.appendAssistantSeparator(!C)):S=this.appendAssistantMessage(a,!C&&!k),S&&this.setAssistantSeparatorContent(S,a);for(const m of U){this.pushTranscriptValue(m.arguments);const g=this.appendToolComponent(m.name,m.id,m.arguments);a.stopReason==="aborted"||a.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(m.id,g)}k&&this.closeOpenGroup(),!d&&!k&&this.recordTurnProse(a,!1)}else if(a.role==="toolResult"){this.pushTranscriptText(this.userMessageText(a));const p=s.get(a.toolCallId);p&&(p.updateResult(a),this.registerCopyBlock(p,"tool",this.toolResultText(a)),this.historyContainer.markDirty(p),this.settleGroupTool(p,a,a.isError===!0),s.delete(a.toolCallId),this.maybeAppendPageBlock(a))}else this.addMessageToChat(a)}for(const[o,a]of s)this.pendingTools.set(o,a);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){const s=new v,i=this.appendTarget,n=[];this.appendTarget=s,this.condensedCopyBlocks.set(s,n);try{if(this.consolidateReplies)return await this.buildCondensedTurns(t,e)&&s.children.length>0?{component:s,copyBlocks:n}:void 0;let r=0;for(const o of t)if(xt(o,this.condensedHistory)){if(r>0&&r%I===0&&(await new Promise(a=>setImmediate(a)),e!==this.snapshotGeneration))return;r++,this.pushTranscriptText(this.userMessageText(o)),this.addMessageToChat(o)}}finally{this.appendTarget=i,this.condensedCopyBlocks.delete(s)}return s.children.length>0?{component:s,copyBlocks:n}:void 0}async buildCondensedTurns(t,e){const s=[{key:M,prose:[],dividers:[]}];for(const o of t){const a=s.at(-1);if(y(o))s.push({key:R(o)??`local-${s.length}`,user:o,prose:[],dividers:[]});else if(ht(o))a.dividers.push(o);else if(o.role==="assistant"&&o.stopReason!=="aborted"&&o.stopReason!=="error"){const p=c(o).trim(),d=R(o);p!==""&&d!==void 0&&a.prose.push({key:d,text:p})}}const i=s.pop();let n=0;const r=l(async(o,a)=>{if(n>0&&n%I===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=a?W(o.prose,this.turnReplies.get(o.key)):"";if(p!==""){const d=new x(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 r(o,!0))return!1;return await r(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()}toggleToolsExpanded(){let t;return this.summarizeToolCalls&&this.foldSettledTools?(this.showGroupSummaries=!this.showGroupSummaries,this.toolOutputExpanded=!this.showGroupSummaries,t={kind:"summaries",shown:this.showGroupSummaries}):(this.toolOutputExpanded=!this.toolOutputExpanded,t={kind:"output",expanded:this.toolOutputExpanded}),this.applyToolDisplay(),t}toggleFoldSettledTools(){return this.foldSettledTools=!this.foldSettledTools,qt(this.foldSettledTools),this.summarizeToolCalls&&this.foldSettledTools&&(this.showGroupSummaries=!0),this.applyToolDisplay(),this.foldSettledTools}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.foldSettledTools&&!t.has(i)),Ut(i)&&i.setExpanded(this.toolOutputExpanded);const e=this.turnFoldedComponents(t),s=new Set;for(const i of this.groups){this.applyGroupDisplay(i,e),s.add(i.recap);for(const n of i.members)s.add(n)}for(const i of this.turnHidden)!e.has(i)&&!s.has(i)&&this.historyContainer.setHidden(i,!1);for(const i of e)!s.has(i)&&!this.historyContainer.hiddenChildren.has(i)&&this.historyContainer.setHidden(i,!0);this.turnHidden=e,this.applyInboxExchangeDisplay(),this.updateFoldedToolSeparators(t),this.historyContainer.markDirty(),this.tui.requestRender()}hidesInboxExchange(){return this.showGroupSummaries&&this.foldSettledTools}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)}toggleShowWorking(){if(!this.consolidateReplies)return null;this.showWorking=!this.showWorking;for(const t of this.turns)this.refreshWorkingRow(t);return this.applyToolDisplay(),this.showWorking}applyTurnReply(t,e){if(!this.deferIfBuilding(()=>this.applyTurnReply(t,e))&&this.consolidateReplies){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.consolidateReplies||this.showWorking)return e;for(const s of this.turns){const i=s===this.openReplyTurn;for(const n of s.members)i&&(n===this.streamingComponent||n===this.streamingToolSeparator||n===this.bashComponent||t.has(n))||e.add(n)}return e}beginTurn(t,e=[]){const s=new x(void 0,this.hideThinking,f(),this.hiddenThinkingLabel,this.markdownTransformers),i=new Kt;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.consolidateReplies&&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=R(t);if(s===""||i===void 0)return;const n=this.currentTurn();n.prose.some(r=>r.key===i)||(n.prose.push({key:i,text:s}),e&&this.refreshTurn(n))}refreshTurn(t){const e=W(t.prose,this.turnReplies.get(t.key));t.reply.updateContent(this.replyMessage(e)),this.historyContainer.setHidden(t.reply,e===""),this.historyContainer.markDirty(t.reply),this.registerCopyBlock(t.reply,"assistant",e),e!==""&&t===this.turns.at(-1)&&(this.lastAssistantText=e),this.refreshWorkingRow(t)}refreshWorkingRow(t){let e=0,s=0;for(const a of t.members)a instanceof A?e++:(a instanceof j||a instanceof _||a instanceof F)&&s++;const i=t.prose.length,n=e>0||s>0||i>1,r=[i>0?O(i,"message","messages"):void 0,e>0?O(e,"tool call","tool calls"):void 0,s>0?O(s,"card","cards"):void 0].filter(a=>a!==void 0),o=this.runActive&&t===this.openReplyTurn;t.working.setLabel(this.dimStyle(`${this.showWorking?"\u25BE":"\u25B8"} ${o?"working \u2014 ":""}${r.join(" \xB7 ")}`)),this.historyContainer.setHidden(t.working,!n),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=_t(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(),kt();break}case"agent_settled":{this.settleRun();break}case"message_start":{if(t.message.role==="custom"||t.message.role==="user")this.addMessageToChat(t.message),this.consolidateReplies&&(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 x(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(G(t.message)&&(i="Interrupted",t.message.errorMessage=i,t.message.stopReason="aborted"),this.streamingComponent.updateContent(t.message),s==="aborted"||s==="error"){const n=i??"Error";for(const r of this.pendingTools.values())r.updateResult({content:[{type:"text",text:n}],isError:!0}),this.registerCopyBlock(r,"tool",n),this.settleGroupTool(r,{content:[{type:"text",text:n}],isError:!0},!0),this.historyContainer.markDirty(r);this.pendingTools.clear()}else for(const n of this.pendingTools.values())n.setArgsComplete(),this.historyContainer.markDirty(n);this.historyContainer.markDirty(this.streamingComponent),this.streamingComponent=void 0,this.streamingToolSeparator=void 0}e&&(this.closeOpenGroup(),this.applyToolDisplay()),this.consolidateReplies&&(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=vt(this.projection,t,e),this.closeOpenGroup(),this.settleBashComponent();let s;s=new P(t,this.componentTui(()=>s),e),this.bashComponent=s,this.append(s),this.tui.requestRender()}bashOutput(t){this.deferIfBuilding(()=>this.bashOutput(t))||(this.projection=Ot(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=ot(t);if(e!==null&&(t.role!=="custom"||t.display===!0)){this.pushTranscriptText(e.body);const s=e.senders.flatMap(n=>n.entries).filter(H).map(n=>n.body.trim()).filter(n=>n!=="");if(!(s.length>0&&e.body.replace(Yt,"").trim()===""&&e.senders.every(n=>n.entries.every(H)))){const n=Z(e.kind),r=new j(e,n,this.toolOutputExpanded,this.dimStyle,o=>this.spinnerStyle(this.labelStyle(o)));rt(e.kind)?(this.closeOpenGroup(),this.append(r)):this.appendGroupMember(r)?.activity.noteCard(e,n)}for(const n of s)this.appendHumanAnswer(n);return}switch(t.role){case"bashExecution":{this.closeOpenGroup(),this.pushTranscriptText(t.output??"");const s=new P(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===st){this.appendGroupMember(new F(this.userMessageText(t),this.toolOutputExpanded,this.crtrOutputTheme()));break}if(t.customType===nt){this.closeOpenGroup(),this.append(new u(1)),this.append(new w(this.dimStyle(`\u2500\u2500 ${this.userMessageText(t)} \u2500\u2500`),1,0)),this.append(new u(1));break}const s=new _(dt(t),void 0,f());s.setExpanded(this.toolOutputExpanded),this.appendGroupMember(s)}break}case"compactionSummary":{this.closeOpenGroup(),this.append(new u(1));const s=new K($(t),f());s.setExpanded(this.toolOutputExpanded),this.append(s);break}case"branchSummary":{this.closeOpenGroup(),this.append(new u(1));const s=new Y($(t),f());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=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),!y(t));const s=J(e);if(s){const i=new X({...s,content:L(s.content)},f());if(i.setExpanded(this.toolOutputExpanded),this.appendUserPart(i,!y(t)),this.registerCopyBlock(i,"user",e),s.userMessage){const n=new B(s.userMessage,f(),void 0,this.markdownTransformers);this.appendUserPart(n,!y(t)),this.registerCopyBlock(n,"user",s.userMessage)}}else{const i=new B(e,f(),void 0,this.markdownTransformers);this.appendUserPart(i,!y(t)),this.registerCopyBlock(i,"user",e)}}appendAssistantMessage(t,e=!1){const s=new x(void 0,this.hideThinking,f(),this.hiddenThinkingLabel,this.markdownTransformers),i=G(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 D;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 B(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 ft,e={members:[],recap:t,activity:new ut(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 D?this.historyContainer.children.at(-1):void 0;i&&this.historyContainer.removeChild(i);const n=this.ensureGroup();i&&(this.append(i),n?.members.push(i));const r=this.makeToolComponent(t,e,s);return r.activityCallId=e,this.appendGroupMember(r),this.registerCopyBlock(r,"tool",""),n&&(n.key??=e,n.toolCount++,n.inFlight.add(r),n.activity.noteCall(e,t,s)),r}noteGroupTool(t,e,s){if(t.activityCallId)for(const i of this.groups)i.members.includes(t)&&i.activity.noteCall(t.activityCallId,e,s)}settleGroupTool(t,e,s=!1){for(const i of this.groups)i.inFlight.delete(t),!(!t.activityCallId||!i.members.includes(t))&&(e===void 0?i.activity.resolveWithoutResult(t.activityCallId):i.activity.settle(t.activityCallId,e,s))}promoteStreamingAssistantToBoundary(t,e=!1){!this.streamingWasGroupMember||!e&&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=Et(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.foldSettledTools&&this.showGroupSummaries&&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 D))continue;const n=e[s+1];i.setFolded(this.foldSettledTools&&!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()!==""),r=i.some(o=>typeof o=="object"&&o!==null&&o.type==="thinking"&&typeof o.thinking=="string"&&o.thinking.trim()!=="");this.foldedToolSeparatorContents.set(t,{hasText:n,hasThinking:r}),t.setSeparatesToolGroup(n||!this.hideThinking&&r)}makeToolComponent(t,e,s){const i=new mt;let n,r;if(t==="bash"){const a=it(s,i);a===void 0?r=yt(this.cwd,i,this.backgroundBashHint):r=a.definition}else if(t==="edit"){const a=ct(this.cwd,i);r=a.definition,n=a.observeResult}else t==="read"?r=Tt(this.cwd,i):t==="write"&&(r=Ct(this.cwd,i));let o;return o=new A(t,e,s,{showImages:this.showImages,imageWidthCells:this.imageWidthCells},r,this.componentTui(()=>o),this.cwd),o.setToolView(r===void 0?void 0:i,n),o.setExpanded(this.toolOutputExpanded),o}append(t){if(this.outsideTurns===0&&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:M,prose:[]},this.turnHidden=new Set,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=tt(t);if(e===void 0||this.pageBlocks.has(e.pageId))return;const s=new et(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 V(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 w(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 w(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.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(){return this.copyBlockRecords.map(t=>t.text).filter(t=>t.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,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(`
|
|
2
2
|
|
|
3
|
-
`)}registerCopyBlock(t,e,s){const i=this.condensedCopyBlocks.get(this.appendTarget);if(i){const
|
|
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
|
|
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};
|
|
@@ -2,7 +2,7 @@ import { type AttachBindingId, type BindingId, type BindingResolution, type User
|
|
|
2
2
|
export type { AttachBindingId } from '../../../core/keybindings/index.js';
|
|
3
3
|
export type AttachBindings = BindingResolution<BindingId>;
|
|
4
4
|
export type AttachActions = Record<AttachBindingId, () => void>;
|
|
5
|
-
export declare const ATTACH_VIEWPORT_BINDINGS: readonly ["crtr.attach.scroll.up", "crtr.attach.scroll.down", "crtr.attach.scroll.page-up", "crtr.attach.scroll.page-down", "crtr.attach.scroll.live", "crtr.attach.mouse.toggle", "crtr.attach.copy.message"];
|
|
5
|
+
export declare const ATTACH_VIEWPORT_BINDINGS: readonly ["crtr.attach.scroll.up", "crtr.attach.scroll.down", "crtr.attach.scroll.page-up", "crtr.attach.scroll.page-down", "crtr.attach.scroll.live", "crtr.attach.mouse.toggle", "crtr.attach.copy.message", "crtr.attach.verbosity.less"];
|
|
6
6
|
export type AttachViewportBindingId = typeof ATTACH_VIEWPORT_BINDINGS[number];
|
|
7
7
|
export type AttachViewportActions = Record<AttachViewportBindingId, () => void>;
|
|
8
8
|
export { backgroundBashHint, inboxOpenHint } from '../../../core/keybindings/index.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var h=Object.defineProperty;var n=(t,r)=>h(t,"name",{value:r,configurable:!0});import{matchesKey as s}from"@earendil-works/pi-tui";import{ATTACH_CONTROL_BINDINGS as u,formatBinding as o,matchesPiTuiInput as f,normalizeShiftedMeta as d}from"../../../core/keybindings/index.js";const p=["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live","crtr.attach.mouse.toggle","crtr.attach.copy.message"];import{backgroundBashHint as
|
|
1
|
+
var h=Object.defineProperty;var n=(t,r)=>h(t,"name",{value:r,configurable:!0});import{matchesKey as s}from"@earendil-works/pi-tui";import{ATTACH_CONTROL_BINDINGS as u,formatBinding as o,matchesPiTuiInput as f,normalizeShiftedMeta as d}from"../../../core/keybindings/index.js";const p=["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live","crtr.attach.mouse.toggle","crtr.attach.copy.message","crtr.attach.verbosity.less"];import{backgroundBashHint as O,inboxOpenHint as S}from"../../../core/keybindings/index.js";function i(t,r,e){return f(t,r,d(e),(c,a)=>s(c,a))}n(i,"matchesAttachBinding");function l(t,r){r[t]()}n(l,"dispatchAttachAction");function A(t,r,e){for(const{actionId:c}of u)if(i(t,c,r))return l(c,e),!0;return!1}n(A,"dispatchAttachBinding");function B(t,r,e){for(const c of p)if(i(t,c,r))return e[c](),!0;return!1}n(B,"dispatchAttachViewportBinding");function I(t){for(const r of["crtr.attach.clear-or-detach","crtr.attach.detach"])if(t.gestures(r).length>0)return o(t,r)}n(I,"detachHint");function T(t){return t.gestures("crtr.attach.detach").length>0?o(t,"crtr.attach.detach"):void 0}n(T,"detachBindingHint");function H(t,r,e,c){const a=t();if(r(a.bindings),e())try{c(a.bindings,a.tmuxPassthrough)}catch{}return a}n(H,"refreshAttachBindingSnapshot");export{p as ATTACH_VIEWPORT_BINDINGS,O as backgroundBashHint,T as detachBindingHint,I as detachHint,l as dispatchAttachAction,A as dispatchAttachBinding,B as dispatchAttachViewportBinding,S as inboxOpenHint,i as matchesAttachBinding,H as refreshAttachBindingSnapshot};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { InputController } from '../input/controller.js';
|
|
2
2
|
import type { FrecencyStore } from '../input/completion-frecency.js';
|
|
3
3
|
import { type ViewerCapabilities } from '../input/capabilities.js';
|
|
4
|
-
import type {
|
|
4
|
+
import type { VerbosityChange } from '../render/chat-view.js';
|
|
5
5
|
import type { KeybindingsManager } from '@earendil-works/pi-tui';
|
|
6
6
|
import type { CopyTarget } from '../render/transcript-copy.js';
|
|
7
7
|
import type { AttachSession } from './context.js';
|
|
@@ -17,14 +17,10 @@ export interface InputWiringHooks {
|
|
|
17
17
|
isDormant: () => boolean;
|
|
18
18
|
/** Copy a viewer-local transcript target and surface its confirmation. */
|
|
19
19
|
copyTarget: (target: CopyTarget) => void;
|
|
20
|
-
/** Ctrl+O
|
|
21
|
-
|
|
22
|
-
/** `/
|
|
23
|
-
|
|
24
|
-
toggleFoldTools: () => boolean;
|
|
25
|
-
/** `/show-working` — expand or fold each consolidated reply's working; returns
|
|
26
|
-
* the new state, or null when consolidated replies are off. */
|
|
27
|
-
toggleShowWorking: () => boolean | null;
|
|
20
|
+
/** Ctrl+O and `/more-detail` — one verbosity level more detail. */
|
|
21
|
+
moreDetail: () => VerbosityChange;
|
|
22
|
+
/** Ctrl+Shift+O and `/less-detail` — one verbosity level less detail. */
|
|
23
|
+
lessDetail: () => VerbosityChange;
|
|
28
24
|
/** Ctrl+T — flip thinking-block visibility; returns true when now HIDDEN. */
|
|
29
25
|
toggleThinking: () => boolean;
|
|
30
26
|
/** `/graph` and the graph keybinding. */
|
|
@@ -49,5 +45,9 @@ export interface InputWiringHooks {
|
|
|
49
45
|
}
|
|
50
46
|
/** Construct the viewer's one capability authority. */
|
|
51
47
|
export declare function createViewerCapabilitiesForInput(ctx: Pick<AttachSession, 'nodeId' | 'remote' | 'role' | 'meta'>, isBrokerOffline: () => boolean): ViewerCapabilities;
|
|
48
|
+
/** The notice after Ctrl+O: the new level and what the next press does. */
|
|
49
|
+
export declare function moreDetailNotice(change: VerbosityChange): string;
|
|
50
|
+
/** The notice after Ctrl+Shift+O: the new level, and that Ctrl+O shows more. */
|
|
51
|
+
export declare function lessDetailNotice(change: VerbosityChange): string;
|
|
52
52
|
/** Build the viewer's InputController with every hook answered. */
|
|
53
53
|
export declare function createInputController(ctx: Pick<AttachSession, 'nodeId' | 'remote' | 'role' | 'meta' | 'socket' | 'tui' | 'editor' | 'containers'>, km: KeybindingsManager, capabilities: ViewerCapabilities, hooks: InputWiringHooks): InputController;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
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};
|
|
@@ -60,14 +60,12 @@ export interface SlashContext {
|
|
|
60
60
|
onColor?: (color: string | null) => void;
|
|
61
61
|
/** Open the focused node's progressively disclosed metadata dossier. */
|
|
62
62
|
onNodeMetadata?: () => void;
|
|
63
|
-
/** `/
|
|
64
|
-
* viewer-local render state (ChatView owns it),
|
|
65
|
-
* and for a remote attach. Absent → the command
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
* `/fold-tools`. Absent → the command notifies it is unwired. */
|
|
70
|
-
onShowWorking?: () => void;
|
|
63
|
+
/** `/more-detail` and `/less-detail` — move this viewer one verbosity level
|
|
64
|
+
* (Ctrl+O / Ctrl+Shift+O). Pure viewer-local render state (ChatView owns it),
|
|
65
|
+
* so it is safe for an observer and for a remote attach. Absent → the command
|
|
66
|
+
* notifies it is unwired. */
|
|
67
|
+
onMoreDetail?: () => void;
|
|
68
|
+
onLessDetail?: () => void;
|
|
71
69
|
/** Toggle mouse wheel scrolling reporting on/off. Viewer-local render state
|
|
72
70
|
* (MouseReporting owns the reporting state and the hardware toggle), so it is
|
|
73
71
|
* safe for an observer and for a remote attach. Absent → the command notifies
|