@north-light/cli 0.3.713 → 0.3.714

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/clients/attach/input/controller.d.ts +2 -0
  2. package/dist/clients/attach/input/controller.js +1 -1
  3. package/dist/clients/attach/input/local-files.d.ts +3 -1
  4. package/dist/clients/attach/input/local-files.js +8 -3
  5. package/dist/clients/attach/render/chat-view.d.ts +1 -1
  6. package/dist/clients/attach/render/chat-view.js +2 -2
  7. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  8. package/dist/clients/attach/session/input-wiring.js +1 -1
  9. package/dist/clients/attach/viewer.js +526 -521
  10. package/dist/commands/node/inspect.js +5 -5
  11. package/dist/core/broker-client/client.js +1 -1
  12. package/dist/core/canvas/canvas.js +1 -1
  13. package/dist/core/canvas/deliveries.js +10 -10
  14. package/dist/core/canvas/schema-pg/029-model-accounts-refresh-claim.sql +3 -0
  15. package/dist/core/canvas/schema-version.d.ts +1 -1
  16. package/dist/core/canvas/schema-version.js +1 -1
  17. package/dist/core/canvas/types.d.ts +1 -0
  18. package/dist/core/checkout-identities.js +1 -1
  19. package/dist/core/import/load/bind.d.ts +8 -0
  20. package/dist/core/import/load/bind.js +15 -15
  21. package/dist/core/import/load/prepare.d.ts +8 -1
  22. package/dist/core/import/load/prepare.js +9 -7
  23. package/dist/core/import/load/run.js +2 -2
  24. package/dist/core/llm/run.d.ts +1 -1
  25. package/dist/core/pool-credential-store.d.ts +5 -5
  26. package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
  27. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  28. package/dist/core/runtime/broker-wedge.d.ts +1 -2
  29. package/dist/core/runtime/broker-wedge.js +2 -2
  30. package/dist/core/subscription-state.d.ts +3 -3
  31. package/dist/core/subscription-state.js +1 -1
  32. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  33. package/dist/daemon/fleet.d.ts +1 -12
  34. package/dist/daemon/fleet.js +2 -2
  35. package/dist/daemon/machine-daemon.js +1 -1
  36. package/dist/daemon/machine-link/holder.js +1 -1
  37. package/dist/daemon/reconcilers/broker-supervision.js +3 -3
  38. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  39. package/package.json +3 -3
  40. package/packages/crouter-api/dist/clients/attach/input/controller.js +1 -1
  41. package/packages/crouter-api/dist/clients/attach/input/local-files.js +18 -2
  42. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -8
  43. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +1 -0
  44. package/packages/crouter-api/dist/clients/attach/viewer.js +15 -0
  45. package/packages/crouter-api/dist/commands/node/inspect.js +4 -3
  46. package/packages/crouter-api/dist/core/broker-client/client.js +1 -1
  47. package/packages/crouter-api/dist/core/canvas/canvas.js +1 -1
  48. package/packages/crouter-api/dist/core/canvas/deliveries.js +1 -1
  49. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  50. package/packages/crouter-api/dist/core/checkout-identities.js +1 -1
  51. package/packages/crouter-api/dist/core/import/load/prepare.js +21 -4
  52. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  53. package/packages/crouter-api/dist/core/pool-credential-store.js +5 -5
  54. package/packages/crouter-api/dist/core/runtime/broker-wedge.js +1 -3
  55. package/packages/crouter-api/dist/core/subscription-state.js +70 -81
  56. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +10 -11
  57. package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
  58. package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +4 -4
  59. package/packages/crouter-api/package.json +1 -1
  60. package/packages/crouter-identity/package.json +1 -1
  61. package/packages/crouter-plugin/package.json +3 -3
  62. package/runtime.lock.json +14 -14
  63. package/scripts/install-runtime.mjs +3 -2
  64. package/scripts/self-update.mjs +5 -1
