@north-light/cli 0.3.709 → 0.3.711
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +1 -1
- package/dist/clients/attach/input/controller.js +2 -2
- package/dist/clients/attach/render/chat-view.d.ts +13 -2
- package/dist/clients/attach/render/chat-view.js +2 -2
- package/dist/clients/attach/session/input-wiring.d.ts +2 -2
- package/dist/clients/attach/session/layout-record.d.ts +15 -0
- package/dist/clients/attach/session/layout-record.js +1 -0
- package/dist/clients/attach/session/reconnect.d.ts +8 -1
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/session/teardown.d.ts +2 -0
- package/dist/clients/attach/session/teardown.js +3 -3
- package/dist/clients/attach/slash/dispatch.js +2 -2
- package/dist/clients/attach/slash/recover.d.ts +10 -0
- package/dist/clients/attach/slash/recover.js +3 -0
- package/dist/clients/attach/viewer.js +520 -516
- package/dist/commands/human/prompts.js +1 -1
- package/dist/commands/human/request.js +1 -1
- package/dist/commands/sys/doctor.js +1 -1
- package/dist/commands/sys/tutorial/scenario.js +2 -2
- package/dist/core/broker-client/client.d.ts +2 -0
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/broker-client/transport-relay.d.ts +6 -0
- package/dist/core/broker-client/transport-relay.js +1 -1
- package/dist/core/broker-client/transport.d.ts +4 -0
- package/dist/core/canvas/daemon-actions.d.ts +1 -1
- package/dist/core/canvas/daemon-actions.js +7 -7
- package/dist/core/canvas/deliveries.d.ts +1 -1
- package/dist/core/canvas/deliveries.js +21 -21
- package/dist/core/canvas/executions.d.ts +1 -1
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -2
- package/dist/core/canvas/managed-worktree-sweep-candidates.js +5 -3
- package/dist/core/canvas/reconciler-leases.d.ts +4 -0
- package/dist/core/canvas/reconciler-leases.js +5 -5
- package/dist/core/canvas/schema-pg/028-machine-calls-worktree-sweep.sql +6 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/conversation-store/client.js +2 -2
- package/dist/core/conversation-store/index.d.ts +5 -2
- package/dist/core/conversation-store/row-store.js +14 -12
- package/dist/core/graph/package-docs.js +5 -5
- package/dist/core/graph/package-publish.js +4 -3
- package/dist/core/human/requests.js +19 -19
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/runtime/broker/client-registry.d.ts +1 -1
- package/dist/core/runtime/broker/client-registry.js +1 -1
- package/dist/core/runtime/broker/turn-replies.js +3 -1
- package/dist/core/runtime/broker-protocol.d.ts +4 -4
- package/dist/core/runtime/broker-protocol.js +3 -3
- package/dist/core/runtime/broker-request.d.ts +2 -0
- package/dist/core/runtime/broker-request.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/model-swap.d.ts +2 -1
- package/dist/core/runtime/model-swap.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +2 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +11 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/session-cycles.d.ts +21 -0
- package/dist/core/runtime/session-cycles.js +1 -1
- package/dist/core/runtime/tmux-driver.d.ts +7 -0
- package/dist/core/runtime/tmux-driver.js +6 -6
- package/dist/core/worktree-machine.d.ts +4 -1
- package/dist/core/worktree-machine.js +1 -1
- package/dist/core/worktree-sweep.d.ts +14 -3
- package/dist/core/worktree-sweep.js +4 -4
- package/dist/daemon/api/app-listener.js +1 -1
- package/dist/daemon/api/handlers/charges.d.ts +1 -1
- package/dist/daemon/api/handlers/charges.js +1 -1
- package/dist/daemon/api/handlers/conversations.js +4 -3
- package/dist/daemon/api/handlers/environments.d.ts +1 -1
- package/dist/daemon/api/handlers/environments.js +1 -1
- package/dist/daemon/api/handlers/limits.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/cron/live-runs.d.ts +3 -0
- package/dist/daemon/cron/live-runs.js +1 -1
- package/dist/daemon/cron/machine-fire.js +1 -1
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/due-sources.d.ts +1 -1
- package/dist/daemon/due-sources.js +1 -1
- package/dist/daemon/due.js +7 -7
- package/dist/daemon/fleet.d.ts +1 -1
- package/dist/daemon/fleet.js +4 -4
- package/dist/daemon/human/finish.js +3 -3
- package/dist/daemon/human/settle.js +1 -1
- package/dist/daemon/reconcilers/action-lane.js +1 -1
- package/dist/daemon/reconcilers/delivery-lane.js +2 -2
- package/dist/daemon/reconcilers/grant-effects.js +1 -1
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/requested-stops.js +2 -2
- package/dist/daemon/runs/observer.d.ts +4 -0
- package/dist/daemon/runs/observer.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
- package/package.json +4 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/clients/attach/input/capabilities.js +1 -0
- package/packages/crouter-api/dist/clients/attach/input/controller.js +2 -2
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +40 -3
- package/packages/crouter-api/dist/clients/attach/session/layout-record.js +52 -0
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +41 -2
- package/packages/crouter-api/dist/clients/attach/session/teardown.js +2 -0
- package/packages/crouter-api/dist/clients/attach/slash/dispatch.js +12 -0
- package/packages/crouter-api/dist/clients/attach/slash/recover.js +133 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +24 -5
- package/packages/crouter-api/dist/commands/human/prompts.js +11 -18
- package/packages/crouter-api/dist/commands/human/request.js +3 -0
- package/packages/crouter-api/dist/commands/sys/doctor.js +17 -0
- package/packages/crouter-api/dist/commands/sys/tutorial/scenario.js +1 -0
- package/packages/crouter-api/dist/core/broker-client/client.js +4 -0
- package/packages/crouter-api/dist/core/broker-client/transport-relay.js +45 -0
- package/packages/crouter-api/dist/core/canvas/daemon-actions.js +3 -2
- package/packages/crouter-api/dist/core/canvas/deliveries.js +7 -3
- package/packages/crouter-api/dist/core/canvas/executions.js +8 -7
- package/packages/crouter-api/dist/core/canvas/reconciler-leases.js +4 -0
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/client.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +14 -1
- package/packages/crouter-api/dist/core/graph/package-docs.js +8 -3
- package/packages/crouter-api/dist/core/graph/package-publish.js +8 -1
- package/packages/crouter-api/dist/core/human/requests.js +2 -2
- package/packages/crouter-api/dist/core/runtime/broker-ownership.js +6 -0
- package/packages/crouter-api/dist/core/runtime/broker-protocol.js +4 -4
- package/packages/crouter-api/dist/core/runtime/broker-request.js +1 -1
- package/packages/crouter-api/dist/core/runtime/model-swap.js +2 -1
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +3 -3
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/executor.js +235 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/core/runtime/session-cycles.js +90 -8
- package/packages/crouter-api/dist/core/runtime/tmux-driver.js +11 -0
- package/packages/crouter-api/dist/core/worktree-machine.js +20 -0
- package/packages/crouter-api/dist/core/worktree-sweep.js +439 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +3 -3
- package/packages/crouter-api/dist/daemon/api/router.js +1 -4
- package/packages/crouter-api/dist/daemon/cron/live-runs.js +4 -5
- package/packages/crouter-api/dist/daemon/cron/machine-fire.js +3 -3
- package/packages/crouter-api/dist/daemon/human/finish.js +2 -1
- package/packages/crouter-api/dist/daemon/human/settle.js +1 -6
- package/packages/crouter-api/dist/daemon/runs/observer.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/install-runtime.mjs +18 -1
- package/scripts/lib/install-source.mjs +49 -0
- package/dist/daemon/reconcilers/idle-sandbox.d.ts +0 -18
- package/dist/daemon/reconcilers/idle-sandbox.js +0 -7
package/dist/api/contract.d.ts
CHANGED
|
@@ -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.
|
|
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`. */
|
package/dist/api/contract.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var o=Object.defineProperty;var
|
|
1
|
+
var o=Object.defineProperty;var n=(e,s)=>o(e,"name",{value:s,configurable:!0});function l(e){const s=e.remote,t=e.role,a=new Set;return s||(a.add("local-canvas-inspect"),a.add("canvas-inbox")),t==="controller"&&(a.add("engine-drive"),a.add("dequeue")),t==="controller"&&!s&&(a.add("wake-dormant"),a.add("auth"),a.add("canvas-resume"),a.add("local-host")),{role:t,remote:s,get nodeId(){return e.nodeId},profileId:e.profileId,permittedOperations:a,permits:n(r=>a.has(r),"permits"),refusal:n((r,i)=>{const c=i===void 0?"":`/${i} `;if(e.isBrokerOffline?.()===!0&&(r==="engine-drive"||r==="dequeue"||r==="auth"))return`${c}needs a live broker; this node is parked \u2014 submit a message to wake it`;if(!a.has(r))return s&&(r==="canvas-resume"||r==="local-canvas-inspect"||r==="canvas-inbox")?`${c}Not available with --canvas because it acts on this machine's local canvas`:s&&t==="controller"?`${c}Not available with --canvas because it acts on this machine, not the remote node`:`${c}is not available to a read-only observer attach (--observer) \u2014 it would drive this node`},"refusal")}}n(l,"createViewerCapabilities");function u(e){switch(e.type){case"prompt":case"steer":case"follow_up":case"abort":case"bash":case"set_model":case"cycle_model":case"cycle_ladder":case"cycle_thinking":case"set_thinking_level":case"set_auto_retry":case"set_auto_compaction":case"compact":case"new_session":case"switch_session":case"fork":case"set_session_name":case"navigate_tree":case"reload":case"export":case"clone":case"share":case"reload_auth":return"engine-drive";default:return}}n(u,"viewerOperationForFrame");function f(e,s,t){if(t)switch(e){case"resume":return"canvas-resume";case"context":case"node-metadata":return"local-canvas-inspect";case"plugins":return;case"inbox":return"canvas-inbox";case"clear":case"resume-session":case"tutorial":return"engine-drive";case"recover":case"promote":case"rename":case"mcp":return"local-host";default:return}if(s)switch(e){case"copy":case"session":case"changelog":case"hotkeys":case"quit":return;case"login":case"logout":return"auth";default:return"engine-drive"}}n(f,"viewerOperationForSlash");export{l as createViewerCapabilities,u as viewerOperationForFrame,f as viewerOperationForSlash};
|
|
@@ -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
|
|
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",
|
|
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
|
-
|
|
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
|
|
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). */
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface LayoutRecord {
|
|
2
|
+
nodeId: string;
|
|
3
|
+
session: string;
|
|
4
|
+
windowIndex: number;
|
|
5
|
+
windowName: string;
|
|
6
|
+
paneIndex: number;
|
|
7
|
+
cwd: string;
|
|
8
|
+
pane: string;
|
|
9
|
+
/** The cloud canvas a remote viewer attached over (`--canvas`); absent for a node on this Mac. */
|
|
10
|
+
canvas?: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function writeLayoutRecord(nodeId: string, pane: string | undefined, cwd: string, canvas?: string): void;
|
|
13
|
+
/** Delete this node's record unless another viewer pane has since claimed it. */
|
|
14
|
+
export declare function removeLayoutRecord(nodeId: string, pane: string | undefined, canvas?: string): void;
|
|
15
|
+
export declare function readLayoutRecords(): LayoutRecord[];
|
|
@@ -0,0 +1 @@
|
|
|
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
|
|
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};
|
|
@@ -17,6 +17,8 @@ export interface TeardownHooks {
|
|
|
17
17
|
/** This viewer's tmux pane, as self-tagged at startup. Used only by the
|
|
18
18
|
* node-done path to close our own pane. */
|
|
19
19
|
tagPane: () => string | undefined;
|
|
20
|
+
/** Drop this viewer's tmux layout record. Called only when the person detached or the node finished, never on a signal or a lost broker. */
|
|
21
|
+
forgetLayout: () => void;
|
|
20
22
|
/** Text the person entered that the broker never received (held frames and the unsent draft before the first welcome); empty once delivered. Printed on every exit. */
|
|
21
23
|
undelivered: () => string[];
|
|
22
24
|
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var m=Object.defineProperty;var t=(r,n)=>m(r,"name",{value:n,configurable:!0});import{closePane as w,currentTmux as S,inTmux as T}from"../../../core/runtime/placement-tmux.js";import{FOCUS_REPORTING_OFF as I}from"./focus-events.js";function v(r,n){const{tui:
|
|
1
|
+
var m=Object.defineProperty;var t=(r,n)=>m(r,"name",{value:n,configurable:!0});import{closePane as w,currentTmux as S,inTmux as T}from"../../../core/runtime/placement-tmux.js";import{FOCUS_REPORTING_OFF as I}from"./focus-events.js";function v(r,n){const{tui:p,socket:i,remote:u}=r;let c=!1;const d=t(()=>{if(!c){c=!0;try{process.stdout.write(I),p.stop()}catch{}}},"restore");process.once("exit",d);let s=!1,a;const g=new Promise(e=>{a=e}),l=t(e=>{if(s)return;if(s=!0,n.stopLocal(),e==="detach"&&i.send({type:"bye"}),i.close(),(e==="detach"||e==="node-done")&&n.forgetLayout(),d(),e==="broker-gone"){const o=n.lastSocketError()??`broker gone \u2014 node ${r.nodeId} is no longer running its engine.`;process.stderr.write(`
|
|
2
2
|
${o}
|
|
3
3
|
Reattach with: ${n.reattachCommand()}
|
|
4
4
|
`)}e==="create-failed"&&process.stderr.write(`
|
|
5
5
|
${n.lastSocketError()??"creating the node failed"}
|
|
6
|
-
`);const
|
|
6
|
+
`);const f=n.undelivered();if(f.length>0&&process.stderr.write(`
|
|
7
7
|
Not delivered:
|
|
8
|
-
${
|
|
8
|
+
${f.join(`
|
|
9
9
|
---
|
|
10
10
|
`)}
|
|
11
11
|
`),e==="node-done"){process.stderr.write(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var L=Object.defineProperty;var i=(t,e)=>L(t,"name",{value:e,configurable:!0});import{execFile as d}from"node:child_process";import{BUILTIN_SLASH_COMMANDS as h}from"../../../core/runtime/pi-vendored.js";import{surfaceTmuxStyleArgs as U}from"../../../core/runtime/surface-bg.js";import{crouterMenuTmuxArgs as E}from"../../../core/runtime/tmux-bindings.js";import{viewerOperationForSlash as $}from"../input/capabilities.js";import{shellQuote as y}from"../../../shared/shell-quote.js";const g=[{name:"tutorial",description:"The guided crouter tutorial \u2014 your agent teaches it, one lesson at a time"},{name:"menu",description:"Open the crouter action menu \u2014 the same menu as Alt+C, for when Option/Alt does not work in your terminal"},{name:"clear",description:"Clear the conversation and free context \u2014 a fresh, empty session (like /new)"},{name:"graph",description:"Toggle the canvas GRAPH view (your local subscription tree)"},{name:"inbox",description:"Toggle the human inbox \u2014 pending asks and reviews for you"},{name:"promote",description:"Promote this node to an orchestrator \u2014 /promote, or /promote <kind> to specialize"},{name:"resume",description:"Open the canvas navigator and swap THIS pane onto the chosen node; parked residents wake only on submitted input"},{name:"resume-session",description:"Switch this node onto one of its saved pi sessions \u2014 picker, or /resume-session <session-path>"},{name:"context",description:"Browse the files in this node\u2019s and its subscriptions\u2019 context dirs in a read-only nvim popup"},{name:"plugins",description:"Open the interactive plugin browser for this machine"},{name:"node-metadata",description:"Inspect this node \u2014 identity, lifecycle, runtime, graph, output, paths, and agent surfaces"},{name:"mcp",description:"MCP servers \u2014 status from the adapter\u2019s config/cache; Enter (or /mcp <server>) connects, reconnects, or re-auths"},{name:"rename",description:"Rename this node everywhere \u2014 node row, viewer window, session chip, tmux pane: /rename <name>"},{name:"color",description:"Color this node \u2014 tmux pane outline + name chip: /color <color> (red, blue, #rrggbb, \u2026) or /color none"},{name:"mouse",description:"Toggle mouse wheel scrolling and drag-select \u2014 off restores tmux drag-select and copy-mode mouse"},{name:"copy-message",description:"Copy the newest message visible in the transcript viewport"},{name:"copy-tool",description:"Copy the newest tool call output"},{name:"copy-transcript",description:"Copy every copyable transcript block"},{name:"more-detail",description:"Show the transcript one verbosity level more open, in this viewer only (Ctrl+O)"},{name:"less-detail",description:"Show the transcript one verbosity level more collapsed, in this viewer only (Ctrl+Shift+O)"}],_=new Map([["resume-node","resume"]]),w=new Set([...g.map(t=>t.name),..._.keys()]),X=new Set(["black","red","green","yellow","blue","magenta","cyan","white","brightred","brightgreen","brightyellow","brightblue","brightmagenta","brightcyan","orange","grey","gray","default"]),M=new Set(["trust"]),T=new Set(Object.keys({off:!0,minimal:!0,low:!0,medium:!0,high:!0,xhigh:!0,max:!0})),v=new Set(h.map(t=>t.name));function b(t){return t.capabilities.nodeId}i(b,"nodeIdFor");function j(t){return t.capabilities.profileId}i(j,"profileIdFor");function N(t,e){const n=$(t,v.has(t),w.has(t));return n===void 0?void 0:e.capabilities.refusal(n,t)}i(N,"readOnlyRefusal");function ie(){return new Set([...v,...w,...M])}i(ie,"locallyConsumedCommandNames");function D(t){const e=/^\/(\S+)\s*([\s\S]*)$/.exec(t.trim());return e===null?void 0:{name:e[1],arg:e[2].trim()}}i(D,"parseSlashCommand");function se(t){return t.trimStart().startsWith("/")}i(se,"isSlashCommand");function ae(t,e){const n=D(t);if(n===void 0)return!1;const{arg:o}=n,r=_.get(n.name)??n.name;if(M.has(r))return e.notify(`/${r} is not supported in attach (Phase 4)`),!0;if(w.has(r)){const s=N(r,e);return s!==void 0?(e.notify(s),!0):H(r,o,e)}if(!v.has(r))return!1;const u=N(r,e);if(u!==void 0)return e.notify(u),!0;switch(r){case"new":return e.send({type:"new_session"}),!0;case"reload":return e.send({type:"reload"}),!0;case"compact":return e.send({type:"compact",instructions:o||void 0}),!0;case"quit":return e.onQuit?(e.onQuit(),!0):(e.send({type:"bye"}),e.notify("Detaching \u2014 the engine keeps running"),!0);case"name":return o?(e.send({type:"set_session_name",name:o}),!0):m(e,"/name <display name>");case"export":{const{path:s,format:a}=K(o,e.cwd??process.cwd());return e.send({type:"export",path:s,format:a}),e.notify(`Exporting session \u2192 ${s}`),!0}case"import":return o?(e.send({type:"switch_session",path:o}),!0):m(e,"/import <path-to-session.jsonl>");case"model":return o?(e.send({type:"set_model",model:o}),!0):f(e.openModelPicker,e,"model","/model <provider/id>");case"fork":return o?(e.send({type:"fork",entryId:o}),!0):f(e.openForkPicker,e,"fork point","/fork <entryId>");case"tree":return o?(e.send({type:"navigate_tree",targetId:o}),!0):f(e.openTreePicker,e,"tree","/tree <entryId>");case"scoped-models":return e.openScopedModelsPicker?(e.openScopedModelsPicker(),!0):(e.notify("The scoped-models view needs the read-op channel, which this viewer has not wired"),!0);case"settings":return Y(o,e);case"session":return e.notify(z(e.state)),!0;case"copy":return e.onCopy?(e.onCopy(),!0):(e.notify("/copy is not available in this viewer"),!0);case"login":return e.openLoginPicker?(e.openLoginPicker(),!0):(e.notify("/login is not available in this viewer"),!0);case"logout":return e.openLogoutPicker?(e.openLogoutPicker(),!0):(e.notify("/logout is not available in this viewer"),!0);case"share":return e.send({type:"share"}),e.notify("Sharing session\u2026"),!0;case"clone":return e.send({type:"clone"}),e.notify("Cloning session\u2026"),!0;case"changelog":return e.notify("/changelog: see https://github.com/earendil-works/pi for release notes (no bundled changelog in this build)"),!0;case"hotkeys":return e.onHelp?(e.onHelp(),!0):(e.notify("/hotkeys is not available in this viewer"),!0);default:return e.notify(`/${r} is not available in attach (Phase 4)`),!0}}i(ae,"dispatchSlashCommand");function P(t,e){const n=i(a=>{const l=$(a,!1,!0);return l===void 0||e.permits(l)},"permitted"),o=g.filter(a=>n(a.name)),r=new Map(g.map(a=>[a.name,a])),u=t.flatMap(a=>{const l=r.get(a.name);return l===void 0?[a]:n(a.name)?[l]:[]}),s=new Set(t.map(a=>a.name));return[...u,...o.filter(a=>!s.has(a.name))]}i(P,"withCanvasCommands");function ue(t,e){return P(t??h,e).map(n=>({name:n.name,description:n.description}))}i(ue,"slashCommandList");function le(t,e){return P(t??h,e).map(n=>({value:`/${n.name}`,label:`/${n.name}`,description:n.description}))}i(le,"commandAutocompleteItems");function H(t,e,n){switch(t){case"clear":return n.send({type:"new_session"}),!0;case"graph":return n.onGraph?n.onGraph():n.notify("The GRAPH overlay is not wired into the viewer yet"),!0;case"inbox":return n.onInbox?n.onInbox():n.notify("The inbox surface is not wired into the viewer yet"),!0;case"menu":return q(n);case"tutorial":return n.send({type:"prompt",text:"The user asked for the crouter tutorial. Run `crtr sys tutorial -h`, pick the track that matches what they want to learn, and teach it one lesson per invocation \u2014 in your own words, letting them try each thing before you move on."}),!0;case"promote":return B(e,n),!0;case"resume":return e?m(n,"/resume \u2014 no argument; use /resume-session <path> to switch pi sessions"):G(n);case"resume-session":return e?(n.send({type:"switch_session",path:e}),!0):f(n.openSessionPicker,n,"session","/resume-session <session-path>");case"mcp":return n.openMcpPicker?n.openMcpPicker(e||void 0):n.notify("The MCP panel is not wired into this viewer"),!0;case"context":return J(n);case"plugins":return Q(n);case"node-metadata":return n.onNodeMetadata?n.onNodeMetadata():n.notify("Node metadata is not wired into this viewer"),!0;case"rename":return R(e,n),!0;case"color":return F(e,n);case"more-detail":return n.onMoreDetail?n.onMoreDetail():n.notify("Verbosity is not wired into this viewer"),!0;case"less-detail":return n.onLessDetail?n.onLessDetail():n.notify("Verbosity is not wired into this viewer"),!0;case"mouse":return n.onToggleMouse?n.onToggleMouse():n.notify("Mouse reporting is not wired into this viewer"),!0;case"copy-message":return n.onCopyTarget?n.onCopyTarget("message"):n.notify("/copy-message is not available in this viewer"),!0;case"copy-tool":return n.onCopyTarget?n.onCopyTarget("tool"):n.notify("/copy-tool is not available in this viewer"),!0;case"copy-transcript":return n.onCopyTarget?n.onCopyTarget("transcript"):n.notify("/copy-transcript is not available in this viewer"),!0;default:return n.notify(`/${t} is not available in attach`),!0}}i(H,"dispatchCanvasCommand");function B(t,e){const n=b(e).trim();if(n===""){e.notify("/promote: no node to promote (viewer has no node id)");return}const o=t.trim().toLowerCase();e.notify(o?`Promoting \u2192 ${o}\u2026`:"Promoting\u2026");const r=["node","promote","--node",n,"--json"];o!==""&&r.push("--kind",o),d("crtr",r,{timeout:15e3,maxBuffer:4*1024*1024},(s,a)=>{let l=null,p=null;try{l=JSON.parse(a)}catch{l=null}if(s&&l===null){const O=typeof s.stdout=="string"?s.stdout:"";try{const C=JSON.parse(O);p=typeof C.message=="string"?C.message:null}catch{p=null}p===null&&(p=s.message)}if(l===null){e.notify(`promote failed: ${p??"unknown error"}`);return}const S=(l.roadmap_ref??"").trim();e.notify(`Promoted to ${l.kind??"orchestrator"} orchestrator \u2014 authoring roadmap${S!==""?` (${S})`:""}.`),e.send({type:"prompt",text:"You have just been promoted to an orchestrator. Your new-role guidance is arriving \u2014 read it, author your roadmap, and start delegating."})}).stdin?.end()}i(B,"promoteNode");function R(t,e){const n=b(e).trim();if(n===""){e.notify("/rename: no node to rename (viewer has no node id)");return}if(t===""){e.notify("Usage: /rename <name>");return}e.send({type:"set_session_name",name:t});const o=process.env.TMUX_PANE;process.env.TMUX!==void 0&&o!==void 0&&o!==""&&d("tmux",["select-pane","-t",o,"-T",t],()=>{}),d("crtr",["node","config","--node",n,"--name",t,"--json"],{timeout:15e3,maxBuffer:4*1024*1024},(r,u)=>{if(r){let s=null;try{const a=JSON.parse(u);s=typeof a.message=="string"?a.message:null}catch{s=null}e.notify(`rename failed: ${s??r.message}`);return}e.notify(`Renamed node \u2192 ${t}`)})}i(R,"renameNode");function c(t){return new Promise(e=>{d("tmux",t,{timeout:5e3},(n,o)=>e(n?"":o))})}i(c,"tmuxCall");async function V(t,e,n){if(n){await c(["set-option","-p","-u","-t",t,"@crtr_color"]);return}await c(["set-option","-p","-t",t,"@crtr_color",e]);for(const o of["pane-border-style","pane-active-border-style"]){const r=(await c(["show-options","-wqv","-t",t,o])).trim();if(r.includes("@crtr_color"))continue;let u=r!==""?r:(await c(["show-options","-gqv",o])).trim();u===""&&(u=o==="pane-active-border-style"?"fg=green":"default");const s=`#{?#{!=:#{@crtr_color},},fg=#{@crtr_color},${u.replace(/,/g,"#,")}}`;await c(["set-option","-w","-t",t,o,s])}}i(V,"paintPaneBorder");function F(t,e){const n=t.trim().toLowerCase();if(n==="")return e.notify("Usage: /color <color> \u2014 a name (red, blue, orange\u2026), colourN, or #rrggbb; /color none to clear"),!0;const o=n==="none"||n==="clear";if(!(o||X.has(n)||/^colour\d{1,3}$/.test(n)||/^#[0-9a-f]{6}$/.test(n)))return e.notify(`Invalid color "${n}" \u2014 use a tmux colour name (${["red","green","yellow","blue","magenta","cyan","orange"].join(", ")}, \u2026), colourN, or #rrggbb`),!0;const u=process.env.TMUX_PANE,s=process.env.TMUX!==void 0&&u!==void 0&&u!=="";return s&&V(u,n,o),e.onColor?.(o?null:n),e.notify(o?"Node color cleared":`Node colored ${n}${s?"":" (chip only \u2014 no tmux pane)"}`),!0}i(F,"colorNode");function G(t){const e=process.env.TMUX_PANE;if(process.env.TMUX===void 0||e===void 0||e==="")return t.notify("/resume needs tmux"),!0;const n=y(t.cwd??process.cwd()),o=j(t),r=o===void 0||o===""?"":` --profile-id ${y(o)}`,u=`crtr canvas browse --return-pane ${e} --cwd ${n}${r}`;return k(u,{w:"97%",h:"95%"}),!0}i(G,"resumeNode");function q(t){const e=process.env.TMUX_PANE;if(process.env.TMUX===void 0||e===void 0||e==="")return t.notify("/menu needs tmux \u2014 the crouter action menu is a tmux menu"),!0;try{d("tmux",["display-menu","-t",e,...E().slice(1)],n=>{n&&t.notify(`/menu failed: ${n.message.split(`
|
|
2
|
-
`)[0]}`)})}catch(n){t.notify(`/menu failed: ${n.message}`)}return!0}i(
|
|
1
|
+
var L=Object.defineProperty;var i=(t,e)=>L(t,"name",{value:e,configurable:!0});import{execFile as l}from"node:child_process";import{BUILTIN_SLASH_COMMANDS as h}from"../../../core/runtime/pi-vendored.js";import{surfaceTmuxStyleArgs as U}from"../../../core/runtime/surface-bg.js";import{crouterMenuTmuxArgs as E}from"../../../core/runtime/tmux-bindings.js";import{viewerOperationForSlash as C}from"../input/capabilities.js";import{formatReport as X,recover as j}from"./recover.js";import{shellQuote as y}from"../../../shared/shell-quote.js";const g=[{name:"tutorial",description:"The guided crouter tutorial \u2014 your agent teaches it, one lesson at a time"},{name:"menu",description:"Open the crouter action menu \u2014 the same menu as Alt+C, for when Option/Alt does not work in your terminal"},{name:"clear",description:"Clear the conversation and free context \u2014 a fresh, empty session (like /new)"},{name:"graph",description:"Toggle the canvas GRAPH view (your local subscription tree)"},{name:"inbox",description:"Toggle the human inbox \u2014 pending asks and reviews for you"},{name:"promote",description:"Promote this node to an orchestrator \u2014 /promote, or /promote <kind> to specialize"},{name:"resume",description:"Open the canvas navigator and swap THIS pane onto the chosen node; parked residents wake only on submitted input"},{name:"resume-session",description:"Switch this node onto one of its saved pi sessions \u2014 picker, or /resume-session <session-path>"},{name:"context",description:"Browse the files in this node\u2019s and its subscriptions\u2019 context dirs in a read-only nvim popup"},{name:"plugins",description:"Open the interactive plugin browser for this machine"},{name:"node-metadata",description:"Inspect this node \u2014 identity, lifecycle, runtime, graph, output, paths, and agent surfaces"},{name:"mcp",description:"MCP servers \u2014 status from the adapter\u2019s config/cache; Enter (or /mcp <server>) connects, reconnects, or re-auths"},{name:"rename",description:"Rename this node everywhere \u2014 node row, viewer window, session chip, tmux pane: /rename <name>"},{name:"color",description:"Color this node \u2014 tmux pane outline + name chip: /color <color> (red, blue, #rrggbb, \u2026) or /color none"},{name:"recover",description:"After a crash or reboot: revive every disconnected node and rebuild the tmux viewer panes that were open"},{name:"mouse",description:"Toggle mouse wheel scrolling and drag-select \u2014 off restores tmux drag-select and copy-mode mouse"},{name:"copy-message",description:"Copy the newest message visible in the transcript viewport"},{name:"copy-tool",description:"Copy the newest tool call output"},{name:"copy-transcript",description:"Copy every copyable transcript block"},{name:"more-detail",description:"Show the transcript one verbosity level more open, in this viewer only (Ctrl+O)"},{name:"less-detail",description:"Show the transcript one verbosity level more collapsed, in this viewer only (Ctrl+Shift+O)"}],_=new Map([["resume-node","resume"]]),w=new Set([...g.map(t=>t.name),..._.keys()]),D=new Set(["black","red","green","yellow","blue","magenta","cyan","white","brightred","brightgreen","brightyellow","brightblue","brightmagenta","brightcyan","orange","grey","gray","default"]),M=new Set(["trust"]),T=new Set(Object.keys({off:!0,minimal:!0,low:!0,medium:!0,high:!0,xhigh:!0,max:!0})),v=new Set(h.map(t=>t.name));function b(t){return t.capabilities.nodeId}i(b,"nodeIdFor");function H(t){return t.capabilities.profileId}i(H,"profileIdFor");function N(t,e){const n=C(t,v.has(t),w.has(t));return n===void 0?void 0:e.capabilities.refusal(n,t)}i(N,"readOnlyRefusal");function ue(){return new Set([...v,...w,...M])}i(ue,"locallyConsumedCommandNames");function R(t){const e=/^\/(\S+)\s*([\s\S]*)$/.exec(t.trim());return e===null?void 0:{name:e[1],arg:e[2].trim()}}i(R,"parseSlashCommand");function de(t){return t.trimStart().startsWith("/")}i(de,"isSlashCommand");function le(t,e){const n=R(t);if(n===void 0)return!1;const{arg:r}=n,o=_.get(n.name)??n.name;if(M.has(o))return e.notify(`/${o} is not supported in attach (Phase 4)`),!0;if(w.has(o)){const s=N(o,e);return s!==void 0?(e.notify(s),!0):B(o,r,e)}if(!v.has(o))return!1;const u=N(o,e);if(u!==void 0)return e.notify(u),!0;switch(o){case"new":return e.send({type:"new_session"}),!0;case"reload":return e.send({type:"reload"}),!0;case"compact":return e.send({type:"compact",instructions:r||void 0}),!0;case"quit":return e.onQuit?(e.onQuit(),!0):(e.send({type:"bye"}),e.notify("Detaching \u2014 the engine keeps running"),!0);case"name":return r?(e.send({type:"set_session_name",name:r}),!0):m(e,"/name <display name>");case"export":{const{path:s,format:a}=Z(r,e.cwd??process.cwd());return e.send({type:"export",path:s,format:a}),e.notify(`Exporting session \u2192 ${s}`),!0}case"import":return r?(e.send({type:"switch_session",path:r}),!0):m(e,"/import <path-to-session.jsonl>");case"model":return r?(e.send({type:"set_model",model:r}),!0):f(e.openModelPicker,e,"model","/model <provider/id>");case"fork":return r?(e.send({type:"fork",entryId:r}),!0):f(e.openForkPicker,e,"fork point","/fork <entryId>");case"tree":return r?(e.send({type:"navigate_tree",targetId:r}),!0):f(e.openTreePicker,e,"tree","/tree <entryId>");case"scoped-models":return e.openScopedModelsPicker?(e.openScopedModelsPicker(),!0):(e.notify("The scoped-models view needs the read-op channel, which this viewer has not wired"),!0);case"settings":return z(r,e);case"session":return e.notify(x(e.state)),!0;case"copy":return e.onCopy?(e.onCopy(),!0):(e.notify("/copy is not available in this viewer"),!0);case"login":return e.openLoginPicker?(e.openLoginPicker(),!0):(e.notify("/login is not available in this viewer"),!0);case"logout":return e.openLogoutPicker?(e.openLogoutPicker(),!0):(e.notify("/logout is not available in this viewer"),!0);case"share":return e.send({type:"share"}),e.notify("Sharing session\u2026"),!0;case"clone":return e.send({type:"clone"}),e.notify("Cloning session\u2026"),!0;case"changelog":return e.notify("/changelog: see https://github.com/earendil-works/pi for release notes (no bundled changelog in this build)"),!0;case"hotkeys":return e.onHelp?(e.onHelp(),!0):(e.notify("/hotkeys is not available in this viewer"),!0);default:return e.notify(`/${o} is not available in attach (Phase 4)`),!0}}i(le,"dispatchSlashCommand");function P(t,e){const n=i(a=>{const d=C(a,!1,!0);return d===void 0||e.permits(d)},"permitted"),r=g.filter(a=>n(a.name)),o=new Map(g.map(a=>[a.name,a])),u=t.flatMap(a=>{const d=o.get(a.name);return d===void 0?[a]:n(a.name)?[d]:[]}),s=new Set(t.map(a=>a.name));return[...u,...r.filter(a=>!s.has(a.name))]}i(P,"withCanvasCommands");function pe(t,e){return P(t??h,e).map(n=>({name:n.name,description:n.description}))}i(pe,"slashCommandList");function ce(t,e){return P(t??h,e).map(n=>({value:`/${n.name}`,label:`/${n.name}`,description:n.description}))}i(ce,"commandAutocompleteItems");function B(t,e,n){switch(t){case"clear":return n.send({type:"new_session"}),!0;case"graph":return n.onGraph?n.onGraph():n.notify("The GRAPH overlay is not wired into the viewer yet"),!0;case"inbox":return n.onInbox?n.onInbox():n.notify("The inbox surface is not wired into the viewer yet"),!0;case"menu":return Q(n);case"tutorial":return n.send({type:"prompt",text:"The user asked for the crouter tutorial. Run `crtr sys tutorial -h`, pick the track that matches what they want to learn, and teach it one lesson per invocation \u2014 in your own words, letting them try each thing before you move on."}),!0;case"promote":return V(e,n),!0;case"resume":return e?m(n,"/resume \u2014 no argument; use /resume-session <path> to switch pi sessions"):J(n);case"resume-session":return e?(n.send({type:"switch_session",path:e}),!0):f(n.openSessionPicker,n,"session","/resume-session <session-path>");case"mcp":return n.openMcpPicker?n.openMcpPicker(e||void 0):n.notify("The MCP panel is not wired into this viewer"),!0;case"context":return W(n);case"plugins":return Y(n);case"node-metadata":return n.onNodeMetadata?n.onNodeMetadata():n.notify("Node metadata is not wired into this viewer"),!0;case"rename":return F(e,n),!0;case"color":return q(e,n);case"more-detail":return n.onMoreDetail?n.onMoreDetail():n.notify("Verbosity is not wired into this viewer"),!0;case"less-detail":return n.onLessDetail?n.onLessDetail():n.notify("Verbosity is not wired into this viewer"),!0;case"recover":return e?m(n,"/recover \u2014 no argument"):process.env.TMUX===void 0?(n.notify("/recover needs tmux"),!0):(n.notify("Recovering \u2014 reviving nodes and rebuilding panes\u2026"),j().then(r=>n.notify(X(r)),r=>n.notify(`recover failed: ${r instanceof Error?r.message:String(r)}`)),!0);case"mouse":return n.onToggleMouse?n.onToggleMouse():n.notify("Mouse reporting is not wired into this viewer"),!0;case"copy-message":return n.onCopyTarget?n.onCopyTarget("message"):n.notify("/copy-message is not available in this viewer"),!0;case"copy-tool":return n.onCopyTarget?n.onCopyTarget("tool"):n.notify("/copy-tool is not available in this viewer"),!0;case"copy-transcript":return n.onCopyTarget?n.onCopyTarget("transcript"):n.notify("/copy-transcript is not available in this viewer"),!0;default:return n.notify(`/${t} is not available in attach`),!0}}i(B,"dispatchCanvasCommand");function V(t,e){const n=b(e).trim();if(n===""){e.notify("/promote: no node to promote (viewer has no node id)");return}const r=t.trim().toLowerCase();e.notify(r?`Promoting \u2192 ${r}\u2026`:"Promoting\u2026");const o=["node","promote","--node",n,"--json"];r!==""&&o.push("--kind",r),l("crtr",o,{timeout:15e3,maxBuffer:4*1024*1024},(s,a)=>{let d=null,p=null;try{d=JSON.parse(a)}catch{d=null}if(s&&d===null){const O=typeof s.stdout=="string"?s.stdout:"";try{const $=JSON.parse(O);p=typeof $.message=="string"?$.message:null}catch{p=null}p===null&&(p=s.message)}if(d===null){e.notify(`promote failed: ${p??"unknown error"}`);return}const S=(d.roadmap_ref??"").trim();e.notify(`Promoted to ${d.kind??"orchestrator"} orchestrator \u2014 authoring roadmap${S!==""?` (${S})`:""}.`),e.send({type:"prompt",text:"You have just been promoted to an orchestrator. Your new-role guidance is arriving \u2014 read it, author your roadmap, and start delegating."})}).stdin?.end()}i(V,"promoteNode");function F(t,e){const n=b(e).trim();if(n===""){e.notify("/rename: no node to rename (viewer has no node id)");return}if(t===""){e.notify("Usage: /rename <name>");return}e.send({type:"set_session_name",name:t});const r=process.env.TMUX_PANE;process.env.TMUX!==void 0&&r!==void 0&&r!==""&&l("tmux",["select-pane","-t",r,"-T",t],()=>{}),l("crtr",["node","config","--node",n,"--name",t,"--json"],{timeout:15e3,maxBuffer:4*1024*1024},(o,u)=>{if(o){let s=null;try{const a=JSON.parse(u);s=typeof a.message=="string"?a.message:null}catch{s=null}e.notify(`rename failed: ${s??o.message}`);return}e.notify(`Renamed node \u2192 ${t}`)})}i(F,"renameNode");function c(t){return new Promise(e=>{l("tmux",t,{timeout:5e3},(n,r)=>e(n?"":r))})}i(c,"tmuxCall");async function G(t,e,n){if(n){await c(["set-option","-p","-u","-t",t,"@crtr_color"]);return}await c(["set-option","-p","-t",t,"@crtr_color",e]);for(const r of["pane-border-style","pane-active-border-style"]){const o=(await c(["show-options","-wqv","-t",t,r])).trim();if(o.includes("@crtr_color"))continue;let u=o!==""?o:(await c(["show-options","-gqv",r])).trim();u===""&&(u=r==="pane-active-border-style"?"fg=green":"default");const s=`#{?#{!=:#{@crtr_color},},fg=#{@crtr_color},${u.replace(/,/g,"#,")}}`;await c(["set-option","-w","-t",t,r,s])}}i(G,"paintPaneBorder");function q(t,e){const n=t.trim().toLowerCase();if(n==="")return e.notify("Usage: /color <color> \u2014 a name (red, blue, orange\u2026), colourN, or #rrggbb; /color none to clear"),!0;const r=n==="none"||n==="clear";if(!(r||D.has(n)||/^colour\d{1,3}$/.test(n)||/^#[0-9a-f]{6}$/.test(n)))return e.notify(`Invalid color "${n}" \u2014 use a tmux colour name (${["red","green","yellow","blue","magenta","cyan","orange"].join(", ")}, \u2026), colourN, or #rrggbb`),!0;const u=process.env.TMUX_PANE,s=process.env.TMUX!==void 0&&u!==void 0&&u!=="";return s&&G(u,n,r),e.onColor?.(r?null:n),e.notify(r?"Node color cleared":`Node colored ${n}${s?"":" (chip only \u2014 no tmux pane)"}`),!0}i(q,"colorNode");function J(t){const e=process.env.TMUX_PANE;if(process.env.TMUX===void 0||e===void 0||e==="")return t.notify("/resume needs tmux"),!0;const n=y(t.cwd??process.cwd()),r=H(t),o=r===void 0||r===""?"":` --profile-id ${y(r)}`,u=`crtr canvas browse --return-pane ${e} --cwd ${n}${o}`;return k(u,{w:"97%",h:"95%"}),!0}i(J,"resumeNode");function Q(t){const e=process.env.TMUX_PANE;if(process.env.TMUX===void 0||e===void 0||e==="")return t.notify("/menu needs tmux \u2014 the crouter action menu is a tmux menu"),!0;try{l("tmux",["display-menu","-t",e,...E().slice(1)],n=>{n&&t.notify(`/menu failed: ${n.message.split(`
|
|
2
|
+
`)[0]}`)})}catch(n){t.notify(`/menu failed: ${n.message}`)}return!0}i(Q,"openActionMenu");function W(t){if(process.env.TMUX===void 0)return t.notify("/context needs tmux"),!0;const e=b(t).trim();return e===""?(t.notify("/context: no node to root on (viewer has no node id)"),!0):(k(`crtr node inspect context --node ${y(e)}`),!0)}i(W,"openContext");function Y(t){return process.env.TMUX===void 0?(t.notify("/plugins needs tmux"),!0):(k("crtr pkg browse"),!0)}i(Y,"openPlugins");function k(t,e={w:"90%",h:"85%"}){try{l("tmux",["display-popup","-E","-w",e.w,"-h",e.h,...U(),t],()=>{})}catch{}}i(k,"popup");function m(t,e){return t.notify(`Usage: ${e}`),!0}i(m,"usage");function K(t,e,n){return t.notify(`Interactive ${e} picker isn't available over view.sock yet \u2014 use ${n}`),!0}i(K,"pickerHint");function f(t,e,n,r){return t?(t(),!0):K(e,n,r)}i(f,"openOrHint");function z(t,e){const[n,...r]=t.split(/\s+/),o=r.join(" ").trim();switch(n){case"thinking":return o?T.has(o)?(e.send({type:"set_thinking_level",level:o}),!0):(e.notify(`Invalid thinking level "${o}" \u2014 choose one of: ${[...T].join(", ")}`),!0):m(e,"/settings thinking <level>");case"auto-retry":return e.send({type:"set_auto_retry",enabled:I(o)}),!0;case"auto-compaction":return e.send({type:"set_auto_compaction",enabled:I(o)}),!0;case"":return e.openSettingsPicker?(e.openSettingsPicker(),!0):A(e);default:return A(e)}}i(z,"handleSettings");function A(t){return t.notify("Settings: /settings thinking <level> | auto-retry on|off | auto-compaction on|off"),!0}i(A,"settingsSummary");function I(t){return/^(on|true|yes|1|enabled?)$/i.test(t.trim())}i(I,"parseBool");function Z(t,e){const n=t||`${e}/pi-export-${Date.now()}.html`,r=n.endsWith(".jsonl")?"jsonl":"html";return{path:n,format:r}}i(Z,"parseExport");function x(t){return t?`Session ${t.sessionName?`"${t.sessionName}" `:""}${t.sessionId} \xB7 model ${t.model?.id??"unknown"} \xB7 thinking ${t.thinkingLevel}`:"Session info unavailable"}i(x,"describeSession");export{g as CANVAS_SLASH_COMMANDS,ce as commandAutocompleteItems,le as dispatchSlashCommand,de as isSlashCommand,ue as locallyConsumedCommandNames,pe as slashCommandList};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export interface RecoverReport {
|
|
2
|
+
revived: number;
|
|
3
|
+
failed: string[];
|
|
4
|
+
frozen: number;
|
|
5
|
+
panes: number;
|
|
6
|
+
skipped: number;
|
|
7
|
+
source: 'snapshot' | 'recent views' | 'none';
|
|
8
|
+
}
|
|
9
|
+
export declare function recover(now?: number): Promise<RecoverReport>;
|
|
10
|
+
export declare function formatReport(r: RecoverReport): string;
|
|
@@ -0,0 +1,3 @@
|
|
|
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};
|