@north-light/cli 0.3.710 → 0.3.712

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 (115) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/clients/attach/input/controller.d.ts +1 -1
  4. package/dist/clients/attach/input/controller.js +2 -2
  5. package/dist/clients/attach/render/chat-view.d.ts +13 -2
  6. package/dist/clients/attach/render/chat-view.js +2 -2
  7. package/dist/clients/attach/session/input-wiring.d.ts +2 -2
  8. package/dist/clients/attach/session/layout-record.d.ts +4 -2
  9. package/dist/clients/attach/session/layout-record.js +1 -1
  10. package/dist/clients/attach/session/reconnect.d.ts +8 -1
  11. package/dist/clients/attach/session/reconnect.js +1 -1
  12. package/dist/clients/attach/slash/recover.js +3 -2
  13. package/dist/clients/attach/viewer.js +405 -404
  14. package/dist/commands/human/prompts.js +1 -1
  15. package/dist/commands/human/request.js +1 -1
  16. package/dist/commands/sys/doctor.js +1 -1
  17. package/dist/commands/sys/tutorial/scenario.js +2 -2
  18. package/dist/core/broker-client/client.d.ts +2 -0
  19. package/dist/core/broker-client/client.js +1 -1
  20. package/dist/core/broker-client/transport-relay.d.ts +6 -0
  21. package/dist/core/broker-client/transport-relay.js +1 -1
  22. package/dist/core/broker-client/transport.d.ts +4 -0
  23. package/dist/core/canvas/daemon-actions.d.ts +1 -1
  24. package/dist/core/canvas/daemon-actions.js +7 -7
  25. package/dist/core/canvas/deliveries.d.ts +1 -1
  26. package/dist/core/canvas/deliveries.js +21 -21
  27. package/dist/core/canvas/executions.d.ts +1 -1
  28. package/dist/core/canvas/executions.js +1 -1
  29. package/dist/core/canvas/reconciler-leases.d.ts +4 -0
  30. package/dist/core/canvas/reconciler-leases.js +5 -5
  31. package/dist/core/conversation-store/client.js +2 -2
  32. package/dist/core/conversation-store/index.d.ts +5 -2
  33. package/dist/core/conversation-store/row-store.js +14 -12
  34. package/dist/core/graph/package-docs.js +5 -5
  35. package/dist/core/graph/package-publish.js +4 -3
  36. package/dist/core/graph/reader.js +3 -3
  37. package/dist/core/human/requests.js +19 -19
  38. package/dist/core/import/load/run.js +2 -2
  39. package/dist/core/permissions/evaluator.js +2 -2
  40. package/dist/core/runtime/broker/client-registry.d.ts +1 -1
  41. package/dist/core/runtime/broker/client-registry.js +1 -1
  42. package/dist/core/runtime/broker/turn-replies.js +3 -1
  43. package/dist/core/runtime/broker-protocol.d.ts +4 -4
  44. package/dist/core/runtime/broker-protocol.js +3 -3
  45. package/dist/core/runtime/broker.js +1 -1
  46. package/dist/core/runtime/placement-tmux.d.ts +1 -0
  47. package/dist/core/runtime/placement-tmux.js +1 -1
  48. package/dist/core/runtime/session-cycles.d.ts +21 -0
  49. package/dist/core/runtime/session-cycles.js +1 -1
  50. package/dist/daemon/api/app-listener.js +1 -1
  51. package/dist/daemon/api/handlers/charges.d.ts +1 -1
  52. package/dist/daemon/api/handlers/charges.js +1 -1
  53. package/dist/daemon/api/handlers/conversations.js +4 -3
  54. package/dist/daemon/api/handlers/environments.d.ts +1 -1
  55. package/dist/daemon/api/handlers/environments.js +1 -1
  56. package/dist/daemon/api/handlers/limits.js +1 -1
  57. package/dist/daemon/api/handlers/nodes.js +1 -1
  58. package/dist/daemon/api/operations.js +1 -1
  59. package/dist/daemon/api/router.js +1 -1
  60. package/dist/daemon/cron/live-runs.d.ts +3 -0
  61. package/dist/daemon/cron/live-runs.js +1 -1
  62. package/dist/daemon/cron/machine-fire.js +1 -1
  63. package/dist/daemon/crtrd.js +12 -12
  64. package/dist/daemon/due-sources.d.ts +1 -1
  65. package/dist/daemon/due-sources.js +1 -1
  66. package/dist/daemon/due.js +7 -7
  67. package/dist/daemon/human/finish.js +3 -3
  68. package/dist/daemon/human/settle.js +1 -1
  69. package/dist/daemon/machine-daemon.js +1 -1
  70. package/dist/daemon/reconcilers/action-lane.js +1 -1
  71. package/dist/daemon/reconcilers/delivery-lane.js +2 -2
  72. package/dist/daemon/reconcilers/grant-effects.js +1 -1
  73. package/dist/daemon/reconcilers/node-lifecycle/requested-stops.js +2 -2
  74. package/package.json +4 -3
  75. package/packages/crouter-api/dist/api/contract.js +1 -1
  76. package/packages/crouter-api/dist/clients/attach/input/controller.js +2 -2
  77. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +40 -3
  78. package/packages/crouter-api/dist/clients/attach/session/layout-record.js +7 -7
  79. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +41 -2
  80. package/packages/crouter-api/dist/clients/attach/slash/recover.js +23 -1
  81. package/packages/crouter-api/dist/clients/attach/viewer.js +21 -10
  82. package/packages/crouter-api/dist/commands/human/prompts.js +11 -18
  83. package/packages/crouter-api/dist/commands/human/request.js +3 -0
  84. package/packages/crouter-api/dist/commands/sys/doctor.js +17 -0
  85. package/packages/crouter-api/dist/commands/sys/tutorial/scenario.js +1 -0
  86. package/packages/crouter-api/dist/core/broker-client/client.js +4 -0
  87. package/packages/crouter-api/dist/core/broker-client/transport-relay.js +45 -0
  88. package/packages/crouter-api/dist/core/canvas/daemon-actions.js +3 -2
  89. package/packages/crouter-api/dist/core/canvas/deliveries.js +7 -3
  90. package/packages/crouter-api/dist/core/canvas/executions.js +8 -7
  91. package/packages/crouter-api/dist/core/canvas/reconciler-leases.js +4 -0
  92. package/packages/crouter-api/dist/core/conversation-store/client.js +1 -1
  93. package/packages/crouter-api/dist/core/conversation-store/row-store.js +14 -1
  94. package/packages/crouter-api/dist/core/graph/package-docs.js +8 -3
  95. package/packages/crouter-api/dist/core/graph/package-publish.js +8 -1
  96. package/packages/crouter-api/dist/core/graph/reader.js +7 -1
  97. package/packages/crouter-api/dist/core/human/requests.js +2 -2
  98. package/packages/crouter-api/dist/core/permissions/evaluator.js +12 -6
  99. package/packages/crouter-api/dist/core/runtime/broker-protocol.js +4 -4
  100. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +2 -2
  101. package/packages/crouter-api/dist/core/runtime/session-cycles.js +90 -8
  102. package/packages/crouter-api/dist/daemon/api/operations.js +3 -3
  103. package/packages/crouter-api/dist/daemon/api/router.js +1 -4
  104. package/packages/crouter-api/dist/daemon/cron/live-runs.js +4 -5
  105. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +3 -3
  106. package/packages/crouter-api/dist/daemon/human/finish.js +2 -1
  107. package/packages/crouter-api/dist/daemon/human/settle.js +1 -6
  108. package/packages/crouter-api/package.json +1 -1
  109. package/packages/crouter-identity/package.json +1 -1
  110. package/packages/crouter-plugin/package.json +3 -3
  111. package/runtime.lock.json +14 -14
  112. package/scripts/install-runtime.mjs +18 -1
  113. package/scripts/lib/install-source.mjs +49 -0
  114. package/dist/daemon/reconcilers/idle-sandbox.d.ts +0 -18
  115. package/dist/daemon/reconcilers/idle-sandbox.js +0 -7
@@ -1,5 +1,5 @@
1
1
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
2
- export declare const CONTRACT_LEVEL = "1.68";
2
+ export declare const CONTRACT_LEVEL = "1.69";
3
3
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
4
4
  export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