@@ -23,6 +23,8 @@ export interface InputControllerHooks {
23
23
  onLessDetail?: () => void;
24
24
  onToggleThinking?: () => void;
25
25
  onRequest?: (frame: ReadOpRequest) => Promise<BrokerDataFrame>;
26
+ /** Resolves true once the broker has welcomed this viewer, false when it never will (parked node, detach, or a long wait). */
27
+ whenBrokerReady?: () => Promise<boolean>;
26
28
  onMountPicker?: (component: Component) => void;
27
29
  onUnmountPicker?: () => void;
28
30
  /** Viewer-local auth entry points. Their presence is an affordance, not
@@ -1,4 +1,4 @@
1
- var p=Object.defineProperty;var r=(l,e)=>p(l,"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 S}from"../../../core/runtime/broker-protocol.js";import{classifySubmit as x}from"../../conversation/submit.js";import{findRefTokens as w}from"../../../shared/inline-ref-grammar.js";import{dispatchSlashCommand as C,isSlashCommand as m}from"../slash/dispatch.js";import{viewerOperationForFrame as T}from"./capabilities.js";import{readClipboardImage as b,writeClipboardImageToFile as I}from"./clipboard-image.js";import{InputOverlayOwner as M}from"./overlay-owner.js";import{attachLocalFiles as D,hasLocalPaths as E}from"./local-files.js";import{announceFallbackEditor as q,NO_EDITOR_MESSAGE as A,resolveEditor as R}from"../../../core/editor-resolver.js";const B=500,F=v.maxLineBytes-4*1024*1024;class Y{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 M(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}openAuthPicker(e){return this.overlays.openAuthPicker(e)}send=r(e=>{this.emitCommand(e)},"send");refuseStarting(e){return this.hooks.isStarting?.()!==!0||e!==void 0&&(e.type==="prompt"||e.type==="follow_up")?!1:(this.notify("The node is starting \u2014 try again in a moment"),!0)}emitCommand(e){if(this.refuseStarting(e))return!1;const t=T(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){if(this.refuseStarting())return;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<B?(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 w(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||m(t)&&this.refuseStarting())return;if(m(t)&&C(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;const c=this.expandImagePlaceholders(i.text);a(c),this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),this.hooks.onMessageSent?.(c,!1),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),h=r(()=>{this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.clearPastedImages()},"sent"),d=r(a=>this.emitDrive(s==="steer"?{type:"steer",text:a}:{type:"prompt",text:a})?(s==="prompt"&&this.hooks.onMessageSent?.(a,!0),this.hooks.onPromptSent?.(),!0):!1,"deliver");this.sendMessage(n,e,i.kind!=="slash",h,d)}sendMessage(e,t,o,i,s){const n=this.hooks.onRequest;if(!o||n===void 0||!E(e)){if(!s(e))return;i(),this.editor.setText("");return}i(),this.editor.setText(""),this.tui.requestRender(),D(e,n).then(h=>{!s(h)&&this.editor.getText().trim()===""&&(this.editor.setText(t),this.tui.requestRender())})}handleFollowUp(){const e=this.editor.getText(),t=e.trim();if(!t)return;const o=this.expandImagePlaceholders(e),i=r(()=>{this.editor.addToHistory(t),this.clearPastedImages()},"sent");this.sendMessage(o,e,!0,i,s=>this.emitDrive({type:"follow_up",text:s}))}async handleDequeue(){if(this.refuseStarting())return;const e=this.capabilities.refusal("dequeue");if(e!==void 0){this.notify(e);return}const t=this.hooks.onRequest;if(t===void 0){this.notify("Restoring queued messages isn't available in this viewer");return}let o;try{o=await t({type:"dequeue"})}catch(s){this.notify(`Could not restore queued messages: ${s instanceof Error?s.message:String(s)}`);return}if(o.kind!=="dequeue"){this.notify("Unexpected reply restoring queued messages");return}const i=[...o.steering,...o.followUp];if(i.length===0){this.notify("No queued messages to restore");return}this.editor.setText([i.join(`
1
+ var p=Object.defineProperty;var r=(l,e)=>p(l,"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 S}from"../../../core/runtime/broker-protocol.js";import{classifySubmit as x}from"../../conversation/submit.js";import{findRefTokens as w}from"../../../shared/inline-ref-grammar.js";import{dispatchSlashCommand as C,isSlashCommand as m}from"../slash/dispatch.js";import{viewerOperationForFrame as T}from"./capabilities.js";import{readClipboardImage as b,writeClipboardImageToFile as I}from"./clipboard-image.js";import{InputOverlayOwner as M}from"./overlay-owner.js";import{attachLocalFiles as D,hasLocalPaths as E}from"./local-files.js";import{announceFallbackEditor as q,NO_EDITOR_MESSAGE as A,resolveEditor as R}from"../../../core/editor-resolver.js";const B=500,F=v.maxLineBytes-4*1024*1024;class Y{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 M(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}openAuthPicker(e){return this.overlays.openAuthPicker(e)}send=r(e=>{this.emitCommand(e)},"send");refuseStarting(e){return this.hooks.isStarting?.()!==!0||e!==void 0&&(e.type==="prompt"||e.type==="follow_up")?!1:(this.notify("The node is starting \u2014 try again in a moment"),!0)}emitCommand(e){if(this.refuseStarting(e))return!1;const t=T(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){if(this.refuseStarting())return;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<B?(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 w(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||m(t)&&this.refuseStarting())return;if(m(t)&&C(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;const c=this.expandImagePlaceholders(i.text);a(c),this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),this.hooks.onMessageSent?.(c,!1),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),h=r(()=>{this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.clearPastedImages()},"sent"),d=r(a=>this.emitDrive(s==="steer"?{type:"steer",text:a}:{type:"prompt",text:a})?(s==="prompt"&&this.hooks.onMessageSent?.(a,!0),this.hooks.onPromptSent?.(),!0):!1,"deliver");this.sendMessage(n,e,i.kind!=="slash",h,d)}sendMessage(e,t,o,i,s){const n=this.hooks.onRequest;if(!o||n===void 0||!E(e)){if(!s(e))return;i(),this.editor.setText("");return}i(),this.editor.setText(""),this.tui.requestRender(),D(e,n,this.hooks.whenBrokerReady).then(h=>{!s(h)&&this.editor.getText().trim()===""&&(this.editor.setText(t),this.tui.requestRender())})}handleFollowUp(){const e=this.editor.getText(),t=e.trim();if(!t)return;const o=this.expandImagePlaceholders(e),i=r(()=>{this.editor.addToHistory(t),this.clearPastedImages()},"sent");this.sendMessage(o,e,!0,i,s=>this.emitDrive({type:"follow_up",text:s}))}async handleDequeue(){if(this.refuseStarting())return;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
 
@@ -12,5 +12,7 @@ export interface PathMatch {
12
12
  export declare function findLocalPaths(text: string): PathMatch[];
13
13
  /** True when `text` names any path, so the caller can keep the plain synchronous send otherwise. */
14
14
  export declare function hasLocalPaths(text: string): boolean;
15
+ /** A user message's text without the trailing runtime note: the note is for the node, not the person. */
16
+ export declare function withoutRuntimeNote(text: string): string;
15
17
  /** Send each local file `text` names to the node and rewrite its path; append a `<runtime>` note for every file that could not go. */
16
- export declare function attachLocalFiles(text: string, request: (frame: ReadOpRequest) => Promise<BrokerDataFrame>): Promise<string>;
18
+ export declare function attachLocalFiles(text: string, request: (frame: ReadOpRequest) => Promise<BrokerDataFrame>, brokerReady?: () => Promise<boolean>): Promise<string>;
@@ -1,6 +1,11 @@
1
- var m=Object.defineProperty;var c=(n,o)=>m(n,"name",{value:o,configurable:!0});import{closeSync as g,constants as y,fstatSync as $,openSync as w,readFileSync as k}from"node:fs";import{homedir as L}from"node:os";const h=16*1024*1024,_=/(?<![\w/~.:-])(~?\/(?:\\ |[^\s'"`<>()[\]{}])+)/g;function p(n){const o=[];for(const i of n.matchAll(_)){const e=i[1].replace(/[.,;:!?]+$/,"");if(e==="/"||e==="~/"||e.startsWith("//"))continue;const r=e.replace(/\\ /g," "),l=r.startsWith("~/")?`${L()}${r.slice(1)}`:r;o.push({start:i.index,end:i.index+e.length,raw:e,path:l})}return o}c(p,"findLocalPaths");function x(n){let o;try{o=w(n,y.O_RDONLY)}catch{return{kind:"missing"}}try{const i=$(o);return i.isFile()?i.size>h?{kind:"too-large",size:i.size}:{kind:"file",bytes:k(o)}:{kind:"not-file"}}finally{g(o)}}c(x,"readLocal");function d(n){return`${(n/(1024*1024)).toFixed(1)} MiB`}c(d,"mib");function F(n){return p(n).length>0}c(F,"hasLocalPaths");async function z(n,o){const i=p(n);if(i.length===0)return n;const e=[],r=new Map,l=[];for(const t of i){const a=r.get(t.path);if(a!==void 0){l.push({match:t,to:a});continue}const f=x(t.path);if(f.kind!=="not-file"){if(f.kind==="missing"){e.push(`${t.raw} does not exist on the person's machine, so it was not sent to you.`);continue}if(f.kind==="too-large"){e.push(`file ${t.raw} is too large (${d(f.size)}; the limit is ${d(h)}), not uploaded.`);continue}try{const s=await o({type:"upload_file",source_path:t.path,data:f.bytes.toString("base64")});if(s.kind!=="upload_file")throw new Error("unexpected reply");r.set(t.path,s.path),l.push({match:t,to:s.path})}catch(s){e.push(`file ${t.raw} could not be uploaded (${s instanceof Error?s.message:String(s)}).`)}}}let u=n;for(const{match:t,to:a}of l.reverse())a===t.path&&t.raw===a||(u=`${u.slice(0,t.start)}${a}${u.slice(t.end)}`);return e.length===0?u:`${u}
1
+ var g=Object.defineProperty;var c=(n,o)=>g(n,"name",{value:o,configurable:!0});import{closeSync as y,constants as _,fstatSync as k,openSync as L,readFileSync as S}from"node:fs";import{homedir as E}from"node:os";const d=16*1024*1024,x=/(?<![\w/~.:-])(~?\/(?:\\ |[^\s'"`<>()[\]{}])+)/g;function p(n){const o=[];for(const r of n.matchAll(x)){const i=r[1].replace(/[.,;:!?]+$/,"");if(i==="/"||i==="~/"||i.startsWith("//"))continue;const s=i.replace(/\\ /g," "),f=s.startsWith("~/")?`${E()}${s.slice(1)}`:s;o.push({start:r.index,end:r.index+i.length,raw:i,path:f})}return o}c(p,"findLocalPaths");function m(n){let o;try{o=L(n,_.O_RDONLY)}catch{return{kind:"missing"}}try{const r=k(o);return r.isFile()?r.size>d?{kind:"too-large",size:r.size}:{kind:"file",bytes:S(o)}:{kind:"not-file"}}finally{y(o)}}c(m,"readLocal");function w(n){return`${(n/(1024*1024)).toFixed(1)} MiB`}c(w,"mib");function F(n){return p(n).length>0}c(F,"hasLocalPaths");const N=/\n\n<runtime>\n[\s\S]*?\n<\/runtime>\s*$/;function O(n){return n.replace(N,"")}c(O,"withoutRuntimeNote");async function v(n,o,r=()=>Promise.resolve(!0)){const i=p(n);if(i.length===0)return n;const s=[];if(!await r()){const t=[...new Set(i.filter(e=>m(e.path).kind==="file").map(e=>e.raw))];return t.length===0?n:`${n}
2
2
 
3
3
  <runtime>
4
- ${e.join(`
4
+ ${t.map(e=>`the node's runtime was not ready, so ${e} was not sent to you.`).join(`
5
5
  `)}
6
- </runtime>`}c(z,"attachLocalFiles");export{h as LOCAL_FILE_MAX_BYTES,z as attachLocalFiles,p as findLocalPaths,F as hasLocalPaths};
6
+ </runtime>`}const f=new Map,h=[];for(const t of i){const e=f.get(t.path);if(e!==void 0){h.push({match:t,to:e});continue}const l=m(t.path);if(l.kind!=="not-file"){if(l.kind==="missing"){s.push(`${t.raw} does not exist on the person's machine, so it was not sent to you.`);continue}if(l.kind==="too-large"){s.push(`file ${t.raw} is too large (${w(l.size)}; the limit is ${w(d)}), not uploaded.`);continue}try{const a=await o({type:"upload_file",source_path:t.path,data:l.bytes.toString("base64")});if(a.kind!=="upload_file")throw new Error("unexpected reply");f.set(t.path,a.path),h.push({match:t,to:a.path})}catch(a){const $=a instanceof Error?a.message:String(a);s.push(a?.code==="unknown_frame"?`this node's runtime is too old to receive files from the viewer; ${t.raw} was not sent.`:`file ${t.raw} could not be uploaded (${$}).`)}}}let u=n;for(const{match:t,to:e}of h.reverse())e===t.path&&t.raw===e||(u=`${u.slice(0,t.start)}${e}${u.slice(t.end)}`);return s.length===0?u:`${u}
7
+
8
+ <runtime>
9
+ ${s.join(`
10
+ `)}
11
+ </runtime>`}c(v,"attachLocalFiles");export{d as LOCAL_FILE_MAX_BYTES,v as attachLocalFiles,p as findLocalPaths,F as hasLocalPaths,O as withoutRuntimeNote};
@@ -380,6 +380,6 @@ export declare class ChatView {
380
380
  private toolResultText;
381
381
  private pushTranscriptText;
382
382
  private pushTranscriptValue;
383
- /** Concatenate the text blocks of a user message (string or content array). */
383
+ /** Concatenate the text blocks of a user message (string or content array), without the viewer's trailing runtime note. */
384
384
  private userMessageText;
385
385
  }
@@ -1,3 +1,3 @@
1
- var W=Object.defineProperty;var h=(a,t)=>W(a,"name",{value:t,configurable:!0});import{Container as U,Loader as N,Markdown as $,Spacer as p,Text as y}from"@earendil-works/pi-tui";import{AssistantMessageComponent as q,BashExecutionComponent as G,BranchSummaryMessageComponent as V,CompactionSummaryMessageComponent as z,CustomMessageComponent as E,parseSkillBlock as Y,SkillInvocationMessageComponent as K,ToolExecutionComponent as J,UserMessageComponent as R}from"@earendil-works/pi-coding-agent";import{attachMarkdownTheme as d}from"../config.js";import{ContextMessageComponent as O}from"./context-message.js";import{presentationFor as X}from"./card-presentation.js";import{detectInlinePageResult as Q,PageBlockComponent as Z}from"./page-block.js";import{CRTR_OUTPUT_CUSTOM_TYPE as tt,CrtrOutputMessageComponent as I,createCrtrBashToolDefinition as et}from"./crtr-output.js";import{endedByAbort as A}from"../../../core/runtime/session-cycles.js";import{isHumanWordsEntry as P,parseCard as st}from"../../../shared/generated-context.js";import{assistantVisibleText as c,isGroupBoundaryKind as it,isTrueUserMessage as g}from"../../../shared/tool-groups.js";import{messageKey as D,normalizeTurnReplyRecord as nt,START_TURN_KEY as rt,turnReplyText as ot}from"../../../shared/turn-replies.js";import{transformDiagramFences as at}from"./diagram.js";import{styleAttachAgentMarkdown as ht,styleAttachMarkdownSource as j,styleAttachMessageMarkdown as lt,styleAttachSummaryMarkdown as F}from"./markdown-source.js";import{createCrtrEditToolDefinition as pt}from"./edit-diff.js";import{GroupActivityRecorder as dt}from"./group-activity.js";import{GroupRecapComponent as ct}from"./group-recap.js";import{FoldedToolCallController as ut,bashCallBackgroundHintLines as ft,createCrtrPlainBashToolDefinition as mt,createCrtrReadToolDefinition as gt,createCrtrWriteToolDefinition as yt}from"./tool-calls.js";import{ringCompletionBell as Ct}from"../chrome/completion-bell.js";import{extractFilePaths as Tt}from"../../../core/human/visible-paths.js";import{extractDocRefs as kt}from"./doc-links.js";import{ViewerAssistantMessageComponent as x}from"./assistant-message.js";import{CompositeViewportSource as bt,MeasuredContainer as w}from"./measured-container.js";import{readConfig as _}from"../../../core/config.js";import{DEFAULT_VERBOSITY as xt,VERBOSITY_LEVELS as u}from"../../../types.js";import{applySnapshot as wt,applyToolGroupSummary as St,applyWorkingActivity as Rt,bashEnd as At,bashOutput as Bt,bashStart as Mt,initialConvState as vt,reduce as Gt}from"../../conversation/projection.js";const H=h(a=>`\x1B[2m${a}\x1B[22m`,"defaultDimStyle"),Et=50;function Ot(){try{return _("user").verbosity}catch{return xt}}h(Ot,"readVerbosity");function It(){try{return _("user").detailed_tool_recaps}catch{return!0}}h(It,"readDetailedToolRecaps");function Pt(a){return typeof a=="object"&&a!==null&&"setExpanded"in a&&typeof a.setExpanded=="function"}h(Pt,"isExpandable");const Dt=/\x1b\[[0-9;]*m/g,jt=/\x1b\[([0-9;]*)m/g;function Ft(a){return a.replace(jt,(t,e)=>{const s=e.split(";"),i=[];for(let n=0;n<s.length;n++){const o=Number(s[n]===""?0:s[n]);if(o===38||o===48||o===58){const r=Number(s[n+1]),l=n+(r===5?2:r===2?4:1);o!==48&&i.push(...s.slice(n,l+1)),n=l;continue}o>=40&&o<=47||o>=100&&o<=107||i.push(String(o))}return i.length>0?`\x1B[${i.join(";")}m`:""})}h(Ft,"stripBackground");const _t=/<from\b[^>]*>[\s\S]*?<\/from>/g;class B extends p{static{h(this,"FoldedToolSeparator")}folded=!1;separatesToolGroup=!1;setFolded(t){this.folded=t,this.refresh()}setSeparatesToolGroup(t){this.separatesToolGroup=t,this.refresh()}refresh(){this.setLines(this.folded&&this.separatesToolGroup?1:0)}}class Ht extends U{static{h(this,"WorkingRow")}label=new y("",1,0);constructor(){super(),this.addChild(new p(1)),this.addChild(this.label)}setLabel(t){this.label.setText(t)}}function M(a,t,e){return`${a} ${a===1?t:e}`}h(M,"plural");class S extends J{static{h(this,"MinimizableToolComponent")}activityCallId;minimized=!1;expandedState=!1;foldController;resultObserver;setToolView(t,e){this.foldController=t,this.resultObserver=e}updateResult(...t){this.resultObserver?.(t[0],t[1]??!1);const e=t[0],s=e.content;Array.isArray(s)&&/^elapsed \d+(?:h \d+)?m \d+s(?:\n|$)/.test(s.at(-1)?.text??"")?super.updateResult({...e,content:s.slice(0,-1)},t[1]):super.updateResult(...t)}setExpanded(t){this.expandedState=t,super.setExpanded(t)}setMinimized(t){!this.foldController||this.minimized===t||(this.minimized=t,this.foldController.setFolded(t),super.setExpanded(this.expandedState))}render(t){if(!this.minimized)return[...super.render(t),...ft(this.foldController?.callComponent(),t)];const e=this.foldController?.callComponent();return e?e.render(t).filter(s=>s.replace(Dt,"").trim().length>0).map(s=>Ft(s).trimEnd()):super.render(t)}}const Lt=h(a=>`\x1B[31m${a}\x1B[39m`,"defaultErrorStyle"),Wt={accent:h(a=>`\x1B[33m${a}\x1B[39m`,"accent"),active:h(a=>`\x1B[36m${a}\x1B[39m`,"active"),info:h(a=>`\x1B[34m${a}\x1B[39m`,"info"),muted:H,faint:H,border:h(a=>a,"border"),surface:h(a=>a,"surface"),bold:h(a=>`\x1B[1m${a}\x1B[22m`,"bold"),error:Lt,warning:h(a=>`\x1B[33m${a}\x1B[39m`,"warning"),diffAdded:h(a=>`\x1B[32m${a}\x1B[39m`,"diffAdded"),diffRemoved:h(a=>`\x1B[91m${a}\x1B[39m`,"diffRemoved"),bashMode:h(a=>`\x1B[32m${a}\x1B[39m`,"bashMode"),bashModeAlt:h(a=>`\x1B[92m${a}\x1B[39m`,"bashModeAlt")};class fe{static{h(this,"ChatView")}tui;container;historyContainer=new w;statusContainer=new w;pendingContainer=new w;pendingSends=[];pendingUndelivered=!1;undeliveredNote;bannerContainer;setBannerHint(t){const e=this.bannerContainer;e!==void 0&&(e.removeChild(e.children[e.children.length-1]),e.addChild(new y(t,1,0)),e.addChild(new p(1)))}transcript;pageBlocks=new Map;pageRefresh=!1;inboxAnswers=new Set;inlinePageBlocks;pageOpenHint;backgroundBashHint;cwd;showImages;imageWidthCells;hideThinking;hiddenThinkingLabel;level;detailedToolRecaps=It();groups=[];openGroup;turnReplies=new Map;turns=[];openReplyTurn;outsideTurns=0;turnHidden=new Set;lastReplyText;groupSummaries=new Map;nodeRoster=new Map;streamingWasGroupMember=!1;onFooterEvent;onActivityChange;spinnerStyle;dimStyle;errorStyle;recapPalette;labelStyle=h(t=>`\x1B[1m${t}\x1B[22m`,"labelStyle");markdownTransformers=[(t,{messageType:e,availableWidth:s})=>e==="assistant"?at(t,s):t,(t,{messageType:e})=>e==="user"?j(t):ht(t)];streamingComponent;streamingToolSeparator;foldedToolSeparatorContents=new Map;pendingTools=new Map;bashComponent;activityLoader;projection=vt();workingActivity=this.projection.workingActivity;runActive=!1;applyingSnapshot=!1;snapshotGeneration=0;deferredFrames=[];lastAssistantText;transcriptFilePaths=[];transcriptDocRefs=[];copyBlockRecords=[];copyIndex=new Map;constructor(t,e,s={}){if(this.tui=t,this.container=e,this.cwd=s.cwd??process.cwd(),this.showImages=s.showImages??!0,this.imageWidthCells=s.imageWidthCells??60,this.hideThinking=s.hideThinking??!1,this.hiddenThinkingLabel=s.hiddenThinkingLabel??"Thinking...",this.level=s.verbosity??Ot(),this.onFooterEvent=s.onFooterEvent,this.onActivityChange=s.onActivityChange,this.inlinePageBlocks=s.inlinePageBlocks??!1,this.pageOpenHint=s.pageOpenHint??(()=>"crtr human list"),this.backgroundBashHint=s.backgroundBashHint??(()=>null),this.recapPalette=s.palette??Wt,this.spinnerStyle=this.recapPalette.active,this.dimStyle=this.recapPalette.muted,this.errorStyle=this.recapPalette.error,s.banner&&s.banner.length>0){const i=new w;i.addChild(new p(1));for(const n of s.banner)i.addChild(new y(n,1,0));i.addChild(new p(1)),this.bannerContainer=i,this.container.addChild(i)}this.container.addChild(this.historyContainer),this.container.addChild(this.pendingContainer),this.onActivityChange||this.container.addChild(this.statusContainer),this.transcript=new bt([...this.bannerContainer?[this.bannerContainer]:[],this.historyContainer,this.pendingContainer,...this.onActivityChange?[]:[this.statusContainer]])}transcriptSource(){return this.transcript}async applySnapshot(t){const e=++this.snapshotGeneration;this.applyingSnapshot=!0,this.deferredFrames.length=0,this.resetChat(),this.projection=wt(t,this.projection),this.workingActivity=this.projection.workingActivity,this.runActive=this.projection.isStreaming,this.seedToolGroupSummaries(this.projection.toolGroupSummaryDetails),this.turnReplies.clear();for(const[o,r]of Object.entries(nt(t.turnReplies)))this.turnReplies.set(o,r);const s=new Map,i=this.projection.messages,n=i.length-1;for(let o=0;o<i.length;o++){if(!this.projection.isStreaming&&o>0&&o%Et===0&&(await new Promise(l=>setImmediate(l)),e!==this.snapshotGeneration))return;const r=i[o];if(r.role==="assistant"){const l=c(r);l.trim()&&(this.lastAssistantText=l,this.pushTranscriptText(l));const v=o===n&&this.projection.isStreaming&&r.stopReason!=="aborted"&&r.stopReason!=="error",C=c(r).trim()!=="",L=this.assistantToolCalls(r),T=r.stopReason==="aborted"||r.stopReason==="error",k=A(r)?"Interrupted":r.errorMessage??"Error";if(T){for(const f of s.values()){const m={content:[{type:"text",text:k}],isError:!0};f.updateResult(m),this.registerCopyBlock(f,"tool",k),this.settleGroupTool(f,m,!0)}s.clear()}(C||T)&&this.closeOpenGroup();let b;v?(this.streamingComponent=new x(void 0,this.hideThinking,d(),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)),b=this.streamingToolSeparator=this.appendAssistantSeparator(!C)):b=this.appendAssistantMessage(r,!C&&!T),b&&this.setAssistantSeparatorContent(b,r);for(const f of L){this.pushTranscriptValue(f.arguments);const m=this.appendToolComponent(f.name,f.id,f.arguments);r.stopReason==="aborted"||r.stopReason==="error"?(m.updateResult({content:[{type:"text",text:k}],isError:!0}),this.registerCopyBlock(m,"tool",k),this.settleGroupTool(m,{content:[{type:"text",text:k}],isError:!0},!0)):s.set(f.id,m)}T&&this.closeOpenGroup(),!v&&!T&&this.recordTurnProse(r,!1)}else if(r.role==="toolResult"){this.pushTranscriptText(this.userMessageText(r));const l=s.get(r.toolCallId);l&&(l.updateResult(r),this.registerCopyBlock(l,"tool",this.toolResultText(r)),this.historyContainer.markDirty(l),this.settleGroupTool(l,r,r.isError===!0),s.delete(r.toolCallId),this.maybeAppendPageBlock(r))}else this.addMessageToChat(r)}for(const[o,r]of s)this.pendingTools.set(o,r);for(const o of this.turns)this.refreshTurn(o);this.confirmPendingSendsIn(i),this.applyToolDisplay(),this.projection.isStreaming&&this.setActivity(this.makeLoader(this.workingActivity)),this.tui.requestRender(),this.applyingSnapshot=!1,this.replayDeferredFrames()}deferIfBuilding(t){return this.applyingSnapshot?(this.deferredFrames.push(t),!0):!1}replayDeferredFrames(){const t=this.deferredFrames.splice(0);for(const e of t)e()}setWorkingActivity(t){if(this.deferIfBuilding(()=>this.setWorkingActivity(t)))return;const e=this.projection.activity===this.workingActivity;this.projection=Rt(this.projection,t),this.workingActivity=this.projection.workingActivity,this.runActive&&e&&this.setActivity(this.makeLoader(this.workingActivity))}settleRun(){this.runActive=!1;for(const t of this.pendingTools.values())this.settleGroupTool(t);if(this.streamingComponent){this.historyContainer.removeChild(this.streamingComponent);for(const t of this.turns)t.members.delete(this.streamingComponent);this.turnHidden.delete(this.streamingComponent),this.unregisterCopyBlock(this.streamingComponent),this.streamingComponent=void 0}this.streamingToolSeparator=void 0,this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay(),this.setActivity(void 0),this.settleBashComponent()}dispose(){this.settleRun()}moreDetail(){const t=u.indexOf(this.level);return this.setLevel(u[(t+1)%u.length]),{level:this.level,atEnd:this.level===u.at(-1)}}lessDetail(){const t=u.indexOf(this.level);return this.setLevel(u[Math.max(0,t-1)]),{level:this.level,atEnd:this.level===u[0]}}setLevel(t){this.level=t;for(const e of this.turns)this.refreshTurn(e);this.applyToolDisplay()}repliesOnly(){return this.level==="replies"}foldsSettledTools(){return u.indexOf(this.level)<=u.indexOf("tools")}showsGroupSummaries(){return u.indexOf(this.level)<=u.indexOf("summaries")}toolOutputExpanded(){return this.level==="full"}applyToolDisplay(){const t=new Set(this.pendingTools.values());for(const i of this.groups)for(const n of i.inFlight)t.add(n);for(const i of this.historyContainer.children)i instanceof S&&i.setMinimized(this.foldsSettledTools()&&!t.has(i)),Pt(i)&&i.setExpanded(this.toolOutputExpanded());const e=this.turnFoldedComponents(t),s=new Set;for(const i of this.groups){this.applyGroupDisplay(i,e),s.add(i.recap);for(const n of i.members)s.add(n)}for(const i of this.turnHidden)!e.has(i)&&!s.has(i)&&this.historyContainer.setHidden(i,!1);for(const i of e)!s.has(i)&&!this.historyContainer.hiddenChildren.has(i)&&this.historyContainer.setHidden(i,!0);this.turnHidden=e,this.applyInboxExchangeDisplay(),this.updateFoldedToolSeparators(t),this.historyContainer.markDirty(),this.tui.requestRender()}hidesInboxExchange(){return this.showsGroupSummaries()}applyInboxExchangeDisplay(){const t=this.hidesInboxExchange();for(const e of this.inboxAnswers)this.historyContainer.setHidden(e,t);for(const e of this.pageBlocks.values())this.historyContainer.setHidden(e,e.settled)}applyTurnReply(t,e){if(!this.deferIfBuilding(()=>this.applyTurnReply(t,e))){this.turnReplies.set(t,e);for(const s of this.turns)s.key===t&&this.refreshTurn(s);this.tui.requestRender()}}turnFoldedComponents(t){const e=new Set;if(!this.repliesOnly())return e;for(const s of this.turns){const i=s===this.openReplyTurn;for(const n of s.members)i&&(n===this.streamingComponent||n===this.streamingToolSeparator||n===this.bashComponent||t.has(n))||e.add(n)}return e}beginTurn(t,e=[]){const s=new x(void 0,this.hideThinking,d(),this.hiddenThinkingLabel,this.markdownTransformers),i=new Ht;this.outsideTurns++;try{this.append(i),this.append(s)}finally{this.outsideTurns--}this.registerCopyBlock(s,"assistant","");const n={key:t,reply:s,working:i,members:new Set,prose:e};return this.turns.push(n),this.openReplyTurn=n,this.refreshTurn(n),n}currentTurn(){return this.openReplyTurn??this.beginTurn(rt)}recordTurnProse(t,e){if(t.role!=="assistant"||t.stopReason==="aborted"||t.stopReason==="error")return;const s=c(t).trim(),i=D(t);if(s===""||i===void 0)return;const n=this.currentTurn();n.prose.some(o=>o.key===i)||(n.prose.push({key:i,text:s}),e&&this.refreshTurn(n))}refreshTurn(t){const e=ot(t.prose,this.turnReplies.get(t.key));t.reply.updateContent(this.replyMessage(e)),this.historyContainer.setHidden(t.reply,e===""||!this.repliesOnly()),this.historyContainer.markDirty(t.reply),this.registerCopyBlock(t.reply,"assistant",e),e!==""&&t===this.turns.at(-1)&&(this.lastReplyText=e),this.refreshWorkingRow(t)}refreshWorkingRow(t){let e=0,s=0;for(const l of t.members)l instanceof S?e++:(l instanceof O||l instanceof E||l instanceof I)&&s++;const i=t.prose.length,n=e>0||s>0||i>1,o=[i>0?M(i,"message","messages"):void 0,e>0?M(e,"tool call","tool calls"):void 0,s>0?M(s,"card","cards"):void 0].filter(l=>l!==void 0),r=this.runActive&&t===this.openReplyTurn;t.working.setLabel(this.dimStyle(`\u25B8 ${r?"working \u2014 ":""}${o.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 q&&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=Gt(this.projection,t),t.type){case"agent_start":{this.runActive=this.projection.isStreaming;for(const e of this.pendingTools.values())this.settleGroupTool(e);this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.setActivity(this.makeLoader(this.workingActivity));break}case"agent_end":{this.settleRun(),Ct();break}case"agent_settled":{this.settleRun();break}case"message_start":{if(t.message.role==="user"&&g(t.message)&&this.confirmPendingSend(this.userMessageText(t.message).trim()),t.message.role==="custom"||t.message.role==="user")this.addMessageToChat(t.message),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();else if(t.message.role==="assistant"){const e=c(t.message).trim()!=="";e&&this.closeOpenGroup(),this.streamingComponent=new x(void 0,this.hideThinking,d(),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(A(t.message)&&(i="Interrupted",t.message.errorMessage=i,t.message.stopReason="aborted"),this.streamingComponent.updateContent(t.message),s==="aborted"||s==="error"){const n=i??"Error";for(const o of this.pendingTools.values())o.updateResult({content:[{type:"text",text:n}],isError:!0}),this.registerCopyBlock(o,"tool",n),this.settleGroupTool(o,{content:[{type:"text",text:n}],isError:!0},!0),this.historyContainer.markDirty(o);this.pendingTools.clear()}else for(const n of this.pendingTools.values())n.setArgsComplete(),this.historyContainer.markDirty(n);this.historyContainer.markDirty(this.streamingComponent),this.streamingComponent=void 0,this.streamingToolSeparator=void 0}e&&(this.closeOpenGroup(),this.applyToolDisplay()),this.recordTurnProse(t.message,!0),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();break}case"tool_execution_start":{this.pushTranscriptValue(t.args);let e=this.pendingTools.get(t.toolCallId);e?this.noteGroupTool(e,t.toolName,t.args):(e=this.appendToolComponent(t.toolName,t.toolCallId,t.args),this.pendingTools.set(t.toolCallId,e)),e.markExecutionStarted(),this.historyContainer.markDirty(e);break}case"tool_execution_update":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.partialResult;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e,!0),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.historyContainer.markDirty(s));break}case"tool_execution_end":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.result;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.pendingTools.delete(t.toolCallId),this.settleGroupTool(s,e,t.isError),this.applyToolDisplay(),this.historyContainer.markDirty(s),this.maybeAppendPageBlock(e));break}case"compaction_start":{const e=t.reason==="manual"?"Compacting context...":"Auto-compacting...";this.setActivity(this.makeLoader(e));break}case"compaction_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.aborted?this.showStatus(t.reason==="manual"?"Compaction cancelled":"Auto-compaction cancelled"):t.result?this.addMessageToChat({role:"compactionSummary",summary:t.result.summary,tokensBefore:t.result.tokensBefore,timestamp:Date.now()}):t.errorMessage&&this.showError(t.errorMessage);break}case"auto_retry_start":{const e=Math.ceil(t.delayMs/1e3);this.setActivity(this.makeLoader(`Retrying (${t.attempt}/${t.maxAttempts}) in ${e}s...`));break}case"auto_retry_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.success||this.showError(`Retry failed after ${t.attempt} attempts: ${t.finalError??"Unknown error"}`);break}case"queue_update":case"session_info_changed":case"thinking_level_changed":this.onFooterEvent?.(t);break;default:break}this.tui.requestRender()}}bashStart(t,e){if(this.deferIfBuilding(()=>this.bashStart(t,e)))return;this.projection=Mt(this.projection,t,e),this.closeOpenGroup(),this.settleBashComponent();let s;s=new G(t,this.componentTui(()=>s),e),this.bashComponent=s,this.append(s),this.tui.requestRender()}bashOutput(t){this.deferIfBuilding(()=>this.bashOutput(t))||(this.projection=Bt(this.projection,t),this.pushTranscriptText(t),this.bashComponent&&(this.bashComponent.appendOutput(t),this.historyContainer.markDirty(this.bashComponent)),this.tui.requestRender())}bashEnd(t){this.deferIfBuilding(()=>this.bashEnd(t))||(this.projection=At(this.projection,t),this.settleBashComponent(t),this.tui.requestRender())}addMessageToChat(t){const e=st(t);if(e!==null&&(t.role!=="custom"||t.display===!0)){this.pushTranscriptText(e.body);const s=e.senders.flatMap(n=>n.entries).filter(P).map(n=>n.body.trim()).filter(n=>n!=="");if(!(s.length>0&&e.body.replace(_t,"").trim()===""&&e.senders.every(n=>n.entries.every(P)))){const n=X(e.kind),o=new O(e,n,this.toolOutputExpanded(),this.dimStyle,r=>this.spinnerStyle(this.labelStyle(r)));it(e.kind)?(this.closeOpenGroup(),this.append(o)):this.appendGroupMember(o)?.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 G(t.command,this.tui,t.excludeFromContext);t.output&&s.appendOutput(t.output),s.setComplete(t.exitCode,t.cancelled,t.truncated?{truncated:!0}:void 0,t.fullOutputPath),this.append(s);break}case"custom":{if(t.display){if(this.pushTranscriptText(this.userMessageText(t)),t.customType===tt){this.appendGroupMember(new I(this.userMessageText(t),this.toolOutputExpanded(),this.crtrOutputTheme()));break}const s=new E(lt(t),void 0,d());s.setExpanded(this.toolOutputExpanded()),this.appendGroupMember(s)}break}case"compactionSummary":{this.closeOpenGroup(),this.append(new p(1));const s=new z(F(t),d());s.setExpanded(this.toolOutputExpanded()),this.append(s);break}case"branchSummary":{this.closeOpenGroup(),this.append(new p(1));const s=new V(F(t),d());s.setExpanded(this.toolOutputExpanded()),this.append(s),this.registerCopyBlock(s,"assistant",t.summary);break}case"user":{if(g(t)&&this.closeOpenGroup(),g(t)){this.outsideTurns++;try{this.appendUserMessage(t)}finally{this.outsideTurns--}this.beginTurn(D(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 p(1),!g(t));const s=Y(e);if(s){const i=new K({...s,content:j(s.content)},d());if(i.setExpanded(this.toolOutputExpanded()),this.appendUserPart(i,!g(t)),this.registerCopyBlock(i,"user",e),s.userMessage){const n=new R(s.userMessage,d(),void 0,this.markdownTransformers);this.appendUserPart(n,!g(t)),this.registerCopyBlock(n,"user",s.userMessage)}}else{const i=new R(e,d(),void 0,this.markdownTransformers);this.appendUserPart(i,!g(t)),this.registerCopyBlock(i,"user",e)}}appendAssistantMessage(t,e=!1){const s=new x(void 0,this.hideThinking,d(),this.hiddenThinkingLabel,this.markdownTransformers),i=A(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 B;return t?this.appendGroupMember(e):this.append(e),e}appendAssistantPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendUserPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendHumanAnswer(t){this.outsideTurns++;try{this.appendHumanAnswerParts(t)}finally{this.outsideTurns--}}appendHumanAnswerParts(t){if(this.closeOpenGroup(),this.chatChildCount()>0){const s=new p(1);this.append(s),this.trackInboxAnswer(s)}const e=new R(t,d(),void 0,this.markdownTransformers);this.append(e),this.trackInboxAnswer(e),this.registerCopyBlock(e,"user",t)}trackInboxAnswer(t){this.inboxAnswers.add(t),this.hidesInboxExchange()&&this.historyContainer.setHidden(t,!0)}ensureGroup(){if(this.openGroup)return this.openGroup;const t=new ct,e={members:[],recap:t,activity:new dt(this.cwd,this.nodeRoster),toolCount:0,inFlight:new Set};return this.append(t),this.historyContainer.setHidden(t,!0),this.groups.push(e),this.openGroup=e,e}closeOpenGroup(){this.openGroup=void 0}appendGroupMember(t){const e=this.ensureGroup();return this.append(t),e&&e.members.push(t),e}removeGroupMember(t){for(const e of this.groups){const s=e.members.indexOf(t);s!==-1&&e.members.splice(s,1)}this.historyContainer.setHidden(t,!1)}appendToolComponent(t,e,s){const i=!this.openGroup&&this.historyContainer.children.at(-1)instanceof B?this.historyContainer.children.at(-1):void 0;i&&this.historyContainer.removeChild(i);const n=this.ensureGroup();i&&(this.append(i),n?.members.push(i));const o=this.makeToolComponent(t,e,s);return o.activityCallId=e,this.appendGroupMember(o),this.registerCopyBlock(o,"tool",""),n&&(n.key??=e,n.toolCount++,n.inFlight.add(o),n.activity.noteCall(e,t,s)),o}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=St(this.projection,t,e);const s=this.projection.toolGroupSummaryDetails[t];s!==void 0&&(this.groupSummaries.set(t,s),this.applyToolDisplay())}applyGroupDisplay(t,e){const s=t.key===void 0?void 0:this.groupSummaries.get(t.key),i=this.showsGroupSummaries()&&t.toolCount>0&&t.inFlight.size===0&&s!==void 0;t.recap.setRecap(i?s:void 0,t.toolCount,t.activity.activity(),this.detailedToolRecaps,this.recapPalette),this.historyContainer.setHidden(t.recap,!i||e.has(t.recap));for(const n of t.members)this.historyContainer.setHidden(n,i||e.has(n))}updateFoldedToolSeparators(t=new Set(this.pendingTools.values())){const e=this.historyContainer.children;for(let s=0;s<e.length;s++){const i=e[s];if(!(i instanceof B))continue;const n=e[s+1];i.setFolded(this.foldsSettledTools()&&!this.historyContainer.hiddenChildren.has(i)&&n instanceof S&&!this.historyContainer.hiddenChildren.has(n)&&!t.has(n)),this.historyContainer.markDirty(i)}}setAssistantSeparatorContent(t,e){const s=e.content,i=Array.isArray(s)?s:[],n=i.some(r=>typeof r=="object"&&r!==null&&r.type==="text"&&typeof r.text=="string"&&r.text.trim()!==""),o=i.some(r=>typeof r=="object"&&r!==null&&r.type==="thinking"&&typeof r.thinking=="string"&&r.thinking.trim()!=="");this.foldedToolSeparatorContents.set(t,{hasText:n,hasThinking:o}),t.setSeparatesToolGroup(n||!this.hideThinking&&o)}makeToolComponent(t,e,s){const i=new ut;let n,o;if(t==="bash"){const l=et(s,i);l===void 0?o=mt(this.cwd,i,this.backgroundBashHint):o=l.definition}else if(t==="edit"){const l=pt(this.cwd,i);o=l.definition,n=l.observeResult}else t==="read"?o=gt(this.cwd,i):t==="write"&&(o=yt(this.cwd,i));let r;return r=new S(t,e,s,{showImages:this.showImages,imageWidthCells:this.imageWidthCells},o,this.componentTui(()=>r),this.cwd),r.setToolView(o===void 0?void 0:i,n),r.setExpanded(this.toolOutputExpanded()),r}append(t){if(this.outsideTurns===0){const e=this.currentTurn();this.historyContainer.addChild(t),e.members.add(t);return}this.historyContainer.addChild(t)}chatChildCount(){return this.historyContainer.children.length}resetChat(){this.setActivity(void 0),this.settleBashComponent(),this.streamingComponent=void 0,this.streamingToolSeparator=void 0,this.streamingWasGroupMember=!1,this.foldedToolSeparatorContents.clear(),this.groups.length=0,this.openGroup=void 0,this.turns.length=0,this.openReplyTurn=void 0,this.turnHidden=new Set,this.lastReplyText=void 0,this.groupSummaries.clear(),this.nodeRoster.clear(),this.pendingTools.clear(),this.lastAssistantText=void 0,this.copyBlockRecords.length=0,this.copyIndex.clear(),this.transcriptFilePaths.length=0,this.transcriptDocRefs.length=0,this.pageBlocks.clear(),this.inboxAnswers.clear(),this.historyContainer.clear()}maybeAppendPageBlock(t){if(!this.inlinePageBlocks)return;const e=Q(t);if(e===void 0||this.pageBlocks.has(e.pageId))return;const s=new Z(e.pageId,this.pageOpenHint);this.pageBlocks.set(e.pageId,s),this.outsideTurns++;try{this.append(s)}finally{this.outsideTurns--}this.loadPageBlock(s)}async loadPageBlock(t){await t.refresh()&&(this.historyContainer.setHidden(t,t.settled),this.historyContainer.markDirty(t),this.tui.requestRender())}refreshInFlightTools(){if(this.pendingTools.size!==0){for(const t of this.pendingTools.values())this.historyContainer.markDirty(t);this.tui.requestRender()}}async refreshPageBlocks(){if(this.pageRefresh)return;const t=[...this.pageBlocks.values()].filter(s=>!s.settled);this.pageRefresh=!0,(await Promise.all(t.map(async s=>{const i=await s.refresh();return i&&(this.historyContainer.setHidden(s,s.settled),this.historyContainer.markDirty(s)),i})).finally(()=>{this.pageRefresh=!1})).some(Boolean)&&this.tui.requestRender()}makeLoader(t){let e;const s={requestRender:h(i=>{e&&!this.onActivityChange&&this.statusContainer.markDirty(e),this.tui.requestRender(i)},"requestRender"),terminal:this.tui.terminal};return e=new N(s,this.spinnerStyle,this.dimStyle,t),e}componentTui(t){return{requestRender:h(e=>{this.historyContainer.markDirty(t()),this.tui.requestRender(e)},"requestRender"),terminal:this.tui.terminal}}settleBashComponent(t){if(!this.bashComponent)return;const e=this.bashComponent;e.setComplete(t?.exitCode,t?.cancelled??!0,t?.truncated?{truncated:!0}:void 0,t?.fullOutputPath),this.historyContainer.markDirty(e),this.bashComponent=void 0}addPendingSend(t,e=!1){const s=t.trim();if(!s)return;const i=[new p(1),new $(s,1,1,d(),{color:this.dimStyle})];for(const n of i)this.pendingContainer.addChild(n);this.pendingSends.push({text:s,parts:i,resend:e}),this.refreshUndeliveredNote(),this.tui.requestRender()}setPendingUndelivered(t){this.pendingUndelivered=t,this.refreshUndeliveredNote(),this.tui.requestRender()}refreshUndeliveredNote(){this.undeliveredNote!==void 0&&this.pendingContainer.removeChild(this.undeliveredNote),this.undeliveredNote=void 0,!(!this.pendingUndelivered||!this.pendingSends.some(t=>t.resend))&&(this.undeliveredNote=new y(this.dimStyle("\u2717 not delivered \u2014 reconnecting; it is sent again when the connection is back"),1,0),this.pendingContainer.addChild(this.undeliveredNote))}unconfirmedSends(t){const e=new Set([...t.queued?.steering??[],...t.queued?.followUp??[]].map(s=>s.trim()));for(const s of t.messages.slice(-50))s.role==="user"&&e.add(this.userMessageText(s).trim());return this.pendingSends.filter(s=>s.resend&&!e.has(s.text)).map(s=>s.text)}stopResendingPendingSends(){for(const t of this.pendingSends)t.resend=!1;this.refreshUndeliveredNote()}confirmPendingSend(t){const e=this.pendingSends.findIndex(n=>n.text===t),s=e>=0?e:0;if(this.pendingSends.length===0)return;const[i]=this.pendingSends.splice(s,1);for(const n of i.parts)this.pendingContainer.removeChild(n);this.refreshUndeliveredNote()}confirmPendingSendsIn(t){if(this.pendingSends.length===0)return;const e=new Set;for(const s of t.slice(-50))s.role==="user"&&e.add(this.userMessageText(s).trim());for(const s of[...this.pendingSends])if(e.has(s.text)){this.pendingSends.splice(this.pendingSends.indexOf(s),1);for(const i of s.parts)this.pendingContainer.removeChild(i)}this.refreshUndeliveredNote()}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 p(1)),this.append(new y(this.dimStyle(t),1,0))}showError(t){if(!this.deferIfBuilding(()=>this.showError(t))){this.closeOpenGroup(),this.outsideTurns++;try{this.append(new p(1)),this.append(new y(this.errorStyle(t),1,0))}finally{this.outsideTurns--}this.tui.requestRender()}}crtrOutputTheme(){return{fg:h((t,e)=>t==="error"?this.errorStyle(e):t==="warning"||t==="accent"||t==="toolTitle"||t==="success"?this.spinnerStyle(e):t==="muted"?this.dimStyle(e):e,"fg"),bg:h((t,e)=>e,"bg"),bold:h(t=>this.labelStyle(t),"bold")}}assistantToolCalls(t){const e=t.content;return Array.isArray(e)?e.filter(s=>typeof s=="object"&&s!==null&&s.type==="toolCall"):[]}getTranscriptFilePathsNewestFirst(){return[...this.transcriptFilePaths]}getTranscriptDocRefsNewestFirst(){return[...this.transcriptDocRefs]}refreshMarkdown(){this.historyContainer.invalidate(),this.tui.requestRender()}getLastAssistantText(){const t=(this.repliesOnly()?this.lastReplyText??this.lastAssistantText:this.lastAssistantText)?.trim();return t||void 0}blockText(t){const e=this.copyIndex.get(t);return e===void 0?void 0:this.copyBlockRecords[e]?.text}copyBlocks(){return this.copyBlockRecords}getLastToolOutputText(){for(let t=this.copyBlockRecords.length-1;t>=0;t--){const e=this.copyBlockRecords[t];if(e.kind==="tool")return e.text.trim()===""?void 0:e.text}}getTranscriptPlainText(){const t=this.inactiveFormBlocks();return this.copyBlockRecords.filter(e=>!t.has(e.block)).map(e=>e.text).filter(e=>e.trim()!=="").join(`
1
+ var N=Object.defineProperty;var h=(a,t)=>N(a,"name",{value:t,configurable:!0});import{Container as U,Loader as $,Markdown as q,Spacer as p,Text as y}from"@earendil-works/pi-tui";import{withoutRuntimeNote as C}from"../input/local-files.js";import{AssistantMessageComponent as V,BashExecutionComponent as E,BranchSummaryMessageComponent as z,CompactionSummaryMessageComponent as Y,CustomMessageComponent as O,parseSkillBlock as K,SkillInvocationMessageComponent as J,ToolExecutionComponent as X,UserMessageComponent as A}from"@earendil-works/pi-coding-agent";import{attachMarkdownTheme as d}from"../config.js";import{ContextMessageComponent as I}from"./context-message.js";import{presentationFor as Q}from"./card-presentation.js";import{detectInlinePageResult as Z,PageBlockComponent as tt}from"./page-block.js";import{CRTR_OUTPUT_CUSTOM_TYPE as et,CrtrOutputMessageComponent as P,createCrtrBashToolDefinition as st}from"./crtr-output.js";import{endedByAbort as B}from"../../../core/runtime/session-cycles.js";import{isHumanWordsEntry as D,parseCard as it}from"../../../shared/generated-context.js";import{assistantVisibleText as c,isGroupBoundaryKind as nt,isTrueUserMessage as g}from"../../../shared/tool-groups.js";import{messageKey as j,normalizeTurnReplyRecord as rt,START_TURN_KEY as ot,turnReplyText as at}from"../../../shared/turn-replies.js";import{transformDiagramFences as ht}from"./diagram.js";import{styleAttachAgentMarkdown as lt,styleAttachMarkdownSource as F,styleAttachMessageMarkdown as pt,styleAttachSummaryMarkdown as _}from"./markdown-source.js";import{createCrtrEditToolDefinition as dt}from"./edit-diff.js";import{GroupActivityRecorder as ct}from"./group-activity.js";import{GroupRecapComponent as ut}from"./group-recap.js";import{FoldedToolCallController as mt,bashCallBackgroundHintLines as ft,createCrtrPlainBashToolDefinition as gt,createCrtrReadToolDefinition as yt,createCrtrWriteToolDefinition as Ct}from"./tool-calls.js";import{ringCompletionBell as Tt}from"../chrome/completion-bell.js";import{extractFilePaths as kt}from"../../../core/human/visible-paths.js";import{extractDocRefs as bt}from"./doc-links.js";import{ViewerAssistantMessageComponent as w}from"./assistant-message.js";import{CompositeViewportSource as xt,MeasuredContainer as S}from"./measured-container.js";import{readConfig as H}from"../../../core/config.js";import{DEFAULT_VERBOSITY as wt,VERBOSITY_LEVELS as u}from"../../../types.js";import{applySnapshot as St,applyToolGroupSummary as Rt,applyWorkingActivity as At,bashEnd as Bt,bashOutput as Mt,bashStart as vt,initialConvState as Gt,reduce as Et}from"../../conversation/projection.js";const L=h(a=>`\x1B[2m${a}\x1B[22m`,"defaultDimStyle"),Ot=50;function It(){try{return H("user").verbosity}catch{return wt}}h(It,"readVerbosity");function Pt(){try{return H("user").detailed_tool_recaps}catch{return!0}}h(Pt,"readDetailedToolRecaps");function Dt(a){return typeof a=="object"&&a!==null&&"setExpanded"in a&&typeof a.setExpanded=="function"}h(Dt,"isExpandable");const jt=/\x1b\[[0-9;]*m/g,Ft=/\x1b\[([0-9;]*)m/g;function _t(a){return a.replace(Ft,(t,e)=>{const s=e.split(";"),i=[];for(let n=0;n<s.length;n++){const o=Number(s[n]===""?0:s[n]);if(o===38||o===48||o===58){const r=Number(s[n+1]),l=n+(r===5?2:r===2?4:1);o!==48&&i.push(...s.slice(n,l+1)),n=l;continue}o>=40&&o<=47||o>=100&&o<=107||i.push(String(o))}return i.length>0?`\x1B[${i.join(";")}m`:""})}h(_t,"stripBackground");const Ht=/<from\b[^>]*>[\s\S]*?<\/from>/g;class M extends p{static{h(this,"FoldedToolSeparator")}folded=!1;separatesToolGroup=!1;setFolded(t){this.folded=t,this.refresh()}setSeparatesToolGroup(t){this.separatesToolGroup=t,this.refresh()}refresh(){this.setLines(this.folded&&this.separatesToolGroup?1:0)}}class Lt extends U{static{h(this,"WorkingRow")}label=new y("",1,0);constructor(){super(),this.addChild(new p(1)),this.addChild(this.label)}setLabel(t){this.label.setText(t)}}function v(a,t,e){return`${a} ${a===1?t:e}`}h(v,"plural");class R extends X{static{h(this,"MinimizableToolComponent")}activityCallId;minimized=!1;expandedState=!1;foldController;resultObserver;setToolView(t,e){this.foldController=t,this.resultObserver=e}updateResult(...t){this.resultObserver?.(t[0],t[1]??!1);const e=t[0],s=e.content;Array.isArray(s)&&/^elapsed \d+(?:h \d+)?m \d+s(?:\n|$)/.test(s.at(-1)?.text??"")?super.updateResult({...e,content:s.slice(0,-1)},t[1]):super.updateResult(...t)}setExpanded(t){this.expandedState=t,super.setExpanded(t)}setMinimized(t){!this.foldController||this.minimized===t||(this.minimized=t,this.foldController.setFolded(t),super.setExpanded(this.expandedState))}render(t){if(!this.minimized)return[...super.render(t),...ft(this.foldController?.callComponent(),t)];const e=this.foldController?.callComponent();return e?e.render(t).filter(s=>s.replace(jt,"").trim().length>0).map(s=>_t(s).trimEnd()):super.render(t)}}const Wt=h(a=>`\x1B[31m${a}\x1B[39m`,"defaultErrorStyle"),Nt={accent:h(a=>`\x1B[33m${a}\x1B[39m`,"accent"),active:h(a=>`\x1B[36m${a}\x1B[39m`,"active"),info:h(a=>`\x1B[34m${a}\x1B[39m`,"info"),muted:L,faint:L,border:h(a=>a,"border"),surface:h(a=>a,"surface"),bold:h(a=>`\x1B[1m${a}\x1B[22m`,"bold"),error:Wt,warning:h(a=>`\x1B[33m${a}\x1B[39m`,"warning"),diffAdded:h(a=>`\x1B[32m${a}\x1B[39m`,"diffAdded"),diffRemoved:h(a=>`\x1B[91m${a}\x1B[39m`,"diffRemoved"),bashMode:h(a=>`\x1B[32m${a}\x1B[39m`,"bashMode"),bashModeAlt:h(a=>`\x1B[92m${a}\x1B[39m`,"bashModeAlt")};class ge{static{h(this,"ChatView")}tui;container;historyContainer=new S;statusContainer=new S;pendingContainer=new S;pendingSends=[];pendingUndelivered=!1;undeliveredNote;bannerContainer;setBannerHint(t){const e=this.bannerContainer;e!==void 0&&(e.removeChild(e.children[e.children.length-1]),e.addChild(new y(t,1,0)),e.addChild(new p(1)))}transcript;pageBlocks=new Map;pageRefresh=!1;inboxAnswers=new Set;inlinePageBlocks;pageOpenHint;backgroundBashHint;cwd;showImages;imageWidthCells;hideThinking;hiddenThinkingLabel;level;detailedToolRecaps=Pt();groups=[];openGroup;turnReplies=new Map;turns=[];openReplyTurn;outsideTurns=0;turnHidden=new Set;lastReplyText;groupSummaries=new Map;nodeRoster=new Map;streamingWasGroupMember=!1;onFooterEvent;onActivityChange;spinnerStyle;dimStyle;errorStyle;recapPalette;labelStyle=h(t=>`\x1B[1m${t}\x1B[22m`,"labelStyle");markdownTransformers=[(t,{messageType:e,availableWidth:s})=>e==="assistant"?ht(t,s):t,(t,{messageType:e})=>e==="user"?F(t):lt(t)];streamingComponent;streamingToolSeparator;foldedToolSeparatorContents=new Map;pendingTools=new Map;bashComponent;activityLoader;projection=Gt();workingActivity=this.projection.workingActivity;runActive=!1;applyingSnapshot=!1;snapshotGeneration=0;deferredFrames=[];lastAssistantText;transcriptFilePaths=[];transcriptDocRefs=[];copyBlockRecords=[];copyIndex=new Map;constructor(t,e,s={}){if(this.tui=t,this.container=e,this.cwd=s.cwd??process.cwd(),this.showImages=s.showImages??!0,this.imageWidthCells=s.imageWidthCells??60,this.hideThinking=s.hideThinking??!1,this.hiddenThinkingLabel=s.hiddenThinkingLabel??"Thinking...",this.level=s.verbosity??It(),this.onFooterEvent=s.onFooterEvent,this.onActivityChange=s.onActivityChange,this.inlinePageBlocks=s.inlinePageBlocks??!1,this.pageOpenHint=s.pageOpenHint??(()=>"crtr human list"),this.backgroundBashHint=s.backgroundBashHint??(()=>null),this.recapPalette=s.palette??Nt,this.spinnerStyle=this.recapPalette.active,this.dimStyle=this.recapPalette.muted,this.errorStyle=this.recapPalette.error,s.banner&&s.banner.length>0){const i=new S;i.addChild(new p(1));for(const n of s.banner)i.addChild(new y(n,1,0));i.addChild(new p(1)),this.bannerContainer=i,this.container.addChild(i)}this.container.addChild(this.historyContainer),this.container.addChild(this.pendingContainer),this.onActivityChange||this.container.addChild(this.statusContainer),this.transcript=new xt([...this.bannerContainer?[this.bannerContainer]:[],this.historyContainer,this.pendingContainer,...this.onActivityChange?[]:[this.statusContainer]])}transcriptSource(){return this.transcript}async applySnapshot(t){const e=++this.snapshotGeneration;this.applyingSnapshot=!0,this.deferredFrames.length=0,this.resetChat(),this.projection=St(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(rt(t.turnReplies)))this.turnReplies.set(o,r);const s=new Map,i=this.projection.messages,n=i.length-1;for(let o=0;o<i.length;o++){if(!this.projection.isStreaming&&o>0&&o%Ot===0&&(await new Promise(l=>setImmediate(l)),e!==this.snapshotGeneration))return;const r=i[o];if(r.role==="assistant"){const l=c(r);l.trim()&&(this.lastAssistantText=l,this.pushTranscriptText(l));const G=o===n&&this.projection.isStreaming&&r.stopReason!=="aborted"&&r.stopReason!=="error",T=c(r).trim()!=="",W=this.assistantToolCalls(r),k=r.stopReason==="aborted"||r.stopReason==="error",b=B(r)?"Interrupted":r.errorMessage??"Error";if(k){for(const m of s.values()){const f={content:[{type:"text",text:b}],isError:!0};m.updateResult(f),this.registerCopyBlock(m,"tool",b),this.settleGroupTool(m,f,!0)}s.clear()}(T||k)&&this.closeOpenGroup();let x;G?(this.streamingComponent=new w(void 0,this.hideThinking,d(),this.hiddenThinkingLabel,this.markdownTransformers),this.appendAssistantPart(this.streamingComponent,!T),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingWasGroupMember=!T,this.streamingComponent.updateContent(r),this.registerCopyBlock(this.streamingComponent,"assistant",c(r)),x=this.streamingToolSeparator=this.appendAssistantSeparator(!T)):x=this.appendAssistantMessage(r,!T&&!k),x&&this.setAssistantSeparatorContent(x,r);for(const m of W){this.pushTranscriptValue(m.arguments);const f=this.appendToolComponent(m.name,m.id,m.arguments);r.stopReason==="aborted"||r.stopReason==="error"?(f.updateResult({content:[{type:"text",text:b}],isError:!0}),this.registerCopyBlock(f,"tool",b),this.settleGroupTool(f,{content:[{type:"text",text:b}],isError:!0},!0)):s.set(m.id,f)}k&&this.closeOpenGroup(),!G&&!k&&this.recordTurnProse(r,!1)}else if(r.role==="toolResult"){this.pushTranscriptText(this.userMessageText(r));const l=s.get(r.toolCallId);l&&(l.updateResult(r),this.registerCopyBlock(l,"tool",this.toolResultText(r)),this.historyContainer.markDirty(l),this.settleGroupTool(l,r,r.isError===!0),s.delete(r.toolCallId),this.maybeAppendPageBlock(r))}else this.addMessageToChat(r)}for(const[o,r]of s)this.pendingTools.set(o,r);for(const o of this.turns)this.refreshTurn(o);this.confirmPendingSendsIn(i),this.applyToolDisplay(),this.projection.isStreaming&&this.setActivity(this.makeLoader(this.workingActivity)),this.tui.requestRender(),this.applyingSnapshot=!1,this.replayDeferredFrames()}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=At(this.projection,t),this.workingActivity=this.projection.workingActivity,this.runActive&&e&&this.setActivity(this.makeLoader(this.workingActivity))}settleRun(){this.runActive=!1;for(const t of this.pendingTools.values())this.settleGroupTool(t);if(this.streamingComponent){this.historyContainer.removeChild(this.streamingComponent);for(const t of this.turns)t.members.delete(this.streamingComponent);this.turnHidden.delete(this.streamingComponent),this.unregisterCopyBlock(this.streamingComponent),this.streamingComponent=void 0}this.streamingToolSeparator=void 0,this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay(),this.setActivity(void 0),this.settleBashComponent()}dispose(){this.settleRun()}moreDetail(){const t=u.indexOf(this.level);return this.setLevel(u[(t+1)%u.length]),{level:this.level,atEnd:this.level===u.at(-1)}}lessDetail(){const t=u.indexOf(this.level);return this.setLevel(u[Math.max(0,t-1)]),{level:this.level,atEnd:this.level===u[0]}}setLevel(t){this.level=t;for(const e of this.turns)this.refreshTurn(e);this.applyToolDisplay()}repliesOnly(){return this.level==="replies"}foldsSettledTools(){return u.indexOf(this.level)<=u.indexOf("tools")}showsGroupSummaries(){return u.indexOf(this.level)<=u.indexOf("summaries")}toolOutputExpanded(){return this.level==="full"}applyToolDisplay(){const t=new Set(this.pendingTools.values());for(const i of this.groups)for(const n of i.inFlight)t.add(n);for(const i of this.historyContainer.children)i instanceof R&&i.setMinimized(this.foldsSettledTools()&&!t.has(i)),Dt(i)&&i.setExpanded(this.toolOutputExpanded());const e=this.turnFoldedComponents(t),s=new Set;for(const i of this.groups){this.applyGroupDisplay(i,e),s.add(i.recap);for(const n of i.members)s.add(n)}for(const i of this.turnHidden)!e.has(i)&&!s.has(i)&&this.historyContainer.setHidden(i,!1);for(const i of e)!s.has(i)&&!this.historyContainer.hiddenChildren.has(i)&&this.historyContainer.setHidden(i,!0);this.turnHidden=e,this.applyInboxExchangeDisplay(),this.updateFoldedToolSeparators(t),this.historyContainer.markDirty(),this.tui.requestRender()}hidesInboxExchange(){return this.showsGroupSummaries()}applyInboxExchangeDisplay(){const t=this.hidesInboxExchange();for(const e of this.inboxAnswers)this.historyContainer.setHidden(e,t);for(const e of this.pageBlocks.values())this.historyContainer.setHidden(e,e.settled)}applyTurnReply(t,e){if(!this.deferIfBuilding(()=>this.applyTurnReply(t,e))){this.turnReplies.set(t,e);for(const s of this.turns)s.key===t&&this.refreshTurn(s);this.tui.requestRender()}}turnFoldedComponents(t){const e=new Set;if(!this.repliesOnly())return e;for(const s of this.turns){const i=s===this.openReplyTurn;for(const n of s.members)i&&(n===this.streamingComponent||n===this.streamingToolSeparator||n===this.bashComponent||t.has(n))||e.add(n)}return e}beginTurn(t,e=[]){const s=new w(void 0,this.hideThinking,d(),this.hiddenThinkingLabel,this.markdownTransformers),i=new Lt;this.outsideTurns++;try{this.append(i),this.append(s)}finally{this.outsideTurns--}this.registerCopyBlock(s,"assistant","");const n={key:t,reply:s,working:i,members:new Set,prose:e};return this.turns.push(n),this.openReplyTurn=n,this.refreshTurn(n),n}currentTurn(){return this.openReplyTurn??this.beginTurn(ot)}recordTurnProse(t,e){if(t.role!=="assistant"||t.stopReason==="aborted"||t.stopReason==="error")return;const s=c(t).trim(),i=j(t);if(s===""||i===void 0)return;const n=this.currentTurn();n.prose.some(o=>o.key===i)||(n.prose.push({key:i,text:s}),e&&this.refreshTurn(n))}refreshTurn(t){const e=at(t.prose,this.turnReplies.get(t.key));t.reply.updateContent(this.replyMessage(e)),this.historyContainer.setHidden(t.reply,e===""||!this.repliesOnly()),this.historyContainer.markDirty(t.reply),this.registerCopyBlock(t.reply,"assistant",e),e!==""&&t===this.turns.at(-1)&&(this.lastReplyText=e),this.refreshWorkingRow(t)}refreshWorkingRow(t){let e=0,s=0;for(const l of t.members)l instanceof R?e++:(l instanceof I||l instanceof O||l instanceof P)&&s++;const i=t.prose.length,n=e>0||s>0||i>1,o=[i>0?v(i,"message","messages"):void 0,e>0?v(e,"tool call","tool calls"):void 0,s>0?v(s,"card","cards"):void 0].filter(l=>l!==void 0),r=this.runActive&&t===this.openReplyTurn;t.working.setLabel(this.dimStyle(`\u25B8 ${r?"working \u2014 ":""}${o.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 V&&t.setHideThinkingBlock(this.hideThinking);for(const[t,e]of this.foldedToolSeparatorContents)t.setSeparatesToolGroup(e.hasText||!this.hideThinking&&e.hasThinking);return this.historyContainer.markDirty(),this.tui.requestRender(),this.hideThinking}handleEvent(t){if(!this.deferIfBuilding(()=>this.handleEvent(t))){switch(this.projection=Et(this.projection,t),t.type){case"agent_start":{this.runActive=this.projection.isStreaming;for(const e of this.pendingTools.values())this.settleGroupTool(e);this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.setActivity(this.makeLoader(this.workingActivity));break}case"agent_end":{this.settleRun(),Tt();break}case"agent_settled":{this.settleRun();break}case"message_start":{if(t.message.role==="user"&&g(t.message)&&this.confirmPendingSend(this.userMessageText(t.message).trim()),t.message.role==="custom"||t.message.role==="user")this.addMessageToChat(t.message),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();else if(t.message.role==="assistant"){const e=c(t.message).trim()!=="";e&&this.closeOpenGroup(),this.streamingComponent=new w(void 0,this.hideThinking,d(),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(B(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 o of this.pendingTools.values())o.updateResult({content:[{type:"text",text:n}],isError:!0}),this.registerCopyBlock(o,"tool",n),this.settleGroupTool(o,{content:[{type:"text",text:n}],isError:!0},!0),this.historyContainer.markDirty(o);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=vt(this.projection,t,e),this.closeOpenGroup(),this.settleBashComponent();let s;s=new E(t,this.componentTui(()=>s),e),this.bashComponent=s,this.append(s),this.tui.requestRender()}bashOutput(t){this.deferIfBuilding(()=>this.bashOutput(t))||(this.projection=Mt(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=Bt(this.projection,t),this.settleBashComponent(t),this.tui.requestRender())}addMessageToChat(t){const e=it(t);if(e!==null&&(t.role!=="custom"||t.display===!0)){this.pushTranscriptText(e.body);const s=e.senders.flatMap(n=>n.entries).filter(D).map(n=>n.body.trim()).filter(n=>n!=="");if(!(s.length>0&&e.body.replace(Ht,"").trim()===""&&e.senders.every(n=>n.entries.every(D)))){const n=Q(e.kind),o=new I(e,n,this.toolOutputExpanded(),this.dimStyle,r=>this.spinnerStyle(this.labelStyle(r)));nt(e.kind)?(this.closeOpenGroup(),this.append(o)):this.appendGroupMember(o)?.activity.noteCard(e,n)}for(const n of s)this.appendHumanAnswer(n);return}switch(t.role){case"bashExecution":{this.closeOpenGroup(),this.pushTranscriptText(t.output??"");const s=new E(t.command,this.tui,t.excludeFromContext);t.output&&s.appendOutput(t.output),s.setComplete(t.exitCode,t.cancelled,t.truncated?{truncated:!0}:void 0,t.fullOutputPath),this.append(s);break}case"custom":{if(t.display){if(this.pushTranscriptText(this.userMessageText(t)),t.customType===et){this.appendGroupMember(new P(this.userMessageText(t),this.toolOutputExpanded(),this.crtrOutputTheme()));break}const s=new O(pt(t),void 0,d());s.setExpanded(this.toolOutputExpanded()),this.appendGroupMember(s)}break}case"compactionSummary":{this.closeOpenGroup(),this.append(new p(1));const s=new Y(_(t),d());s.setExpanded(this.toolOutputExpanded()),this.append(s);break}case"branchSummary":{this.closeOpenGroup(),this.append(new p(1));const s=new z(_(t),d());s.setExpanded(this.toolOutputExpanded()),this.append(s),this.registerCopyBlock(s,"assistant",t.summary);break}case"user":{if(g(t)&&this.closeOpenGroup(),g(t)){this.outsideTurns++;try{this.appendUserMessage(t)}finally{this.outsideTurns--}this.beginTurn(j(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 p(1),!g(t));const s=K(e);if(s){const i=new J({...s,content:F(s.content)},d());if(i.setExpanded(this.toolOutputExpanded()),this.appendUserPart(i,!g(t)),this.registerCopyBlock(i,"user",e),s.userMessage){const n=new A(s.userMessage,d(),void 0,this.markdownTransformers);this.appendUserPart(n,!g(t)),this.registerCopyBlock(n,"user",s.userMessage)}}else{const i=new A(e,d(),void 0,this.markdownTransformers);this.appendUserPart(i,!g(t)),this.registerCopyBlock(i,"user",e)}}appendAssistantMessage(t,e=!1){const s=new w(void 0,this.hideThinking,d(),this.hiddenThinkingLabel,this.markdownTransformers),i=B(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 M;return t?this.appendGroupMember(e):this.append(e),e}appendAssistantPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendUserPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendHumanAnswer(t){this.outsideTurns++;try{this.appendHumanAnswerParts(t)}finally{this.outsideTurns--}}appendHumanAnswerParts(t){if(this.closeOpenGroup(),this.chatChildCount()>0){const s=new p(1);this.append(s),this.trackInboxAnswer(s)}const e=new A(t,d(),void 0,this.markdownTransformers);this.append(e),this.trackInboxAnswer(e),this.registerCopyBlock(e,"user",t)}trackInboxAnswer(t){this.inboxAnswers.add(t),this.hidesInboxExchange()&&this.historyContainer.setHidden(t,!0)}ensureGroup(){if(this.openGroup)return this.openGroup;const t=new ut,e={members:[],recap:t,activity:new ct(this.cwd,this.nodeRoster),toolCount:0,inFlight:new Set};return this.append(t),this.historyContainer.setHidden(t,!0),this.groups.push(e),this.openGroup=e,e}closeOpenGroup(){this.openGroup=void 0}appendGroupMember(t){const e=this.ensureGroup();return this.append(t),e&&e.members.push(t),e}removeGroupMember(t){for(const e of this.groups){const s=e.members.indexOf(t);s!==-1&&e.members.splice(s,1)}this.historyContainer.setHidden(t,!1)}appendToolComponent(t,e,s){const i=!this.openGroup&&this.historyContainer.children.at(-1)instanceof M?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 o=this.makeToolComponent(t,e,s);return o.activityCallId=e,this.appendGroupMember(o),this.registerCopyBlock(o,"tool",""),n&&(n.key??=e,n.toolCount++,n.inFlight.add(o),n.activity.noteCall(e,t,s)),o}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=Rt(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 M))continue;const n=e[s+1];i.setFolded(this.foldsSettledTools()&&!this.historyContainer.hiddenChildren.has(i)&&n instanceof R&&!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(r=>typeof r=="object"&&r!==null&&r.type==="text"&&typeof r.text=="string"&&r.text.trim()!==""),o=i.some(r=>typeof r=="object"&&r!==null&&r.type==="thinking"&&typeof r.thinking=="string"&&r.thinking.trim()!=="");this.foldedToolSeparatorContents.set(t,{hasText:n,hasThinking:o}),t.setSeparatesToolGroup(n||!this.hideThinking&&o)}makeToolComponent(t,e,s){const i=new mt;let n,o;if(t==="bash"){const l=st(s,i);l===void 0?o=gt(this.cwd,i,this.backgroundBashHint):o=l.definition}else if(t==="edit"){const l=dt(this.cwd,i);o=l.definition,n=l.observeResult}else t==="read"?o=yt(this.cwd,i):t==="write"&&(o=Ct(this.cwd,i));let r;return r=new R(t,e,s,{showImages:this.showImages,imageWidthCells:this.imageWidthCells},o,this.componentTui(()=>r),this.cwd),r.setToolView(o===void 0?void 0:i,n),r.setExpanded(this.toolOutputExpanded()),r}append(t){if(this.outsideTurns===0){const e=this.currentTurn();this.historyContainer.addChild(t),e.members.add(t);return}this.historyContainer.addChild(t)}chatChildCount(){return this.historyContainer.children.length}resetChat(){this.setActivity(void 0),this.settleBashComponent(),this.streamingComponent=void 0,this.streamingToolSeparator=void 0,this.streamingWasGroupMember=!1,this.foldedToolSeparatorContents.clear(),this.groups.length=0,this.openGroup=void 0,this.turns.length=0,this.openReplyTurn=void 0,this.turnHidden=new Set,this.lastReplyText=void 0,this.groupSummaries.clear(),this.nodeRoster.clear(),this.pendingTools.clear(),this.lastAssistantText=void 0,this.copyBlockRecords.length=0,this.copyIndex.clear(),this.transcriptFilePaths.length=0,this.transcriptDocRefs.length=0,this.pageBlocks.clear(),this.inboxAnswers.clear(),this.historyContainer.clear()}maybeAppendPageBlock(t){if(!this.inlinePageBlocks)return;const e=Z(t);if(e===void 0||this.pageBlocks.has(e.pageId))return;const s=new tt(e.pageId,this.pageOpenHint);this.pageBlocks.set(e.pageId,s),this.outsideTurns++;try{this.append(s)}finally{this.outsideTurns--}this.loadPageBlock(s)}async loadPageBlock(t){await t.refresh()&&(this.historyContainer.setHidden(t,t.settled),this.historyContainer.markDirty(t),this.tui.requestRender())}refreshInFlightTools(){if(this.pendingTools.size!==0){for(const t of this.pendingTools.values())this.historyContainer.markDirty(t);this.tui.requestRender()}}async refreshPageBlocks(){if(this.pageRefresh)return;const t=[...this.pageBlocks.values()].filter(s=>!s.settled);this.pageRefresh=!0,(await Promise.all(t.map(async s=>{const i=await s.refresh();return i&&(this.historyContainer.setHidden(s,s.settled),this.historyContainer.markDirty(s)),i})).finally(()=>{this.pageRefresh=!1})).some(Boolean)&&this.tui.requestRender()}makeLoader(t){let e;const s={requestRender:h(i=>{e&&!this.onActivityChange&&this.statusContainer.markDirty(e),this.tui.requestRender(i)},"requestRender"),terminal:this.tui.terminal};return e=new $(s,this.spinnerStyle,this.dimStyle,t),e}componentTui(t){return{requestRender:h(e=>{this.historyContainer.markDirty(t()),this.tui.requestRender(e)},"requestRender"),terminal:this.tui.terminal}}settleBashComponent(t){if(!this.bashComponent)return;const e=this.bashComponent;e.setComplete(t?.exitCode,t?.cancelled??!0,t?.truncated?{truncated:!0}:void 0,t?.fullOutputPath),this.historyContainer.markDirty(e),this.bashComponent=void 0}addPendingSend(t,e=!1){const s=t.trim();if(!s)return;const i=[new p(1),new q(C(s).trim(),1,1,d(),{color:this.dimStyle})];for(const n of i)this.pendingContainer.addChild(n);this.pendingSends.push({text:s,parts:i,resend:e}),this.refreshUndeliveredNote(),this.tui.requestRender()}setPendingUndelivered(t){this.pendingUndelivered=t,this.refreshUndeliveredNote(),this.tui.requestRender()}refreshUndeliveredNote(){this.undeliveredNote!==void 0&&this.pendingContainer.removeChild(this.undeliveredNote),this.undeliveredNote=void 0,!(!this.pendingUndelivered||!this.pendingSends.some(t=>t.resend))&&(this.undeliveredNote=new y(this.dimStyle("\u2717 not delivered \u2014 reconnecting; it is sent again when the connection is back"),1,0),this.pendingContainer.addChild(this.undeliveredNote))}unconfirmedSends(t){const e=new Set([...t.queued?.steering??[],...t.queued?.followUp??[]].map(s=>s.trim()));for(const s of t.messages.slice(-50))s.role==="user"&&e.add(this.userMessageText(s).trim());return this.pendingSends.filter(s=>s.resend&&!e.has(C(s.text).trim())).map(s=>s.text)}stopResendingPendingSends(){for(const t of this.pendingSends)t.resend=!1;this.refreshUndeliveredNote()}confirmPendingSend(t){const e=this.pendingSends.findIndex(n=>C(n.text).trim()===t),s=e>=0?e:0;if(this.pendingSends.length===0)return;const[i]=this.pendingSends.splice(s,1);for(const n of i.parts)this.pendingContainer.removeChild(n);this.refreshUndeliveredNote()}confirmPendingSendsIn(t){if(this.pendingSends.length===0)return;const e=new Set;for(const s of t.slice(-50))s.role==="user"&&e.add(this.userMessageText(s).trim());for(const s of[...this.pendingSends])if(e.has(C(s.text).trim())){this.pendingSends.splice(this.pendingSends.indexOf(s),1);for(const i of s.parts)this.pendingContainer.removeChild(i)}this.refreshUndeliveredNote()}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 p(1)),this.append(new y(this.dimStyle(t),1,0))}showError(t){if(!this.deferIfBuilding(()=>this.showError(t))){this.closeOpenGroup(),this.outsideTurns++;try{this.append(new p(1)),this.append(new y(this.errorStyle(t),1,0))}finally{this.outsideTurns--}this.tui.requestRender()}}crtrOutputTheme(){return{fg:h((t,e)=>t==="error"?this.errorStyle(e):t==="warning"||t==="accent"||t==="toolTitle"||t==="success"?this.spinnerStyle(e):t==="muted"?this.dimStyle(e):e,"fg"),bg:h((t,e)=>e,"bg"),bold:h(t=>this.labelStyle(t),"bold")}}assistantToolCalls(t){const e=t.content;return Array.isArray(e)?e.filter(s=>typeof s=="object"&&s!==null&&s.type==="toolCall"):[]}getTranscriptFilePathsNewestFirst(){return[...this.transcriptFilePaths]}getTranscriptDocRefsNewestFirst(){return[...this.transcriptDocRefs]}refreshMarkdown(){this.historyContainer.invalidate(),this.tui.requestRender()}getLastAssistantText(){const t=(this.repliesOnly()?this.lastReplyText??this.lastAssistantText:this.lastAssistantText)?.trim();return t||void 0}blockText(t){const e=this.copyIndex.get(t);return e===void 0?void 0:this.copyBlockRecords[e]?.text}copyBlocks(){return this.copyBlockRecords}getLastToolOutputText(){for(let t=this.copyBlockRecords.length-1;t>=0;t--){const e=this.copyBlockRecords[t];if(e.kind==="tool")return e.text.trim()===""?void 0:e.text}}getTranscriptPlainText(){const t=this.inactiveFormBlocks();return this.copyBlockRecords.filter(e=>!t.has(e.block)).map(e=>e.text).filter(e=>e.trim()!=="").join(`
2
2
 
3
- `)}inactiveFormBlocks(){const t=new Set;if(!this.repliesOnly())for(const e of this.turns)t.add(e.reply);return t}registerCopyBlock(t,e,s){const i=this.copyIndex.get(t);i===void 0?(this.copyIndex.set(t,this.copyBlockRecords.length),this.copyBlockRecords.push({block:t,kind:e,text:s})):this.copyBlockRecords[i].text=s}unregisterCopyBlock(t){const e=this.copyIndex.get(t);if(e!==void 0){this.copyBlockRecords.splice(e,1),this.copyIndex.delete(t);for(let s=e;s<this.copyBlockRecords.length;s++)this.copyIndex.set(this.copyBlockRecords[s].block,s)}}toolResultText(t){if(typeof t=="string")return t;if(typeof t=="object"&&t!==null&&"content"in t){const e=t.content;if(typeof e=="string")return e;if(Array.isArray(e))return e.filter(s=>typeof s=="object"&&s!==null&&s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}try{const e=JSON.stringify(t);return typeof e=="string"?e:""}catch{return""}}pushTranscriptText(t){const e=t.trim();if(e==="")return;const s=[...new Set(kt(e).reverse())];if(s.length>0){const o=[...s,...this.transcriptDocRefs.filter(r=>!s.includes(r))].slice(0,50);this.transcriptDocRefs.splice(0,this.transcriptDocRefs.length,...o)}const i=Tt([e],this.cwd);if(i.length===0)return;const n=[...i,...this.transcriptFilePaths.filter(o=>!i.includes(o))].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{fe as ChatView};
3
+ `)}inactiveFormBlocks(){const t=new Set;if(!this.repliesOnly())for(const e of this.turns)t.add(e.reply);return t}registerCopyBlock(t,e,s){const i=this.copyIndex.get(t);i===void 0?(this.copyIndex.set(t,this.copyBlockRecords.length),this.copyBlockRecords.push({block:t,kind:e,text:s})):this.copyBlockRecords[i].text=s}unregisterCopyBlock(t){const e=this.copyIndex.get(t);if(e!==void 0){this.copyBlockRecords.splice(e,1),this.copyIndex.delete(t);for(let s=e;s<this.copyBlockRecords.length;s++)this.copyIndex.set(this.copyBlockRecords[s].block,s)}}toolResultText(t){if(typeof t=="string")return t;if(typeof t=="object"&&t!==null&&"content"in t){const e=t.content;if(typeof e=="string")return e;if(Array.isArray(e))return e.filter(s=>typeof s=="object"&&s!==null&&s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}try{const e=JSON.stringify(t);return typeof e=="string"?e:""}catch{return""}}pushTranscriptText(t){const e=t.trim();if(e==="")return;const s=[...new Set(bt(e).reverse())];if(s.length>0){const o=[...s,...this.transcriptDocRefs.filter(r=>!s.includes(r))].slice(0,50);this.transcriptDocRefs.splice(0,this.transcriptDocRefs.length,...o)}const i=kt([e],this.cwd);if(i.length===0)return;const n=[...i,...this.transcriptFilePaths.filter(o=>!i.includes(o))].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"?C(e):Array.isArray(e)?C(e.filter(s=>typeof s=="object"&&s!==null&&s.type==="text").map(s=>s.text).join("")):""}}export{ge as ChatView};
@@ -43,6 +43,8 @@ export interface InputWiringHooks {
43
43
  onPromptSent: () => void;
44
44
  /** A new message left the editor; show it pending until echoed. `viaSocket`: it went to the broker socket, not to a parked node's wake message. */
45
45
  onMessageSent: (text: string, viaSocket: boolean) => void;
46
+ /** Resolves true once the broker's first welcome arrived, false when it will not. */
47
+ whenBrokerReady: () => Promise<boolean>;
46
48
  /** Send a frame to the broker; before the broker's first welcome the viewer holds it. */
47
49
  send: (frame: ClientToBroker) => void;
48
50
  /** True while the node is still being created: only plain messages, `!` commands and follow-ups are accepted (held until the welcome). */
@@ -1 +1 @@
1
- var P=Object.defineProperty;var t=(n,a)=>P(n,"name",{value:a,configurable:!0});import{InputController as D}from"../input/controller.js";import{createViewerCapabilities as S}from"../input/capabilities.js";import{VERBOSITY_LABELS as f}from"../../../core/user-settings.js";import{VERBOSITY_LEVELS as c}from"../../../types.js";import{cliClient as b}from"../../../commands/api-client.js";import{buildLoginPicker as I,buildLogoutPicker as M}from"../overlays/auth.js";import{defaultAgentDir as C}from"../config.js";function x(n,a){return S({get nodeId(){return n.nodeId},profileId:n.meta.profile_id??void 0,remote:n.remote,role:n.role,isBrokerOffline:a})}t(x,"createViewerCapabilitiesForInput");function s({level:n}){return`Verbosity: ${f[n]} (${c.indexOf(n)+1}/${c.length})`}t(s,"verbosityName");function T(n){return n.atEnd?`${s(n)} \u2014 Ctrl+O again goes back to ${f[c[0]]}`:`${s(n)} \u2014 Ctrl+O shows more`}t(T,"moreDetailNotice");function v(n){return n.atEnd?`${s(n)}, the most collapsed level \u2014 Ctrl+O shows more`:`${s(n)} \u2014 Ctrl+O shows more`}t(v,"lessDetailNotice");function A(n,a,d,e){const{socket:w,tui:l,editor:m,containers:g}=n,{setNotice:i}=e,p=t(()=>e.send({type:"reload_auth"}),"reloadAuth"),y=d.permits("auth")?{openLoginPicker:t(()=>{const r=e.agentDir()??C();u.openAuthPicker(()=>I(l,r,p,o=>i(o)))},"openLoginPicker"),openLogoutPicker:t(()=>{const r=e.agentDir()??C();u.openAuthPicker(()=>M(r,p,o=>i(o)))},"openLogoutPicker")}:{},u=new D(l,m,a,{onCommand:e.send,onDialogResponse:e.send,onNotice:t(r=>i(r),"onNotice"),onGraph:e.toggleGraph,onInbox:e.toggleInbox,onHelp:e.toggleHelp,onNodeMetadata:e.openNodeMetadata,onQuit:e.quit,onCopy:t(()=>e.copyTarget("last-assistant"),"onCopy"),onCopyTarget:e.copyTarget,onToggleMouse:t(()=>{const r=e.toggleMouse();i(r?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"onToggleMouse"),onColor:e.setChipColor,onPromptSent:e.onPromptSent,onMessageSent:e.onMessageSent,frecency:e.frecency,knownRefNames:t(()=>m.getResolvedRefNames(),"knownRefNames"),onMoreDetail:t(()=>i(T(e.moreDetail())),"onMoreDetail"),onLessDetail:t(()=>i(v(e.lessDetail())),"onLessDetail"),onToggleThinking:t(()=>i(e.toggleThinking()?"Thinking blocks: hidden":"Thinking blocks: visible"),"onToggleThinking"),onRequest:t(r=>{const o=d.refusal("engine-drive");return o===void 0?w.request(r):Promise.reject(new Error(o))},"onRequest"),onMountPicker:t(r=>{g.pickerPanel.addChild(r),l.requestRender()},"onMountPicker"),onUnmountPicker:t(()=>{g.pickerPanel.clear(),l.requestRender()},"onUnmountPicker"),isDormant:e.isDormant,isStarting:e.isStarting,onDormantSubmit:d.permits("wake-dormant")?r=>{(async()=>{try{const o=await b().sendMessage(n.nodeId,{body:r,from:"human"});i(o.revived?"\u21BB waking node\u2026":"\u2709 delivered \u2014 node reads on next wake")}catch(o){i(`Couldn't wake node: ${o instanceof Error?o.message:String(o)}`)}})()}:void 0,...y},d);return u}t(A,"createInputController");export{A as createInputController,x as createViewerCapabilitiesForInput,v as lessDetailNotice,T as moreDetailNotice};
1
+ var P=Object.defineProperty;var t=(n,a)=>P(n,"name",{value:a,configurable:!0});import{InputController as D}from"../input/controller.js";import{createViewerCapabilities as S}from"../input/capabilities.js";import{VERBOSITY_LABELS as f}from"../../../core/user-settings.js";import{VERBOSITY_LEVELS as c}from"../../../types.js";import{cliClient as b}from"../../../commands/api-client.js";import{buildLoginPicker as I,buildLogoutPicker as M}from"../overlays/auth.js";import{defaultAgentDir as C}from"../config.js";function x(n,a){return S({get nodeId(){return n.nodeId},profileId:n.meta.profile_id??void 0,remote:n.remote,role:n.role,isBrokerOffline:a})}t(x,"createViewerCapabilitiesForInput");function s({level:n}){return`Verbosity: ${f[n]} (${c.indexOf(n)+1}/${c.length})`}t(s,"verbosityName");function R(n){return n.atEnd?`${s(n)} \u2014 Ctrl+O again goes back to ${f[c[0]]}`:`${s(n)} \u2014 Ctrl+O shows more`}t(R,"moreDetailNotice");function T(n){return n.atEnd?`${s(n)}, the most collapsed level \u2014 Ctrl+O shows more`:`${s(n)} \u2014 Ctrl+O shows more`}t(T,"lessDetailNotice");function A(n,a,d,e){const{socket:w,tui:l,editor:m,containers:g}=n,{setNotice:i}=e,p=t(()=>e.send({type:"reload_auth"}),"reloadAuth"),y=d.permits("auth")?{openLoginPicker:t(()=>{const r=e.agentDir()??C();u.openAuthPicker(()=>I(l,r,p,o=>i(o)))},"openLoginPicker"),openLogoutPicker:t(()=>{const r=e.agentDir()??C();u.openAuthPicker(()=>M(r,p,o=>i(o)))},"openLogoutPicker")}:{},u=new D(l,m,a,{onCommand:e.send,onDialogResponse:e.send,onNotice:t(r=>i(r),"onNotice"),onGraph:e.toggleGraph,onInbox:e.toggleInbox,onHelp:e.toggleHelp,onNodeMetadata:e.openNodeMetadata,onQuit:e.quit,onCopy:t(()=>e.copyTarget("last-assistant"),"onCopy"),onCopyTarget:e.copyTarget,onToggleMouse:t(()=>{const r=e.toggleMouse();i(r?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"onToggleMouse"),onColor:e.setChipColor,onPromptSent:e.onPromptSent,onMessageSent:e.onMessageSent,whenBrokerReady:e.whenBrokerReady,frecency:e.frecency,knownRefNames:t(()=>m.getResolvedRefNames(),"knownRefNames"),onMoreDetail:t(()=>i(R(e.moreDetail())),"onMoreDetail"),onLessDetail:t(()=>i(T(e.lessDetail())),"onLessDetail"),onToggleThinking:t(()=>i(e.toggleThinking()?"Thinking blocks: hidden":"Thinking blocks: visible"),"onToggleThinking"),onRequest:t(r=>{const o=d.refusal("engine-drive");return o===void 0?w.request(r):Promise.reject(new Error(o))},"onRequest"),onMountPicker:t(r=>{g.pickerPanel.addChild(r),l.requestRender()},"onMountPicker"),onUnmountPicker:t(()=>{g.pickerPanel.clear(),l.requestRender()},"onUnmountPicker"),isDormant:e.isDormant,isStarting:e.isStarting,onDormantSubmit:d.permits("wake-dormant")?r=>{(async()=>{try{const o=await b().sendMessage(n.nodeId,{body:r,from:"human"});i(o.revived?"\u21BB waking node\u2026":"\u2709 delivered \u2014 node reads on next wake")}catch(o){i(`Couldn't wake node: ${o instanceof Error?o.message:String(o)}`)}})()}:void 0,...y},d);return u}t(A,"createInputController");export{A as createInputController,x as createViewerCapabilitiesForInput,T as lessDetailNotice,R as moreDetailNotice};