5
5
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -1 +1 @@
1
- var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.68",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
1
+ var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.69",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
@@ -36,7 +36,7 @@ export interface InputControllerHooks {
36
36
  onPromptSent?: () => void;
37
37
  /** A new message (not a steer) left the editor; the viewer shows it pending
38
38
  * until the engine echoes it. */
39
- onMessageSent?: (text: string) => void;
39
+ onMessageSent?: (text: string, viaSocket: boolean) => void;
40
40
  /** Per-user completion frecency store — usage recorded here biases the sort
41
41
  * order the next time `/` completion opens. */
42
42
  frecency?: FrecencyStore;
@@ -1,7 +1,7 @@
1
- var l=Object.defineProperty;var n=(c,e)=>l(c,"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 d}from"../slash/dispatch.js";import{viewerOperationForFrame as b}from"./capabilities.js";import{readClipboardImage as T,writeClipboardImageToFile as I}from"./clipboard-image.js";import{InputOverlayOwner as D}from"./overlay-owner.js";import{announceFallbackEditor as E,NO_EDITOR_MESSAGE as M,resolveEditor as A}from"../../../core/editor-resolver.js";const q=500,B=v.maxLineBytes-4*1024*1024;class z{static{n(this,"InputController")}tui;editor;keybindings;hooks;capabilities;overlays;state;lastEscapeAt=0;pastedImages=new Map;pasteSeq=0;constructor(e,t,o,i,s){this.tui=e,this.editor=t,this.keybindings=o,this.hooks=i,this.capabilities=s,this.overlays=new D(e,t,o,{send:n(r=>this.emitCommand(r),"send"),notify:n(r=>this.notify(r),"notify"),onDialogResponse:i.onDialogResponse,onRequest:i.onRequest,onMountPicker:i.onMountPicker,onUnmountPicker:i.onUnmountPicker,state:n(()=>this.state,"state")}),this.wire()}cycleLadder(e){this.emitCommand({type:"cycle_ladder",direction:e})}sendInterrupting(e){return this.emitDrive({type:"prompt",text:e,interrupt:!0})}abortTurn(){return this.state?.isStreaming!==!0?!1:this.emitCommand({type:"abort"})}attachDialog(e){this.overlays.attachDialog(e)}dismissDialog(e){this.overlays.dismissDialog(e)}setState(e){this.state=e}openAuthPicker(e){return this.overlays.openAuthPicker(e)}send=n(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=b(e),o=t===void 0?void 0:this.capabilities.refusal(t);return o===void 0?(this.hooks.onCommand(e),!0):(this.notify(o),!1)}openBrokerPicker(e){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<q?(this.lastEscapeAt=0,this.openBrokerPicker(()=>{this.overlays.openTreePicker()})):this.lastEscapeAt=t},this.editor.onPasteImage=()=>{this.handlePaste()};const e=this.editor;e.onPasteImagePath=t=>(this.attachImage(t),!0),this.editor.onAction("app.session.new",()=>this.emitCommand({type:"new_session"})),this.editor.onAction("app.model.cycleForward",()=>this.emitCommand({type:"cycle_model",direction:"forward"})),this.editor.onAction("app.model.cycleBackward",()=>this.emitCommand({type:"cycle_model",direction:"backward"})),this.editor.onAction("app.thinking.cycle",()=>this.emitCommand({type:"cycle_thinking"})),this.editor.onAction("app.message.followUp",()=>this.handleFollowUp()),this.editor.onAction("app.message.dequeue",()=>{this.handleDequeue()}),this.editor.onAction("app.tools.expand",()=>this.hooks.onMoreDetail?.()),this.editor.onAction("app.thinking.toggle",()=>this.hooks.onToggleThinking?.()),this.editor.onAction("app.editor.external",()=>{this.openExternalEditor()}),this.editor.onAction("app.model.select",()=>this.openBrokerPicker(()=>{this.overlays.openModelPicker()})),this.editor.onAction("app.session.tree",()=>this.openBrokerPicker(()=>{this.overlays.openTreePicker()})),this.editor.onAction("app.session.fork",()=>this.openBrokerPicker(()=>{this.overlays.openForkPicker()})),this.editor.onAction("app.session.resume",()=>this.openBrokerPicker(()=>{this.overlays.openSessionPicker()}))}slashContext(){return{send:this.send,notify:n(e=>this.notify(e),"notify"),capabilities:this.capabilities,state:this.state,cwd:process.cwd(),onGraph:this.hooks.onGraph,onInbox:this.hooks.onInbox,onHelp:this.hooks.onHelp,onQuit:this.hooks.onQuit,onCopy:this.hooks.onCopy,onCopyTarget:this.hooks.onCopyTarget,onToggleMouse:this.hooks.onToggleMouse,onColor:this.hooks.onColor,onNodeMetadata:this.hooks.onNodeMetadata,onMoreDetail:this.hooks.onMoreDetail,onLessDetail:this.hooks.onLessDetail,openModelPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openModelPicker()}),"openModelPicker"),openSessionPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openSessionPicker()}),"openSessionPicker"),openForkPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openForkPicker()}),"openForkPicker"),openTreePicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openTreePicker()}),"openTreePicker"),openSettingsPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openSettingsPicker()}),"openSettingsPicker"),openScopedModelsPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openScopedModelsPicker()}),"openScopedModelsPicker"),openMcpPicker:n(e=>this.overlays.openMcpPicker(e),"openMcpPicker"),openLoginPicker:this.hooks.openLoginPicker,openLogoutPicker:this.hooks.openLogoutPicker}}recordCommandUse(e){const t=this.hooks.frecency;if(!t)return;const o=e.slice(1).split(/\s/,1)[0];o&&t.record(`command:${o}`)}recordCompletionUse(e){const t=this.hooks.frecency;if(!t)return;const o=e.trim();if(d(o)){this.recordCommandUse(o);return}const i=this.hooks.knownRefNames?.();if(!i||i.size===0)return;const s=new Set;for(const r of w(e))i.has(r.candidate)&&!s.has(r.candidate)&&(s.add(r.candidate),t.record(`ref:${r.candidate}`))}handleSubmit(e){const t=e.trim();if(!t||d(t)&&this.refuseStarting())return;if(d(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 h=this.expandImagePlaceholders(i.text);a(h),this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),this.hooks.onMessageSent?.(h),this.hooks.onPromptSent?.();return}if(i.kind==="bash"){if(!this.emitDrive({type:"bash",command:i.command,excludeFromContext:i.excludeFromContext}))return;this.editor.addToHistory(i.trimmed),this.editor.setText("");return}const s=i.kind==="slash"?this.state?.isStreaming===!0?"steer":"prompt":i.kind;if(s!=="steer"&&s!=="prompt")return;const r=this.expandImagePlaceholders(i.kind==="slash"?e:i.text);this.emitDrive(s==="steer"?{type:"steer",text:r}:{type:"prompt",text:r})&&(this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),s==="prompt"&&this.hooks.onMessageSent?.(r),this.hooks.onPromptSent?.())}handleFollowUp(){const e=this.editor.getText(),t=e.trim();t&&this.emitDrive({type:"follow_up",text:this.expandImagePlaceholders(e)})&&(this.editor.addToHistory(t),this.editor.setText(""),this.clearPastedImages())}async handleDequeue(){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 n=(c,e)=>p(c,"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 d}from"../slash/dispatch.js";import{viewerOperationForFrame as b}from"./capabilities.js";import{readClipboardImage as T,writeClipboardImageToFile as I}from"./clipboard-image.js";import{InputOverlayOwner as D}from"./overlay-owner.js";import{announceFallbackEditor as E,NO_EDITOR_MESSAGE as M,resolveEditor as A}from"../../../core/editor-resolver.js";const q=500,B=v.maxLineBytes-4*1024*1024;class z{static{n(this,"InputController")}tui;editor;keybindings;hooks;capabilities;overlays;state;lastEscapeAt=0;pastedImages=new Map;pasteSeq=0;constructor(e,t,o,i,s){this.tui=e,this.editor=t,this.keybindings=o,this.hooks=i,this.capabilities=s,this.overlays=new D(e,t,o,{send:n(r=>this.emitCommand(r),"send"),notify:n(r=>this.notify(r),"notify"),onDialogResponse:i.onDialogResponse,onRequest:i.onRequest,onMountPicker:i.onMountPicker,onUnmountPicker:i.onUnmountPicker,state:n(()=>this.state,"state")}),this.wire()}cycleLadder(e){this.emitCommand({type:"cycle_ladder",direction:e})}sendInterrupting(e){return this.emitDrive({type:"prompt",text:e,interrupt:!0})}abortTurn(){return this.state?.isStreaming!==!0?!1:this.emitCommand({type:"abort"})}attachDialog(e){this.overlays.attachDialog(e)}dismissDialog(e){this.overlays.dismissDialog(e)}setState(e){this.state=e}openAuthPicker(e){return this.overlays.openAuthPicker(e)}send=n(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=b(e),o=t===void 0?void 0:this.capabilities.refusal(t);return o===void 0?(this.hooks.onCommand(e),!0):(this.notify(o),!1)}openBrokerPicker(e){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<q?(this.lastEscapeAt=0,this.openBrokerPicker(()=>{this.overlays.openTreePicker()})):this.lastEscapeAt=t},this.editor.onPasteImage=()=>{this.handlePaste()};const e=this.editor;e.onPasteImagePath=t=>(this.attachImage(t),!0),this.editor.onAction("app.session.new",()=>this.emitCommand({type:"new_session"})),this.editor.onAction("app.model.cycleForward",()=>this.emitCommand({type:"cycle_model",direction:"forward"})),this.editor.onAction("app.model.cycleBackward",()=>this.emitCommand({type:"cycle_model",direction:"backward"})),this.editor.onAction("app.thinking.cycle",()=>this.emitCommand({type:"cycle_thinking"})),this.editor.onAction("app.message.followUp",()=>this.handleFollowUp()),this.editor.onAction("app.message.dequeue",()=>{this.handleDequeue()}),this.editor.onAction("app.tools.expand",()=>this.hooks.onMoreDetail?.()),this.editor.onAction("app.thinking.toggle",()=>this.hooks.onToggleThinking?.()),this.editor.onAction("app.editor.external",()=>{this.openExternalEditor()}),this.editor.onAction("app.model.select",()=>this.openBrokerPicker(()=>{this.overlays.openModelPicker()})),this.editor.onAction("app.session.tree",()=>this.openBrokerPicker(()=>{this.overlays.openTreePicker()})),this.editor.onAction("app.session.fork",()=>this.openBrokerPicker(()=>{this.overlays.openForkPicker()})),this.editor.onAction("app.session.resume",()=>this.openBrokerPicker(()=>{this.overlays.openSessionPicker()}))}slashContext(){return{send:this.send,notify:n(e=>this.notify(e),"notify"),capabilities:this.capabilities,state:this.state,cwd:process.cwd(),onGraph:this.hooks.onGraph,onInbox:this.hooks.onInbox,onHelp:this.hooks.onHelp,onQuit:this.hooks.onQuit,onCopy:this.hooks.onCopy,onCopyTarget:this.hooks.onCopyTarget,onToggleMouse:this.hooks.onToggleMouse,onColor:this.hooks.onColor,onNodeMetadata:this.hooks.onNodeMetadata,onMoreDetail:this.hooks.onMoreDetail,onLessDetail:this.hooks.onLessDetail,openModelPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openModelPicker()}),"openModelPicker"),openSessionPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openSessionPicker()}),"openSessionPicker"),openForkPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openForkPicker()}),"openForkPicker"),openTreePicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openTreePicker()}),"openTreePicker"),openSettingsPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openSettingsPicker()}),"openSettingsPicker"),openScopedModelsPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openScopedModelsPicker()}),"openScopedModelsPicker"),openMcpPicker:n(e=>this.overlays.openMcpPicker(e),"openMcpPicker"),openLoginPicker:this.hooks.openLoginPicker,openLogoutPicker:this.hooks.openLogoutPicker}}recordCommandUse(e){const t=this.hooks.frecency;if(!t)return;const o=e.slice(1).split(/\s/,1)[0];o&&t.record(`command:${o}`)}recordCompletionUse(e){const t=this.hooks.frecency;if(!t)return;const o=e.trim();if(d(o)){this.recordCommandUse(o);return}const i=this.hooks.knownRefNames?.();if(!i||i.size===0)return;const s=new Set;for(const r of w(e))i.has(r.candidate)&&!s.has(r.candidate)&&(s.add(r.candidate),t.record(`ref:${r.candidate}`))}handleSubmit(e){const t=e.trim();if(!t||d(t)&&this.refuseStarting())return;if(d(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 h=this.expandImagePlaceholders(i.text);a(h),this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),this.hooks.onMessageSent?.(h,!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 r=this.expandImagePlaceholders(i.kind==="slash"?e:i.text);this.emitDrive(s==="steer"?{type:"steer",text:r}:{type:"prompt",text:r})&&(this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),s==="prompt"&&this.hooks.onMessageSent?.(r,!0),this.hooks.onPromptSent?.())}handleFollowUp(){const e=this.editor.getText(),t=e.trim();t&&this.emitDrive({type:"follow_up",text:this.expandImagePlaceholders(e)})&&(this.editor.addToHistory(t),this.editor.setText(""),this.clearPastedImages())}async handleDequeue(){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
 
5
5
  `)),this.tui.requestRender(),this.notify(`Restored ${i.length} queued message${i.length>1?"s":""} to editor`)}emitDrive(e){try{const t=Buffer.byteLength(S(e));if(t>B)return this.notify(`Message too large to send (${Math.round(t/(1024*1024))} MiB) \u2014 shorten the text or remove an attached image`),!1}catch{return this.notify("Message could not be encoded"),!1}return this.emitCommand(e)}async handlePaste(){try{const e=await T();if(!e){this.notify("No image in the clipboard");return}if(!e.image){this.notify(e.note??"Image not pasted");return}this.attachImage(I(e.image),e.note)}catch{this.notify("Could not read the clipboard image")}}attachImage(e,t){const o=++this.pasteSeq;this.pastedImages.set(o,e);const i=this.editor.getText();this.editor.insertTextAtCursor(`${i&&!/\s$/.test(i)?" ":""}[Image #${o}] `),this.notify(t?`Image #${o} attached (${t})`:`Image #${o} attached`),this.tui.requestRender()}expandImagePlaceholders(e){return e.replace(/\[Image #(\d+)\]/g,(t,o)=>this.pastedImages.get(Number(o))??t)}clearPastedImages(){this.pastedImages.clear(),this.pasteSeq=0}async openExternalEditor(){const e=A();if(e===null){this.notify(M);return}const t=e.command,o=this.editor,i=P(y(),`crtr-attach-editor-${Date.now()}.pi.md`);try{g(i,o.getExpandedText?.()??this.editor.getText(),"utf-8"),this.tui.stop();const[s,...r]=t.split(" ");process.stdout.write(`Launching external editor: ${t}
6
6
  The viewer resumes when it exits.
7
- `),E(e);const a=await new Promise(h=>{const m=u(s,[...r,i],{stdio:"inherit",shell:process.platform==="win32"});m.on("error",()=>h(null)),m.on("close",p=>h(p))});a===null&&e.source==="fallback"&&this.notify(`Could not launch ${t} \u2014 set $EDITOR to an editor you have installed`),a===0&&this.editor.setText(f(i,"utf-8").replace(/\n$/,""))}catch(s){this.notify(`External editor failed: ${s instanceof Error?s.message:String(s)}`)}finally{try{k(i)}catch{}this.tui.start(),this.tui.requestRender(!0)}}notify(e){this.hooks.onNotice?.(e)}}export{z as InputController};
7
+ `),E(e);const a=await new Promise(h=>{const m=u(s,[...r,i],{stdio:"inherit",shell:process.platform==="win32"});m.on("error",()=>h(null)),m.on("close",l=>h(l))});a===null&&e.source==="fallback"&&this.notify(`Could not launch ${t} \u2014 set $EDITOR to an editor you have installed`),a===0&&this.editor.setText(f(i,"utf-8").replace(/\n$/,""))}catch(s){this.notify(`External editor failed: ${s instanceof Error?s.message:String(s)}`)}finally{try{k(i)}catch{}this.tui.start(),this.tui.requestRender(!0)}}notify(e){this.hooks.onNotice?.(e)}}export{z as InputController};
@@ -75,6 +75,9 @@ export declare class ChatView {
75
75
  * welcome snapshot rebuild never drops them. */
76
76
  private readonly pendingContainer;
77
77
  private readonly pendingSends;
78
+ /** True while the viewer is redialing a closed connection. */
79
+ private pendingUndelivered;
80
+ private undeliveredNote;
78
81
  /** Optional banner, above history and status in the viewport's flat source. */
79
82
  private readonly bannerContainer;
80
83
  /** Add one line to the banner after construction: a new root learns its id only when its create returns. */
@@ -326,8 +329,16 @@ export declare class ChatView {
326
329
  /** Complete and release the live bash component before ChatView gives up ownership. */
327
330
  private settleBashComponent;
328
331
  /** Show a message the person just sent as pending: gray text, no background,
329
- * until the engine echoes it as a user message. */
330
- addPendingSend(text: string): void;
332
+ * until the engine echoes it as a user message. `resend`: it went to the broker
333
+ * socket, so a reconnect sends it again when the fresh snapshot does not hold it. */
334
+ addPendingSend(text: string, resend?: boolean): void;
335
+ /** While the viewer redials, say under the pending messages that they were not delivered. */
336
+ setPendingUndelivered(on: boolean): void;
337
+ private refreshUndeliveredNote;
338
+ /** After a reconnect: the pending messages sent to the broker socket that the fresh snapshot holds neither as a user message nor in its queue, oldest first. */
339
+ unconfirmedSends(snapshot: BrokerSnapshot): string[];
340
+ /** The pending messages were handed to a parked node's wake message, so a reconnect must not send them again. */
341
+ stopResendingPendingSends(): void;
331
342
  /** The engine echoed a user message: the matching pending send landed. */
332
343
  private confirmPendingSend;
333
344
  /** A snapshot rebuild: drop pending sends whose text the history now holds. */
@@ -1,3 +1,3 @@
1
- var W=Object.defineProperty;var h=(a,t)=>W(a,"name",{value:t,configurable:!0});import{Container as $,Loader as q,Markdown as V,Spacer as p,Text as k}from"@earendil-works/pi-tui";import{AssistantMessageComponent as U,BashExecutionComponent as E,BranchSummaryMessageComponent as N,CompactionSummaryMessageComponent as z,CustomMessageComponent as O,parseSkillBlock as Y,SkillInvocationMessageComponent as K,ToolExecutionComponent as J,UserMessageComponent as R}from"@earendil-works/pi-coding-agent";import{attachMarkdownTheme as d}from"../config.js";import{ContextMessageComponent as I}from"./context-message.js";import{presentationFor as X}from"./card-presentation.js";import{detectInlinePageResult as Q,PageBlockComponent as Z}from"./page-block.js";import{CRTR_OUTPUT_CUSTOM_TYPE as tt,CrtrOutputMessageComponent as v,createCrtrBashToolDefinition as et}from"./crtr-output.js";import{endedByAbort as A}from"../../../core/runtime/session-cycles.js";import{isHumanWordsEntry as D,parseCard as st}from"../../../shared/generated-context.js";import{assistantVisibleText as c,isGroupBoundaryKind as it,isTrueUserMessage as g}from"../../../shared/tool-groups.js";import{messageKey as P,normalizeTurnReplyRecord as nt,START_TURN_KEY as ot,turnReplyText as rt}from"../../../shared/turn-replies.js";import{transformDiagramFences as at}from"./diagram.js";import{styleAttachAgentMarkdown as ht,styleAttachMarkdownSource as j,styleAttachMessageMarkdown as lt,styleAttachSummaryMarkdown as F}from"./markdown-source.js";import{createCrtrEditToolDefinition as pt}from"./edit-diff.js";import{GroupActivityRecorder as dt}from"./group-activity.js";import{GroupRecapComponent as ct}from"./group-recap.js";import{FoldedToolCallController as ut,bashCallBackgroundHintLines as mt,createCrtrPlainBashToolDefinition as ft,createCrtrReadToolDefinition as gt,createCrtrWriteToolDefinition as yt}from"./tool-calls.js";import{ringCompletionBell as Ct}from"../chrome/completion-bell.js";import{extractFilePaths as Tt}from"../../../core/human/visible-paths.js";import{extractDocRefs as kt}from"./doc-links.js";import{ViewerAssistantMessageComponent as x}from"./assistant-message.js";import{CompositeViewportSource as bt,MeasuredContainer as w}from"./measured-container.js";import{readConfig as _}from"../../../core/config.js";import{DEFAULT_VERBOSITY as xt,VERBOSITY_LEVELS as u}from"../../../types.js";import{applySnapshot as wt,applyToolGroupSummary as St,applyWorkingActivity as Rt,bashEnd as At,bashOutput as Bt,bashStart as Mt,initialConvState as Gt,reduce as Et}from"../../conversation/projection.js";const H=h(a=>`\x1B[2m${a}\x1B[22m`,"defaultDimStyle"),Ot=50;function It(){try{return _("user").verbosity}catch{return xt}}h(It,"readVerbosity");function vt(){try{return _("user").detailed_tool_recaps}catch{return!0}}h(vt,"readDetailedToolRecaps");function Dt(a){return typeof a=="object"&&a!==null&&"setExpanded"in a&&typeof a.setExpanded=="function"}h(Dt,"isExpandable");const Pt=/\x1b\[[0-9;]*m/g,jt=/\x1b\[([0-9;]*)m/g;function Ft(a){return a.replace(jt,(t,e)=>{const s=e.split(";"),i=[];for(let n=0;n<s.length;n++){const r=Number(s[n]===""?0:s[n]);if(r===38||r===48||r===58){const o=Number(s[n+1]),l=n+(o===5?2:o===2?4:1);r!==48&&i.push(...s.slice(n,l+1)),n=l;continue}r>=40&&r<=47||r>=100&&r<=107||i.push(String(r))}return i.length>0?`\x1B[${i.join(";")}m`:""})}h(Ft,"stripBackground");const _t=/<from\b[^>]*>[\s\S]*?<\/from>/g;class B extends 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 ${static{h(this,"WorkingRow")}label=new k("",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),...mt(this.foldController?.callComponent(),t)];const e=this.foldController?.callComponent();return e?e.render(t).filter(s=>s.replace(Pt,"").trim().length>0).map(s=>Ft(s).trimEnd()):super.render(t)}}const Lt=h(a=>`\x1B[31m${a}\x1B[39m`,"defaultErrorStyle"),Wt={accent:h(a=>`\x1B[33m${a}\x1B[39m`,"accent"),active:h(a=>`\x1B[36m${a}\x1B[39m`,"active"),info:h(a=>`\x1B[34m${a}\x1B[39m`,"info"),muted:H,faint:H,border:h(a=>a,"border"),surface:h(a=>a,"surface"),bold:h(a=>`\x1B[1m${a}\x1B[22m`,"bold"),error:Lt,warning:h(a=>`\x1B[33m${a}\x1B[39m`,"warning"),diffAdded:h(a=>`\x1B[32m${a}\x1B[39m`,"diffAdded"),diffRemoved:h(a=>`\x1B[91m${a}\x1B[39m`,"diffRemoved"),bashMode:h(a=>`\x1B[32m${a}\x1B[39m`,"bashMode"),bashModeAlt:h(a=>`\x1B[92m${a}\x1B[39m`,"bashModeAlt")};class me{static{h(this,"ChatView")}tui;container;historyContainer=new w;statusContainer=new w;pendingContainer=new w;pendingSends=[];bannerContainer;setBannerHint(t){const e=this.bannerContainer;e!==void 0&&(e.removeChild(e.children[e.children.length-1]),e.addChild(new k(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=vt();groups=[];openGroup;turnReplies=new Map;turns=[];openReplyTurn;outsideTurns=0;turnHidden=new Set;lastReplyText;groupSummaries=new Map;nodeRoster=new Map;streamingWasGroupMember=!1;onFooterEvent;onActivityChange;spinnerStyle;dimStyle;errorStyle;recapPalette;labelStyle=h(t=>`\x1B[1m${t}\x1B[22m`,"labelStyle");markdownTransformers=[(t,{messageType:e,availableWidth:s})=>e==="assistant"?at(t,s):t,(t,{messageType:e})=>e==="user"?j(t):ht(t)];streamingComponent;streamingToolSeparator;foldedToolSeparatorContents=new Map;pendingTools=new Map;bashComponent;activityLoader;projection=Gt();workingActivity=this.projection.workingActivity;runActive=!1;applyingSnapshot=!1;snapshotGeneration=0;deferredFrames=[];lastAssistantText;transcriptFilePaths=[];transcriptDocRefs=[];copyBlockRecords=[];copyIndex=new Map;constructor(t,e,s={}){if(this.tui=t,this.container=e,this.cwd=s.cwd??process.cwd(),this.showImages=s.showImages??!0,this.imageWidthCells=s.imageWidthCells??60,this.hideThinking=s.hideThinking??!1,this.hiddenThinkingLabel=s.hiddenThinkingLabel??"Thinking...",this.level=s.verbosity??It(),this.onFooterEvent=s.onFooterEvent,this.onActivityChange=s.onActivityChange,this.inlinePageBlocks=s.inlinePageBlocks??!1,this.pageOpenHint=s.pageOpenHint??(()=>"crtr human list"),this.backgroundBashHint=s.backgroundBashHint??(()=>null),this.recapPalette=s.palette??Wt,this.spinnerStyle=this.recapPalette.active,this.dimStyle=this.recapPalette.muted,this.errorStyle=this.recapPalette.error,s.banner&&s.banner.length>0){const i=new w;i.addChild(new p(1));for(const n of s.banner)i.addChild(new k(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[r,o]of Object.entries(nt(t.turnReplies)))this.turnReplies.set(r,o);const s=new Map,i=this.projection.messages,n=i.length-1;for(let r=0;r<i.length;r++){if(!this.projection.isStreaming&&r>0&&r%Ot===0&&(await new Promise(l=>setImmediate(l)),e!==this.snapshotGeneration))return;const o=i[r];if(o.role==="assistant"){const l=c(o);l.trim()&&(this.lastAssistantText=l,this.pushTranscriptText(l));const G=r===n&&this.projection.isStreaming&&o.stopReason!=="aborted"&&o.stopReason!=="error",y=c(o).trim()!=="",L=this.assistantToolCalls(o),C=o.stopReason==="aborted"||o.stopReason==="error",T=A(o)?"Interrupted":o.errorMessage??"Error";if(C){for(const m of s.values()){const f={content:[{type:"text",text:T}],isError:!0};m.updateResult(f),this.registerCopyBlock(m,"tool",T),this.settleGroupTool(m,f,!0)}s.clear()}(y||C)&&this.closeOpenGroup();let b;G?(this.streamingComponent=new x(void 0,this.hideThinking,d(),this.hiddenThinkingLabel,this.markdownTransformers),this.appendAssistantPart(this.streamingComponent,!y),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingWasGroupMember=!y,this.streamingComponent.updateContent(o),this.registerCopyBlock(this.streamingComponent,"assistant",c(o)),b=this.streamingToolSeparator=this.appendAssistantSeparator(!y)):b=this.appendAssistantMessage(o,!y&&!C),b&&this.setAssistantSeparatorContent(b,o);for(const m of L){this.pushTranscriptValue(m.arguments);const f=this.appendToolComponent(m.name,m.id,m.arguments);o.stopReason==="aborted"||o.stopReason==="error"?(f.updateResult({content:[{type:"text",text:T}],isError:!0}),this.registerCopyBlock(f,"tool",T),this.settleGroupTool(f,{content:[{type:"text",text:T}],isError:!0},!0)):s.set(m.id,f)}C&&this.closeOpenGroup(),!G&&!C&&this.recordTurnProse(o,!1)}else if(o.role==="toolResult"){this.pushTranscriptText(this.userMessageText(o));const l=s.get(o.toolCallId);l&&(l.updateResult(o),this.registerCopyBlock(l,"tool",this.toolResultText(o)),this.historyContainer.markDirty(l),this.settleGroupTool(l,o,o.isError===!0),s.delete(o.toolCallId),this.maybeAppendPageBlock(o))}else this.addMessageToChat(o)}for(const[r,o]of s)this.pendingTools.set(r,o);for(const r of this.turns)this.refreshTurn(r);this.confirmPendingSendsIn(i),this.applyToolDisplay(),this.projection.isStreaming&&this.setActivity(this.makeLoader(this.workingActivity)),this.tui.requestRender(),this.applyingSnapshot=!1,this.replayDeferredFrames()}deferIfBuilding(t){return this.applyingSnapshot?(this.deferredFrames.push(t),!0):!1}replayDeferredFrames(){const t=this.deferredFrames.splice(0);for(const e of t)e()}setWorkingActivity(t){if(this.deferIfBuilding(()=>this.setWorkingActivity(t)))return;const e=this.projection.activity===this.workingActivity;this.projection=Rt(this.projection,t),this.workingActivity=this.projection.workingActivity,this.runActive&&e&&this.setActivity(this.makeLoader(this.workingActivity))}settleRun(){this.runActive=!1;for(const t of this.pendingTools.values())this.settleGroupTool(t);if(this.streamingComponent){this.historyContainer.removeChild(this.streamingComponent);for(const t of this.turns)t.members.delete(this.streamingComponent);this.turnHidden.delete(this.streamingComponent),this.unregisterCopyBlock(this.streamingComponent),this.streamingComponent=void 0}this.streamingToolSeparator=void 0,this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay(),this.setActivity(void 0),this.settleBashComponent()}dispose(){this.settleRun()}moreDetail(){const t=u.indexOf(this.level);return this.setLevel(u[(t+1)%u.length]),{level:this.level,atEnd:this.level===u.at(-1)}}lessDetail(){const t=u.indexOf(this.level);return this.setLevel(u[Math.max(0,t-1)]),{level:this.level,atEnd:this.level===u[0]}}setLevel(t){this.level=t;for(const e of this.turns)this.refreshTurn(e);this.applyToolDisplay()}repliesOnly(){return this.level==="replies"}foldsSettledTools(){return u.indexOf(this.level)<=u.indexOf("tools")}showsGroupSummaries(){return u.indexOf(this.level)<=u.indexOf("summaries")}toolOutputExpanded(){return this.level==="full"}applyToolDisplay(){const t=new Set(this.pendingTools.values());for(const i of this.groups)for(const n of i.inFlight)t.add(n);for(const i of this.historyContainer.children)i instanceof S&&i.setMinimized(this.foldsSettledTools()&&!t.has(i)),Dt(i)&&i.setExpanded(this.toolOutputExpanded());const e=this.turnFoldedComponents(t),s=new Set;for(const i of this.groups){this.applyGroupDisplay(i,e),s.add(i.recap);for(const n of i.members)s.add(n)}for(const i of this.turnHidden)!e.has(i)&&!s.has(i)&&this.historyContainer.setHidden(i,!1);for(const i of e)!s.has(i)&&!this.historyContainer.hiddenChildren.has(i)&&this.historyContainer.setHidden(i,!0);this.turnHidden=e,this.applyInboxExchangeDisplay(),this.updateFoldedToolSeparators(t),this.historyContainer.markDirty(),this.tui.requestRender()}hidesInboxExchange(){return this.showsGroupSummaries()}applyInboxExchangeDisplay(){const t=this.hidesInboxExchange();for(const e of this.inboxAnswers)this.historyContainer.setHidden(e,t);for(const e of this.pageBlocks.values())this.historyContainer.setHidden(e,e.settled)}applyTurnReply(t,e){if(!this.deferIfBuilding(()=>this.applyTurnReply(t,e))){this.turnReplies.set(t,e);for(const s of this.turns)s.key===t&&this.refreshTurn(s);this.tui.requestRender()}}turnFoldedComponents(t){const e=new Set;if(!this.repliesOnly())return e;for(const s of this.turns){const i=s===this.openReplyTurn;for(const n of s.members)i&&(n===this.streamingComponent||n===this.streamingToolSeparator||n===this.bashComponent||t.has(n))||e.add(n)}return e}beginTurn(t,e=[]){const s=new x(void 0,this.hideThinking,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(ot)}recordTurnProse(t,e){if(t.role!=="assistant"||t.stopReason==="aborted"||t.stopReason==="error")return;const s=c(t).trim(),i=P(t);if(s===""||i===void 0)return;const n=this.currentTurn();n.prose.some(r=>r.key===i)||(n.prose.push({key:i,text:s}),e&&this.refreshTurn(n))}refreshTurn(t){const e=rt(t.prose,this.turnReplies.get(t.key));t.reply.updateContent(this.replyMessage(e)),this.historyContainer.setHidden(t.reply,e===""||!this.repliesOnly()),this.historyContainer.markDirty(t.reply),this.registerCopyBlock(t.reply,"assistant",e),e!==""&&t===this.turns.at(-1)&&(this.lastReplyText=e),this.refreshWorkingRow(t)}refreshWorkingRow(t){let e=0,s=0;for(const l of t.members)l instanceof S?e++:(l instanceof I||l instanceof O||l instanceof v)&&s++;const i=t.prose.length,n=e>0||s>0||i>1,r=[i>0?M(i,"message","messages"):void 0,e>0?M(e,"tool call","tool calls"):void 0,s>0?M(s,"card","cards"):void 0].filter(l=>l!==void 0),o=this.runActive&&t===this.openReplyTurn;t.working.setLabel(this.dimStyle(`\u25B8 ${o?"working \u2014 ":""}${r.join(" \xB7 ")}`)),this.historyContainer.setHidden(t.working,!n||!this.repliesOnly()),this.historyContainer.markDirty(t.working)}replyMessage(t){return{role:"assistant",content:t===""?[]:[{type:"text",text:t}],stopReason:"stop"}}toggleThinking(){this.hideThinking=!this.hideThinking;for(const t of this.historyContainer.children)t instanceof U&&t.setHideThinkingBlock(this.hideThinking);for(const[t,e]of this.foldedToolSeparatorContents)t.setSeparatesToolGroup(e.hasText||!this.hideThinking&&e.hasThinking);return this.historyContainer.markDirty(),this.tui.requestRender(),this.hideThinking}handleEvent(t){if(!this.deferIfBuilding(()=>this.handleEvent(t))){switch(this.projection=Et(this.projection,t),t.type){case"agent_start":{this.runActive=this.projection.isStreaming;for(const e of this.pendingTools.values())this.settleGroupTool(e);this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.setActivity(this.makeLoader(this.workingActivity));break}case"agent_end":{this.settleRun(),Ct();break}case"agent_settled":{this.settleRun();break}case"message_start":{if(t.message.role==="user"&&g(t.message)&&this.confirmPendingSend(this.userMessageText(t.message).trim()),t.message.role==="custom"||t.message.role==="user")this.addMessageToChat(t.message),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();else if(t.message.role==="assistant"){const e=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 r of this.pendingTools.values())r.updateResult({content:[{type:"text",text:n}],isError:!0}),this.registerCopyBlock(r,"tool",n),this.settleGroupTool(r,{content:[{type:"text",text:n}],isError:!0},!0),this.historyContainer.markDirty(r);this.pendingTools.clear()}else for(const n of this.pendingTools.values())n.setArgsComplete(),this.historyContainer.markDirty(n);this.historyContainer.markDirty(this.streamingComponent),this.streamingComponent=void 0,this.streamingToolSeparator=void 0}e&&(this.closeOpenGroup(),this.applyToolDisplay()),this.recordTurnProse(t.message,!0),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();break}case"tool_execution_start":{this.pushTranscriptValue(t.args);let e=this.pendingTools.get(t.toolCallId);e?this.noteGroupTool(e,t.toolName,t.args):(e=this.appendToolComponent(t.toolName,t.toolCallId,t.args),this.pendingTools.set(t.toolCallId,e)),e.markExecutionStarted(),this.historyContainer.markDirty(e);break}case"tool_execution_update":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.partialResult;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e,!0),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.historyContainer.markDirty(s));break}case"tool_execution_end":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.result;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.pendingTools.delete(t.toolCallId),this.settleGroupTool(s,e,t.isError),this.applyToolDisplay(),this.historyContainer.markDirty(s),this.maybeAppendPageBlock(e));break}case"compaction_start":{const e=t.reason==="manual"?"Compacting context...":"Auto-compacting...";this.setActivity(this.makeLoader(e));break}case"compaction_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.aborted?this.showStatus(t.reason==="manual"?"Compaction cancelled":"Auto-compaction cancelled"):t.result?this.addMessageToChat({role:"compactionSummary",summary:t.result.summary,tokensBefore:t.result.tokensBefore,timestamp:Date.now()}):t.errorMessage&&this.showError(t.errorMessage);break}case"auto_retry_start":{const e=Math.ceil(t.delayMs/1e3);this.setActivity(this.makeLoader(`Retrying (${t.attempt}/${t.maxAttempts}) in ${e}s...`));break}case"auto_retry_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.success||this.showError(`Retry failed after ${t.attempt} attempts: ${t.finalError??"Unknown error"}`);break}case"queue_update":case"session_info_changed":case"thinking_level_changed":this.onFooterEvent?.(t);break;default:break}this.tui.requestRender()}}bashStart(t,e){if(this.deferIfBuilding(()=>this.bashStart(t,e)))return;this.projection=Mt(this.projection,t,e),this.closeOpenGroup(),this.settleBashComponent();let s;s=new E(t,this.componentTui(()=>s),e),this.bashComponent=s,this.append(s),this.tui.requestRender()}bashOutput(t){this.deferIfBuilding(()=>this.bashOutput(t))||(this.projection=Bt(this.projection,t),this.pushTranscriptText(t),this.bashComponent&&(this.bashComponent.appendOutput(t),this.historyContainer.markDirty(this.bashComponent)),this.tui.requestRender())}bashEnd(t){this.deferIfBuilding(()=>this.bashEnd(t))||(this.projection=At(this.projection,t),this.settleBashComponent(t),this.tui.requestRender())}addMessageToChat(t){const e=st(t);if(e!==null&&(t.role!=="custom"||t.display===!0)){this.pushTranscriptText(e.body);const s=e.senders.flatMap(n=>n.entries).filter(D).map(n=>n.body.trim()).filter(n=>n!=="");if(!(s.length>0&&e.body.replace(_t,"").trim()===""&&e.senders.every(n=>n.entries.every(D)))){const n=X(e.kind),r=new I(e,n,this.toolOutputExpanded(),this.dimStyle,o=>this.spinnerStyle(this.labelStyle(o)));it(e.kind)?(this.closeOpenGroup(),this.append(r)):this.appendGroupMember(r)?.activity.noteCard(e,n)}for(const n of s)this.appendHumanAnswer(n);return}switch(t.role){case"bashExecution":{this.closeOpenGroup(),this.pushTranscriptText(t.output??"");const s=new E(t.command,this.tui,t.excludeFromContext);t.output&&s.appendOutput(t.output),s.setComplete(t.exitCode,t.cancelled,t.truncated?{truncated:!0}:void 0,t.fullOutputPath),this.append(s);break}case"custom":{if(t.display){if(this.pushTranscriptText(this.userMessageText(t)),t.customType===tt){this.appendGroupMember(new v(this.userMessageText(t),this.toolOutputExpanded(),this.crtrOutputTheme()));break}const s=new O(lt(t),void 0,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 N(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(P(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 r=this.makeToolComponent(t,e,s);return r.activityCallId=e,this.appendGroupMember(r),this.registerCopyBlock(r,"tool",""),n&&(n.key??=e,n.toolCount++,n.inFlight.add(r),n.activity.noteCall(e,t,s)),r}noteGroupTool(t,e,s){if(t.activityCallId)for(const i of this.groups)i.members.includes(t)&&i.activity.noteCall(t.activityCallId,e,s)}settleGroupTool(t,e,s=!1){for(const i of this.groups)i.inFlight.delete(t),!(!t.activityCallId||!i.members.includes(t))&&(e===void 0?i.activity.resolveWithoutResult(t.activityCallId):i.activity.settle(t.activityCallId,e,s))}promoteStreamingAssistantToBoundary(t,e=!1){!this.streamingWasGroupMember||!e&&c(t).trim()===""||(this.streamingComponent&&this.removeGroupMember(this.streamingComponent),this.streamingToolSeparator&&this.removeGroupMember(this.streamingToolSeparator),this.streamingWasGroupMember=!1,this.closeOpenGroup())}seedToolGroupSummaries(t){this.groupSummaries.clear();for(const[e,s]of Object.entries(t))this.groupSummaries.set(e,s)}applyToolGroupSummary(t,e){if(this.deferIfBuilding(()=>this.applyToolGroupSummary(t,e)))return;this.projection=St(this.projection,t,e);const s=this.projection.toolGroupSummaryDetails[t];s!==void 0&&(this.groupSummaries.set(t,s),this.applyToolDisplay())}applyGroupDisplay(t,e){const s=t.key===void 0?void 0:this.groupSummaries.get(t.key),i=this.showsGroupSummaries()&&t.toolCount>0&&t.inFlight.size===0&&s!==void 0;t.recap.setRecap(i?s:void 0,t.toolCount,t.activity.activity(),this.detailedToolRecaps,this.recapPalette),this.historyContainer.setHidden(t.recap,!i||e.has(t.recap));for(const n of t.members)this.historyContainer.setHidden(n,i||e.has(n))}updateFoldedToolSeparators(t=new Set(this.pendingTools.values())){const e=this.historyContainer.children;for(let s=0;s<e.length;s++){const i=e[s];if(!(i instanceof B))continue;const n=e[s+1];i.setFolded(this.foldsSettledTools()&&!this.historyContainer.hiddenChildren.has(i)&&n instanceof S&&!this.historyContainer.hiddenChildren.has(n)&&!t.has(n)),this.historyContainer.markDirty(i)}}setAssistantSeparatorContent(t,e){const s=e.content,i=Array.isArray(s)?s:[],n=i.some(o=>typeof o=="object"&&o!==null&&o.type==="text"&&typeof o.text=="string"&&o.text.trim()!==""),r=i.some(o=>typeof o=="object"&&o!==null&&o.type==="thinking"&&typeof o.thinking=="string"&&o.thinking.trim()!=="");this.foldedToolSeparatorContents.set(t,{hasText:n,hasThinking:r}),t.setSeparatesToolGroup(n||!this.hideThinking&&r)}makeToolComponent(t,e,s){const i=new ut;let n,r;if(t==="bash"){const l=et(s,i);l===void 0?r=ft(this.cwd,i,this.backgroundBashHint):r=l.definition}else if(t==="edit"){const l=pt(this.cwd,i);r=l.definition,n=l.observeResult}else t==="read"?r=gt(this.cwd,i):t==="write"&&(r=yt(this.cwd,i));let o;return o=new S(t,e,s,{showImages:this.showImages,imageWidthCells:this.imageWidthCells},r,this.componentTui(()=>o),this.cwd),o.setToolView(r===void 0?void 0:i,n),o.setExpanded(this.toolOutputExpanded()),o}append(t){if(this.outsideTurns===0){const e=this.currentTurn();this.historyContainer.addChild(t),e.members.add(t);return}this.historyContainer.addChild(t)}chatChildCount(){return this.historyContainer.children.length}resetChat(){this.setActivity(void 0),this.settleBashComponent(),this.streamingComponent=void 0,this.streamingToolSeparator=void 0,this.streamingWasGroupMember=!1,this.foldedToolSeparatorContents.clear(),this.groups.length=0,this.openGroup=void 0,this.turns.length=0,this.openReplyTurn=void 0,this.turnHidden=new Set,this.lastReplyText=void 0,this.groupSummaries.clear(),this.nodeRoster.clear(),this.pendingTools.clear(),this.lastAssistantText=void 0,this.copyBlockRecords.length=0,this.copyIndex.clear(),this.transcriptFilePaths.length=0,this.transcriptDocRefs.length=0,this.pageBlocks.clear(),this.inboxAnswers.clear(),this.historyContainer.clear()}maybeAppendPageBlock(t){if(!this.inlinePageBlocks)return;const e=Q(t);if(e===void 0||this.pageBlocks.has(e.pageId))return;const s=new Z(e.pageId,this.pageOpenHint);this.pageBlocks.set(e.pageId,s),this.outsideTurns++;try{this.append(s)}finally{this.outsideTurns--}this.loadPageBlock(s)}async loadPageBlock(t){await t.refresh()&&(this.historyContainer.setHidden(t,t.settled),this.historyContainer.markDirty(t),this.tui.requestRender())}refreshInFlightTools(){if(this.pendingTools.size!==0){for(const t of this.pendingTools.values())this.historyContainer.markDirty(t);this.tui.requestRender()}}async refreshPageBlocks(){if(this.pageRefresh)return;const t=[...this.pageBlocks.values()].filter(s=>!s.settled);this.pageRefresh=!0,(await Promise.all(t.map(async s=>{const i=await s.refresh();return i&&(this.historyContainer.setHidden(s,s.settled),this.historyContainer.markDirty(s)),i})).finally(()=>{this.pageRefresh=!1})).some(Boolean)&&this.tui.requestRender()}makeLoader(t){let e;const s={requestRender:h(i=>{e&&!this.onActivityChange&&this.statusContainer.markDirty(e),this.tui.requestRender(i)},"requestRender"),terminal:this.tui.terminal};return e=new q(s,this.spinnerStyle,this.dimStyle,t),e}componentTui(t){return{requestRender:h(e=>{this.historyContainer.markDirty(t()),this.tui.requestRender(e)},"requestRender"),terminal:this.tui.terminal}}settleBashComponent(t){if(!this.bashComponent)return;const e=this.bashComponent;e.setComplete(t?.exitCode,t?.cancelled??!0,t?.truncated?{truncated:!0}:void 0,t?.fullOutputPath),this.historyContainer.markDirty(e),this.bashComponent=void 0}addPendingSend(t){const e=t.trim();if(!e)return;const s=[new p(1),new V(e,1,1,d(),{color:this.dimStyle})];for(const i of s)this.pendingContainer.addChild(i);this.pendingSends.push({text:e,parts:s}),this.tui.requestRender()}confirmPendingSend(t){const e=this.pendingSends.findIndex(n=>n.text===t),s=e>=0?e:0;if(this.pendingSends.length===0)return;const[i]=this.pendingSends.splice(s,1);for(const n of i.parts)this.pendingContainer.removeChild(n)}confirmPendingSendsIn(t){if(this.pendingSends.length===0)return;const e=new Set;for(const s of t.slice(-50))s.role==="user"&&e.add(this.userMessageText(s).trim());for(const s of[...this.pendingSends])if(e.has(s.text)){this.pendingSends.splice(this.pendingSends.indexOf(s),1);for(const i of s.parts)this.pendingContainer.removeChild(i)}}setActivity(t){if(this.activityLoader?.stop(),this.activityLoader=t,this.onActivityChange){this.onActivityChange(t);return}this.statusContainer.clear(),t&&this.statusContainer.addChild(t)}showStatus(t){this.closeOpenGroup(),this.append(new p(1)),this.append(new k(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 k(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 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(`
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 r=[...s,...this.transcriptDocRefs.filter(o=>!s.includes(o))].slice(0,50);this.transcriptDocRefs.splice(0,this.transcriptDocRefs.length,...r)}const i=Tt([e],this.cwd);if(i.length===0)return;const n=[...i,...this.transcriptFilePaths.filter(r=>!i.includes(r))].slice(0,50);this.transcriptFilePaths.splice(0,this.transcriptFilePaths.length,...n)}pushTranscriptValue(t){try{const e=typeof t=="string"?t:JSON.stringify(t);typeof e=="string"&&this.pushTranscriptText(e)}catch{}}userMessageText(t){const e=t.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(s=>typeof s=="object"&&s!==null&&s.type==="text").map(s=>s.text).join(""):""}}export{me as ChatView};
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};
@@ -41,8 +41,8 @@ export interface InputWiringHooks {
41
41
  setChipColor: (color: string | null) => void;
42
42
  /** A prompt or steer was accepted from the editor. */
43
43
  onPromptSent: () => void;
44
- /** A new message left the editor; show it pending until echoed. */
45
- onMessageSent: (text: string) => void;
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
+ onMessageSent: (text: string, viaSocket: boolean) => void;
46
46
  /** Send a frame to the broker; before the broker's first welcome the viewer holds it. */
47
47
  send: (frame: ClientToBroker) => void;
48
48
  /** True while the node is still being created: only plain messages, `!` commands and follow-ups are accepted (held until the welcome). */
@@ -6,8 +6,10 @@ export interface LayoutRecord {
6
6
  paneIndex: number;
7
7
  cwd: string;
8
8
  pane: string;
9
+ /** The cloud canvas a remote viewer attached over (`--canvas`); absent for a node on this Mac. */
10
+ canvas?: string;
9
11
  }
10
- export declare function writeLayoutRecord(nodeId: string, pane: string | undefined, cwd: string): void;
12
+ export declare function writeLayoutRecord(nodeId: string, pane: string | undefined, cwd: string, canvas?: string): void;
11
13
  /** Delete this node's record unless another viewer pane has since claimed it. */
12
- export declare function removeLayoutRecord(nodeId: string, pane: string | undefined): void;
14
+ export declare function removeLayoutRecord(nodeId: string, pane: string | undefined, canvas?: string): void;
13
15
  export declare function readLayoutRecords(): LayoutRecord[];
@@ -1 +1 @@
1
- var f=Object.defineProperty;var t=(r,e)=>f(r,"name",{value:e,configurable:!0});import{mkdirSync as a,readdirSync as m,readFileSync as s,rmSync as y,writeFileSync as w}from"node:fs";import{join as c}from"node:path";import{runtimeRoot as p}from"../../../core/layout.js";import{paneCoordinates as h}from"../../../core/runtime/placement-tmux.js";function i(){return c(p(),"viewer-panes")}t(i,"recordsDir");function u(r){return c(i(),`${r}.json`)}t(u,"recordPath");function j(r,e,n){if(e===void 0||e==="")return;const o=h(e);if(o===null)return;const d={nodeId:r,session:o.session,windowIndex:o.windowIndex,windowName:o.windowName,paneIndex:o.paneIndex,cwd:n,pane:e};try{a(i(),{recursive:!0}),w(u(r),JSON.stringify(d))}catch{}}t(j,"writeLayoutRecord");function v(r,e){try{const n=JSON.parse(s(u(r),"utf8"));(e===void 0||n.pane===e)&&y(u(r),{force:!0})}catch{}}t(v,"removeLayoutRecord");function J(){let r;try{r=m(i())}catch{return[]}const e=[];for(const n of r)if(n.endsWith(".json"))try{e.push(JSON.parse(s(c(i(),n),"utf8")))}catch{}return e}t(J,"readLayoutRecords");export{J as readLayoutRecords,v as removeLayoutRecord,j as writeLayoutRecord};
1
+ var m=Object.defineProperty;var t=(e,r)=>m(e,"name",{value:r,configurable:!0});import{mkdirSync as a,readdirSync as y,readFileSync as f,rmSync as p,writeFileSync as w}from"node:fs";import{join as u}from"node:path";import{runtimeRoot as h}from"../../../core/layout.js";import{paneCoordinates as S}from"../../../core/runtime/placement-tmux.js";function c(){return u(h(),"viewer-panes")}t(c,"recordsDir");function d(e,r){return u(c(),r===void 0?`${e}.json`:`${r.replace(/[^A-Za-z0-9._-]/g,"_")}--${e}.json`)}t(d,"recordPath");function J(e,r,n,o){if(r===void 0||r==="")return;const i=S(r);if(i===null)return;const s={nodeId:e,session:i.session,windowIndex:i.windowIndex,windowName:i.windowName,paneIndex:i.paneIndex,cwd:n,pane:r,...o===void 0?{}:{canvas:o}};try{a(c(),{recursive:!0}),w(d(e,o),JSON.stringify(s))}catch{}}t(J,"writeLayoutRecord");function L(e,r,n){try{const o=JSON.parse(f(d(e,n),"utf8"));(r===void 0||o.pane===r)&&p(d(e,n),{force:!0})}catch{}}t(L,"removeLayoutRecord");function O(){let e;try{e=y(c())}catch{return[]}const r=[];for(const n of e)if(n.endsWith(".json"))try{r.push(JSON.parse(f(u(c(),n),"utf8")))}catch{}return r}t(O,"readLayoutRecords");export{O as readLayoutRecords,L as removeLayoutRecord,J as writeLayoutRecord};
@@ -1,5 +1,5 @@
1
1
  import type { ClientRole } from '../../../core/runtime/broker-protocol.js';
2
- import type { BrokerToClient } from '../../../core/runtime/broker-protocol.js';
2
+ import type { BrokerSnapshot, BrokerToClient } from '../../../core/runtime/broker-protocol.js';
3
3
  import type { AttachSession } from './context.js';
4
4
  export interface ReconnectHooks {
5
5
  /** This viewer's fixed role, resolved from the original attach flags. */
@@ -21,6 +21,10 @@ export interface ReconnectHooks {
21
21
  /** Called once each time the node is first seen as dormant. A stopped broker
22
22
  * will relay no final session event, so the viewer clears live-only display. */
23
23
  onEnterDormancy: () => void;
24
+ /** The connection closed and a redial began, for a node that is not parked. */
25
+ onReconnecting?: () => void;
26
+ /** The first welcome after a successful redial, after `onFrame` handled it. */
27
+ onReconnected?: (snapshot: BrokerSnapshot) => void;
24
28
  }
25
29
  export interface ReconnectSupervisor {
26
30
  /** Send the hello handshake. Called once after `tui.start()`, then again on
@@ -36,6 +40,9 @@ export interface ReconnectSupervisor {
36
40
  /** Install the permanent frame/error/close handlers. Call once, AFTER the
37
41
  * connect race is settled and its temporary listeners are gone. */
38
42
  install: () => void;
43
+ /** Check that the connection still answers, and redial it when it does not. Called when the person sends, when the pane gains
44
+ * focus, and after the computer wakes: a connection whose network path went away reports no close by itself for minutes. */
45
+ probe: () => void;
39
46
  /** Cancel the current delay/redial wait. Ordinary attach never calls this;
40
47
  * bounded companion surfaces call it before closing their socket. */
41
48
  stop: () => void;
@@ -1 +1 @@
1
- var A=Object.defineProperty;var n=(s,e)=>A(s,"name",{value:e,configurable:!0});import{AttachRefusedError as C,reconnectShouldGiveUp as I}from"../../../core/broker-client/index.js";const P=1e3,M=3e3;function L(s,e){const{socket:i,canvasSource:R}=s;let m,f=!1,l=!1,D=!1,a=!1,E=n(()=>{},"resolveStopped"),u,w;const _=new Promise(r=>{E=r}),N=n(r=>a?Promise.resolve(!1):new Promise(c=>{const d=n(t=>{u=void 0,w=void 0,c(t)},"settle");u=setTimeout(()=>d(!0),r),w=n(()=>{u!==void 0&&clearTimeout(u),d(!1)},"cancelRetry")}),"waitForRetry");let g=!1,p=!1;const v=n(()=>{p=!1,i.send({type:"hello",role:e.role,client_id:e.clientId,term:{cols:process.stdout.columns??80,rows:process.stdout.rows??24}})},"sendHello"),T=n(async(r=!1)=>{f=!0;let c=!r;c&&e.setNotice("\u21BB node refreshing \u2014 reconnecting\u2026",{sticky:!0});let d=200;try{for(;!a&&!e.isTornDown();){let t;try{t=await R.getRow(s.nodeId)}catch{t=void 0}if(t!==void 0&&I(t)){D=t!==null;break}const y=t?.status==="dead"||t?.status==="canceled",o=t?.status==="idle"||t?.intent==="idle-release"||t?.status==="done",S=o&&!l;l=o,S&&e.onEnterDormancy(),(c||!o)&&(e.setNotice(y?`node is ${t?.status} \u2014 waiting for a revive`:o?"":"\u21BB node refreshing \u2014 reconnecting\u2026",{sticky:!o}),c=!o);try{if(!await Promise.race([i.redial({brokerUnavailableIsExpected:o||y}).then(()=>!0),_.then(()=>!1)])||a||e.isTornDown())return;v(),l=!1,e.setNotice("");return}catch{if(!await N(o||y?M:Math.min(d,P)))return;d*=2}}}finally{f=!1}!a&&!e.isTornDown()&&e.teardown(D?"node-done":"broker-gone")},"attemptReconnect");return{sendHello:v,startDormant:n(()=>{f||a||e.isTornDown()||(l=!0,e.onEnterDormancy(),T(!0))},"startDormant"),isDormant:n(()=>l,"isDormant"),lastSocketError:n(()=>m,"lastSocketError"),install:n(async()=>{i.on("frame",r=>{r.type==="welcome"&&(g=!0),e.onFrame(r)}),i.on("error",r=>{m=r.message,r instanceof C&&(p=!0)}),i.on("close",()=>{if(!e.isTornDown()&&!f){if(e.remote&&e.role==="controller"&&p&&!g){m=`the remote canvas refused the attach to ${s.nodeId}. A writable attach needs message permission on the node; with read permission only, attach with --observer.`,e.teardown("broker-gone");return}T()}})},"install"),stop:n(()=>{a||(a=!0,w?.(),E())},"stop")}}n(L,"createReconnect");export{L as createReconnect};
1
+ var O=Object.defineProperty;var n=(f,e)=>O(f,"name",{value:e,configurable:!0});import{AttachRefusedError as L,reconnectShouldGiveUp as h}from"../../../core/broker-client/index.js";const U=1e3,B=3e3,F=5e3,A=5e3,G=15e3;function $(f,e){const{socket:c,canvasSource:N}=f;let p,u=!1,l=!1,T=!1,s=!1,g=n(()=>{},"resolveStopped"),w,y;const R=new Promise(r=>{g=r}),P=n(r=>s?Promise.resolve(!1):new Promise(i=>{const t=n(d=>{w=void 0,y=void 0,i(d)},"settle");w=setTimeout(()=>t(!0),r),y=n(()=>{w!==void 0&&clearTimeout(w),t(!1)},"cancelRetry")}),"waitForRetry");let m=!1,E=!1,_=!1,D=!1;const S=n(()=>{s||u||l||!m||e.isTornDown()||c.probe(F).then(r=>{r||(_=!0)})},"probe"),C=n(()=>{E=!1,c.send({type:"hello",role:e.role,client_id:e.clientId,term:{cols:process.stdout.columns??80,rows:process.stdout.rows??24}})},"sendHello"),b=n(async(r=!1)=>{u=!0;let i=!r;const t=_?"\u21BB connection lost \u2014 reconnecting\u2026":"\u21BB node refreshing \u2014 reconnecting\u2026";i&&e.setNotice(t,{sticky:!0}),r||e.onReconnecting?.();let d=200;try{for(;!s&&!e.isTornDown();){let o;try{o=await N.getRow(f.nodeId)}catch{o=void 0}if(o!==void 0&&h(o)){T=o!==null;break}const v=o?.status==="dead"||o?.status==="canceled",a=o?.status==="idle"||o?.intent==="idle-release"||o?.status==="done",I=a&&!l;l=a,I&&e.onEnterDormancy(),(i||!a)&&(e.setNotice(v?`node is ${o?.status} \u2014 waiting for a revive`:a?"":t,{sticky:!a}),i=!a);try{if(!await Promise.race([c.redial({brokerUnavailableIsExpected:a||v}).then(()=>!0),R.then(()=>!1)])||s||e.isTornDown())return;D=!0,_=!1,C(),l=!1,e.setNotice("");return}catch{if(!await P(a||v?B:Math.min(d,U)))return;d*=2}}}finally{u=!1}!s&&!e.isTornDown()&&e.teardown(T?"node-done":"broker-gone")},"attemptReconnect");return{sendHello:C,startDormant:n(()=>{u||s||e.isTornDown()||(l=!0,e.onEnterDormancy(),b(!0))},"startDormant"),isDormant:n(()=>l,"isDormant"),probe:S,lastSocketError:n(()=>p,"lastSocketError"),install:n(async()=>{c.on("frame",t=>{const d=!m;t.type==="welcome"&&(m=!0),e.onFrame(t),t.type==="welcome"&&D&&(D=!1,d||e.onReconnected?.(t.snapshot))});let r=Date.now();const i=setInterval(()=>{const t=Date.now();t-r>A+G&&S(),r=t},A);i.unref(),R.then(()=>clearInterval(i)),c.on("error",t=>{p=t.message,t instanceof L&&(E=!0)}),c.on("close",()=>{if(!e.isTornDown()&&!u){if(e.remote&&e.role==="controller"&&E&&!m){p=`the remote canvas refused the attach to ${f.nodeId}. A writable attach needs message permission on the node; with read permission only, attach with --observer.`,e.teardown("broker-gone");return}b()}})},"install"),stop:n(()=>{s||(s=!0,y?.(),g())},"stop")}}n($,"createReconnect");export{$ as createReconnect};
@@ -1,2 +1,3 @@
1
- var u=Object.defineProperty;var w=(n,t)=>u(n,"name",{value:t,configurable:!0});import{existsSync as m,statSync as h,openSync as v,readSync as I,closeSync as g}from"node:fs";import{join as _}from"node:path";import{routes as y}from"../../../api/index.js";import{cliClient as $}from"../../../commands/api-client.js";import{runtimeRoot as x}from"../../../core/layout.js";import{liveViewerPanes as S}from"../../../core/runtime/tmux-driver.js";import{openViewerPane as k,selectLayout as N}from"../../../core/runtime/placement-tmux.js";import{readLayoutRecords as z}from"../session/layout-record.js";const L=8*1024*1024,B=60*6e4;function O(n){const t=_(x(),"crtrd.log");if(!m(t))return[];const r=h(t).size,l=Math.max(0,r-L),i=Buffer.alloc(r-l),s=v(t,"r");try{I(s,i,0,i.length,l)}finally{g(s)}const f=[];for(const a of i.toString("utf8").split(`
2
- `))if(a.includes("daemon.timing.view_open_received"))try{const d=JSON.parse(a);d.event==="daemon.timing.view_open_received"&&d.node_id!==void 0&&n-Date.parse(d.ts)<=B&&!f.includes(d.node_id)&&f.push(d.node_id)}catch{}return f}w(O,"recentViewOpens");async function V(n=Date.now()){const t=$(),r=await t.request("POST",y.reviveAll()),l=new Set(r.failed.map(e=>e.node_id)),i={revived:r.revived.length,failed:r.failed.map(e=>`${e.node_id}: ${e.error}`),frozen:r.frozen.length,panes:0,skipped:0,source:"none"};let s=z();if(s.length>0)i.source="snapshot";else{const e=O(n);e.length>0&&(i.source="recent views"),s=[];for(const o of e)s.push({nodeId:o,session:"",windowIndex:s.length,windowName:"",paneIndex:0,cwd:"",pane:""})}const f=new Set(S().map(e=>e.nodeId)),a=[];for(const e of s){if(f.has(e.nodeId)||l.has(e.nodeId)){i.skipped++;continue}try{const o=await t.getNode(e.nodeId);if(o.status==="done"||o.status==="canceled"||o.final_report!=null){i.skipped++;continue}const c=e.cwd===""?o.cwd:e.cwd,p=e.session===""?c.split("/").filter(Boolean).pop()??"crtr":e.session;a.push({...e,cwd:c,session:p,windowName:e.windowName===""?o.name:e.windowName})}catch{i.skipped++}}a.sort((e,o)=>e.session.localeCompare(o.session)||e.windowIndex-o.windowIndex||e.paneIndex-o.paneIndex);const d=new Map;for(const e of a){const o=`${e.session} ${e.windowIndex}`,c=d.get(o),p=k(e.nodeId,e.session,{name:e.windowName,cwd:e.cwd,waitForBroker:!0,...c===void 0?{}:{besidePane:c}});if(p===null){i.failed.push(`${e.nodeId}: tmux refused to open a pane`);continue}c===void 0?d.set(o,p.pane):p.window!==null&&N(p.window,"even-horizontal"),i.panes++}return i}w(V,"recover");function F(n){const t=[`revived ${n.revived}`,`${n.panes} pane${n.panes===1?"":"s"} recreated (${n.source})`];return n.frozen>0&&t.push(`${n.frozen} waiting for broker slots`),n.skipped>0&&t.push(`${n.skipped} skipped (already viewed, finished, or not revivable)`),n.failed.length>0&&t.push(`${n.failed.length} failed: ${n.failed.join("; ")}`),`Recovered \u2014 ${t.join(", ")}`}w(F,"formatReport");export{F as formatReport,V as recover};
1
+ var m=Object.defineProperty;var l=(n,o)=>m(n,"name",{value:o,configurable:!0});import{existsSync as v,statSync as h,openSync as I,readSync as g,closeSync as $}from"node:fs";import{spawnSync as y}from"node:child_process";import{join as S}from"node:path";import{routes as _}from"../../../api/index.js";import{cliClient as x}from"../../../commands/api-client.js";import{runtimeRoot as k}from"../../../core/layout.js";import{liveViewerPanes as N}from"../../../core/runtime/tmux-driver.js";import{openViewerPane as z,selectLayout as L}from"../../../core/runtime/placement-tmux.js";import{readLayoutRecords as B}from"../session/layout-record.js";const O=8*1024*1024,P=60*6e4;function V(n){const o=S(k(),"crtrd.log");if(!v(o))return[];const d=h(o).size,c=Math.max(0,d-O),t=Buffer.alloc(d-c),r=I(o,"r");try{g(r,t,0,t.length,c)}finally{$(r)}const f=[];for(const u of t.toString("utf8").split(`
2
+ `))if(u.includes("daemon.timing.view_open_received"))try{const i=JSON.parse(u);i.event==="daemon.timing.view_open_received"&&i.node_id!==void 0&&n-Date.parse(i.ts)<=P&&!f.includes(i.node_id)&&f.push(i.node_id)}catch{}return f}l(V,"recentViewOpens");function b(){const n=y("ps",["-axo","command"],{encoding:"utf8"}).stdout??"",o=new Set;for(const d of n.split(`
3
+ `)){const c=/surface\s+attach\s+to\s+(\S+)(?:\s+--observer)?\s+--canvas\s+'?([^'\s]+)'?/.exec(d);c!==null&&o.add(`${c[2]} ${c[1]}`)}return o}l(b,"runningCloudViewers");async function E(n=Date.now()){const o=x(),d=await o.request("POST",_.reviveAll()),c=new Set(d.failed.map(e=>e.node_id)),t={revived:d.revived.length,failed:d.failed.map(e=>`${e.node_id}: ${e.error}`),frozen:d.frozen.length,panes:0,skipped:0,source:"none"};let r=B();if(r.length>0)t.source="snapshot";else{const e=V(n);e.length>0&&(t.source="recent views"),r=[];for(const s of e)r.push({nodeId:s,session:"",windowIndex:r.length,windowName:"",paneIndex:0,cwd:"",pane:""})}const f=new Set(N().map(e=>e.nodeId)),u=b(),i=[];for(const e of r){if(e.canvas!==void 0){if(u.has(`${e.canvas} ${e.nodeId}`)){t.skipped++;continue}i.push({...e,windowName:e.windowName===""?e.nodeId:e.windowName,cwd:e.cwd===""?process.cwd():e.cwd});continue}if(f.has(e.nodeId)||c.has(e.nodeId)){t.skipped++;continue}try{const s=await o.getNode(e.nodeId);if(s.status==="done"||s.status==="canceled"||s.final_report!=null){t.skipped++;continue}const a=e.cwd===""?s.cwd:e.cwd,p=e.session===""?a.split("/").filter(Boolean).pop()??"crtr":e.session;i.push({...e,cwd:a,session:p,windowName:e.windowName===""?s.name:e.windowName})}catch{t.skipped++}}i.sort((e,s)=>e.session.localeCompare(s.session)||e.windowIndex-s.windowIndex||e.paneIndex-s.paneIndex);const w=new Map;for(const e of i){const s=`${e.session} ${e.windowIndex}`,a=w.get(s),p=z(e.nodeId,e.session,{name:e.windowName,cwd:e.cwd,waitForBroker:e.canvas===void 0,...e.canvas===void 0?{}:{canvas:e.canvas},...a===void 0?{}:{besidePane:a}});if(p===null){t.failed.push(`${e.nodeId}: tmux refused to open a pane`);continue}a===void 0?w.set(s,p.pane):p.window!==null&&L(p.window,"even-horizontal"),t.panes++}return t}l(E,"recover");function G(n){const o=[`revived ${n.revived}`,`${n.panes} pane${n.panes===1?"":"s"} recreated (${n.source})`];return n.frozen>0&&o.push(`${n.frozen} waiting for broker slots`),n.skipped>0&&o.push(`${n.skipped} skipped (already viewed, finished, or not revivable)`),n.failed.length>0&&o.push(`${n.failed.length} failed: ${n.failed.join("; ")}`),`Recovered \u2014 ${o.join(", ")}`}l(G,"formatReport");export{G as formatReport,E as recover};