@hydra-acp/cli 0.1.198 → 0.1.199

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +45 -45
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -36,7 +36,7 @@ stderr: ${u}`:`npm install ${n.packageSpec} failed (${l})`))})})}catch(t){if(t.c
36
36
  `:""}}function qp(n){if(n===null||typeof n!="object")return[];let e=n.rawOutput;if(e===null||typeof e!="object")return[];let t=e.metadata;if(t===null||typeof t!="object")return[];let r=t.files;if(!Array.isArray(r))return[];let s=[];for(let o of r){if(o===null||typeof o!="object")continue;let i=o;if(typeof i.filePath!="string"||i.filePath.length===0)continue;let a=i.patch,d=a!==null&&typeof a=="object"?a:void 0;s.push({path:i.filePath,...typeof i.additions=="number"?{added:i.additions}:{},...typeof i.deletions=="number"?{removed:i.deletions}:{},...typeof a=="string"?{patch:a}:{},...typeof d?.__hydraBlob=="string"?{patchRef:{hash:d.__hydraBlob,bytes:typeof d.bytes=="number"?d.bytes:0}}:{}})}return s}var mN,ZC,Wp,vi=j(()=>{"use strict";mN=new Set(["edit","delete","move"]);ZC="edit",Wp=class{kinds=new Map;note(e,t){t!==void 0&&t.length>0&&!this.kinds.has(e)&&this.kinds.set(e,t)}get(e){return this.kinds.get(e)}effective(e,t){return t!==void 0&&t.length>0?t:this.kinds.get(e)}clear(){this.kinds.clear()}get size(){return this.kinds.size}}});function Ia(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function Yw(n){let e=n.rawInput;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Qw(n){return typeof n.file_path=="string"?n.file_path:typeof n.path=="string"?n.path:void 0}function zp(n){let e=n.content;if(!Array.isArray(e))return[];let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(s.type!=="diff")continue;let o=Ia(s.oldText),i=Ia(s.newText);o===void 0&&i===void 0||t.push({...typeof s.path=="string"?{path:s.path}:{},...o?{old:o}:{},...i?{new:i}:{}})}return t}function Kp(n){let e=Yw(n);if(!e)return;let t=Qw(e);if(e.old_string!==void 0||e.new_string!==void 0){let r=Ia(e.old_string),s=Ia(e.new_string);return{...t!==void 0?{path:t}:{},...r?{old:r}:{},...s?{new:s}:{}}}if(e.content!==void 0){let r=Ia(e.content);return{...t!==void 0?{path:t}:{},old:{text:""},...r?{new:r}:{}}}}function gN(n){let e=Yw(n),t=e?Qw(e):void 0;if(!e||t===void 0||!Array.isArray(e.edits))return[];let r=[];for(let s of e.edits){if(!s||typeof s!="object")continue;let o=s,i=Ia(o.old_string),a=Ia(o.new_string);i===void 0||a===void 0||r.push({path:t,old:i,new:a})}return r}function eR(n){return qp(n).map(e=>({path:e.path,...e.patch!==void 0?{patch:{text:e.patch}}:{},...e.patchRef!==void 0?{patch:{ref:e.patchRef}}:{}}))}function Gp(n){let e=gN(n);if(e.length>0)return e;let t=zp(n).filter(s=>s.path!==void 0);if(t.length>0)return t;let r=Kp(n);return r?.path!==void 0?[r]:eR(n)}function tR(n){let e=new Set,t=Yw(n),r=[...zp(n).map(s=>s.path),Kp(n)?.path,t&&Array.isArray(t.edits)?Qw(t):void 0,...eR(n).map(s=>s.path)];for(let s of r)typeof s=="string"&&s.length>0&&e.add(s);return[...e]}function nR(n){return n.patch!==void 0?n.patch.text!==void 0?Cc(n.patch.text):{oldText:"",newText:""}:{oldText:n.old?.text??"",newText:n.new?.text??""}}var fu=j(()=>{"use strict";vi()});function pu(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}function Xw(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object")return;let t=e.claudeCode;if(!t||typeof t!="object")return;let r=t.parentToolUseId;return typeof r=="string"?r:void 0}var rR=j(()=>{"use strict"});import{posix as yN}from"path";import wN from"strip-ansi";function Gt(n){return wN(n).replace(bN,"")}function ot(n){return Gt(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function aR(n){let e=[];for(let t of n)t.patch!==void 0?e.push({path:t.path,...Cc(t.patch)}):t.patchRef!==void 0&&e.push({path:t.path,oldText:"",newText:"",patchRef:t.patchRef});return e}function Xs(n,e={}){if(!n||typeof n!="object")return null;let t=n,r=t.sessionUpdate??t.kind;if(typeof r!="string")return null;switch(r){case"agent_message_chunk":return CN(t);case"agent_thought_chunk":case"agent_thought":return RN(t);case"user_message_chunk":return AN(t);case"prompt_received":return TN(t);case"tool_call":return EN(t,e);case"tool_call_update":return ON(t,e);case"plan":return NN(t);case"current_mode_update":return DN(t);case"_hydra_current_model_update":return HN(t);case"turn_complete":return BN(t);case"_hydra_turn_started":return iR(t,"turn-started");case"_hydra_turn_ended":return iR(t,"turn-ended");case"usage_update":return IN(t);case"available_commands_update":return SN(t);case"_hydra_available_modes_update":return xN(t);case"session_info_update":return vN(t);case"config_option_update":return kN(t);default:return{kind:"unknown",sessionUpdate:r,raw:n}}}function kN(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.id!="string"||typeof s.currentValue!="string"||!Array.isArray(s.options))continue;let o=[];for(let i of s.options){if(!i||typeof i!="object")continue;let a=i;typeof a.value=="string"&&o.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:s.id,name:typeof s.name=="string"?s.name:s.id,type:"select",currentValue:s.currentValue,options:o,...typeof s.category=="string"?{category:s.category}:{}})}return{kind:"config-options",options:t}}function vN(n){let e=qt(n,"title"),t=e!==void 0?ot(e):void 0,r=n._meta,s,o;if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let d=a.agentId;if(typeof d=="string"&&(s=d),"pendingAgentSwap"in a){let c=a.pendingAgentSwap;typeof c=="string"?o=c:c===null&&(o=null)}}}if(t===void 0&&s===void 0&&o===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),s!==void 0&&(i.agentId=s),o!==void 0&&(i.pendingAgentSwap=o),i}function Jp(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t;if(typeof r.name!="string"||r.name.length===0)continue;let s=r.name.startsWith("/")?r.name:`/${r.name}`,o={name:ot(s)};typeof r.description=="string"&&(o.description=ot(r.description)),e.push(o)}return e}function SN(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:Jp(e)}:null}function xN(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.id!="string"||s.id.length===0)continue;let o={id:ot(s.id)};typeof s.name=="string"&&(o.name=ot(s.name)),typeof s.description=="string"&&(o.description=ot(s.description)),t.push(o)}return{kind:"available-modes",modes:t}}function IN(n){let e={kind:"usage-update"};if(typeof n.used=="number"&&(e.used=n.used),typeof n.size=="number"&&(e.size=n.size),n.cost&&typeof n.cost=="object"){let t=n.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function CN(n){let e=hu(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:pu(n)}}function RN(n){let e=typeof n.text=="string"?Gt(n.text):hu(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:pu(n)}}function AN(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e["hydra-acp"];if(r&&typeof r=="object"&&!Array.isArray(r)&&r.compatFor==="prompt_received")return null}let t=hu(n.content);return t===null?null:{kind:"user-text",text:t}}function TN(n){let e=UN(n.prompt);return e===null?null:{kind:"user-text",text:e}}function dR(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function cR(n){let e=zp(n)[0];if(e)return sR(e);let t=Kp(n);return t?.old?.text!==void 0&&t.new?.text!==void 0?sR(t):null}function sR(n){return{...n.path!==void 0?{path:n.path}:{},oldText:n.old?.text??"",newText:n.new?.text??"",...n.old?.ref?{oldRef:n.old.ref}:{},...n.new?.ref?{newRef:n.new.ref}:{}}}function lR(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:Gt(t)}function EN(n,e={}){let t=qt(n,"toolCallId")??qt(n,"id");if(!t)return null;let r=qt(n,"title")??qt(n,"name")??qt(n,"label")??"tool call",s=qt(n,"name")??qt(n,"title");if(dR(s)){let b=lR(n);if(b!==null){let g=qt(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:b};return g!==void 0&&(h.status=g),h}}let o=pR(ot(r),n,e),i=qt(n,"status"),a=qt(n,"kind"),d={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(d.status=i),a!==void 0&&(d.rawKind=a);let c=cR(n);c!==null&&(d.editDiff=c);let l=fR(n);l!==void 0&&(d.detail=l);let u=Zw(n);u!==void 0&&(d.detailFull=u);let f=uR(n);f!==void 0&&(d.locations=f);let p=pu(n);p!==void 0&&(d.workerTaskId=p);let m=Xw(n);return m!==void 0&&(d.parentToolUseId=m),d}function uR(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r;if(typeof s.path!="string"||s.path.length===0)continue;let o={path:s.path};typeof s.line=="number"&&Number.isFinite(s.line)&&s.line>=1&&(o.line=Math.floor(s.line)),t.push(o)}return t.length>0?t:void 0}function fR(n){let e=Zw(n);if(e===void 0)return;let t=ot(e),r=n.rawInput;return r&&typeof r.command=="string"?_N(t,oR):$N(t,oR)}function Zw(n){let e=n.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return Gt(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let r=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(r!==void 0&&r.length>0)return V(ot(r))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let r=t.path;if(typeof r=="string"&&r.length>0)return V(ot(r))}}}function MN(n){for(let e of PN)if(n.startsWith(e))return!0;return!1}function pR(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return V(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let r=e.rawInput;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=r,o=[s.file_path,s.filePath,s.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${n}`||i.endsWith(`/${n}`)||i===n))return V(i)}return MN(n)?V(`/${n}`):t.cwd&&t.cwd.length>0?V(yN.resolve(t.cwd,n)):n}function _N(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function $N(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),r=t.indexOf("/");return r>=0&&r<e/2?`\u2026${t.slice(r)}`:`\u2026${t}`}function ON(n,e={}){let t=qt(n,"toolCallId")??qt(n,"id");if(!t)return null;let r=qt(n,"title"),s=r!==void 0?pR(ot(r),n,e):void 0,o=qt(n,"status"),i=cR(n),a=fR(n),d=eb(n);if(!(s!==void 0||i!==null||a!==void 0||d!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let l=qt(n,"name")??r;if(dR(l)){let g={kind:"exit-plan-mode",toolCallId:t},h=lR(n);return h!==null&&(g.plan=h),o!==void 0&&(g.status=o),g}let u={kind:"tool-call-update",toolCallId:t};s!==void 0&&(u.title=s),a!==void 0&&(u.detail=a);let f=Zw(n);f!==void 0&&(u.detailFull=f);let p=uR(n);if(p!==void 0&&(u.locations=p),d!==void 0&&(u.resultSummary=d),o!==void 0&&(u.status=o),i!==null&&(u.editDiff=i),o==="failed"){let g=FN(n);g!==null&&(u.errorText=g),LN(n,g)&&(u.upstreamInterrupted=!0)}let m=pu(n);m!==void 0&&(u.workerTaskId=m);let b=Xw(n);return b!==void 0&&(u.parentToolUseId=b),u}function eb(n){if(!n||typeof n!="object")return;let e=n.rawOutput;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,r=l=>{let u=t[l];return typeof u=="number"&&Number.isFinite(u)?u:void 0},s=(l,u,f=`${u}s`)=>`${l} ${l===1?u:f}`,o=[],i=r("totalMatches");i!==void 0&&o.push(s(i,"match","matches"));let a=r("totalFiles");a!==void 0&&o.push(s(a,"file"));let d=r("referenceCount");d!==void 0&&o.push(s(d,"reference")),o.length>0&&t.truncated===!0&&o.push("truncated");let c=r("exitCode");return c!==void 0&&c!==0&&o.push(`exit ${c}`),o.length>0?o.join(", "):void 0}function hR(n){if(!n||typeof n!="object")return[];let e=n.rawOutput;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e,r=[];for(let s of["content","stdout","stderr"]){let o=t[s];typeof o=="string"?o.length>0&&r.push(o):o&&typeof o=="object"&&!Array.isArray(o)&&r.push(o)}return r}function FN(n){let e=n.content;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let o=hu(r.content);if(o!==null&&o.length>0)return o}let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.error;if(typeof r=="string"&&r.length>0)return Gt(r)}return null}function LN(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let r=t.metadata;if(r&&typeof r=="object"&&r.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function NN(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let r of e){if(!r||typeof r!="object")continue;let s=r,o=typeof s.content=="string"?ot(s.content):void 0;if(!o)continue;let i={content:o};typeof s.status=="string"&&(i.status=s.status),typeof s.priority=="string"&&(i.priority=s.priority),t.push(i)}return{kind:"plan",entries:t}}function DN(n){let e=qt(n,"currentModeId")??qt(n,"currentMode")??qt(n,"mode");return e?{kind:"mode-changed",mode:ot(e)}:null}function HN(n){let e=qt(n,"currentModel")??qt(n,"model");if(!e)return null;let t=n.availableModels,r=Array.isArray(t)?t.map(s=>typeof s=="object"&&s!==null?s.modelId:typeof s=="string"?s:void 0).filter(s=>typeof s=="string"&&s.length>0):void 0;return{kind:"model-changed",model:ot(e),...r&&r.length>0?{availableModels:r}:{}}}function BN(n){let e=qt(n,"stopReason"),t=n._meta,r=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,s={kind:"turn-complete"};return e!==void 0&&(s.stopReason=e),r&&(s.amended=!0),s}function iR(n,e){let r=n._meta?.["hydra-acp"],s=r?.unsolicited===!0;if(e==="turn-started"){let i=r?.cause?.label,a={kind:e,unsolicited:s};return typeof i=="string"&&i.length>0&&(a.cause=i),a}let o={kind:e,unsolicited:s};return typeof r?.reason=="string"&&(o.reason=r.reason),o}function hu(n){if(typeof n=="string")return Gt(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?Gt(e.text):null}function UN(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let r=hu(t);r!==null&&e.push(r)}return e.length===0?null:e.join("")}function qt(n,e){let t=n[e];return typeof t=="string"?t:void 0}var bN,oR,PN,Ho=j(()=>{"use strict";Se();vi();fu();rR();bN=/[\x00-\x08\x0b-\x1f\x7f]/g;oR=64;PN=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function tb(n,e){let t=Gt(n).split(`
37
37
  `),r=Gt(e).split(`
38
38
  `);return t.length>0&&t[t.length-1]===""&&t.pop(),r.length>0&&r[r.length-1]===""&&r.pop(),{oldLines:t,newLines:r}}function Vp(n,e){let{oldLines:t,newLines:r}=tb(n,e),s=0,o=0;for(let i of nb(t,r))i.op==="+"?s++:i.op==="-"&&o++;return{added:s,removed:o}}function nb(n,e){let t=0,r=Math.min(n.length,e.length);for(;t<r&&n[t]===e[t];)t++;let s=n.length,o=e.length;for(;s>t&&o>t&&n[s-1]===e[o-1];)s--,o--;let i=[];for(let a=0;a<t;a++)i.push({op:"=",text:n[a]});i.push(...WN(n.slice(t,s),e.slice(t,o)));for(let a=s;a<n.length;a++)i.push({op:"=",text:n[a]});return i}function WN(n,e){let t=n.length,r=e.length;if(t===0||r===0){let d=[];for(let c of n)d.push({op:"-",text:c});for(let c of e)d.push({op:"+",text:c});return d}let s=Array.from({length:t+1},()=>new Array(r+1).fill(0));for(let d=t-1;d>=0;d--)for(let c=r-1;c>=0;c--)n[d]===e[c]?s[d][c]=s[d+1][c+1]+1:s[d][c]=Math.max(s[d+1][c],s[d][c+1]);let o=[],i=0,a=0;for(;i<t&&a<r;)n[i]===e[a]?(o.push({op:"=",text:n[i]}),i++,a++):s[i+1][a]>=s[i][a+1]?(o.push({op:"-",text:n[i]}),i++):(o.push({op:"+",text:e[a]}),a++);for(;i<t;)o.push({op:"-",text:n[i]}),i++;for(;a<r;)o.push({op:"+",text:e[a]}),a++;return o}var rb=j(()=>{"use strict";Ho()});function jN(n){let e=0,t=0,r=!1;for(let s of n.split(`
39
- `)){if(s.startsWith("@@")){r=!0;continue}r&&(s.startsWith("+")?e++:s.startsWith("-")&&t++)}return{added:e,removed:t}}function qN(n){let e=[];for(let t of Gp(n))if(t.path!==void 0){if(t.patch!==void 0){t.patch.text!==void 0&&e.push({path:t.path,...jN(t.patch.text)});continue}t.old!==void 0&&t.old.text===void 0||t.new!==void 0&&t.new.text===void 0||e.push({path:t.path,...Vp(t.old?.text??"",t.new?.text??"")})}return e}function mR(n){let e=n.update;if(!e||e.sessionUpdate!=="tool_call"&&e.sessionUpdate!=="tool_call_update")return n;let t=qN(e);if(t.length===0)return n;let r=e._meta??{},s=r[sb]??{};return{...n,update:{...e,_meta:{...r,[sb]:{...s,editStats:t}}}}}function gR(n){if(!n||typeof n!="object")return;let t=n._meta?.[sb];if(!Array.isArray(t?.editStats))return;let r=[];for(let s of t.editStats){let o=s;typeof o.path=="string"&&typeof o.added=="number"&&typeof o.removed=="number"&&r.push({path:o.path,added:o.added,removed:o.removed})}return r}var sb,ob=j(()=>{"use strict";fu();rb();sb="hydra-acp"});function ib(n){for(let e of yR)if(n.startsWith(e)&&n.length>e.length)return n.slice(e.length)}function wR(n){return yR.map(e=>`${e}${n}`)}var yR,bR=j(()=>{"use strict";yR=["hydra-acp-","hydra-"]});function Zs(n){return`${n.name}:${n.localId}`}function eo(n){let e=n.indexOf(":");if(e===-1)return;let t=n.slice(0,e),r=n.slice(e+1);if(!(t.length===0||r.length===0))return{name:t,localId:r}}var mu=j(()=>{"use strict"});import{createHmac as zN}from"crypto";function KN(n,e){return zN("sha256",n).update(e).digest("hex")}function ab(n,e){let t=JSON.stringify(e),r=KN(n.secret,t);fetch(n.callbackUrl,{method:"POST",headers:{"Content-Type":"application/json","X-Hydra-Turn-Notify-Signature":r},body:t}).catch(()=>{})}var kR=j(()=>{"use strict"});import*as SR from"fs/promises";function eD(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var GN,JN,Rc,VN,YN,QN,XN,ZN,vR,Yp,xR=j(()=>{"use strict";GN=64*1024*1024,JN=1*1024*1024,Rc=64*1024,VN=6e4,YN=100,QN=1e3,XN=64*1024,ZN=256*1024,vR=20;Yp=class{storage;maxCapacityBytes;currentCapacityBytes;writeCursor=0;closed=!1;waiters=[];filePath;fileCapBytes;fileBytesWritten=0;fileCapReached=!1;onFileCapReached;logWriteError;fileWriteChain=Promise.resolve();constructor(e={}){if(this.maxCapacityBytes=e.capacityBytes??GN,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(JN,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,t){let r=Math.max(0,Math.min(t,Rc));if(r===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let s=e,o=0,i=this.oldestAvailable;s<i&&(o=i-s,s=i);let a=this.writeCursor-s;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:s};return o>0&&(u.gap=o),this.closed&&(u.eof=!0),u}let d=Math.min(a,r),l={bytes:this.sliceFromRing(s,d),nextCursor:s+d};return o>0&&(l.gap=o),this.closed&&s+d>=this.writeCursor&&(l.eof=!0),l}tail(e){let t=Math.max(0,Math.min(e,Rc)),r=this.oldestAvailable,s=this.writeCursor-t,o=Math.max(r,s),i=s<r;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let t=Math.max(0,Math.min(e,Rc)),r=this.oldestAvailable,s=r>0,o=r,i=Math.min(this.writeCursor,o+t);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:s}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let r=Math.max(0,Math.min(t,VN));return r===0?Promise.resolve("timeout"):new Promise(s=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),s(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,s("timeout")},r)};this.waiters.push(o)})}grep(e){let t=this.oldestAvailable,r=e.cursor,s=r??t,o=0;r!==void 0&&r<t&&(o=t-r,s=t),s>this.writeCursor&&(s=this.writeCursor);let i=this.sliceFromRing(s,this.writeCursor-s),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(eD(e.pattern),d),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??YN,QN)),f=Math.max(1,Math.min(e.maxBytes??XN,ZN)),p=Math.max(0,Math.min(e.contextBefore??0,vR)),m=Math.max(0,Math.min(e.contextAfter??0,vR)),b=[],g=[],h=[],y=0,k=!1,S=0,I=0,x=(E,M)=>{for(let z of h)z.remaining>0&&(z.match.after===void 0&&(z.match.after=[]),z.match.after.push({cursor:E,line:M}),z.remaining--,y+=M.length);for(;h.length>0&&h[0].remaining===0;)h.shift();if(c.test(M)!==l&&b.length<u){let z={cursor:E,line:M};if(p>0&&g.length>0){z.before=g.slice();for(let re of z.before)y+=re.line.length}y+=M.length,b.push(z),m>0&&h.push({match:z,remaining:m})}if(p>0)for(g.push({cursor:E,line:M});g.length>p;)g.shift();let K=b.length>=u&&h.length===0,Y=y>=f;return K||Y};for(let E=0;E<i.length;E++){if(i[E]!==10)continue;let M=i.subarray(S,E).toString("utf8"),F=s+S;if(S=E+1,I=S,x(F,M)){k=!0;break}}if(!k&&S<i.length&&this.closed){let E=i.subarray(S).toString("utf8"),M=s+S;x(M,E)&&(k=!0),I=i.length}let C=Math.min(s+I,this.writeCursor),$={matches:b,truncated:k,nextCursor:C,scannedBytes:I};return o>0&&($.gap=o),this.closed&&C>=this.writeCursor&&($.eof=!0),$}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let r of t)r.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let r=this.currentCapacityBytes;for(;r<t&&r<this.maxCapacityBytes;)r=Math.min(this.maxCapacityBytes,r*2);if(r===this.currentCapacityBytes)return;let s=Buffer.alloc(r);this.storage.copy(s,0,0,this.writeCursor),this.storage=s,this.currentCapacityBytes=r}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let o=t-this.currentCapacityBytes;e.copy(this.storage,0,o,t);return}let r=this.writeCursor%this.currentCapacityBytes,s=this.currentCapacityBytes-r;t<=s?e.copy(this.storage,r,0,t):(e.copy(this.storage,r,0,s),e.copy(this.storage,0,s,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let r=Buffer.alloc(t),s=e%this.currentCapacityBytes,o=Math.min(t,this.currentCapacityBytes-s);return this.storage.copy(r,0,s,s+o),o<t&&this.storage.copy(r,o,0,t-o),r}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let r=this.fileCapBytes-this.fileBytesWritten;if(r<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let s=e.length<=r?e:e.subarray(0,r);this.fileBytesWritten+=s.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>SR.appendFile(t,s)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Ac,u8,IR=j(()=>{"use strict";Ac=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent | status>",description:"Schedule a swap to a different agent (synthesizes a brief in the target's idiom, rotates on idle); `status` reports any pending swap"},{verb:"workspace",name:"hydra workspace",argsHint:"<start [name] [--clean] | sync | merge | apply | stop | detach | clean [--deep] | discard | status>",description:"Move this session into an isolated workspace so its edits cannot collide with other work, then land or discard them. `start` copies your uncommitted changes in and leaves the real tree untouched; `start --clean` leaves them behind so the workspace begins at the last commit. `stop` merges and returns; `discard` throws the work away and returns; `detach` returns without merging, leaving the workspace and its branch intact; `merge` lands the work without leaving; `apply` also stays, but delivers the work as ONE staged, uncommitted changeset instead of as the agent's commits, so you review and commit it yourself, with no fast-forward needed, which is what makes it work once the source has moved on; `clean` throws away everything done in the workspace and stays there, putting it back exactly as `start --clean` would have made it (add `--deep` to rebuild dependencies and carried config files too, rather than keeping them); `sync` pulls the source's committed history INTO the workspace, so you can test against what you will land onto, and because landing is fast-forward-only, syncing is also how you recover once the source has moved on. `start <name>` naming a workspace another live session is already in JOINS it instead of making a second one, so two sessions can share a checkout deliberately: edits interleave, `stop` behaves as `detach` while anyone else is still there, and the work lands when the last of them leaves."},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"fork",name:"hydra fork",argsHint:"[--verbatim] [prompt]",description:"Fork this conversation into a new session (default: synthesis mode with a synopsis brief; pass --verbatim to slice at the last completed turn instead). A prompt is sent to the fork as its first turn once it's ready."},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],u8=new Map(Ac.map(n=>[n.verb,n]))});function CR(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function Tc(n,e){return Ec(n,e.map(t=>t.modelId))}function Ec(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=CR(n),r=e.filter(o=>CR(o)===t);if(r.length===1)return{kind:"resolved",modelId:r[0],requested:n};if(r.length>1)return{kind:"ambiguous",requested:n,candidates:r};let s=n.toLowerCase();if(s.length>0){let o=e.filter(i=>i.toLowerCase().includes(s));if(o.length===1)return{kind:"resolved",modelId:o[0],requested:n};if(o.length>1)return{kind:"ambiguous",requested:n,candidates:o}}return{kind:"unknown",requested:n}}var Qp=j(()=>{"use strict"});function sD(n){if(!n||n.status!=="completed"||n.sessionUpdate!=="tool_call"&&n.sessionUpdate!=="tool_call_update")return!1;let e=n._meta,t=e!==null&&typeof e=="object"&&nD in e;return n.title===tD||t}function oD(n){if(!n||n.sessionUpdate!=="agent_message_chunk")return!1;let e=n.content;return!e||typeof e!="object"||Array.isArray(e)?!1:e.text===rD}function AR(n){return sD(n)||oD(n)}function TR(n,e){return n!==void 0&&n>=aD&&e>0&&e<n*dD}var tD,nD,rD,RR,iD,aD,dD,Xp,ER=j(()=>{"use strict";tD="Compact conversation",nD="contextCompaction",rD=`
39
+ `)){if(s.startsWith("@@")){r=!0;continue}r&&(s.startsWith("+")?e++:s.startsWith("-")&&t++)}return{added:e,removed:t}}function qN(n){let e=[];for(let t of Gp(n))if(t.path!==void 0){if(t.patch!==void 0){t.patch.text!==void 0&&e.push({path:t.path,...jN(t.patch.text)});continue}t.old!==void 0&&t.old.text===void 0||t.new!==void 0&&t.new.text===void 0||e.push({path:t.path,...Vp(t.old?.text??"",t.new?.text??"")})}return e}function mR(n){let e=n.update;if(!e||e.sessionUpdate!=="tool_call"&&e.sessionUpdate!=="tool_call_update")return n;let t=qN(e);if(t.length===0)return n;let r=e._meta??{},s=r[sb]??{};return{...n,update:{...e,_meta:{...r,[sb]:{...s,editStats:t}}}}}function gR(n){if(!n||typeof n!="object")return;let t=n._meta?.[sb];if(!Array.isArray(t?.editStats))return;let r=[];for(let s of t.editStats){let o=s;typeof o.path=="string"&&typeof o.added=="number"&&typeof o.removed=="number"&&r.push({path:o.path,added:o.added,removed:o.removed})}return r}var sb,ob=j(()=>{"use strict";fu();rb();sb="hydra-acp"});function ib(n){for(let e of yR)if(n.startsWith(e)&&n.length>e.length)return n.slice(e.length)}function wR(n){return yR.map(e=>`${e}${n}`)}var yR,bR=j(()=>{"use strict";yR=["hydra-acp-","hydra-"]});function Zs(n){return`${n.name}:${n.localId}`}function eo(n){let e=n.indexOf(":");if(e===-1)return;let t=n.slice(0,e),r=n.slice(e+1);if(!(t.length===0||r.length===0))return{name:t,localId:r}}var mu=j(()=>{"use strict"});import{createHmac as zN}from"crypto";function KN(n,e){return zN("sha256",n).update(e).digest("hex")}function ab(n,e){let t=JSON.stringify(e),r=KN(n.secret,t);fetch(n.callbackUrl,{method:"POST",headers:{"Content-Type":"application/json","X-Hydra-Turn-Notify-Signature":r},body:t}).catch(()=>{})}var kR=j(()=>{"use strict"});import*as SR from"fs/promises";function eD(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var GN,JN,Rc,VN,YN,QN,XN,ZN,vR,Yp,xR=j(()=>{"use strict";GN=64*1024*1024,JN=1*1024*1024,Rc=64*1024,VN=6e4,YN=100,QN=1e3,XN=64*1024,ZN=256*1024,vR=20;Yp=class{storage;maxCapacityBytes;currentCapacityBytes;writeCursor=0;closed=!1;waiters=[];filePath;fileCapBytes;fileBytesWritten=0;fileCapReached=!1;onFileCapReached;logWriteError;fileWriteChain=Promise.resolve();constructor(e={}){if(this.maxCapacityBytes=e.capacityBytes??GN,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(JN,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,t){let r=Math.max(0,Math.min(t,Rc));if(r===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let s=e,o=0,i=this.oldestAvailable;s<i&&(o=i-s,s=i);let a=this.writeCursor-s;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:s};return o>0&&(u.gap=o),this.closed&&(u.eof=!0),u}let d=Math.min(a,r),l={bytes:this.sliceFromRing(s,d),nextCursor:s+d};return o>0&&(l.gap=o),this.closed&&s+d>=this.writeCursor&&(l.eof=!0),l}tail(e){let t=Math.max(0,Math.min(e,Rc)),r=this.oldestAvailable,s=this.writeCursor-t,o=Math.max(r,s),i=s<r;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let t=Math.max(0,Math.min(e,Rc)),r=this.oldestAvailable,s=r>0,o=r,i=Math.min(this.writeCursor,o+t);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:s}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let r=Math.max(0,Math.min(t,VN));return r===0?Promise.resolve("timeout"):new Promise(s=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),s(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,s("timeout")},r)};this.waiters.push(o)})}grep(e){let t=this.oldestAvailable,r=e.cursor,s=r??t,o=0;r!==void 0&&r<t&&(o=t-r,s=t),s>this.writeCursor&&(s=this.writeCursor);let i=this.sliceFromRing(s,this.writeCursor-s),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(eD(e.pattern),d),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??YN,QN)),f=Math.max(1,Math.min(e.maxBytes??XN,ZN)),p=Math.max(0,Math.min(e.contextBefore??0,vR)),m=Math.max(0,Math.min(e.contextAfter??0,vR)),b=[],g=[],h=[],y=0,k=!1,S=0,I=0,x=(P,M)=>{for(let z of h)z.remaining>0&&(z.match.after===void 0&&(z.match.after=[]),z.match.after.push({cursor:P,line:M}),z.remaining--,y+=M.length);for(;h.length>0&&h[0].remaining===0;)h.shift();if(c.test(M)!==l&&b.length<u){let z={cursor:P,line:M};if(p>0&&g.length>0){z.before=g.slice();for(let re of z.before)y+=re.line.length}y+=M.length,b.push(z),m>0&&h.push({match:z,remaining:m})}if(p>0)for(g.push({cursor:P,line:M});g.length>p;)g.shift();let K=b.length>=u&&h.length===0,Y=y>=f;return K||Y};for(let P=0;P<i.length;P++){if(i[P]!==10)continue;let M=i.subarray(S,P).toString("utf8"),F=s+S;if(S=P+1,I=S,x(F,M)){k=!0;break}}if(!k&&S<i.length&&this.closed){let P=i.subarray(S).toString("utf8"),M=s+S;x(M,P)&&(k=!0),I=i.length}let C=Math.min(s+I,this.writeCursor),$={matches:b,truncated:k,nextCursor:C,scannedBytes:I};return o>0&&($.gap=o),this.closed&&C>=this.writeCursor&&($.eof=!0),$}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let r of t)r.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let r=this.currentCapacityBytes;for(;r<t&&r<this.maxCapacityBytes;)r=Math.min(this.maxCapacityBytes,r*2);if(r===this.currentCapacityBytes)return;let s=Buffer.alloc(r);this.storage.copy(s,0,0,this.writeCursor),this.storage=s,this.currentCapacityBytes=r}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let o=t-this.currentCapacityBytes;e.copy(this.storage,0,o,t);return}let r=this.writeCursor%this.currentCapacityBytes,s=this.currentCapacityBytes-r;t<=s?e.copy(this.storage,r,0,t):(e.copy(this.storage,r,0,s),e.copy(this.storage,0,s,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let r=Buffer.alloc(t),s=e%this.currentCapacityBytes,o=Math.min(t,this.currentCapacityBytes-s);return this.storage.copy(r,0,s,s+o),o<t&&this.storage.copy(r,o,0,t-o),r}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let r=this.fileCapBytes-this.fileBytesWritten;if(r<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let s=e.length<=r?e:e.subarray(0,r);this.fileBytesWritten+=s.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>SR.appendFile(t,s)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Ac,u8,IR=j(()=>{"use strict";Ac=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent | status>",description:"Schedule a swap to a different agent (synthesizes a brief in the target's idiom, rotates on idle); `status` reports any pending swap"},{verb:"workspace",name:"hydra workspace",argsHint:"<start [name] [--clean] | sync | merge | apply | stop | detach | clean [--deep] | discard | status>",description:"Move this session into an isolated workspace so its edits cannot collide with other work, then land or discard them. `start` copies your uncommitted changes in and leaves the real tree untouched; `start --clean` leaves them behind so the workspace begins at the last commit. `stop` merges and returns; `discard` throws the work away and returns; `detach` returns without merging, leaving the workspace and its branch intact; `merge` lands the work without leaving; `apply` also stays, but delivers the work as ONE staged, uncommitted changeset instead of as the agent's commits, so you review and commit it yourself, with no fast-forward needed, which is what makes it work once the source has moved on; `clean` throws away everything done in the workspace and stays there, putting it back exactly as `start --clean` would have made it (add `--deep` to rebuild dependencies and carried config files too, rather than keeping them); `sync` pulls the source's committed history INTO the workspace, so you can test against what you will land onto, and because landing is fast-forward-only, syncing is also how you recover once the source has moved on. `start <name>` naming a workspace another live session is already in JOINS it instead of making a second one, so two sessions can share a checkout deliberately: edits interleave, `stop` behaves as `detach` while anyone else is still there, and the work lands when the last of them leaves."},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"fork",name:"hydra fork",argsHint:"[--verbatim] [prompt]",description:"Fork this conversation into a new session (default: synthesis mode with a synopsis brief; pass --verbatim to slice at the last completed turn instead). A prompt is sent to the fork as its first turn once it's ready."},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],u8=new Map(Ac.map(n=>[n.verb,n]))});function CR(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function Tc(n,e){return Ec(n,e.map(t=>t.modelId))}function Ec(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=CR(n),r=e.filter(o=>CR(o)===t);if(r.length===1)return{kind:"resolved",modelId:r[0],requested:n};if(r.length>1)return{kind:"ambiguous",requested:n,candidates:r};let s=n.toLowerCase();if(s.length>0){let o=e.filter(i=>i.toLowerCase().includes(s));if(o.length===1)return{kind:"resolved",modelId:o[0],requested:n};if(o.length>1)return{kind:"ambiguous",requested:n,candidates:o}}return{kind:"unknown",requested:n}}var Qp=j(()=>{"use strict"});function sD(n){if(!n||n.status!=="completed"||n.sessionUpdate!=="tool_call"&&n.sessionUpdate!=="tool_call_update")return!1;let e=n._meta,t=e!==null&&typeof e=="object"&&nD in e;return n.title===tD||t}function oD(n){if(!n||n.sessionUpdate!=="agent_message_chunk")return!1;let e=n.content;return!e||typeof e!="object"||Array.isArray(e)?!1:e.text===rD}function AR(n){return sD(n)||oD(n)}function TR(n,e){return n!==void 0&&n>=aD&&e>0&&e<n*dD}var tD,nD,rD,RR,iD,aD,dD,Xp,ER=j(()=>{"use strict";tD="Compact conversation",nD="contextCompaction",rD=`
40
40
 
41
41
  Compacting completed.`;RR=[`## Objective
42
42
  `,`## Important Details
@@ -58,11 +58,11 @@ Compacting completed.`;RR=[`## Objective
58
58
  ${r.join(`
59
59
  `)}`}function Cb(n,e){for(let t of n.split(/\r?\n/)){let r=t.trim();if(r)return r.length>e?`${r.slice(0,e)}\u2026`:r}}var eA,tA,kb,TD,ED,PD,MD,Yt,GR,_D,rh,$D,OD,vb,HD,BD,UD,Mc,WD,qD,VR,KD,dH,mr=j(()=>{"use strict";ob();bR();Bp();mu();Jw();kR();vi();xR();IR();Qp();uu();ER();cb();LR();BR();qR();bb();fn();kc();eA="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",tA=ZR(eA,16),kb=ZR(eA,16),TD=20,ED=20,PD=5,MD=32,Yt="hydra_session_";GR=["start","merge","apply","sync","stop","detach","discard","clean","status"],_D=1e3,rh=300*1e3,$D=64,OD=new Set(["task-notification","peer","coordinator","observer","observer-activity"]);vb=120;HD=128,BD=new Set(["local_bash"]),UD=1e3,Mc=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;modelVerb=Qs;modelVerbConfirmed=!1;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;side;forkSynthesisState;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;_summarizedThroughEntry;get summarizedThroughEntry(){return this._summarizedThroughEntry}set summarizedThroughEntry(e){this._summarizedThroughEntry=e}currentModel;currentMode;compactionState;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;agentTurnInFlight=!1;swapInFlight=!1;opencodeSummary=new Xp;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleWorkspaceSnapshotHook;scheduleCompactionHook;resolveAgentIdHook;getCompactionStateHook;getUpstreamGenerationsHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;lastUnsolicitedCancelAt=0;cancelReopenStreak=0;static UNSOLICITED_REOPEN_WINDOW_MS=1e4;static UNSOLICITED_REOPEN_LIMIT=3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}_titleSeedPending=!0;_upstreamRespawned=!1;promptStartedAt;turnRanTool=!1;unsolicitedTurn;pendingSteerDetach;supersededAutonomousTurn;autonomousSalvage;lastBackgroundTask;toolLabels=new Map;armedTasks=new Map;lastArmedBroadcast;liveBackgroundTasks=new Map;sawBackgroundTaskLevel=!1;sawTurnComplete=!1;appendCount=0;historyMaxEntries;compactEvery;permissionCallbacks=new Map;attentionFlags=new Map;get hasPermissionFlag(){for(let e of this.attentionFlags.values())if(e.source==="daemon"&&e.reason.startsWith("permission:"))return!0;return!1}attentionFlagsChangeHandlers=[];internalPromptCapture;idleTimeoutMs;idleTimer;orphanTimeoutMs;orphanTimer;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;lastSeq=0;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;persistWatermarkHook;uncompactHook;forkHook;mcpServersConfig;forwardedEnv;workspace;workspaceError;workspaceNotes=[];workspaceHook;workspacePreambleSent=!1;formerWorkspace;departureNoteSent=!1;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Wp;filesEditedSeen=new Set;openToolCalls=new Map;agentChangeHandlers=[];retiringGenerationCost;retiringGenerationUsed;rotationLifetimeCost;agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];configOptionsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;costLedgerProbe;get persistableUsage(){if(!(!this._currentUsage&&!this.cumulativeCost))return{...this._currentUsage??{},...this.cumulativeCost?{cumulativeCost:this.cumulativeCost}:{cumulativeCost:void 0}}}get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},t=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:t||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;pendingTurnNotifiers=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${Yt}${tA()}`,this.cwd=e.cwd,this.workspace=e.workspace,this.workspaceError=e.workspaceError,this.workspaceHook=e.workspaceHook,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.side=e.side,this.forkSynthesisState=e.forkSynthesisState,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleWorkspaceSnapshotHook=e.scheduleWorkspaceSnapshot,this.scheduleCompactionHook=e.scheduleCompaction,this.resolveAgentIdHook=e.resolveAgentId,this.getCompactionStateHook=e.getCompactionState,this.getUpstreamGenerationsHook=e.getUpstreamGenerations,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.reloadsUpstreamLedger&&this.armCostLedgerProbe(),e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),e.agentConfigOptions&&e.agentConfigOptions.length>0&&(this.agentAdvertisedConfigOptions=[...e.agentConfigOptions]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.orphanTimeoutMs=e.orphanTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.idleEventTimeoutMs>0&&this.onIdle(t=>t.notifyChain("session.idle",{}),{debounceMs:this.idleEventTimeoutMs}),this.spawnReplacementAgent=e.spawnReplacementAgent,this.mintMcpServersForSwap=e.mintMcpServersForSwap,this.loadExistingAgentSession=e.loadExistingAgentSession,this.clearRollbackBreadcrumbHook=e.clearRollbackBreadcrumbHook,this.onCompactionSwapHook=e.onCompactionSwapHook,this.persistWatermarkHook=e.persistWatermarkHook,this.uncompactHook=e.uncompactHook,this.forkHook=e.forkHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0,this._titleSeedPending=!1),e.upstreamRespawned&&(this._upstreamRespawned=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let t=e.compactionState;(t.status==="requested"||t.status==="running"||t.status==="swap_pending"||t.status==="swap_deferred")&&(t.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:t.attempts}:this._liveCompactionPhase={phase:t.status==="requested"?"started":"iteration",iter:t.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let t of e.attentionFlags)this.attentionFlags.set(`${t.source}::${t.reason}`,t);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??_D,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.resetModelVerb(e.modelVerb),this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"_hydra_available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"_hydra_current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e,t){this.resetBackgroundTaskLevel(),t?.respawn&&(this._upstreamRespawned=!0),e.connection.onNotification("session/update",r=>{if(this.internalPromptCapture){eH(this.internalPromptCapture,r);return}this.maybeEmitToolEdges(r),this.runResponseChain(r)}),e.connection.onNotification("_claude/sdkMessage",r=>{this.applyBackgroundTaskLevel(r)}),e.connection.onRequest("session/request_permission",async r=>{let s=await this.runAgentRequestChain("session/request_permission",r),o=YR(s.shortCircuit?r:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:o??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let i=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:o??null,outcome:i,sourceWasTransformer:!1}),i}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(r=>{this.handleOrphanError(r)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>n.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,t=new Set,r=0,s="session/update"){let o=e,i=s==="session/update"?this.injectCumulativeCost(e):e,a=`response:${s}`;for(let u=r;u<this.transformChain.length;u++){let f=this.transformChain[u];if(t.has(f.name)||!f.intercepts.has(a))continue;let p=`t_${kb()}`,m;try{m=await f.connection.request("hydra-acp/transformer/message",{token:p,phase:"response",method:s,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(g){this.logger?.warn(`transformer ${f.name} error on ${a}: ${g.message}`);continue}let b=m?.action??"continue";if(b==="stop")return;if(b==="processing"){let g=u,h=i,y=new Set(t),k=s;await new Promise(S=>{let I=setTimeout(()=>{this.pendingClaims.delete(p)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:p,transformerName:f.name}),this.runResponseChain(h,new Set([...y,f.name]),g+1,k).then(()=>S()).catch(()=>S()))},rh);typeof I.unref=="function"&&I.unref(),this.pendingClaims.set(p,{resolve:()=>S(),timer:I,transformerName:f.name,method:k,envelope:h,chainIdx:g,originatedBy:y,side:"response"})});return}m?.payload&&typeof m.payload=="object"&&(i=m.payload),t.add(f.name)}if(s!=="session/update")return;this.noteAgentActivity(i);let d=i.update;(AR(d)||this.agentId==="opencode"&&this.opencodeSummary.feed(d))&&this.armRecallFromSelfCompaction();let c=tH(i);if(c!==null){this.setAgentAdvertisedCommands(c);return}let l=ZD(i);if(l!==null){this.setAgentAdvertisedModes(l);return}if(this.noteModelVerbHint(QC(i.update),"session/update"),this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(o)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",mR(i))}armRecallFromSelfCompaction(){this.armRecallInPlace().catch(e=>{this.logger?.warn(`armRecallInPlace failed: ${e.message}`)})}async armRecallInPlace(){if(!this.historyStore)return;let e=await this.historyStore.getRecallTotalCount(this.sessionId).catch(()=>0);if(!(e<=(this._summarizedThroughEntry??0))){if(this._summarizedThroughEntry=e,this.persistWatermarkHook)try{this.persistWatermarkHook(e)}catch(t){this.logger?.warn(`armRecallInPlace: persistWatermarkHook failed: ${t.message}`)}this.broadcastQueueNotification("hydra-acp/context_self_compacted",{sessionId:this.sessionId})}}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let t=[];for(let r of this.clients.values()){if(e&&r.clientId===e)continue;let s={clientId:r.clientId};r.clientInfo?.name&&(s.name=r.clientInfo.name),r.clientInfo?.version&&(s.version=r.clientInfo.version),t.push(s)}return t}get turnStartedAt(){return this.promptStartedAt}get inUnsolicitedTurn(){return this.unsolicitedTurn!==void 0}get agentPid(){return this.agent.pid}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return await this.quiesceBlocker()===void 0}async quiesceBlocker(){if(this.agentTurnInFlight)return"the agent is still working; wait for the current turn to finish, then try again";if(this.unsolicitedTurn!==void 0)return"the agent is part-way through a turn it started by itself; wait for it to finish or interrupt it (^C), then try again";if(this.internalPromptCapture!==void 0)return"hydra is driving the agent right now (compaction seed or transcript injection); this clears by itself, so try again in a moment";if(this.modelChangeInFlight)return"a model change is still settling; try again in a moment";if(this.modeChangeInFlight)return"a mode change is still settling; try again in a moment";let e=this.pendingOneShotBackgroundTasks();if(e.length>0)return`${e.length} background task(s) still running (${e.join(", ")}); a swap would kill the agent process and abandon them. Wait for them to finish, or cancel them, then try again`;let t=await this.openToolCallIdsInHistory();if(t.length>0)return`${t.length} tool call(s) from an earlier turn never reported a result, so the session still reads as busy. ^C closes an abandoned chain; failing that it clears as new history accumulates`}isQuiescedSync(){return!(this.promptInFlight||this.unsolicitedTurn!==void 0||this.modeChangeInFlight||this.modelChangeInFlight)}async swapIntoWorkspace(e){await this.swapUpstream({...e.synopsis!==void 0?{artifact:e.synopsis}:{},note:e.note,framing:"swap",...e.title!==void 0?{title:e.title}:{},tailK:8,tailFloor:4,summarizedThroughEntry:e.historyLength,newCwd:e.cwd,reason:e.workspace!==void 0?"workspace-enter":"workspace-leave"}),this.workspace=e.workspace,e.left!==void 0?(this.formerWorkspace={path:e.left.path,sourceCwd:e.cwd,removed:e.left.removed},this.departureNoteSent=!1):this.formerWorkspace=void 0}async swapUpstream(e){let t=await this.quiesceBlocker();if(t!==void 0)throw new Error(`session is not quiesced for swap: ${t}`);if(this.swapInFlight)throw new Error("a swap is already in progress for this session");this.swapInFlight=!0;try{await this.doSwapUpstream(e)}finally{this.swapInFlight=!1}}async doSwapUpstream(e){this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let t=this.agentId,r=e.newAgentId??this.agentId,s=r!==this.agentId,o=e.reason!==void 0&&e.reason!=="compaction"?e.reason:s?"agent-swap":"compaction",i=e.newCwd??this.cwd,a=this.agentArgs,d=this.forwardedEnv,c=this.currentModel,l=this.currentMode,u=this.spawnReplacementAgent;if(!u)throw new Error("agent spawning not configured for this session");let f=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],p=await u({agentId:r,cwd:i,agentArgs:a,...d?{forwardedEnv:d}:{},mcpServers:f});if(this.accumulateAndResetCost(),this.cwd=i,this.wireAgent(p.agent,{respawn:!0}),!s){let F=await xa({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:c,agentReportedModel:p.initialModel,logger:this.logger});this.applyAgentConfigOptionResponse(F.result,"model"),await Sa({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:l,agentReportedMode:p.initialMode,logger:this.logger})}p.agent.connection.drainBuffered("session/update");let m=[];if(this.historyStore)try{m=await this.historyStore.load(this.sessionId)}catch(F){this.logger?.warn(`swapUpstream: historyStore.load failed: ${F.message}`)}let b=gb({...e.artifact!==void 0?{synopsis:e.artifact}:{},...e.note!==void 0?{note:e.note}:{},...e.framing!==void 0?{framing:e.framing}:{},title:e.title,tail:m,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{},recallArmed:(e.summarizedThroughEntry??this._summarizedThroughEntry??0)>0});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};let g,h;try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:b}]});let F=this.internalPromptCapture;g=F.lastUsed,h=F.lastSize,this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${b.length} toolCalls=${F.toolCalls} thinkingChars=${F.thinkingChars} messageChars=${F.messageChars} used=${F.lastUsed??"?"} size=${F.lastSize??"?"} reply=${JSON.stringify(F.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}g!==void 0&&(this.maybeApplyAgentUsage({update:{sessionUpdate:"usage_update",used:g,...h!==void 0?{size:h}:{}}}),this.broadcastCurrentUsage());let y=this.upstreamSessionId,k=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let S=this.agent;if(this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,this.resetModelVerb(p.modelVerb),s&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[]),this.agentAdvertisedConfigOptions=p.initialConfigOptions??[]),this.broadcastMergedCommands(),this.broadcastConfigOptions(),this.notifyAgentChange("swapUpstream",o,e.runId,g),e.summarizedThroughEntry!==void 0&&this.persistWatermarkHook)try{this.persistWatermarkHook(e.summarizedThroughEntry)}catch(F){this.logger?.warn(`swapUpstream: persistWatermarkHook failed: ${F.message}`)}if(!s&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:y,...k!==void 0?{previousSummarizedThroughEntry:k}:{},...e.runId!==void 0?{runId:e.runId}:{}})}catch(F){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${F.message}`)}let I=await this.retireAgent(S,s?"agent switch":e.reason==="workspace-enter"||e.reason==="workspace-leave"?"workspace move":"compaction swap");this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:y,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),s||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),s&&this.broadcastAgentSwitch(t,r);let x=I.length>0?`
60
60
  Stopped ${I.length} background task(s) with the previous agent: ${I.join(", ")}. Re-arm anything still needed.
61
- `:"",E=(e.reason==="workspace-enter"||e.reason==="workspace-leave"?"":s?`
61
+ `:"",P=(e.reason==="workspace-enter"||e.reason==="workspace-leave"?"":s?`
62
62
  Switched to ${r}.
63
63
  `:`
64
64
  Compaction completed.
65
- `)+x,M=E===""?void 0:E;if(M!==void 0){let F=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:M},_meta:{"hydra-acp":{synthetic:!0}}}});for(let K of this.clients.values())K.connection.notify("session/update",F).catch(()=>{})}this.updatedAt=Date.now()}async rollbackToUpstream(e){let t=await this.quiesceBlocker();if(t!==void 0)throw new Error(`session is not quiesced for rollback: ${t}`);let r=this.loadExistingAgentSession;if(!r)throw new Error("loadExistingAgentSession not configured for this session");let s=this.agentId,o=this.cwd,i=this.agentArgs,a=this.forwardedEnv,d=this.currentModel,c=this.currentMode,l=await r(e.previousUpstreamSessionId,{agentId:s,cwd:o,agentArgs:i,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(l.agent,{respawn:!0});let u=await xa({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:d,agentReportedModel:l.initialModel,logger:this.logger});this.applyAgentConfigOptionResponse(u.result,"model"),await Sa({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:c,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.resetModelVerb(l.modelVerb),this.broadcastMergedCommands(),this.broadcastConfigOptions(),await this.retireAgent(f,"rollback"),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0}),this.notifyAgentChange("rollbackToUpstream","rollback"),this.updatedAt=Date.now()}async reloadUpstreamAfterAgentLoss(){let e=this.loadExistingAgentSession;if(!e)throw new Error("loadExistingAgentSession not configured for this session");let t=this.currentModel,r=this.currentMode,s=await e(this.upstreamSessionId,{agentId:this.agentId,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(s.agent,{respawn:!0});let o=await xa({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:t,agentReportedModel:s.initialModel,logger:this.logger});this.applyAgentConfigOptionResponse(o.result,"model"),await Sa({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:r,agentReportedMode:s.initialMode,logger:this.logger}),s.agent.connection.drainBuffered("session/update");let i=this.agent;this.agent=s.agent,this.upstreamSessionId=s.upstreamSessionId,this.agentMeta=s.agentMeta,this.agentCapabilities=s.agentCapabilities,this.resetModelVerb(s.modelVerb),this.broadcastMergedCommands(),this.broadcastConfigOptions(),await this.retireAgent(i,"upstream-lost"),this.notifyAgentChange("reloadUpstreamAfterAgentLoss"),this.updatedAt=Date.now()}async openToolCallIdsInHistory(e=TD){if(!this.historyStore)return[];let t=await this.historyStore.load(this.sessionId),r=t.length>e?t.slice(-e):t,s=new Set,o=new Set;for(let i of r){let d=i.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let c=d.sessionUpdate,l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(!l)continue;let u=d.status;c==="tool_call"&&s.add(l),(c==="tool_call"||c==="tool_call_update")&&(u==="completed"||u==="failed")&&o.add(l)}return[...s].filter(i=>!o.has(i))}async getHistorySnapshot(e="inline",t){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e,...t!==void 0?{maxEntries:t}:{}}).catch(()=>[]):[]}async*iterRecallNewestFirst(){this.historyStore&&(yield*this.historyStore.iterRecallNewestFirst(this.sessionId))}async getRecallTotalCount(){return this.historyStore?this.historyStore.getRecallTotalCount(this.sessionId).catch(()=>0):0}async sliceRecallHistory(e,t){return this.historyStore?(await this.historyStore.rangeSlice(this.sessionId,e,t).catch(()=>[])).map(s=>s.entry):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}broadcastClientUpdate(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let r of this.clients.values())r.connection.notify("session/update",t).catch(()=>{})}broadcastCompactionPhase(e){let t=e.phase;t==="swapped"||t==="failed"||t==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let r=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"_hydra_compaction",...e}});for(let s of this.broadcastHandlers)try{s({method:"session/update",params:r,recordedAt:Date.now()})}catch{}for(let s of this.clients.values())s.connection.notify("session/update",r).catch(()=>{});this.notifyChain("compaction",{...e})}broadcastWorkspacePhase(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"_hydra_workspace",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:t,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",t).catch(()=>{});this.notifyChain("workspace",{...e})}broadcastSyntheticText(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e},_meta:{"hydra-acp":{synthetic:!0}}}});for(let r of this.clients.values())r.connection.notify("session/update",t).catch(()=>{})}attach(e,t,r={}){if(this.closed)throw tr(new Error("session is closed"),G.SessionNotFound);if(this.clients.has(e.clientId))throw tr(new Error(`client ${e.clientId} is already attached`),G.AlreadyAttached);return this.clients.set(e.clientId,e),this.cancelOrphanTimer(),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,r)}async loadReplay(e,t){let r=d=>t.raw?d:Zp(d),s=t.historyLimit===0?1/0:t.historyLimit??this.historyMaxEntries,o=Sc(await this.getHistorySnapshot(t.toolContent??"inline",s===1/0?1/0:s*2),this.side),i=rH(o.filter(d=>!bu(d.method,d.params)),s),a=this.buildStateSnapshotReplay();if(e==="after_message"){let d=t.afterSeq!==void 0?sH(i,t.afterSeq):t.afterMessageId?oh(i,t.afterMessageId):-1;return d<0?{entries:[...a,...r(i)],appliedPolicy:"full"}:{entries:[...a,...r(i.slice(d+1))],appliedPolicy:"after_message"}}return{entries:[...a,...r(i)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,r=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:r}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let o={sessionUpdate:"_hydra_current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(o.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(o.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:r})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:r});let s=this.mergedAvailableCommands();if(s.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:s}},recordedAt:r}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"_hydra_available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:r}),this.currentUsage!==void 0){let o=this.currentUsage,i={sessionUpdate:"usage_update"};if(typeof o.used=="number"&&(i.used=o.used),typeof o.size=="number"&&(i.size=o.size),typeof o.costAmount=="number"||typeof o.costCurrency=="string"){let a={};typeof o.costAmount=="number"&&(a.amount=o.costAmount),typeof o.costCurrency=="string"&&(a.currency=o.costCurrency),i.cost=a}Object.keys(i).length>1&&e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:r})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"_hydra_compaction",...this._liveCompactionPhase}},recordedAt:r}),e}replayPendingPermissions(e){for(let t of this.attentionFlags.values()){if(t.source!=="daemon"||!t.reason.startsWith("permission:"))continue;let r=t.reason.slice(11),s=this.permissionCallbacks.get(r);s&&s(e)}}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.scheduleOrphanCheck(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let r={sessionUpdate:"client_disconnected",client:t,timestamp:new Date().toISOString()};for(let s of this.clients.values())s.connection.notify("session/update",{sessionId:this.sessionId,update:r}).catch(()=>{})}reportIsolationBreach(e,t){let r=this.workspace;if(r===void 0){let s=this.formerWorkspace;s!==void 0&&nh(e,s.path)&&(this.logger?.warn?.(`STALE WORKSPACE WRITE on session ${this.sessionId}: the agent wrote ${e}, which is inside the workspace this session already left. That work will not reach ${s.sourceCwd}.`),this.notifyChain("workspace.staleWrite",{path:e,formerWorkspacePath:s.path,sourceCwd:s.sourceCwd,toolCallId:t}));return}jR(e,r.sourceCwd,r.path)&&(this.logger?.warn?.(`ISOLATION BREACH on session ${this.sessionId}: the agent wrote ${e}, which is in the source tree ${r.sourceCwd}, not its workspace ${r.path}. The user's checkout has been modified.`),this.notifyChain("workspace.breach",{path:e,sourceCwd:r.sourceCwd,workspacePath:r.path,toolCallId:t}))}applyDepartedPromptRewrite(e){let t=this.formerWorkspace;if(t===void 0)return e;let r=!1,s=QR(e,o=>wb(o,t.path)?(r=!0,yb(o,t.path,t.sourceCwd).text):o);if(!this.departureNoteSent||r){let o=UR({sourceCwd:t.sourceCwd,formerWorkspacePath:t.path,removed:t.removed});s=Sb(s,`${o}
65
+ `)+x,M=P===""?void 0:P;if(M!==void 0){let F=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:M},_meta:{"hydra-acp":{synthetic:!0}}}});for(let K of this.clients.values())K.connection.notify("session/update",F).catch(()=>{})}this.updatedAt=Date.now()}async rollbackToUpstream(e){let t=await this.quiesceBlocker();if(t!==void 0)throw new Error(`session is not quiesced for rollback: ${t}`);let r=this.loadExistingAgentSession;if(!r)throw new Error("loadExistingAgentSession not configured for this session");let s=this.agentId,o=this.cwd,i=this.agentArgs,a=this.forwardedEnv,d=this.currentModel,c=this.currentMode,l=await r(e.previousUpstreamSessionId,{agentId:s,cwd:o,agentArgs:i,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(l.agent,{respawn:!0});let u=await xa({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:d,agentReportedModel:l.initialModel,logger:this.logger});this.applyAgentConfigOptionResponse(u.result,"model"),await Sa({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:c,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.resetModelVerb(l.modelVerb),this.broadcastMergedCommands(),this.broadcastConfigOptions(),await this.retireAgent(f,"rollback"),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0}),this.notifyAgentChange("rollbackToUpstream","rollback"),this.updatedAt=Date.now()}async reloadUpstreamAfterAgentLoss(){let e=this.loadExistingAgentSession;if(!e)throw new Error("loadExistingAgentSession not configured for this session");let t=this.currentModel,r=this.currentMode,s=await e(this.upstreamSessionId,{agentId:this.agentId,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(s.agent,{respawn:!0});let o=await xa({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:t,agentReportedModel:s.initialModel,logger:this.logger});this.applyAgentConfigOptionResponse(o.result,"model"),await Sa({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:r,agentReportedMode:s.initialMode,logger:this.logger}),s.agent.connection.drainBuffered("session/update");let i=this.agent;this.agent=s.agent,this.upstreamSessionId=s.upstreamSessionId,this.agentMeta=s.agentMeta,this.agentCapabilities=s.agentCapabilities,this.resetModelVerb(s.modelVerb),this.broadcastMergedCommands(),this.broadcastConfigOptions(),await this.retireAgent(i,"upstream-lost"),this.notifyAgentChange("reloadUpstreamAfterAgentLoss"),this.updatedAt=Date.now()}async openToolCallIdsInHistory(e=TD){if(!this.historyStore)return[];let t=await this.historyStore.load(this.sessionId),r=t.length>e?t.slice(-e):t,s=new Set,o=new Set;for(let i of r){let d=i.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let c=d.sessionUpdate,l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(!l)continue;let u=d.status;c==="tool_call"&&s.add(l),(c==="tool_call"||c==="tool_call_update")&&(u==="completed"||u==="failed")&&o.add(l)}return[...s].filter(i=>!o.has(i))}async getHistorySnapshot(e="inline",t){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e,...t!==void 0?{maxEntries:t}:{}}).catch(()=>[]):[]}async*iterRecallNewestFirst(){this.historyStore&&(yield*this.historyStore.iterRecallNewestFirst(this.sessionId))}async getRecallTotalCount(){return this.historyStore?this.historyStore.getRecallTotalCount(this.sessionId).catch(()=>0):0}async sliceRecallHistory(e,t){return this.historyStore?(await this.historyStore.rangeSlice(this.sessionId,e,t).catch(()=>[])).map(s=>s.entry):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}broadcastClientUpdate(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let r of this.clients.values())r.connection.notify("session/update",t).catch(()=>{})}broadcastCompactionPhase(e){let t=e.phase;t==="swapped"||t==="failed"||t==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let r=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"_hydra_compaction",...e}});for(let s of this.broadcastHandlers)try{s({method:"session/update",params:r,recordedAt:Date.now()})}catch{}for(let s of this.clients.values())s.connection.notify("session/update",r).catch(()=>{});this.notifyChain("compaction",{...e})}broadcastWorkspacePhase(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"_hydra_workspace",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:t,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",t).catch(()=>{});this.notifyChain("workspace",{...e})}broadcastSyntheticText(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e},_meta:{"hydra-acp":{synthetic:!0}}}});for(let r of this.clients.values())r.connection.notify("session/update",t).catch(()=>{})}attach(e,t,r={}){if(this.closed)throw tr(new Error("session is closed"),G.SessionNotFound);if(this.clients.has(e.clientId))throw tr(new Error(`client ${e.clientId} is already attached`),G.AlreadyAttached);return this.clients.set(e.clientId,e),this.cancelOrphanTimer(),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,r)}async loadReplay(e,t){let r=d=>t.raw?d:Zp(d),s=t.historyLimit===0?1/0:t.historyLimit??this.historyMaxEntries,o=Sc(await this.getHistorySnapshot(t.toolContent??"inline",s===1/0?1/0:s*2),this.side),i=rH(o.filter(d=>!bu(d.method,d.params)),s),a=this.buildStateSnapshotReplay();if(e==="after_message"){let d=t.afterSeq!==void 0?sH(i,t.afterSeq):t.afterMessageId?oh(i,t.afterMessageId):-1;return d<0?{entries:[...a,...r(i)],appliedPolicy:"full"}:{entries:[...a,...r(i.slice(d+1))],appliedPolicy:"after_message"}}return{entries:[...a,...r(i)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,r=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:r}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let o={sessionUpdate:"_hydra_current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(o.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(o.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:r})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:r});let s=this.mergedAvailableCommands();if(s.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:s}},recordedAt:r}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"_hydra_available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:r}),this.currentUsage!==void 0){let o=this.currentUsage,i={sessionUpdate:"usage_update"};if(typeof o.used=="number"&&(i.used=o.used),typeof o.size=="number"&&(i.size=o.size),typeof o.costAmount=="number"||typeof o.costCurrency=="string"){let a={};typeof o.costAmount=="number"&&(a.amount=o.costAmount),typeof o.costCurrency=="string"&&(a.currency=o.costCurrency),i.cost=a}Object.keys(i).length>1&&e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:r})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"_hydra_compaction",...this._liveCompactionPhase}},recordedAt:r}),e}replayPendingPermissions(e){for(let t of this.attentionFlags.values()){if(t.source!=="daemon"||!t.reason.startsWith("permission:"))continue;let r=t.reason.slice(11),s=this.permissionCallbacks.get(r);s&&s(e)}}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.scheduleOrphanCheck(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let r={sessionUpdate:"client_disconnected",client:t,timestamp:new Date().toISOString()};for(let s of this.clients.values())s.connection.notify("session/update",{sessionId:this.sessionId,update:r}).catch(()=>{})}reportIsolationBreach(e,t){let r=this.workspace;if(r===void 0){let s=this.formerWorkspace;s!==void 0&&nh(e,s.path)&&(this.logger?.warn?.(`STALE WORKSPACE WRITE on session ${this.sessionId}: the agent wrote ${e}, which is inside the workspace this session already left. That work will not reach ${s.sourceCwd}.`),this.notifyChain("workspace.staleWrite",{path:e,formerWorkspacePath:s.path,sourceCwd:s.sourceCwd,toolCallId:t}));return}jR(e,r.sourceCwd,r.path)&&(this.logger?.warn?.(`ISOLATION BREACH on session ${this.sessionId}: the agent wrote ${e}, which is in the source tree ${r.sourceCwd}, not its workspace ${r.path}. The user's checkout has been modified.`),this.notifyChain("workspace.breach",{path:e,sourceCwd:r.sourceCwd,workspacePath:r.path,toolCallId:t}))}applyDepartedPromptRewrite(e){let t=this.formerWorkspace;if(t===void 0)return e;let r=!1,s=QR(e,o=>wb(o,t.path)?(r=!0,yb(o,t.path,t.sourceCwd).text):o);if(!this.departureNoteSent||r){let o=UR({sourceCwd:t.sourceCwd,formerWorkspacePath:t.path,removed:t.removed});s=Sb(s,`${o}
66
66
 
67
67
  `),this.departureNoteSent=!0}return s}applyWorkspacePromptRewrite(e){let t=this.workspace;if(t===void 0)return this.applyDepartedPromptRewrite(e);let r=!1,s=QR(e,i=>wb(i,t.sourceCwd)?(r=!0,yb(i,t.sourceCwd,t.path).text):i);if(!this.workspacePreambleSent||r){let i=WR({workspacePath:t.path,sourceCwd:t.sourceCwd,notes:this.workspaceNotes,...this.workspacePreambleSent?{reassert:!0}:{}});s=Sb(s,`${i}
68
68
 
@@ -161,7 +161,7 @@ That is why the daemon started here could not bind. Point both at the same absol
161
161
  `)break;if(k!=="*"||n[y+1]==="*")continue;let S=n[y-1],I=n[y+1]??"";if(!(S===" "||S===" "||S==="*")&&!/[A-Za-z0-9]/.test(I)){h=y;break}}if(h!==-1&&h>f+1){let y=n.slice(f+1,h),k=Oi(y,r,i+cc),S=c;d+=`${cc}${k.styled}${a(i)}`;for(let I of k.links)u.push({start:S+I.start,end:S+I.end,url:I.url});c+=k.cleanLength,k.ansi&&(l=!0),f=h+1;continue}}}if(p==="_"){let m=f>0?n[f-1]:"",b=n[f+1]??"";if(b!==""&&b!==" "&&b!==" "&&b!==`
162
162
  `&&b!=="_"&&!/[A-Za-z0-9_]/.test(m)){let h=-1;for(let y=f+1;y<n.length;y++){let k=n[y];if(k===`
163
163
  `)break;if(k!=="_")continue;let S=n[y-1],I=n[y+1]??"";if(!(S===" "||S===" "||S==="_")&&!/[A-Za-z0-9_]/.test(I)){h=y;break}}if(h!==-1&&h>f+1){let y=n.slice(f+1,h),k=Oi(y,r,i+cc),S=c;d+=`${cc}${k.styled}${a(i)}`;for(let I of k.links)u.push({start:S+I.start,end:S+I.end,url:I.url});c+=k.cleanLength,k.ansi&&(l=!0),f=h+1;continue}}}if(p==="`"){let m=n.indexOf("`",f+1);if(m!==-1&&m>f+1){let b=n.slice(f+1,m);d+=`${s}${b}${a(i)}`,c+=b.length,f=m+1;continue}}if(p==="["){let m=n.indexOf("]",f+1);if(m!==-1&&n[m+1]==="("&&m>f+1){let b=-1;{let g=1,h=m+2;for(;h<n.length;){let y=n[h];if(y==="\\"&&h+1<n.length){h+=2;continue}if(y==="(")g+=1;else if(y===")"&&(g-=1,g===0)){b=h;break}h+=1}}if(b!==-1&&b>m+2){let g=n.slice(f+1,m),h=n.slice(m+2,b),y=Oi(g,r,i+o),k=c;d+=`${o}${y.styled}${a(i)}`;for(let S of y.links)u.push({start:k+S.start,end:k+S.end,url:S.url});c+=y.cleanLength,u.push({start:k,end:c,url:h}),f=b+1;continue}}}d+=p,c+=1,f+=1}return{styled:d,links:u,cleanLength:c,ansi:l}}function NE(n,e){let{proseStyle:t,highlightCode:r,prefixStyle:s,firstPrefix:o=" ",inlineOpts:i,maxWidth:a}=e,d=[],c=n.replace(/^\s+/,"").split(`
164
- `),l=!1,u="",f="",p=null,m=[],b=o!==" ",g=(k,S,I=" ",x,C,$)=>{let E={prefix:I,body:k,bodyStyle:S};s!==void 0&&(E.prefixStyle=s),x&&x.length>0&&(E.links=x),C&&(E.ansi=!0),$!==void 0&&$>0&&(E.hangingIndent=$),d.push(E)},h=()=>b?(b=!1,o):" ",y=()=>{if(m.length===0){f="",p=null;return}if(f.length>0&&(g(f,r?"muted":t," ",p===null?void 0:[p]),f="",p=null),r){let k=HE(u,m);for(let S of k){let I={prefix:" ",body:S.body,bodyStyle:"code",fillRow:!0};s!==void 0&&(I.prefixStyle=s),S.ansi&&(I.ansi=!0),d.push(I)}}else for(let k of m)g(k,t);m=[],u=""};for(let k=0;k<c.length;k++){let S=c[k],I=l?S.match(/^\s*`{3,}\s*$/):S.match(/^\s*`{3,}(.*)$/);if(I){if(l)y(),l=!1;else{l=!0;let K=m2(I[1]??"");u=K.lang,f=K.header,p=K.headerLink??null}continue}if(l){m.push(S);continue}let x=S.match(/^(#{1,6})\s+(.*)$/);if(x){let K=x[1].length,Y=x[2]??"",z=r?K===1?"heading-1":K===2?"heading-2":"heading-3":t,re=r?Rp(z):i;g(Bk(Y,re),z,h());continue}let C=c[k+1];if(S.includes("|")&&C!==void 0&&s2(C)&&Zu(S).length===Zu(C).length){let K=Zu(S),Y=[],z=k+2;for(;z<c.length&&c[z].includes("|");)Y.push(Zu(c[z])),z++;let re=u2(K,Y,a);for(let Q of re)s!==void 0&&(Q.prefixStyle=s),d.push(Q);k=z-1;continue}let $=S.match(/^(\s*)[-*+]\s+(.*)$/);if($){let K=$[1]??"",Y=$[2]??"",z=Oi(Y,i),re=K.length+2,Q=z.links.map(ke=>({start:ke.start+re,end:ke.end+re,url:ke.url}));g(`${K}\u2022 ${z.styled}`,t,h(),Q,z.ansi,K.length+2);continue}let E=S.match(/^(\s*)(\d+)\.\s+(.*)$/);if(E){let K=E[1]??"",Y=E[2]??"",z=E[3]??"",re=Oi(z,i),Q=K.length+Y.length+2,ke=re.links.map(xe=>({start:xe.start+Q,end:xe.end+Q,url:xe.url}));g(`${K}${Y}. ${re.styled}`,t,h(),ke,re.ansi,K.length+Y.length+2);continue}let M=S.trim()==="",F=Oi(S,i);g(F.styled,t,M?" ":h(),F.links,F.ansi)}for(l&&y();d.length>0&&d[d.length-1].body==="";)d.pop();return d}function zo(n,e){return NE(n,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function nl(n){return NE(n,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:WI()})}function Zu(n){let e=n.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let t=[],r="",s=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="\\"&&o+1<e.length&&e[o+1]==="|"){r+="|",o+=1;continue}if(i==="`"){s=!s,r+=i;continue}if(i==="|"&&!s){t.push(r.trim()),r="";continue}r+=i}return t.push(r.trim()),t}function s2(n){if(!n.includes("|"))return!1;let e=Zu(n);return e.length===0?!1:e.every(t=>/^:?-+:?$/.test(t))}function Lm(n){let e=n.replace(/\*\*(.+?)\*\*/g,"$1").replace(/(^|[^A-Za-z0-9*])\*([^\s*](?:[^*\n]*?[^\s*])?)\*(?![A-Za-z0-9])/g,"$1$2").replace(/(^|[^A-Za-z0-9_])_([^\s_](?:[^_\n]*?[^\s_])?)_(?![A-Za-z0-9_])/g,"$1$2").replace(/`([^`]+)`/g,"$1");return Nm(e)}function a2(n){let e=[],t=0;for(;t<n.length;){let r=n[t];if(r===" "||r===" "){let i=t;for(;i<n.length&&(n[i]===" "||n[i]===" ");)i++;let a=n.slice(t,i);e.push({text:a,isWS:!0,width:Nm(a)}),t=i;continue}let s="",o=t;for(;o<n.length;){let i=n[o];if(i===" "||i===" ")break;if(n[o]==="*"&&n[o+1]==="*"){let a=n.indexOf("**",o+2);a===-1?(s+="**",o+=2):(s+=n.slice(o,a+2),o=a+2);continue}if(i==="*"&&n[o+1]!=="*"){let a=s.length>0?s[s.length-1]:o>0?n[o-1]:"",d=n[o+1]??"";if(d!==""&&d!==" "&&d!==" "&&d!=="*"&&!/[A-Za-z0-9]/.test(a)){let l=-1;for(let u=o+1;u<n.length;u++){if(n[u]!=="*"||n[u+1]==="*")continue;let p=n[u-1],m=n[u+1]??"";if(!(p===" "||p===" "||p==="*")&&!/[A-Za-z0-9]/.test(m)){l=u;break}}if(l!==-1&&l>o+1){s+=n.slice(o,l+1),o=l+1;continue}}}if(i==="_"){let a=s.length>0?s[s.length-1]:o>0?n[o-1]:"",d=n[o+1]??"";if(d!==""&&d!==" "&&d!==" "&&d!=="_"&&!/[A-Za-z0-9_]/.test(a)){let l=-1;for(let u=o+1;u<n.length;u++){if(n[u]!=="_")continue;let p=n[u-1],m=n[u+1]??"";if(!(p===" "||p===" "||p==="_")&&!/[A-Za-z0-9_]/.test(m)){l=u;break}}if(l!==-1&&l>o+1){s+=n.slice(o,l+1),o=l+1;continue}}}if(i==="`"){let a=n.indexOf("`",o+1);a===-1?(s+="`",o+=1):(s+=n.slice(o,a+1),o=a+1);continue}s+=i,o+=1}e.push({text:s,isWS:!1,width:Lm(s)}),t=o}return e}function d2(n,e){let t=[],r="",s=0;for(let o of n){let i=Nm(o);s>0&&s+i>e?(t.push(r),r=o,s=i):(r+=o,s+=i)}return r.length>0&&t.push(r),t}function c2(n,e){if(e<=0)return n.length===0?[""]:[n.map(i=>i.text).join("")];let t=[],r="",s=0,o=()=>{t.push(r.replace(/[ \t]+$/,"")),r="",s=0};for(let i of n){if(i.isWS){if(s===0)continue;r+=i.text,s+=i.width;continue}if(i.width>e){if(s>0&&o(),i.text.includes("**")||i.text.includes("`")||i.text.includes("*")||i.text.includes("_"))t.push(i.text);else{let d=d2(i.text,e);for(let l=0;l<d.length-1;l++)t.push(d[l]);let c=d[d.length-1]??"";r=c,s=Nm(c)}continue}if(s===0){r=i.text,s=i.width;continue}s+i.width>e?(o(),r=i.text,s=i.width):(r+=i.text,s+=i.width)}return(r.length>0||t.length===0)&&o(),t}function l2(n,e){let t=n.length;if(n.reduce((l,u)=>l+u,0)<=e)return n.slice();let s=n.map(l=>Math.min(l,DE)),o=s.reduce((l,u)=>l+u,0);if(o>=e)return s;let i=e-o,a=n.map((l,u)=>({i:u,slack:Math.max(0,l-s[u])})).filter(l=>l.slack>0),d=a.reduce((l,u)=>l+u.slack,0);if(d===0)return s;for(let l of a){let u=Math.floor(i*l.slack/d);s[l.i]=s[l.i]+Math.min(u,l.slack)}o=s.reduce((l,u)=>l+u,0);let c=e-o;for(;c>0;){let l=-1,u=0;for(let f=0;f<t;f++){let p=n[f]-s[f];p>u&&(u=p,l=f)}if(l<0)break;s[l]=s[l]+1,c--}return s}function u2(n,e,t){let r=n.length,s=new Array(r).fill(0);for(let c=0;c<r;c++)s[c]=Lm(n[c]??"");for(let c of e)for(let l=0;l<r;l++){let u=c[l]??"",f=Lm(u);f>s[l]&&(s[l]=f)}let o=s.slice();if(t!==void 0){let c=Math.max(r*DE,t-o2-(r-1)*i2);o=l2(s,c)}let i=(c,l,u)=>{let f=[],p=1;for(let b=0;b<r;b++){let g=c[b]??"",h=o[b],y=c2(a2(g),h);f.push(y),y.length>p&&(p=y.length)}let m=[];for(let b=0;b<p;b++){let g=[];for(let h=0;h<r;h++){let y=f[h][b]??"",k=o[h],S=Lm(y),I=Bk(y,u);g.push(I+" ".repeat(Math.max(0,k-S)))}m.push({prefix:" ",body:g.join(" \u2502 "),bodyStyle:l})}return m},a=[];a.push(...i(n,"heading-3",Rp("heading-3")));let d=[];for(let c=0;c<r;c++)d.push("\u2500".repeat(o[c]));a.push({prefix:" ",body:d.join("\u2500\u253C\u2500"),bodyStyle:"muted"});for(let c of e)a.push(...i(c,"agent"));return a}function HE(n,e){if(n.length===0||!Fm(n))return e.map(a=>({body:a,ansi:!1}));let t=e.join(`
164
+ `),l=!1,u="",f="",p=null,m=[],b=o!==" ",g=(k,S,I=" ",x,C,$)=>{let P={prefix:I,body:k,bodyStyle:S};s!==void 0&&(P.prefixStyle=s),x&&x.length>0&&(P.links=x),C&&(P.ansi=!0),$!==void 0&&$>0&&(P.hangingIndent=$),d.push(P)},h=()=>b?(b=!1,o):" ",y=()=>{if(m.length===0){f="",p=null;return}if(f.length>0&&(g(f,r?"muted":t," ",p===null?void 0:[p]),f="",p=null),r){let k=HE(u,m);for(let S of k){let I={prefix:" ",body:S.body,bodyStyle:"code",fillRow:!0};s!==void 0&&(I.prefixStyle=s),S.ansi&&(I.ansi=!0),d.push(I)}}else for(let k of m)g(k,t);m=[],u=""};for(let k=0;k<c.length;k++){let S=c[k],I=l?S.match(/^\s*`{3,}\s*$/):S.match(/^\s*`{3,}(.*)$/);if(I){if(l)y(),l=!1;else{l=!0;let K=m2(I[1]??"");u=K.lang,f=K.header,p=K.headerLink??null}continue}if(l){m.push(S);continue}let x=S.match(/^(#{1,6})\s+(.*)$/);if(x){let K=x[1].length,Y=x[2]??"",z=r?K===1?"heading-1":K===2?"heading-2":"heading-3":t,re=r?Rp(z):i;g(Bk(Y,re),z,h());continue}let C=c[k+1];if(S.includes("|")&&C!==void 0&&s2(C)&&Zu(S).length===Zu(C).length){let K=Zu(S),Y=[],z=k+2;for(;z<c.length&&c[z].includes("|");)Y.push(Zu(c[z])),z++;let re=u2(K,Y,a);for(let Q of re)s!==void 0&&(Q.prefixStyle=s),d.push(Q);k=z-1;continue}let $=S.match(/^(\s*)[-*+]\s+(.*)$/);if($){let K=$[1]??"",Y=$[2]??"",z=Oi(Y,i),re=K.length+2,Q=z.links.map(ke=>({start:ke.start+re,end:ke.end+re,url:ke.url}));g(`${K}\u2022 ${z.styled}`,t,h(),Q,z.ansi,K.length+2);continue}let P=S.match(/^(\s*)(\d+)\.\s+(.*)$/);if(P){let K=P[1]??"",Y=P[2]??"",z=P[3]??"",re=Oi(z,i),Q=K.length+Y.length+2,ke=re.links.map(xe=>({start:xe.start+Q,end:xe.end+Q,url:xe.url}));g(`${K}${Y}. ${re.styled}`,t,h(),ke,re.ansi,K.length+Y.length+2);continue}let M=S.trim()==="",F=Oi(S,i);g(F.styled,t,M?" ":h(),F.links,F.ansi)}for(l&&y();d.length>0&&d[d.length-1].body==="";)d.pop();return d}function zo(n,e){return NE(n,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function nl(n){return NE(n,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:WI()})}function Zu(n){let e=n.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let t=[],r="",s=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="\\"&&o+1<e.length&&e[o+1]==="|"){r+="|",o+=1;continue}if(i==="`"){s=!s,r+=i;continue}if(i==="|"&&!s){t.push(r.trim()),r="";continue}r+=i}return t.push(r.trim()),t}function s2(n){if(!n.includes("|"))return!1;let e=Zu(n);return e.length===0?!1:e.every(t=>/^:?-+:?$/.test(t))}function Lm(n){let e=n.replace(/\*\*(.+?)\*\*/g,"$1").replace(/(^|[^A-Za-z0-9*])\*([^\s*](?:[^*\n]*?[^\s*])?)\*(?![A-Za-z0-9])/g,"$1$2").replace(/(^|[^A-Za-z0-9_])_([^\s_](?:[^_\n]*?[^\s_])?)_(?![A-Za-z0-9_])/g,"$1$2").replace(/`([^`]+)`/g,"$1");return Nm(e)}function a2(n){let e=[],t=0;for(;t<n.length;){let r=n[t];if(r===" "||r===" "){let i=t;for(;i<n.length&&(n[i]===" "||n[i]===" ");)i++;let a=n.slice(t,i);e.push({text:a,isWS:!0,width:Nm(a)}),t=i;continue}let s="",o=t;for(;o<n.length;){let i=n[o];if(i===" "||i===" ")break;if(n[o]==="*"&&n[o+1]==="*"){let a=n.indexOf("**",o+2);a===-1?(s+="**",o+=2):(s+=n.slice(o,a+2),o=a+2);continue}if(i==="*"&&n[o+1]!=="*"){let a=s.length>0?s[s.length-1]:o>0?n[o-1]:"",d=n[o+1]??"";if(d!==""&&d!==" "&&d!==" "&&d!=="*"&&!/[A-Za-z0-9]/.test(a)){let l=-1;for(let u=o+1;u<n.length;u++){if(n[u]!=="*"||n[u+1]==="*")continue;let p=n[u-1],m=n[u+1]??"";if(!(p===" "||p===" "||p==="*")&&!/[A-Za-z0-9]/.test(m)){l=u;break}}if(l!==-1&&l>o+1){s+=n.slice(o,l+1),o=l+1;continue}}}if(i==="_"){let a=s.length>0?s[s.length-1]:o>0?n[o-1]:"",d=n[o+1]??"";if(d!==""&&d!==" "&&d!==" "&&d!=="_"&&!/[A-Za-z0-9_]/.test(a)){let l=-1;for(let u=o+1;u<n.length;u++){if(n[u]!=="_")continue;let p=n[u-1],m=n[u+1]??"";if(!(p===" "||p===" "||p==="_")&&!/[A-Za-z0-9_]/.test(m)){l=u;break}}if(l!==-1&&l>o+1){s+=n.slice(o,l+1),o=l+1;continue}}}if(i==="`"){let a=n.indexOf("`",o+1);a===-1?(s+="`",o+=1):(s+=n.slice(o,a+1),o=a+1);continue}s+=i,o+=1}e.push({text:s,isWS:!1,width:Lm(s)}),t=o}return e}function d2(n,e){let t=[],r="",s=0;for(let o of n){let i=Nm(o);s>0&&s+i>e?(t.push(r),r=o,s=i):(r+=o,s+=i)}return r.length>0&&t.push(r),t}function c2(n,e){if(e<=0)return n.length===0?[""]:[n.map(i=>i.text).join("")];let t=[],r="",s=0,o=()=>{t.push(r.replace(/[ \t]+$/,"")),r="",s=0};for(let i of n){if(i.isWS){if(s===0)continue;r+=i.text,s+=i.width;continue}if(i.width>e){if(s>0&&o(),i.text.includes("**")||i.text.includes("`")||i.text.includes("*")||i.text.includes("_"))t.push(i.text);else{let d=d2(i.text,e);for(let l=0;l<d.length-1;l++)t.push(d[l]);let c=d[d.length-1]??"";r=c,s=Nm(c)}continue}if(s===0){r=i.text,s=i.width;continue}s+i.width>e?(o(),r=i.text,s=i.width):(r+=i.text,s+=i.width)}return(r.length>0||t.length===0)&&o(),t}function l2(n,e){let t=n.length;if(n.reduce((l,u)=>l+u,0)<=e)return n.slice();let s=n.map(l=>Math.min(l,DE)),o=s.reduce((l,u)=>l+u,0);if(o>=e)return s;let i=e-o,a=n.map((l,u)=>({i:u,slack:Math.max(0,l-s[u])})).filter(l=>l.slack>0),d=a.reduce((l,u)=>l+u.slack,0);if(d===0)return s;for(let l of a){let u=Math.floor(i*l.slack/d);s[l.i]=s[l.i]+Math.min(u,l.slack)}o=s.reduce((l,u)=>l+u,0);let c=e-o;for(;c>0;){let l=-1,u=0;for(let f=0;f<t;f++){let p=n[f]-s[f];p>u&&(u=p,l=f)}if(l<0)break;s[l]=s[l]+1,c--}return s}function u2(n,e,t){let r=n.length,s=new Array(r).fill(0);for(let c=0;c<r;c++)s[c]=Lm(n[c]??"");for(let c of e)for(let l=0;l<r;l++){let u=c[l]??"",f=Lm(u);f>s[l]&&(s[l]=f)}let o=s.slice();if(t!==void 0){let c=Math.max(r*DE,t-o2-(r-1)*i2);o=l2(s,c)}let i=(c,l,u)=>{let f=[],p=1;for(let b=0;b<r;b++){let g=c[b]??"",h=o[b],y=c2(a2(g),h);f.push(y),y.length>p&&(p=y.length)}let m=[];for(let b=0;b<p;b++){let g=[];for(let h=0;h<r;h++){let y=f[h][b]??"",k=o[h],S=Lm(y),I=Bk(y,u);g.push(I+" ".repeat(Math.max(0,k-S)))}m.push({prefix:" ",body:g.join(" \u2502 "),bodyStyle:l})}return m},a=[];a.push(...i(n,"heading-3",Rp("heading-3")));let d=[];for(let c=0;c<r;c++)d.push("\u2500".repeat(o[c]));a.push({prefix:" ",body:d.join("\u2500\u253C\u2500"),bodyStyle:"muted"});for(let c of e)a.push(...i(c,"agent"));return a}function HE(n,e){if(n.length===0||!Fm(n))return e.map(a=>({body:a,ansi:!1}));let t=e.join(`
165
165
  `),r=`${JI()}\0${n}\0${t}`,s=Wa.get(r),o;if(s!==void 0)Wa.delete(r),Wa.set(r,s),o=s;else{let a;try{a=n2(t,{language:n,theme:VI(),ignoreIllegals:!0})}catch{return e.map(d=>({body:d,ansi:!1}))}if(o=a,Wa.size>=f2){let d=Wa.keys().next().value;d!==void 0&&Wa.delete(d)}Wa.set(r,o)}let i=o.split(`
166
166
  `);return i.length!==e.length?e.map(a=>({body:a,ansi:!1})):i.map((a,d)=>({body:a,ansi:a!==e[d]}))}function BE(n){if(!n)return"";let e=n.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return Fm("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return Fm("makefile")?"makefile":"";let t=e.lastIndexOf(".");if(t<0)return"";let r=e.slice(t),s=p2[r];return s&&Fm(s)?s:""}function m2(n){let e=n.trim().split(/\s+/)[0]??"";if(e.length===0)return{lang:"",header:""};let t=e.match(h2);if(!t&&!e.includes("/")&&!e.includes("\\"))return{lang:e.toLowerCase(),header:""};let r=t?t[3]:e,s=V(r),o=t?`${s}:${t[1]}-${t[2]}`:s;return{lang:BE(r),header:o,headerLink:{start:0,end:o.length,url:t?`${s}#L${t[1]}`:s}}}function Dk(n,e,t,r,s,o){let i=n.replace(/^\s+/,"").split(`
167
167
  `),a=[];s&&a.push({prefix:"\u21B3 ",prefixStyle:"muted",body:`from ${s}`,bodyStyle:"muted"});for(let d of i){let c={prefix:e,prefixStyle:r??t,body:d,bodyStyle:t};o&&(c.fillRow=!0),a.push(c)}return a}function g2(n){return n<1024?`${n} B`:n<1024*1024?`${Math.round(n/1024)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function jr(n){let e=Math.floor(n/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),r=e%60;if(t<60)return r===0?`${t}m`:`${t}m ${r}s`;let s=Math.floor(t/60),o=t%60;return o===0?`${s}h`:`${s}h ${o}m`}function Dm(n){let e=new Date(n),t=o=>String(o).padStart(2,"0"),r=`${t(e.getMonth()+1)}/${t(e.getDate())}/${e.getFullYear()}`,s=`${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`;return`${r} ${s}`}function UE(n){if(n.length<=4096&&n.split(`
@@ -235,7 +235,7 @@ Synced ${r.synced.length} session(s); skipped ${r.skipped} already tracked.
235
235
  failed to spawn ${e.command}: ${d.message}
236
236
  `),o({exitCode:-1})})}catch(a){i(),process.stdout.write(`
237
237
  failed to spawn ${e.command}: ${a.message}
238
- `),o({exitCode:-1})}})}function rq(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.kind==="terminal"&&typeof e.command=="string"&&Array.isArray(e.args)}async function uv(n,e){let t;try{t=await e.authenticate(n.id)}catch(r){return{kind:"error",message:r instanceof Error&&r.message.length>0?r.message:String(r)}}if(rq(t)){let r={command:t.command,args:t.args,env:t.env,cwd:t.cwd},s=await e.runTerminalAuth(r);return s.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:s.exitCode}}return{kind:"retry"}}async function LP(n,e,t,r,s){kr();let o=Q2(e,t,r),i=!1,a,d,c=null,l=null,u=null,f=null,p=(k,S,I,x)=>{let C=At(I,k.contentW-3);if(n.moveTo(k.contentX,S),x){H(n,"list-selected",ks(` ${C}`,k.contentW));return}H(n,"modal-label"," "),H(n,"content",C),3+C.length<k.contentW&&n.noFormat(" ".repeat(k.contentW-3-C.length))},m=()=>{let k=4;o.command&&k++,o.url&&k++,o.methodLines&&(k+=1+o.methodLines.length),a&&k++,d&&k++;let S=zn(n,{contentHeight:k,contentWidth:80,title:"Authentication required"}),I=S.contentW,x=0;if(a&&(n.moveTo(S.contentX,S.contentY+x),H(n,"modal-note",At(` ${a}`,I)),x++),d&&(n.moveTo(S.contentX,S.contentY+x),H(n,"modal-error",At(` ${d}`,I)),x++),n.moveTo(S.contentX,S.contentY+x),H(n,"modal-title",At(` ${o.title}`,I)),x+=2,n.moveTo(S.contentX,S.contentY+x),H(n,"content",At(` ${o.description}`,I)),x++,o.command&&(n.moveTo(S.contentX,S.contentY+x),H(n,"modal-label"," Run: "),H(n,"modal-value",At(o.command,I-7)),x++),o.url&&(n.moveTo(S.contentX,S.contentY+x),H(n,"modal-label"," Docs: "),H(n,"modal-value",At(o.url,I-7)),x++),o.methodLines){n.moveTo(S.contentX,S.contentY+x),H(n,"modal-label"," Methods reported by the agent:"),x++,l=S.contentY+x;for(let C of o.methodLines)p(S,S.contentY+x,C.label,C.index===u),x++}else l=null;return x++,n.moveTo(S.contentX,S.contentY+x),H(n,"modal-hint",` ${o.footer}`),c=S,S},b=()=>{let k=c,S=l;if(!(k===null||S===null||!o.methodLines))for(let I of o.methodLines)p(k,S+I.index,I.label,I.index===u)},g=k=>{let S=l,I=o.methodLines?.length??0;if(S===null||I===0)return null;let x=k-S;return x>=0&&x<I?x:null},h=o.methodLines?.length??0;return qr({term:n,render:()=>{m()},onKey:(k,S,I,x)=>{if(i)return;let C=X2(k,I,h);if(C.kind!=="ignore"){if(C.kind==="retry"||C.kind==="back"||C.kind==="cancel"){x(C.kind);return}C.kind==="selectMethod"&&y(C.index,x)}},onMouse:(k,S,I)=>{if(i)return;if(k==="MOUSE_LEFT_BUTTON_PRESSED"){f={x:S?.x??-1,y:S?.y??-1};return}let x=S?.y;if(typeof x!="number")return;if(k==="MOUSE_MOTION"){let M=g(x);M!==u&&(u=M,b());return}if(k!=="MOUSE_LEFT_BUTTON_RELEASED")return;let C=S?.x,$=f!==null&&C===f.x&&x===f.y;if(f=null,!$)return;if(c!==null&&typeof C=="number"&&(C<c.x||C>=c.x+c.w||x<c.y||x>=c.y+c.h)){I("back");return}let E=g(x);E!==null&&y(E,I)}});function y(k,S){let I=o.methodLines?.[k]?.method;if(!I||!s?.authenticate)return;i=!0,u=null,d=void 0,a=`Authenticating with ${$P(I)}\u2026`,m();let x=s.runTerminalAuth??(C=>nq(n,C));(async()=>{let C=await uv(I,{authenticate:s.authenticate,runTerminalAuth:x});if(C.kind==="terminal-completed"){S("terminal-completed");return}if(C.kind==="retry"){S("retry");return}if(C.kind==="error"){d=C.message,a=void 0,i=!1,m();return}a=void 0,d=`auth process exited with code ${C.exitCode??"(signal)"}`,i=!1,m()})()}}var V2,Y2,fv=j(()=>{"use strict";ma();du();kc();Li();xn();V2="This agent requires authentication before use.",Y2="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as qP}from"timers/promises";function pq(n){return!("method"in n)&&"id"in n&&n.id!==void 0}var cq,lq,uq,fq,cl,pv=j(()=>{"use strict";ec();La();cq=200,lq=5e3,uq=2,fq=60,cl=class{constructor(e){this.opts=e}opts;current;outboundQueue=[];flushing=!1;messageHandlers=[];closeHandlers=[];destroyed=!1;firstConnect=!0;reconnectInFlight;connectGate;releaseConnectGate;pendingRequests=new Map;async start(){await this.connectWithRetry()}onMessage(e){this.messageHandlers.push(e)}onClose(e){this.closeHandlers.push(e)}async send(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(this.connectGate||!this.current||this.flushing){this.outboundQueue.push(e);return}this.outboundQueue.push(e),await this.flushQueue()}async request(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(!this.current)throw new Error("resilient ws stream not connected");let t=e.id,r=new Promise((s,o)=>{this.pendingRequests.set(t,{resolve:s,reject:o})});try{await this.current.send(e)}catch(s){throw this.pendingRequests.delete(t),s}return r}async close(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),qP(2e3)]),this.current&&await this.current.close().catch(()=>{}),this.pendingRequests.size>0){let e=new Error("resilient ws stream is destroyed");for(let{reject:t}of this.pendingRequests.values())t(e);this.pendingRequests.clear()}for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,t=cq;for(;!this.destroyed;)try{let r=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,s=typeof this.opts.subprotocols=="function"?await this.opts.subprotocols():this.opts.subprotocols,o=await No(r,s);this.bindStream(Nr(o));let i=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(a=>{this.releaseConnectGate=a});try{if(this.opts.onConnect)try{await this.opts.onConnect(i)}catch(a){this.log(`hydra-acp: post-connect handler failed: ${a.message}`)}}finally{this.releaseConnectGate?.(),this.releaseConnectGate=void 0,this.connectGate=void 0}await this.flushQueue();return}catch(r){if(e+=1,this.opts.onConnectFailure&&this.opts.onConnectFailure(r),e>=fq)throw new Error(`hydra-acp: gave up reconnecting after ${e} attempts: ${r.message}`);if(this.log(`hydra-acp: connect attempt ${e} failed (${r.message}); retrying in ${t}ms`),await qP(t),this.destroyed)return;t=Math.min(t*uq,lq)}}bindStream(e){this.current=e,e.onMessage(t=>{if(pq(t)&&t.id!==null){let r=this.pendingRequests.get(t.id);r&&(this.pendingRequests.delete(t.id),r.resolve(t))}for(let r of this.messageHandlers)r(t)}),e.onClose(t=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let r=t??new Error("ws closed before response");for(let{reject:s}of this.pendingRequests.values())s(r);this.pendingRequests.clear()}this.scheduleReconnect(t)}})}async flushQueue(){if(!this.flushing){this.flushing=!0;try{for(;!this.destroyed&&this.current&&this.outboundQueue.length>0;){let e=this.outboundQueue[0];try{await this.current.send(e)}catch(t){this.scheduleReconnect(t);return}this.outboundQueue.shift()}}finally{this.flushing=!1}}}scheduleReconnect(e){if(!(this.destroyed||this.reconnectInFlight)){if(this.log(`hydra-acp: connection lost (${e?.message??"no error"}); reconnecting...`),this.opts.onDisconnect)try{this.opts.onDisconnect(e)}catch(t){this.log(`hydra-acp: onDisconnect handler threw: ${t.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(t){for(let r of this.closeHandlers)r(t);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
238
+ `),o({exitCode:-1})}})}function rq(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.kind==="terminal"&&typeof e.command=="string"&&Array.isArray(e.args)}async function uv(n,e){let t;try{t=await e.authenticate(n.id)}catch(r){return{kind:"error",message:r instanceof Error&&r.message.length>0?r.message:String(r)}}if(rq(t)){let r={command:t.command,args:t.args,env:t.env,cwd:t.cwd},s=await e.runTerminalAuth(r);return s.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:s.exitCode}}return{kind:"retry"}}async function LP(n,e,t,r,s){kr();let o=Q2(e,t,r),i=!1,a,d,c=null,l=null,u=null,f=null,p=(k,S,I,x)=>{let C=At(I,k.contentW-3);if(n.moveTo(k.contentX,S),x){H(n,"list-selected",ks(` ${C}`,k.contentW));return}H(n,"modal-label"," "),H(n,"content",C),3+C.length<k.contentW&&n.noFormat(" ".repeat(k.contentW-3-C.length))},m=()=>{let k=4;o.command&&k++,o.url&&k++,o.methodLines&&(k+=1+o.methodLines.length),a&&k++,d&&k++;let S=zn(n,{contentHeight:k,contentWidth:80,title:"Authentication required"}),I=S.contentW,x=0;if(a&&(n.moveTo(S.contentX,S.contentY+x),H(n,"modal-note",At(` ${a}`,I)),x++),d&&(n.moveTo(S.contentX,S.contentY+x),H(n,"modal-error",At(` ${d}`,I)),x++),n.moveTo(S.contentX,S.contentY+x),H(n,"modal-title",At(` ${o.title}`,I)),x+=2,n.moveTo(S.contentX,S.contentY+x),H(n,"content",At(` ${o.description}`,I)),x++,o.command&&(n.moveTo(S.contentX,S.contentY+x),H(n,"modal-label"," Run: "),H(n,"modal-value",At(o.command,I-7)),x++),o.url&&(n.moveTo(S.contentX,S.contentY+x),H(n,"modal-label"," Docs: "),H(n,"modal-value",At(o.url,I-7)),x++),o.methodLines){n.moveTo(S.contentX,S.contentY+x),H(n,"modal-label"," Methods reported by the agent:"),x++,l=S.contentY+x;for(let C of o.methodLines)p(S,S.contentY+x,C.label,C.index===u),x++}else l=null;return x++,n.moveTo(S.contentX,S.contentY+x),H(n,"modal-hint",` ${o.footer}`),c=S,S},b=()=>{let k=c,S=l;if(!(k===null||S===null||!o.methodLines))for(let I of o.methodLines)p(k,S+I.index,I.label,I.index===u)},g=k=>{let S=l,I=o.methodLines?.length??0;if(S===null||I===0)return null;let x=k-S;return x>=0&&x<I?x:null},h=o.methodLines?.length??0;return qr({term:n,render:()=>{m()},onKey:(k,S,I,x)=>{if(i)return;let C=X2(k,I,h);if(C.kind!=="ignore"){if(C.kind==="retry"||C.kind==="back"||C.kind==="cancel"){x(C.kind);return}C.kind==="selectMethod"&&y(C.index,x)}},onMouse:(k,S,I)=>{if(i)return;if(k==="MOUSE_LEFT_BUTTON_PRESSED"){f={x:S?.x??-1,y:S?.y??-1};return}let x=S?.y;if(typeof x!="number")return;if(k==="MOUSE_MOTION"){let M=g(x);M!==u&&(u=M,b());return}if(k!=="MOUSE_LEFT_BUTTON_RELEASED")return;let C=S?.x,$=f!==null&&C===f.x&&x===f.y;if(f=null,!$)return;if(c!==null&&typeof C=="number"&&(C<c.x||C>=c.x+c.w||x<c.y||x>=c.y+c.h)){I("back");return}let P=g(x);P!==null&&y(P,I)}});function y(k,S){let I=o.methodLines?.[k]?.method;if(!I||!s?.authenticate)return;i=!0,u=null,d=void 0,a=`Authenticating with ${$P(I)}\u2026`,m();let x=s.runTerminalAuth??(C=>nq(n,C));(async()=>{let C=await uv(I,{authenticate:s.authenticate,runTerminalAuth:x});if(C.kind==="terminal-completed"){S("terminal-completed");return}if(C.kind==="retry"){S("retry");return}if(C.kind==="error"){d=C.message,a=void 0,i=!1,m();return}a=void 0,d=`auth process exited with code ${C.exitCode??"(signal)"}`,i=!1,m()})()}}var V2,Y2,fv=j(()=>{"use strict";ma();du();kc();Li();xn();V2="This agent requires authentication before use.",Y2="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as qP}from"timers/promises";function pq(n){return!("method"in n)&&"id"in n&&n.id!==void 0}var cq,lq,uq,fq,cl,pv=j(()=>{"use strict";ec();La();cq=200,lq=5e3,uq=2,fq=60,cl=class{constructor(e){this.opts=e}opts;current;outboundQueue=[];flushing=!1;messageHandlers=[];closeHandlers=[];destroyed=!1;firstConnect=!0;reconnectInFlight;connectGate;releaseConnectGate;pendingRequests=new Map;async start(){await this.connectWithRetry()}onMessage(e){this.messageHandlers.push(e)}onClose(e){this.closeHandlers.push(e)}async send(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(this.connectGate||!this.current||this.flushing){this.outboundQueue.push(e);return}this.outboundQueue.push(e),await this.flushQueue()}async request(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(!this.current)throw new Error("resilient ws stream not connected");let t=e.id,r=new Promise((s,o)=>{this.pendingRequests.set(t,{resolve:s,reject:o})});try{await this.current.send(e)}catch(s){throw this.pendingRequests.delete(t),s}return r}async close(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),qP(2e3)]),this.current&&await this.current.close().catch(()=>{}),this.pendingRequests.size>0){let e=new Error("resilient ws stream is destroyed");for(let{reject:t}of this.pendingRequests.values())t(e);this.pendingRequests.clear()}for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,t=cq;for(;!this.destroyed;)try{let r=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,s=typeof this.opts.subprotocols=="function"?await this.opts.subprotocols():this.opts.subprotocols,o=await No(r,s);this.bindStream(Nr(o));let i=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(a=>{this.releaseConnectGate=a});try{if(this.opts.onConnect)try{await this.opts.onConnect(i)}catch(a){this.log(`hydra-acp: post-connect handler failed: ${a.message}`)}}finally{this.releaseConnectGate?.(),this.releaseConnectGate=void 0,this.connectGate=void 0}await this.flushQueue();return}catch(r){if(e+=1,this.opts.onConnectFailure&&this.opts.onConnectFailure(r),e>=fq)throw new Error(`hydra-acp: gave up reconnecting after ${e} attempts: ${r.message}`);if(this.log(`hydra-acp: connect attempt ${e} failed (${r.message}); retrying in ${t}ms`),await qP(t),this.destroyed)return;t=Math.min(t*uq,lq)}}bindStream(e){this.current=e,e.onMessage(t=>{if(pq(t)&&t.id!==null){let r=this.pendingRequests.get(t.id);r&&(this.pendingRequests.delete(t.id),r.resolve(t))}for(let r of this.messageHandlers)r(t)}),e.onClose(t=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let r=t??new Error("ws closed before response");for(let{reject:s}of this.pendingRequests.values())s(r);this.pendingRequests.clear()}this.scheduleReconnect(t)}})}async flushQueue(){if(!this.flushing){this.flushing=!0;try{for(;!this.destroyed&&this.current&&this.outboundQueue.length>0;){let e=this.outboundQueue[0];try{await this.current.send(e)}catch(t){this.scheduleReconnect(t);return}this.outboundQueue.shift()}}finally{this.flushing=!1}}}scheduleReconnect(e){if(!(this.destroyed||this.reconnectInFlight)){if(this.log(`hydra-acp: connection lost (${e?.message??"no error"}); reconnecting...`),this.opts.onDisconnect)try{this.opts.onDisconnect(e)}catch(t){this.log(`hydra-acp: onDisconnect handler threw: ${t.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(t){for(let r of this.closeHandlers)r(t);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
239
239
  `)}}});function zP(n,e){let t=n&&typeof n=="object"?n.options:void 0;if(Array.isArray(t)){for(let o of e){let i=t.find(a=>typeof a=="object"&&a!==null&&a.kind===o&&typeof a.optionId=="string");if(i?.optionId!==void 0)return i.optionId}let s=t.find(o=>typeof o=="object"&&o!==null&&typeof o.optionId=="string");if(s?.optionId!==void 0)return s.optionId}let r=e[0]??"allow";return console.warn(`[permission-pick] no optionId match for preferredKinds=${JSON.stringify(e)}; falling back to kind name ${JSON.stringify(r)} (agent will likely reject)`),r}function Qa(n){return{outcome:{outcome:"selected",optionId:zP(n,["allow_once","allow_always"])}}}function KP(n){return{outcome:{outcome:"selected",optionId:zP(n,["reject_once","reject_always"])}}}function tg(n){return n&&typeof n=="object"?n:void 0}function af(n){return typeof n=="string"&&n.length>0?n:void 0}function GP(n){let e=tg(n),t=tg(e?.toolCall),r={paths:[]};if(!t)return r;let s=af(t.kind);s&&(r.kind=s);let o=new Set,i=c=>{let l=af(c);l&&!o.has(l)&&(o.add(l),r.paths.push(l))},a=t.locations;if(Array.isArray(a))for(let c of a)i(tg(c)?.path);let d=tg(t.rawInput);if(d){i(d.file_path),i(d.filePath),i(d.path);let c=af(d.command);c&&(r.command=c);let l=af(d.url);l&&(r.url=l);let u=af(d.description);u&&(r.description=u)}return r}function JP(n){let e=[];return n.command?e.push(`$ ${n.command}`):n.url?e.push(n.url):n.paths.length===1?e.push(n.paths[0]):n.paths.length>1?e.push(`${n.paths[0]} (+${n.paths.length-1} more)`):n.description&&e.push(n.description),e.join(" ").replace(/\s+/g," ").trim()}var ng=j(()=>{"use strict"});function yz(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function fM(n){let t=(n.split("-",1)[0]??n).split("."),r=Number(t[0]),s=Number(t[1]),o=Number(t[2]);return!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(o)?null:[r,s,o]}function wz(n,e){let t=fM(n),r=fM(e);if(!t||!r)return n!==e;for(let s=0;s<3;s++){let o=t[s],i=r[s];if(o>i)return!0;if(o<i)return!1}return!1}async function df(){if(Di!==void 0)return Di;if(yz())return Di=null,Di;try{let n=await import("update-notifier"),t=(n.default??n)({pkg:{name:pM,version:Fe}}),r=t.update;if(r&&typeof r.latest=="string"&&typeof r.current=="string"&&wz(r.latest,r.current)){try{t.config?.set?.("update",r)}catch{}Di={current:r.current,latest:r.latest,type:typeof r.type=="string"?r.type:"unknown"}}else{if(r&&typeof r.latest=="string"&&typeof r.current=="string")try{t.config?.set?.("update",void 0)}catch{}Di=null}}catch{Di=null}return Di}function cf(n){return`hydra-acp ${n.latest} available (current ${n.current}) \xB7 run: npm update -g ${pM}`}var pM,Di,yv=j(()=>{"use strict";rr();pM="@hydra-acp/cli"});import*as kv from"net";import*as mM from"path";function Sz(n){return n.HERDR_ENV==="1"&&!!n.HERDR_SOCKET_PATH&&!!n.HERDR_PANE_ID}function xz(n,e,t){return new Promise(r=>{let s;try{s=`${JSON.stringify({id:t,method:e.method,params:e.params})}
240
240
  `}catch{r(!1);return}let o;try{o=kv.connect(n)}catch{r(!1);return}let i=!1,a=d=>{i||(i=!0,o.destroy(),r(d))};o.on("connect",()=>o.write(s)),o.on("data",()=>a(!0)),o.on("error",()=>a(!1)),o.on("close",()=>a(!1)),o.setTimeout(bz,()=>a(!1))})}function Za(n,e,t){return new Promise((r,s)=>{let o;try{o=kv.connect(n)}catch(c){s(c);return}let i="",a=!1,d=(c,l)=>{a||(a=!0,o.destroy(),c?s(c):r(l))};o.on("connect",()=>{o.write(`${JSON.stringify({id:"hydra-req",method:e,params:t})}
241
241
  `)}),o.on("data",c=>{i+=c.toString("utf8");let l=i.indexOf(`
@@ -255,38 +255,38 @@ failed to spawn ${e.command}: ${a.message}
255
255
  `+t,this.buffer.splice(this.row+1,1)}killWord(){let e=this.currentLine();if(this.col===0){this.backspace();return}let r=e.slice(0,this.col).match(bf);if(r!==null){this.killBuffer=r[0];let i=this.col-r[0].length;this.setCurrentLine(e.slice(0,i)+e.slice(this.col)),this.col=i;return}let s=this.col;for(;s>0&&/\s/.test(e[s-1]??"");)s-=1;for(;s>0&&!/\s/.test(e[s-1]??"");)s-=1;let o=e.slice(s,this.col);o.length>0&&(this.killBuffer=o),this.setCurrentLine(e.slice(0,s)+e.slice(this.col)),this.col=s}killWordAlpha(){let e=this.currentLine();if(this.col===0){this.backspace();return}let r=e.slice(0,this.col).match(bf);if(r!==null){this.killBuffer=r[0];let a=this.col-r[0].length;this.setCurrentLine(e.slice(0,a)+e.slice(this.col)),this.col=a;return}let s=/[A-Za-z0-9_]/,o=this.col;for(;o>0&&!s.test(e[o-1]??"");)o-=1;for(;o>0&&s.test(e[o-1]??"");)o-=1;let i=e.slice(o,this.col);i.length>0&&(this.killBuffer=i),this.setCurrentLine(e.slice(0,o)+e.slice(this.col)),this.col=o}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let t=this.currentLine().slice(0,this.col).match(bf);if(t!==null){this.col-=t[0].length;return}this.col-=1;return}this.row>0&&(this.row-=1,this.col=this.currentLine().length)}moveRight(){let e=this.currentLine();if(this.col<e.length){let r=e.slice(this.col).match(qv);if(r!==null){this.col+=r[0].length;return}this.col+=1;return}this.row<this.buffer.length-1&&(this.row+=1,this.col=0)}moveWordBackward(){if(this.col===0){if(this.row===0)return;this.row-=1,this.col=this.currentLine().length;return}let e=this.currentLine(),t=this.col;for(;t>0&&/\s/.test(e[t-1]??"");)t-=1;let s=e.slice(0,t).match(bf);if(s!==null){this.col=t-s[0].length;return}for(;t>0&&!/\s/.test(e[t-1]??"");)t-=1;this.col=t}moveWordForward(){let e=this.currentLine();if(this.col>=e.length){if(this.row>=this.buffer.length-1)return;this.row+=1,this.col=0;return}let t=this.col;for(;t<e.length&&/\s/.test(e[t]??"");)t+=1;let s=e.slice(t).match(qv);if(s!==null){this.col=t+s[0].length;return}for(;t<e.length&&!/\s/.test(e[t]??"");)t+=1;this.col=t}handleUp(){return this.row>0?(this.row-=1,this.col=Math.min(this.col,this.currentLine().length),[]):this.queueIndex===-1&&this.historyIndex===-1?this.queue.length===0&&this.history.length===0?[]:(this.savedDraft={buffer:[...this.buffer],row:this.row,col:this.col},this.savedAttachments=[...this.attachments],this.attachments=[],this.queue.length>0?(this.queueIndex=this.queue.length-1,this.loadEntry(this.queue[this.queueIndex]??"")):(this.historyIndex=this.history.length-1,this.loadEntry(this.history[this.historyIndex]??"")),[]):this.queueIndex>=0?this.queueIndex>0?(this.queueIndex-=1,this.loadEntry(this.queue[this.queueIndex]??""),[]):this.history.length===0?[]:(this.queueIndex=-1,this.historyIndex=this.history.length-1,this.loadEntry(this.history[this.historyIndex]??""),[]):(this.historyIndex>0&&(this.historyIndex-=1,this.loadEntry(this.history[this.historyIndex]??"")),[])}handleDown(){return this.row<this.buffer.length-1&&this.historyIndex===-1&&this.queueIndex===-1?(this.row+=1,this.col=Math.min(this.col,this.currentLine().length),[]):this.historyIndex>=0?this.historyIndex<this.history.length-1?(this.historyIndex+=1,this.loadEntry(this.history[this.historyIndex]??""),[]):(this.historyIndex=-1,this.queue.length>0?(this.queueIndex=0,this.loadEntry(this.queue[this.queueIndex]??""),[]):(this.restoreDraft(),[])):this.queueIndex>=0?this.queueIndex<this.queue.length-1?(this.queueIndex+=1,this.loadEntry(this.queue[this.queueIndex]??""),[]):(this.queueIndex=-1,this.restoreDraft(),[]):[]}restoreDraft(){this.savedDraft?(this.buffer=[...this.savedDraft.buffer],this.row=this.savedDraft.row,this.col=this.savedDraft.col,this.savedDraft=null,this.attachments=this.savedAttachments??[],this.savedAttachments=null):this.clearBuffer()}startHistorySearch(){let e=this.bufferText().toLowerCase();if(e.length===0)return this.historySearch={query:"",matchIndices:[],cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},[];let t=this.findHistoryMatches(e);return t.length===0?[{type:"escalate-search",query:e}]:(this.historySearch={query:e,matchIndices:t,cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},this.loadEntry(this.history[t[0]]??""),[])}advanceHistorySearch(){if(this.historySearch===null)return[];let e=this.historySearch;if(e.cursor>=e.matchIndices.length-1){if(e.query.length===0)return[];let s=e.query,o=e.savedDraft;return this.historySearch=null,this.buffer=[...o.buffer],this.row=o.row,this.col=o.col,[{type:"escalate-search",query:s}]}e.cursor+=1;let r=e.matchIndices[e.cursor];return this.loadEntry(this.history[r]??""),[]}retreatHistorySearch(){if(this.historySearch===null||this.historySearch.cursor===0)return;this.historySearch.cursor-=1;let e=this.historySearch.matchIndices[this.historySearch.cursor];this.loadEntry(this.history[e]??"")}mutateHistorySearchQuery(e){if(this.historySearch===null)return[];if(e.length===0){this.historySearch.query="",this.historySearch.matchIndices=[],this.historySearch.cursor=0;let r=this.historySearch.savedDraft;return this.buffer=[...r.buffer],this.row=r.row,this.col=r.col,[]}let t=this.findHistoryMatches(e);if(t.length===0){let r=this.historySearch.savedDraft;return this.historySearch=null,this.buffer=[...r.buffer],this.row=r.row,this.col=r.col,[{type:"escalate-search",query:e}]}return this.historySearch.query=e,this.historySearch.matchIndices=t,this.historySearch.cursor=0,this.loadEntry(this.history[t[0]]??""),[]}findHistoryMatches(e){let t=[];for(let r=this.history.length-1;r>=0;r--){let s=this.history[r]??"";(e.length===0||s.toLowerCase().includes(e))&&t.push(r)}return t}cancelHistorySearch(){if(this.historySearch===null)return;let e=this.historySearch.savedDraft;this.historySearch=null,this.buffer=[...e.buffer],this.row=e.row,this.col=e.col}loadEntry(e){this.buffer=e.split(`
256
256
  `),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),t=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let o=this.queueIndex,i=[...this.attachments];return this.clearBuffer(),t.trim().length===0?[{type:"queue-remove",index:o}]:[{type:"queue-edit",index:o,text:t,displayText:e,attachments:i}]}if(t.trim().length===0&&this.attachments.length===0)return[];let r=this.planMode,s=[...this.attachments];return this.clearBuffer(),[{type:"send",text:t,displayText:e,planMode:r,attachments:s}]}amend(){let e=this.bufferText(),t=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let o=this.queueIndex,i=this.planMode,a=[...this.attachments],d=t.trim().length===0&&a.length===0;return this.clearBuffer(),d?[{type:"queue-remove",index:o}]:[{type:"queue-remove",index:o},{type:"amend",text:t,displayText:e,planMode:i,attachments:a}]}if(t.trim().length===0&&this.attachments.length===0)return[];let r=this.planMode,s=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:t,displayText:e,planMode:r,attachments:s}]}handleHome(){return this.row!==0||this.col!==0?(this.row=0,this.col=0,[]):[{type:"scroll-to-top"}]}handleEnd(){let e=this.buffer.length-1,t=(this.buffer[e]??"").length;return this.row!==e||this.col!==t?(this.row=e,this.col=t,[]):[{type:"scroll-to-bottom"}]}handleCtrlC(){if(this.queueIndex>=0){let e=this.queueIndex;return this.queueIndex=-1,this.restoreDraft(),[{type:"queue-remove",index:e}]}return!this.bufferIsEmpty()||this.attachments.length>0?(this.recordEdit(),this.buffer=[""],this.row=0,this.col=0,this.attachments=[],this.historyIndex=-1,this.savedDraft=null,this.savedAttachments=null,[]):this.turnRunning?[{type:"cancel"}]:[{type:"exit"}]}}});function LK(){let n=FK.map(e=>{let t=process.listeners(e);for(let s of t)process.off(e,s);let r=()=>{};return process.on(e,r),{signal:e,listeners:t,noop:r}});return()=>{for(let{signal:e,listeners:t,noop:r}of n){process.off(e,r);for(let s of t)process.on(e,s)}}}async function xg(n,e){let t=e.write??(o=>{process.stdout.write(o)}),r=LK();e.suspend(),t(kP),n.banner!==void 0&&t(n.banner);let s=e.spawn??(await import("child_process")).spawn;return await new Promise(o=>{let i=!1,a=d=>{if(!i){i=!0;try{e.resume()}finally{r()}d.error?e.notify?.(`${n.program} failed: ${d.error.message}`):d.exitCode!==null&&d.exitCode!==0&&e.notify?.(`${n.program} exited ${d.exitCode}`),o(d)}};try{let d=s(n.program,n.args,{stdio:"inherit",cwd:n.cwd});d.on("exit",c=>a({exitCode:c})),d.on("error",c=>a({exitCode:null,error:c}))}catch(d){a({exitCode:null,error:d})}})}var FK,zv=j(()=>{"use strict";Va();FK=process.platform==="win32"?["SIGINT"]:["SIGINT","SIGQUIT"]});import{mkdtempSync as NK,readFileSync as DK,rmSync as HK,writeFileSync as BK}from"fs";import{tmpdir as UK}from"os";import{join as h_}from"path";function WK(n=process.env){let e=[n.HYDRA_EDITOR,n.VISUAL,n.EDITOR].find(r=>r!==void 0&&r.trim()!=="");if(e===void 0)return null;let t=e.split(/\s+/).filter(r=>r.length>0);return t.length>0?t:null}async function Ig(n,e){let t=WK(e.env);if(t===null)return e.notify?.("no $HYDRA_EDITOR, $VISUAL or $EDITOR set \u2014 nothing to edit with"),null;let[r,...s]=t,o=NK(h_(UK(),"hydra-acp-edit-")),i=h_(o,"prompt.md");BK(i,n,"utf8");try{let a={program:r,args:[...s,i],banner:`\u2500 ${r} \u2014 save and quit to return to hydra \u2500
257
257
  `},c=await(e.runForeground??xg)(a,e);if(c.error||c.exitCode!==null&&c.exitCode!==0)return null;let l=DK(i,"utf8");return l.endsWith(`
258
- `)?l.slice(0,-1):l}finally{HK(o,{recursive:!0,force:!0})}}var Kv=j(()=>{"use strict";zv()});var gl,Cg,Gv=j(()=>{"use strict";gl=class{constructor(e){this.term=e}term;lastFrameRows=new Map;lastFrameW=0;lastFrameH=0;clearCache(){this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0}ensureSize(e,t){return e!==this.lastFrameW||t!==this.lastFrameH?(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=t,!0):!1}invalidate(e,t){this.lastFrameRows.delete(e===void 0?String(t):`${e}:${t}`)}paintRow(e,t,r,s){if(e<1||e>this.term.height)return!1;let o=s?.region,i=o===void 0?String(e):`${o}:${e}`;return this.lastFrameRows.get(i)===t?!1:(this.lastFrameRows.set(i,t),this.term.moveTo(s?.column??1,e),r(),this.term.styleReset(),s?.erase!==!1&&this.term.eraseLineAfter(),!0)}},Cg=class{constructor(e){this.deps=e}deps;lastRepaintAt=0;timer=null;get pendingTimer(){return this.timer}schedule(){if(!this.deps.isStarted())return;if(this.deps.isRepaintPaused()){this.deps.markRepaintPending();return}let e=this.deps.throttleMs();if(e<=0){this.deps.doRepaint();return}let r=Date.now()-this.lastRepaintAt;if(r>=e){this.cancel(),this.deps.doRepaint();return}this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.doRepaint()},e-r))}noteRepaintStart(){this.lastRepaintAt=Date.now(),this.cancel()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}}});var m_,g_=j(()=>{"use strict";m_=["toggle-mode","switch-session","show-help","detach","toggle-options","rename-session","choose-model","choose-agent","choose-mode","choose-config","copy","open","open-session","none"]});import jK from"ansi-regex";import xs from"string-width";function Ss(n){let e=0;for(let t of n)e+=xs(t.text);return e}function Rg(n,e){let t=[];for(let r of n){if(t.length>0){let s=r.separator??e.separator;s.length>0&&t.push({text:s,token:e.separatorToken})}t.push(...r.chunks)}return t}function w_(n,e){let t=Ss(n)-e;if(t<=0)return n;let r=n.map(o=>({...o})),s=r.map((o,i)=>({c:o,i})).filter(({c:o})=>o.flex===!0&&o.truncatable!==!1).map(({i:o})=>o);for(;t>0&&s.length>0;){let o=-1,i=0;for(let l of s){let u=r[l];if(u===void 0)continue;let f=xs(u.text)-(u.minWidth??0);f>i&&(i=f,o=l)}if(o<0)break;let a=r[o];if(a===void 0)break;let d=Math.min(t,i),c=xs(a.text)-d;a.text=Ag(a.text,c),t-=d}return r}function qK(n){let e=[];y_.lastIndex=0;let t=0,r;for(;(r=y_.exec(n))!==null;)r.index>t&&e.push({text:n.slice(t,r.index),ansi:!1}),e.push({text:r[0],ansi:!0}),t=r.index+r[0].length;return t<n.length&&e.push({text:n.slice(t),ansi:!1}),e}function Ag(n,e){if(e<=0)return"";if(xs(n)<=e)return n;if(e===1)return"\u2026";let t="",r=0;e:for(let s of qK(n)){if(s.ansi){t+=s.text;continue}for(let o of s.text){let i=xs(o);if(r+i>e-1)break e;t+=o,r+=i}}return t+"\u2026"}function b_(n,e){let t=[],r=0;for(let s of n){let o=e-r;if(o<=0)break;let i=xs(s.text);if(i<=o)t.push(s),r+=i;else{if(s.truncatable===!1)break;t.push({...s,text:Ag(s.text,o)});break}}return t}function Jv(n,e,t,r){let s=xs(r.prefix)+xs(r.suffix),o=xs(r.pad),i=[...e],a=[...t],d=C=>{let $=0;for(let E of C){let M=xs(E.text);$+=E.flex===!0?Math.min(M,E.minWidth??0):M}return $},c=()=>{let C=Rg(i,r),$=Rg(a,r);return s+(C.length>0?d(C)+o*2:0)+($.length>0?d($)+o*2:0)+r.minGap};for(;c()>n;){let C=null,$=-1,E=1/0;if(i.forEach((M,F)=>{M.priority<E&&(E=M.priority,C="l",$=F)}),a.forEach((M,F)=>{M.priority<E&&(E=M.priority,C="r",$=F)}),C===null||E===1/0)break;C==="l"?i=i.filter((M,F)=>F!==$):a=a.filter((M,F)=>F!==$)}let l=Rg(i,r),u=Rg(a,r),f=s+(l.length>0?o*2:0)+(u.length>0?o*2:0)+r.minGap,p=Math.max(0,n-f),m=Ss(u);Ss(l)+m>p&&(l=w_(l,Math.max(0,p-m))),Ss(l)+Ss(u)>p&&(u=w_(u,Math.max(0,p-Ss(l)))),Ss(l)+Ss(u)>p&&(u=b_(u,p),l=b_(l,Math.max(0,p-Ss(u))));let b=[],g=[],h=1,y=(C,$,E)=>{if(C.length===0)return;let M=xs(C),F={...E??{},text:C,token:$,start:h,width:M};if(b.push(F),F.id!==void 0){let K=g.find(Y=>Y.id===F.id);K!==void 0?K.end=h+M-1:g.push({id:F.id,start:h,end:h+M-1,action:F.action??"none",doubleAction:F.doubleAction??"none",value:F.value??F.text})}h+=M};if(y(r.prefix,r.ruleToken),l.length>0){y(r.pad,r.padToken);for(let C of l)y(C.text,C.token,C);y(r.pad,r.padToken)}let k=s+(l.length>0?Ss(l)+o*2:0)+(u.length>0?Ss(u)+o*2:0),S=Math.max(r.minGap,n-k);S>0&&r.fill.length>0&&y(r.fill.repeat(S),r.ruleToken);let I=null;if(u.length>0){I=h,y(r.pad,r.padToken);for(let C of u)y(C.text,C.token,C);y(r.pad,r.padToken)}y(r.suffix,r.ruleToken);let x=b.map(C=>`${C.token}${C.text}`).join("\0");return{chunks:b,signature:x,hits:g,rightStart:I}}var y_,k_,Tg=j(()=>{"use strict";g_();y_=jK(),k_=m_});function Vv(n){return n.banner.status==="ready"&&n.banner.armedSince!==void 0}function zK(n){let e=n.banner.status,t=e==="busy"&&n.banner.stalled===!0,r;n.statusLabel!==void 0?r=n.statusLabel:t?r="Stalled":e==="busy"?r="Thinking":Vv(n)?r="Waiting":r=e.charAt(0).toUpperCase()+e.slice(1);let s;return t||e==="disconnected"?s="status-alert":e==="busy"||Vv(n)?s="status-active":e==="cold"?s="status-cold":s="status-ready",{label:r,token:s}}function ho(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}k`:String(n)}function KK(n){if(!n)return null;let e=[];return typeof n.used=="number"?typeof n.size=="number"&&n.size>0?e.push(`${ho(n.used)}/${ho(n.size)}`):e.push(ho(n.used)):typeof n.size=="number"&&e.push(`/${ho(n.size)}`),typeof n.costAmount=="number"&&e.push(Am(n.costAmount,n.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function GK(n){if(n.banner.hintsExhausted===!0&&!n.hintsRevealed)return null;let e=n.banner.hint;return e.length===0?null:e.map((t,r)=>{let o={text:t.id==="mode"&&(n.banner.currentMode??"")!==""?`${t.label}: ${n.banner.currentMode}`:t.label,token:"modal-hint",action:t.action};return{id:t.id,chunks:[o],priority:20+(e.length-r)}})}function v_(n){if(n.transient===null)return null;let e=n.transient.kind==="search"?"bar-indicator":"modal-note";return{id:"transient",chunks:[{text:n.transient.text,token:e}],priority:1/0}}var Yv,Boe,Eg=j(()=>{"use strict";Ek();Se();mr();Ko();Yv={status:{priority:1/0,resolve:n=>{let{label:e,token:t}=zK(n);return[{text:e,token:t}]}},elapsed:{priority:60,resolve:n=>{if(Vv(n)){let r=Date.now()-n.banner.armedSince;return r<1e3?null:[{text:jr(r),token:"status-active"}]}if(n.banner.status!=="busy"||n.banner.elapsedMs===void 0||n.banner.elapsedMs<1e3)return null;let t=n.banner.stalled===!0?"status-alert":"status-active";return[{text:jr(n.banner.elapsedMs),token:t}]}},sessionId:{priority:40,resolve:n=>{let e=Qe(n.session.sessionId);if(!e)return null;let t={text:e,token:"rule-meta",doubleAction:"copy",value:e};return n.scope==="btw"&&(t.action="open-session"),[t]}},sessionIdFull:{priority:40,resolve:n=>n.session.sessionId?[{text:n.session.sessionId,token:"rule-meta",doubleAction:"copy"}]:null},queued:{priority:50,resolve:n=>n.banner.queued>0?[{text:`${n.banner.queued} queued`,token:"status-queued"}]:null},scroll:{priority:30,resolve:n=>n.scrollOffset>0?[{text:`\u2191 ${n.scrollOffset}`,token:"bar-indicator"}]:null},usage:{priority:45,resolve:n=>{let e=KK(n.session.usage);return e?[{text:e,token:"content",doubleAction:"copy"}]:null}},tokens:{priority:45,resolve:n=>{let e=n.session.usage;return!e||typeof e.used!="number"?null:[{text:typeof e.size=="number"&&e.size>0?`${ho(e.used)}/${ho(e.size)}`:ho(e.used),token:"content",doubleAction:"copy"}]}},cost:{priority:45,resolve:n=>{let e=n.session.usage;return!e||typeof e.costAmount!="number"?null:[{text:Am(e.costAmount,e.costCurrency),token:"content",doubleAction:"copy"}]}},cwd:{priority:70,resolve:()=>null,resolveGroups:n=>{let e=n.session.workspace;if(e===void 0){let r=V(n.session.cwd);return r?[{id:"cwd",priority:70,chunks:[{text:r,token:"bar-text",flex:!0,minWidth:8,doubleAction:"open",value:n.session.cwd}]}]:null}let t=V(e.sourceCwd);return t?[{id:"cwd",priority:70,chunks:[{text:t,token:"bar-text",flex:!0,minWidth:8,doubleAction:"open",value:e.sourceCwd}]},{id:"cwdWorkspace",priority:69,separator:" ",chunks:[{text:`[${e.label}]`,token:"bar-text",doubleAction:"open",value:e.path}]}]:null}},cwdFull:{priority:70,resolve:n=>n.session.cwd?[{text:n.session.cwd,token:"bar-text",flex:!0,minWidth:8,doubleAction:"open"}]:null},title:{priority:75,resolve:n=>{let e=n.session.title?.trim();return e?[{text:e,token:"bar-text",flex:!0,minWidth:8,doubleAction:"rename-session",value:e}]:null}},agent:{priority:80,resolve:n=>n.session.agent?[{text:n.session.agent,token:"content",doubleAction:"choose-agent"}]:null},model:{priority:65,resolve:n=>n.session.model?[{text:n.session.model,token:"content",doubleAction:"choose-model"}]:null},agentModel:{priority:80,resolve:n=>{let e=oE(n.session.agent,n.session.model);return e?[{text:e,token:"content",flex:!0,minWidth:6,doubleAction:"choose-model",value:e}]:null}},mode:{priority:55,resolve:n=>n.banner.currentMode?[{text:n.banner.currentMode,token:"rule-meta",doubleAction:"choose-mode",value:"mode"}]:null},helpHint:{priority:20,resolve:()=>null,resolveGroups:GK}},Boe=Object.keys(Yv)});function S_(n){return typeof n=="string"?n===Qv?null:n:n.field??null}function x_(n,e,t){if(!t.some(a=>a===Qv))return t;let r=new Set;for(let a of t){let d=S_(a);d!==null&&r.add(d)}let s=JK[n][e].filter(a=>{let d=S_(a);return d===null||!r.has(d)}),o=[],i=!1;for(let a of t){if(a===Qv){i||(o.push(...s),i=!0);continue}o.push(a)}return o}function YK(n){if(typeof n!="string")return n;let t=VK.exec(n)?.[1];return t!==void 0?{script:t}:{field:n}}function I_(n){if(n!==void 0)return k_.includes(n)?n:"none"}function QK(n,e){let t=`${n}:${e.id}`;return{...e,chunks:e.chunks.map(r=>({...r,id:t}))}}function XK(n,e){let t=n;if(e.style!==void 0){let r=e.style;t=t.map(s=>({...s,token:r}))}if(e.minWidth!==void 0&&(t=t.map(r=>({...r,flex:!0,minWidth:e.minWidth}))),e.maxWidth!==void 0){let r=e.maxWidth;if(t=t.map(s=>({...s,text:Ag(s.text,r)})).filter(s=>s.text.length>0),t.length===0)return null}return e.truncate===!1&&(t=t.map(r=>({...r,truncatable:!1}))),t}function ZK(n,e){let t=n.map(o=>({...o,chunks:[...o.chunks]})),r=t[0];if(e.prefix!==void 0&&e.prefix.length>0&&r!==void 0){let o=r.chunks[0];o!==void 0&&r.chunks.unshift({text:e.prefix,token:o.token})}let s=t[t.length-1];if(e.suffix!==void 0&&e.suffix.length>0&&s!==void 0){let o=s.chunks[s.chunks.length-1];o!==void 0&&s.chunks.push({text:e.suffix,token:o.token})}return t}function kf(n,e,t){let r=[];for(let s of e){let o=YK(s),i;if(o.text!==void 0){if(o.text.length===0)continue;i=[{id:`text:${o.text}`,priority:10,chunks:[{text:o.text,token:"rule-meta"}]}]}else if(o.script!==void 0){let u=t.scriptOutputs.get(o.script);if(u===void 0||u.length===0)continue;i=[{id:`script:${o.script}`,priority:10,chunks:[{text:u,token:"rule-meta"}]}]}else{let u=o.field??"",f=Yv[u];if(f===void 0)continue;if(f.resolveGroups!==void 0){let p=f.resolveGroups(t);if(p===null)continue;i=p}else{let p=f.resolve(t);if(p===null||p.length===0)continue;i=[{id:u,priority:f.priority,chunks:p}]}}let a=[];for(let u of i){let f=XK(u.chunks,o);f!==null&&a.push({...u,priority:o.priority??u.priority,chunks:f})}if(a.length===0)continue;a=ZK(a,o);let d=I_(o.onClick),c=I_(o.onDoubleClick);(d!==void 0||c!==void 0)&&(a=a.map(u=>({...u,chunks:u.chunks.map(f=>({...f,...d!==void 0?{action:d}:{},...c!==void 0?{doubleAction:c}:{}}))})));let l=a[0];o.separator!==void 0&&l!==void 0&&(l.separator=o.separator);for(let u of a)r.push(QK(n,u))}return r}function vf(n){let e=(t,r)=>({left:x_(t,"left",r.left),right:x_(t,"right",r.right)});return{composer:{top:e("composerTop",n.composer.top),bottom:e("composerBottom",n.composer.bottom)},sessionbar:e("sessionbar",n.sessionbar)}}var Xv,Qv,JK,VK,Zv=j(()=>{"use strict";et();Eg();Tg();Tg();Xv={composerTop:{prefix:"\u2500\u2500",suffix:"\u2500\u2500",fill:"\u2500",pad:" ",separator:" \xB7 ",separatorToken:"rule-meta",ruleToken:"rule",padToken:"rule-pad",minGap:0},composerBottom:{prefix:"",suffix:"\u2500\u2500",fill:"\u2500",pad:" ",separator:" \xB7 ",separatorToken:"rule-meta",ruleToken:"rule",padToken:"rule-pad",minGap:0},btw:{prefix:"\u2500\u2500",suffix:"\u2500\u2500",fill:"\u2500",pad:" ",separator:" \xB7 ",separatorToken:"rule-meta",ruleToken:"rule",padToken:"rule-pad",minGap:0},sessionbar:{prefix:"",suffix:"",fill:" ",pad:"",separator:" \xB7 ",separatorToken:"content",ruleToken:"content",padToken:"content",minGap:1}},Qv="...",JK={composerTop:{left:ca,right:la},btw:{left:ca,right:la},composerBottom:{left:zd,right:Kd},sessionbar:{left:Gd,right:Jd}};VK=/^\$\((.+)\)\s*$/});import{resolve as eG}from"path";function tS(n){return!tG.has(n)}function nG(n){return n.replace(/\s+/gu," ").trim()}function rG(n,e,t){let r=n.trim();for(let s of[e,t]){if(s===void 0||s==="")continue;let o=r.toLowerCase(),i=s.toLowerCase();if(o===i)return"";o.startsWith(`${i} `)&&(r=r.slice(s.length).trimStart())}return r}function sG(n){let e=n.trim();return e===""?!0:!/[\s/.]/u.test(e)}function oG(n){switch(n){case"read":return"read";case"edit":return"edit";case"delete":return"delete";case"move":return"move";case"search":return"search";case"execute":return"run";case"fetch":return"fetch";case"think":return"think";default:return C_}}function iG(n,e){if(!tS(n.status))return null;let t=oG(n.rawKind),r=c=>c===void 0?"":rG(nG(c),t,n.rawKind),s=n.editDiff?.path??jp(n.locations),o=s===void 0||s===""?void 0:e===null?s:eG(e,s),i=r(n.latestTitle),a=t!==C_&&sG(i)?"":i,d=r(n.detail)||aG(o)||a;return{verb:t,detail:d===""?void 0:d,startedAt:n.startedAt,path:o}}function aG(n){return n===void 0?"":n.split(/[\\/]/).filter(t=>t!=="").at(-1)??""}function R_(n,e,t){let r=[];for(let s of n){let o=e.get(s);if(o===void 0||Fc(s,o.latestTitle))continue;let i=iG(o,t);i!==null&&r.push(i)}return r}var eS,tG,C_,nS=j(()=>{"use strict";vi();xh();eS=4,tG=new Set(["completed","succeeded","ok","failed","error","rejected","cancelled","canceled"]);C_="tool"});function Sf(n){let e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s`;let t=Math.floor(e/60),r=e%60;return t<60?`${t}m ${String(r).padStart(2,"0")}s`:`${Math.floor(t/60)}h ${String(t%60).padStart(2,"0")}m`}function A_(n,e){return e<=0?n:Math.floor(Math.max(0,n)/e)*e}function rS(n){if(n<1e3)return String(n);if(n<1e6){let e=n/1e3;return`${e<10?e.toFixed(1):Math.round(e)}K`}return`${(n/1e6).toFixed(1)}M`}function dG(n,e){if(e<=0)return"";let t=Math.max(0,Math.min(1,n)),r=Math.round(t*e*8),s=Math.floor(r/8),o=r%8,i=o===0?"":"\u258F\u258E\u258D\u258C\u258B\u258A\u2589"[o-1];return"\u2588".repeat(Math.min(e,s))+(s<e?i:"")+"\xB7".repeat(Math.max(0,e-s-(i?1:0)))}function Kr(n,e){return{body:n,bodyStyle:e}}function Pg(n,e,t){let{cellWidth:r,truncate:s}=t.metrics,o=t.width-r(n)-r(e);return o<1?{body:s(`${n} ${e}`,t.width),bodyStyle:"muted"}:{prefix:`${n}${" ".repeat(o)}`,prefixStyle:"muted",body:e,bodyStyle:"sidebar-value"}}function $_(n,e,t,r){let s={body:n,bodyStyle:t,openPath:e,item:!0};if(r!==void 0&&r.length>0){let o=n.indexOf(r);o!==-1&&(s.openSpan={start:o,end:o+r.length})}return s}function Is(n,e,t){let{cellWidth:r,truncate:s}=t.metrics,o=t.width-r(n)-r(e);return o<1?s(`${n} ${e}`,t.width):`${n}${" ".repeat(o)}${e}`}function E_(n){return n==="in_progress"?0:n==="completed"?2:1}function hG(n){return[...n].sort((e,t)=>E_(e.status)-E_(t.status))}function O_(n){let e=n.map(r=>r.split("/").pop()??r),t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);return n.map((r,s)=>{let o=e[s];return(t.get(o)??0)<=1?o:r.split("/").slice(-2).join("/")})}function wG(n,e,t){let{cellWidth:r,truncate:s}=t.metrics;if(e<=0)return"";if(r(n)<=e)return n;let o=n.slice(n.lastIndexOf("/")+1);if(o!==n&&r(o)<=e)return o;let i=o.length<n.length?o:n;for(let a=1;a<i.length;a++){let d=`\u2026${i.slice(a)}`;if(r(d)<=e)return d}return s(i,e)}function P_(n){if(n<1024)return`${Math.max(0,Math.round(n))}B`;let e=n/(1024*1024);return e<1?`${Math.round(n/1024)}K`:e<1024?e<10?`${e.toFixed(1)}M`:`${Math.round(e)}M`:`${(e/1024).toFixed(1)}G`}function __(n){if(n===void 0)return"\u2013".padStart(M_);let e=n*100;return(e<100?`${e.toFixed(1)}%`:`${Math.round(e)}%`).padStart(M_)}var Bi,T_,cG,lG,uG,fG,pG,mG,gG,yG,bG,M_,kG,vG,SG,xG,IG,CG,F_,L_=j(()=>{"use strict";nS();Bi=5;T_=5e3,cG={id:"activity",relevant:()=>!0,versionKey:n=>n.busySince!==null?`busy:${Math.floor((n.now-n.busySince)/1e3)}`:n.armedSince!==null?`running:${Math.floor((n.now-n.armedSince)/1e3)}`:n.lastTurnEndedAt!==null?`idle:${A_(n.now-n.lastTurnEndedAt,T_)}`:"fresh",render:(n,e)=>n.busySince!==null?[Kr(Is("\u25CF thinking",Sf(n.now-n.busySince),e),"status-active")]:n.armedSince!==null?[Kr(Is("\u25D0 waiting",Sf(n.now-n.armedSince),e),"status-active")]:n.lastTurnEndedAt!==null?[Kr(Is("\u25CB idle",Sf(A_(n.now-n.lastTurnEndedAt,T_)),e),"status-idle")]:[Kr("\u25CB ready","status-idle")]},lG={id:"tasks",title:"tasks",relevant:n=>n.armedTasks.length>0,versionKey:(n,e)=>{let t=n.armedTasks.slice(0,Bi);return`${e.width}|${n.armedTasks.length}|`+t.map(r=>{let s=Math.floor(Math.max(0,n.now-r.since)/1e3);return`${r.taskId??r.label}:${s}`}).join("\0")},render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=[];for(let o of n.armedTasks.slice(0,Bi)){let i=Sf(Math.max(0,n.now-o.since)),a="\u25D0 ",d=e.width-r(a)-r(i)-1,c=o.label.length>0?o.label:o.taskType??"background task",l=d<4?a.trim():`${a}${t(c,d)}`;s.push(Kr(Is(l,i,e),"status-active"))}return n.armedTasks.length>Bi&&s.push(Kr(` +${n.armedTasks.length-Bi} more`,"muted")),s}},uG={id:"tools",title:"tools",relevant:n=>n.running.length>0,versionKey:(n,e)=>{let t=n.running.slice(0,eS);return`${e.width}|${n.running.length}|`+t.map(r=>{let s=r.startedAt===void 0?"":Math.floor(Math.max(0,n.now-r.startedAt)/1e3);return`${r.verb}:${r.detail??""}:${s}`}).join("\0")},render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=[],o=n.running.slice(0,eS);for(let i of o){let a=i.startedAt===void 0?"":Sf(Math.max(0,n.now-i.startedAt)),d=`\u25B8 ${i.verb}`,c=e.width-r(d)-(a===""?0:r(a)+1)-1,l=i.detail===void 0||c<4?"":` ${t(i.detail,c)}`,u=`${d}${l}`,f=a===""?u:Is(u,a,e),p={body:f,bodyStyle:"tool-status-running",openPath:i.path};if(i.path!==void 0){let m=i.path.slice(i.path.lastIndexOf("/")+1),b=m.length>0?f.indexOf(m):-1;b!==-1&&(p.openSpan={start:b,end:b+m.length})}s.push(p)}return n.running.length>o.length&&s.push(Kr(` +${n.running.length-o.length} more`,"muted")),s}},fG={id:"context",title:"context",relevant:n=>n.usage.used!==void 0||n.usage.costAmount!==void 0,versionKey:(n,e)=>`${n.usage.used??""}/${n.usage.size??""}/${n.usage.costAmount??""}/${e.width}`,render:(n,e)=>{let t=[],{used:r,size:s,costAmount:o,costCurrency:i}=n.usage;if(r!==void 0&&s!==void 0&&s>0){let a=r/s;t.push(Kr(Is(`${rS(r)}/${rS(s)}`,`${Math.round(a*100)}%`,e),a>=.9?"meter-warn":"metric")),t.push(Kr(dG(a,e.width),a>=.9?"meter-warn":"meter-fill"))}else r!==void 0&&t.push(Kr(Is("tokens",rS(r),e),"metric"));if(o!==void 0){let a=i==="USD"||i===void 0?"$":`${i} `;t.push(Kr(Is("cost",`${a}${o.toFixed(2)}`,e),"muted"))}return t}},pG={id:"queue",relevant:n=>n.queued>0,versionKey:(n,e)=>`${n.queued}/${e.width}`,render:(n,e)=>[Kr(Is("queued",String(n.queued),e),"status-queued")]};mG={id:"todo",title:"todo",pageSize:Bi,relevant:n=>n.plan.length>0,titleNote:n=>`${n.plan.filter(e=>e.status==="completed").length}/${n.plan.length}`,versionKey:(n,e)=>`${e.width}|`+n.plan.map(t=>`${t.status}:${t.content}`).join("\0"),render:(n,e)=>{let{truncate:t}=e.metrics,r=[];for(let s of hG(n.plan)){let o=s.status==="completed"?"\u2713":s.status==="in_progress"?"\u25B8":"\xB7",i=s.status==="completed"?"plan-done":s.status==="in_progress"?"plan":"plan-pending";r.push({body:t(`${o} ${s.content}`,e.width),bodyStyle:i,item:!0})}return r}};gG={id:"files",title:"edited",pageSize:Bi,relevant:n=>n.editedFiles.length>0,titleNote:n=>n.editedFiles.length>1?`${n.editedFiles.length} files`:void 0,versionKey:(n,e)=>`${e.width}|`+n.editedFiles.map(t=>`${t.path}:${t.added??""}:${t.removed??""}`).join("\0"),render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=[...n.editedFiles].reverse(),o=[],i=O_(s.map(a=>a.path));return s.forEach((a,d)=>{let c=a.added!==void 0||a.removed!==void 0?`+${a.added??0} -${a.removed??0}`:"",l=e.width-(c?r(c)+1:0),u=t(i[d],Math.max(1,l));o.push($_(c?Is(u,c,e):u,a.path,"file-path",u))}),o}},yG={id:"git",title:"git",pageSize:Bi,relevant:n=>n.git!==null&&(n.git.staged>0||n.git.unstaged>0||n.git.untracked>0||n.git.ahead>0||n.git.behind>0),titleNote:n=>n.git!==null&&n.git.files.length>1?`${n.git.files.length} files`:void 0,versionKey:(n,e)=>{let t=n.git;if(t===null)return"none";let r=t.files.map(s=>`${s.state}:${s.path}`).join("\0");return`${e.width}|${t.branch}|${t.staged}|${t.unstaged}|${t.untracked}|${t.ahead}|${t.behind}|${r}`},render:(n,e)=>{let t=n.git;if(t===null)return[];let{truncate:r,cellWidth:s}=e.metrics,o=[];if(t.branch!==null){let d=(t.ahead>0?`\u2191${t.ahead}`:"")+(t.behind>0?`\u2193${t.behind}`:"");o.push(d?Pg(r(t.branch,e.width-d.length-1),d,e):{body:r(t.branch,e.width)})}let i=t.files,a=O_(i.map(d=>d.path));return i.forEach((d,c)=>{let l=d.state==="staged"?"git-staged":d.state==="dirty"?"git-dirty":"git-untracked",u=e.width-s(d.state)-1,f=r(a[c],Math.max(1,u));o.push($_(Is(f,d.state,e),d.path,l,f))}),o}};bG={id:"info",title:"info",relevant:n=>n.agent!==null||n.model!==null||n.sessionId!==null||n.workspace!==null,versionKey:(n,e)=>`${e.width}|${n.agent}|${n.model}|${n.mode}|${n.configOptions.map(t=>`${t.id}=${t.value}`).join(",")}|${n.sessionId}|${n.host}|${n.workspace?.label??""}`,render:(n,e)=>{let{cellWidth:t}=e.metrics,r=[],s=(c,l,u)=>{let f=e.width-t(c)-1,p=Pg(c,wG(l,f,e),e);r.push(u===void 0?p:{...p,doubleAction:u})},o=c=>n.configOptions.find(l=>l.id===c)?.value??null,i=n.agent??o("agent");i!==null&&s("agent",i,{action:"choose-agent",value:"agent"});let a=n.model??o("model");a!==null&&s("model",a,{action:"choose-model",value:"model"});let d=n.mode??o("mode");d!==null&&s("session mode",d,{action:"choose-mode",value:"mode"});for(let c of n.configOptions)c.id==="agent"||c.id==="model"||c.id==="mode"||s(c.name.toLowerCase(),c.value,{action:"choose-config",value:c.id});if(n.host!==null&&s("host",n.host,{action:"copy",value:n.host}),n.sessionId!==null&&s("id",n.sessionId,{action:"copy",value:n.sessionId}),n.workspace!==null){let c=Pg("workspace",n.workspace.label,e);r.push({...c,openPath:n.workspace.path})}return r}};M_=5;kG="\u25CF",vG="\u25D0",SG="\u25CB",xG="\u25E6",IG={id:"sessions",title:"sessions",pageSize:Bi,relevant:n=>n.liveSessions.length>0,titleNote:(n,e,t)=>{if(!t)return;let r=n.liveSessions.filter(s=>s.blocked).length;return r>0?`${r} blocked`:`${n.liveSessions.length} live`},versionKey:(n,e)=>`${e.width}|`+n.liveSessions.map(t=>`${t.blocked?"w":""}${t.busy?"b":""}${t.armed?"r":""}:${t.sessionId}:${t.label}`).join("\0"),render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=i=>(i.blocked?0:3)+(i.busy?0:i.armed?1:2);return[...n.liveSessions].sort((i,a)=>s(i)-s(a)).map(i=>{let a=i.busy||i.armed,d=`${i.blocked?xG:" "}${i.busy?kG:i.armed?vG:SG}`,c=r(d),l=t(i.label,Math.max(1,e.width-c-1)),u=Math.max(1,e.width-r(l)-c);return{prefix:`${l}${" ".repeat(u)}`,prefixStyle:a?"status-active":"sidebar-value",body:d,bodyStyle:a?"status-active":i.blocked?"status-blocked":"status-idle",doubleAction:{action:"open-session",value:i.sessionId},item:!0}})}},CG={id:"resources",title:"resources",relevant:n=>n.resources.length>0,versionKey:(n,e)=>`${e.width}|`+n.resources.map(t=>`${t.label}:${P_(t.rssBytes)}:${__(t.cpuFraction)}:${t.processes}`).join("\0"),render:(n,e)=>{let{cellWidth:t,truncate:r}=e.metrics;return n.resources.map(s=>{let o=`${P_(s.rssBytes)} ${__(s.cpuFraction)}`,i=s.processes>1?`${s.label} \xD7${s.processes}`:s.label,a=e.width-t(o)-1;return Pg(r(i,Math.max(1,a)),o,e)})}},F_=[cG,lG,fG,pG,mG,gG,yG,IG,CG,bG,uG]});function AG(n){let e="",t=[],r=0;for(;r<n.length;){let s=n[r];if(s==="["){let o=n.indexOf("]",r+1);if(o!==-1&&n[o+1]==="("&&o>r+1){let i=-1,a=1,d=o+2;for(;d<n.length;){let c=n[d];if(c==="\\"&&d+1<n.length){d+=2;continue}if(c==="(")a+=1;else if(c===")"&&(a-=1,a===0)){i=d;break}d+=1}if(i!==-1&&i>o+2){let c=n.slice(r+1,o),l=n.slice(o+2,i),u=e.length;e+=c,t.push({start:u,end:e.length,url:l}),r=i+1;continue}}}e+=s,r+=1}return{body:e,links:t}}function N_(n){let e=Gt(n).trim();return e.length===0?null:e}function TG(n){return typeof n!="string"}function Mg(n){return typeof n=="string"?n:n.id}function _g(n){return n.filter(TG)}function sS(n,e){let t=new Map;for(let r of _g(n)){let s=r.refreshMs??e,o=t.get(r.script);t.set(r.script,o===void 0?s:Math.min(o,s))}return t}function D_(n){return{id:n.id,title:n.title??n.id,relevant:e=>e.processOutputs.has(n.script),versionKey:(e,t)=>`${t.width}:${e.processOutputs.get(n.script)??""}`,render:(e,t)=>{let r=e.processOutputs.get(n.script);if(r===void 0)return[];let{truncate:s}=t.metrics,o=r.split(`
258
+ `)?l.slice(0,-1):l}finally{HK(o,{recursive:!0,force:!0})}}var Kv=j(()=>{"use strict";zv()});var gl,Cg,Gv=j(()=>{"use strict";gl=class{constructor(e){this.term=e}term;lastFrameRows=new Map;lastFrameW=0;lastFrameH=0;clearCache(){this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0}ensureSize(e,t){return e!==this.lastFrameW||t!==this.lastFrameH?(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=t,!0):!1}invalidate(e,t){this.lastFrameRows.delete(e===void 0?String(t):`${e}:${t}`)}paintRow(e,t,r,s){if(e<1||e>this.term.height)return!1;let o=s?.region,i=o===void 0?String(e):`${o}:${e}`;return this.lastFrameRows.get(i)===t?!1:(this.lastFrameRows.set(i,t),this.term.moveTo(s?.column??1,e),r(),this.term.styleReset(),s?.erase!==!1&&this.term.eraseLineAfter(),!0)}},Cg=class{constructor(e){this.deps=e}deps;lastRepaintAt=0;timer=null;get pendingTimer(){return this.timer}schedule(){if(!this.deps.isStarted())return;if(this.deps.isRepaintPaused()){this.deps.markRepaintPending();return}let e=this.deps.throttleMs();if(e<=0){this.deps.doRepaint();return}let r=Date.now()-this.lastRepaintAt;if(r>=e){this.cancel(),this.deps.doRepaint();return}this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.doRepaint()},e-r))}noteRepaintStart(){this.lastRepaintAt=Date.now(),this.cancel()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}}});var m_,g_=j(()=>{"use strict";m_=["toggle-mode","switch-session","show-help","detach","toggle-options","rename-session","choose-model","choose-agent","choose-mode","choose-config","copy","open","open-session","none"]});import jK from"ansi-regex";import xs from"string-width";function Ss(n){let e=0;for(let t of n)e+=xs(t.text);return e}function Rg(n,e){let t=[];for(let r of n){if(t.length>0){let s=r.separator??e.separator;s.length>0&&t.push({text:s,token:e.separatorToken})}t.push(...r.chunks)}return t}function w_(n,e){let t=Ss(n)-e;if(t<=0)return n;let r=n.map(o=>({...o})),s=r.map((o,i)=>({c:o,i})).filter(({c:o})=>o.flex===!0&&o.truncatable!==!1).map(({i:o})=>o);for(;t>0&&s.length>0;){let o=-1,i=0;for(let l of s){let u=r[l];if(u===void 0)continue;let f=xs(u.text)-(u.minWidth??0);f>i&&(i=f,o=l)}if(o<0)break;let a=r[o];if(a===void 0)break;let d=Math.min(t,i),c=xs(a.text)-d;a.text=Ag(a.text,c),t-=d}return r}function qK(n){let e=[];y_.lastIndex=0;let t=0,r;for(;(r=y_.exec(n))!==null;)r.index>t&&e.push({text:n.slice(t,r.index),ansi:!1}),e.push({text:r[0],ansi:!0}),t=r.index+r[0].length;return t<n.length&&e.push({text:n.slice(t),ansi:!1}),e}function Ag(n,e){if(e<=0)return"";if(xs(n)<=e)return n;if(e===1)return"\u2026";let t="",r=0;e:for(let s of qK(n)){if(s.ansi){t+=s.text;continue}for(let o of s.text){let i=xs(o);if(r+i>e-1)break e;t+=o,r+=i}}return t+"\u2026"}function b_(n,e){let t=[],r=0;for(let s of n){let o=e-r;if(o<=0)break;let i=xs(s.text);if(i<=o)t.push(s),r+=i;else{if(s.truncatable===!1)break;t.push({...s,text:Ag(s.text,o)});break}}return t}function Jv(n,e,t,r){let s=xs(r.prefix)+xs(r.suffix),o=xs(r.pad),i=[...e],a=[...t],d=C=>{let $=0;for(let P of C){let M=xs(P.text);$+=P.flex===!0?Math.min(M,P.minWidth??0):M}return $},c=()=>{let C=Rg(i,r),$=Rg(a,r);return s+(C.length>0?d(C)+o*2:0)+($.length>0?d($)+o*2:0)+r.minGap};for(;c()>n;){let C=null,$=-1,P=1/0;if(i.forEach((M,F)=>{M.priority<P&&(P=M.priority,C="l",$=F)}),a.forEach((M,F)=>{M.priority<P&&(P=M.priority,C="r",$=F)}),C===null||P===1/0)break;C==="l"?i=i.filter((M,F)=>F!==$):a=a.filter((M,F)=>F!==$)}let l=Rg(i,r),u=Rg(a,r),f=s+(l.length>0?o*2:0)+(u.length>0?o*2:0)+r.minGap,p=Math.max(0,n-f),m=Ss(u);Ss(l)+m>p&&(l=w_(l,Math.max(0,p-m))),Ss(l)+Ss(u)>p&&(u=w_(u,Math.max(0,p-Ss(l)))),Ss(l)+Ss(u)>p&&(u=b_(u,p),l=b_(l,Math.max(0,p-Ss(u))));let b=[],g=[],h=1,y=(C,$,P)=>{if(C.length===0)return;let M=xs(C),F={...P??{},text:C,token:$,start:h,width:M};if(b.push(F),F.id!==void 0){let K=g.find(Y=>Y.id===F.id);K!==void 0?K.end=h+M-1:g.push({id:F.id,start:h,end:h+M-1,action:F.action??"none",doubleAction:F.doubleAction??"none",value:F.value??F.text})}h+=M};if(y(r.prefix,r.ruleToken),l.length>0){y(r.pad,r.padToken);for(let C of l)y(C.text,C.token,C);y(r.pad,r.padToken)}let k=s+(l.length>0?Ss(l)+o*2:0)+(u.length>0?Ss(u)+o*2:0),S=Math.max(r.minGap,n-k);S>0&&r.fill.length>0&&y(r.fill.repeat(S),r.ruleToken);let I=null;if(u.length>0){I=h,y(r.pad,r.padToken);for(let C of u)y(C.text,C.token,C);y(r.pad,r.padToken)}y(r.suffix,r.ruleToken);let x=b.map(C=>`${C.token}${C.text}`).join("\0");return{chunks:b,signature:x,hits:g,rightStart:I}}var y_,k_,Tg=j(()=>{"use strict";g_();y_=jK(),k_=m_});function Vv(n){return n.banner.status==="ready"&&n.banner.armedSince!==void 0}function zK(n){let e=n.banner.status,t=e==="busy"&&n.banner.stalled===!0,r;n.statusLabel!==void 0?r=n.statusLabel:t?r="Stalled":e==="busy"?r="Thinking":Vv(n)?r="Waiting":r=e.charAt(0).toUpperCase()+e.slice(1);let s;return t||e==="disconnected"?s="status-alert":e==="busy"||Vv(n)?s="status-active":e==="cold"?s="status-cold":s="status-ready",{label:r,token:s}}function ho(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}k`:String(n)}function KK(n){if(!n)return null;let e=[];return typeof n.used=="number"?typeof n.size=="number"&&n.size>0?e.push(`${ho(n.used)}/${ho(n.size)}`):e.push(ho(n.used)):typeof n.size=="number"&&e.push(`/${ho(n.size)}`),typeof n.costAmount=="number"&&e.push(Am(n.costAmount,n.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function GK(n){if(n.banner.hintsExhausted===!0&&!n.hintsRevealed)return null;let e=n.banner.hint;return e.length===0?null:e.map((t,r)=>{let o={text:t.id==="mode"&&(n.banner.currentMode??"")!==""?`${t.label}: ${n.banner.currentMode}`:t.label,token:"modal-hint",action:t.action};return{id:t.id,chunks:[o],priority:20+(e.length-r)}})}function v_(n){if(n.transient===null)return null;let e=n.transient.kind==="search"?"bar-indicator":"modal-note";return{id:"transient",chunks:[{text:n.transient.text,token:e}],priority:1/0}}var Yv,Boe,Eg=j(()=>{"use strict";Ek();Se();mr();Ko();Yv={status:{priority:1/0,resolve:n=>{let{label:e,token:t}=zK(n);return[{text:e,token:t}]}},elapsed:{priority:60,resolve:n=>{if(Vv(n)){let r=Date.now()-n.banner.armedSince;return r<1e3?null:[{text:jr(r),token:"status-active"}]}if(n.banner.status!=="busy"||n.banner.elapsedMs===void 0||n.banner.elapsedMs<1e3)return null;let t=n.banner.stalled===!0?"status-alert":"status-active";return[{text:jr(n.banner.elapsedMs),token:t}]}},sessionId:{priority:40,resolve:n=>{let e=Qe(n.session.sessionId);if(!e)return null;let t={text:e,token:"rule-meta",doubleAction:"copy",value:e};return n.scope==="btw"&&(t.action="open-session"),[t]}},sessionIdFull:{priority:40,resolve:n=>n.session.sessionId?[{text:n.session.sessionId,token:"rule-meta",doubleAction:"copy"}]:null},queued:{priority:50,resolve:n=>n.banner.queued>0?[{text:`${n.banner.queued} queued`,token:"status-queued"}]:null},scroll:{priority:30,resolve:n=>n.scrollOffset>0?[{text:`\u2191 ${n.scrollOffset}`,token:"bar-indicator"}]:null},usage:{priority:45,resolve:n=>{let e=KK(n.session.usage);return e?[{text:e,token:"content",doubleAction:"copy"}]:null}},tokens:{priority:45,resolve:n=>{let e=n.session.usage;return!e||typeof e.used!="number"?null:[{text:typeof e.size=="number"&&e.size>0?`${ho(e.used)}/${ho(e.size)}`:ho(e.used),token:"content",doubleAction:"copy"}]}},cost:{priority:45,resolve:n=>{let e=n.session.usage;return!e||typeof e.costAmount!="number"?null:[{text:Am(e.costAmount,e.costCurrency),token:"content",doubleAction:"copy"}]}},cwd:{priority:70,resolve:()=>null,resolveGroups:n=>{let e=n.session.workspace;if(e===void 0){let r=V(n.session.cwd);return r?[{id:"cwd",priority:70,chunks:[{text:r,token:"bar-text",flex:!0,minWidth:8,doubleAction:"open",value:n.session.cwd}]}]:null}let t=V(e.sourceCwd);return t?[{id:"cwd",priority:70,chunks:[{text:t,token:"bar-text",flex:!0,minWidth:8,doubleAction:"open",value:e.sourceCwd}]},{id:"cwdWorkspace",priority:69,separator:" ",chunks:[{text:`[${e.label}]`,token:"bar-text",doubleAction:"open",value:e.path}]}]:null}},cwdFull:{priority:70,resolve:n=>n.session.cwd?[{text:n.session.cwd,token:"bar-text",flex:!0,minWidth:8,doubleAction:"open"}]:null},title:{priority:75,resolve:n=>{let e=n.session.title?.trim();return e?[{text:e,token:"bar-text",flex:!0,minWidth:8,doubleAction:"rename-session",value:e}]:null}},agent:{priority:80,resolve:n=>n.session.agent?[{text:n.session.agent,token:"content",doubleAction:"choose-agent"}]:null},model:{priority:65,resolve:n=>n.session.model?[{text:n.session.model,token:"content",doubleAction:"choose-model"}]:null},agentModel:{priority:80,resolve:n=>{let e=oE(n.session.agent,n.session.model);return e?[{text:e,token:"content",flex:!0,minWidth:6,doubleAction:"choose-model",value:e}]:null}},mode:{priority:55,resolve:n=>n.banner.currentMode?[{text:n.banner.currentMode,token:"rule-meta",doubleAction:"choose-mode",value:"mode"}]:null},helpHint:{priority:20,resolve:()=>null,resolveGroups:GK}},Boe=Object.keys(Yv)});function S_(n){return typeof n=="string"?n===Qv?null:n:n.field??null}function x_(n,e,t){if(!t.some(a=>a===Qv))return t;let r=new Set;for(let a of t){let d=S_(a);d!==null&&r.add(d)}let s=JK[n][e].filter(a=>{let d=S_(a);return d===null||!r.has(d)}),o=[],i=!1;for(let a of t){if(a===Qv){i||(o.push(...s),i=!0);continue}o.push(a)}return o}function YK(n){if(typeof n!="string")return n;let t=VK.exec(n)?.[1];return t!==void 0?{script:t}:{field:n}}function I_(n){if(n!==void 0)return k_.includes(n)?n:"none"}function QK(n,e){let t=`${n}:${e.id}`;return{...e,chunks:e.chunks.map(r=>({...r,id:t}))}}function XK(n,e){let t=n;if(e.style!==void 0){let r=e.style;t=t.map(s=>({...s,token:r}))}if(e.minWidth!==void 0&&(t=t.map(r=>({...r,flex:!0,minWidth:e.minWidth}))),e.maxWidth!==void 0){let r=e.maxWidth;if(t=t.map(s=>({...s,text:Ag(s.text,r)})).filter(s=>s.text.length>0),t.length===0)return null}return e.truncate===!1&&(t=t.map(r=>({...r,truncatable:!1}))),t}function ZK(n,e){let t=n.map(o=>({...o,chunks:[...o.chunks]})),r=t[0];if(e.prefix!==void 0&&e.prefix.length>0&&r!==void 0){let o=r.chunks[0];o!==void 0&&r.chunks.unshift({text:e.prefix,token:o.token})}let s=t[t.length-1];if(e.suffix!==void 0&&e.suffix.length>0&&s!==void 0){let o=s.chunks[s.chunks.length-1];o!==void 0&&s.chunks.push({text:e.suffix,token:o.token})}return t}function kf(n,e,t){let r=[];for(let s of e){let o=YK(s),i;if(o.text!==void 0){if(o.text.length===0)continue;i=[{id:`text:${o.text}`,priority:10,chunks:[{text:o.text,token:"rule-meta"}]}]}else if(o.script!==void 0){let u=t.scriptOutputs.get(o.script);if(u===void 0||u.length===0)continue;i=[{id:`script:${o.script}`,priority:10,chunks:[{text:u,token:"rule-meta"}]}]}else{let u=o.field??"",f=Yv[u];if(f===void 0)continue;if(f.resolveGroups!==void 0){let p=f.resolveGroups(t);if(p===null)continue;i=p}else{let p=f.resolve(t);if(p===null||p.length===0)continue;i=[{id:u,priority:f.priority,chunks:p}]}}let a=[];for(let u of i){let f=XK(u.chunks,o);f!==null&&a.push({...u,priority:o.priority??u.priority,chunks:f})}if(a.length===0)continue;a=ZK(a,o);let d=I_(o.onClick),c=I_(o.onDoubleClick);(d!==void 0||c!==void 0)&&(a=a.map(u=>({...u,chunks:u.chunks.map(f=>({...f,...d!==void 0?{action:d}:{},...c!==void 0?{doubleAction:c}:{}}))})));let l=a[0];o.separator!==void 0&&l!==void 0&&(l.separator=o.separator);for(let u of a)r.push(QK(n,u))}return r}function vf(n){let e=(t,r)=>({left:x_(t,"left",r.left),right:x_(t,"right",r.right)});return{composer:{top:e("composerTop",n.composer.top),bottom:e("composerBottom",n.composer.bottom)},sessionbar:e("sessionbar",n.sessionbar)}}var Xv,Qv,JK,VK,Zv=j(()=>{"use strict";et();Eg();Tg();Tg();Xv={composerTop:{prefix:"\u2500\u2500",suffix:"\u2500\u2500",fill:"\u2500",pad:" ",separator:" \xB7 ",separatorToken:"rule-meta",ruleToken:"rule",padToken:"rule-pad",minGap:0},composerBottom:{prefix:"",suffix:"\u2500\u2500",fill:"\u2500",pad:" ",separator:" \xB7 ",separatorToken:"rule-meta",ruleToken:"rule",padToken:"rule-pad",minGap:0},btw:{prefix:"\u2500\u2500",suffix:"\u2500\u2500",fill:"\u2500",pad:" ",separator:" \xB7 ",separatorToken:"rule-meta",ruleToken:"rule",padToken:"rule-pad",minGap:0},sessionbar:{prefix:"",suffix:"",fill:" ",pad:"",separator:" \xB7 ",separatorToken:"content",ruleToken:"content",padToken:"content",minGap:1}},Qv="...",JK={composerTop:{left:ca,right:la},btw:{left:ca,right:la},composerBottom:{left:zd,right:Kd},sessionbar:{left:Gd,right:Jd}};VK=/^\$\((.+)\)\s*$/});import{resolve as eG}from"path";function tS(n){return!tG.has(n)}function nG(n){return n.replace(/\s+/gu," ").trim()}function rG(n,e,t){let r=n.trim();for(let s of[e,t]){if(s===void 0||s==="")continue;let o=r.toLowerCase(),i=s.toLowerCase();if(o===i)return"";o.startsWith(`${i} `)&&(r=r.slice(s.length).trimStart())}return r}function sG(n){let e=n.trim();return e===""?!0:!/[\s/.]/u.test(e)}function oG(n){switch(n){case"read":return"read";case"edit":return"edit";case"delete":return"delete";case"move":return"move";case"search":return"search";case"execute":return"run";case"fetch":return"fetch";case"think":return"think";default:return C_}}function iG(n,e){if(!tS(n.status))return null;let t=oG(n.rawKind),r=c=>c===void 0?"":rG(nG(c),t,n.rawKind),s=n.editDiff?.path??jp(n.locations),o=s===void 0||s===""?void 0:e===null?s:eG(e,s),i=r(n.latestTitle),a=t!==C_&&sG(i)?"":i,d=r(n.detail)||aG(o)||a;return{verb:t,detail:d===""?void 0:d,startedAt:n.startedAt,path:o}}function aG(n){return n===void 0?"":n.split(/[\\/]/).filter(t=>t!=="").at(-1)??""}function R_(n,e,t){let r=[];for(let s of n){let o=e.get(s);if(o===void 0||Fc(s,o.latestTitle))continue;let i=iG(o,t);i!==null&&r.push(i)}return r}var eS,tG,C_,nS=j(()=>{"use strict";vi();xh();eS=4,tG=new Set(["completed","succeeded","ok","failed","error","rejected","cancelled","canceled"]);C_="tool"});function Sf(n){let e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s`;let t=Math.floor(e/60),r=e%60;return t<60?`${t}m ${String(r).padStart(2,"0")}s`:`${Math.floor(t/60)}h ${String(t%60).padStart(2,"0")}m`}function A_(n,e){return e<=0?n:Math.floor(Math.max(0,n)/e)*e}function rS(n){if(n<1e3)return String(n);if(n<1e6){let e=n/1e3;return`${e<10?e.toFixed(1):Math.round(e)}K`}return`${(n/1e6).toFixed(1)}M`}function dG(n,e){if(e<=0)return"";let t=Math.max(0,Math.min(1,n)),r=Math.round(t*e*8),s=Math.floor(r/8),o=r%8,i=o===0?"":"\u258F\u258E\u258D\u258C\u258B\u258A\u2589"[o-1];return"\u2588".repeat(Math.min(e,s))+(s<e?i:"")+"\xB7".repeat(Math.max(0,e-s-(i?1:0)))}function Kr(n,e){return{body:n,bodyStyle:e}}function Pg(n,e,t){let{cellWidth:r,truncate:s}=t.metrics,o=t.width-r(n)-r(e);return o<1?{body:s(`${n} ${e}`,t.width),bodyStyle:"muted"}:{prefix:`${n}${" ".repeat(o)}`,prefixStyle:"muted",body:e,bodyStyle:"sidebar-value"}}function $_(n,e,t,r){let s={body:n,bodyStyle:t,openPath:e,item:!0};if(r!==void 0&&r.length>0){let o=n.indexOf(r);o!==-1&&(s.openSpan={start:o,end:o+r.length})}return s}function Is(n,e,t){let{cellWidth:r,truncate:s}=t.metrics,o=t.width-r(n)-r(e);return o<1?s(`${n} ${e}`,t.width):`${n}${" ".repeat(o)}${e}`}function E_(n){return n==="in_progress"?0:n==="completed"?2:1}function hG(n){return[...n].sort((e,t)=>E_(e.status)-E_(t.status))}function O_(n){let e=n.map(r=>r.split("/").pop()??r),t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);return n.map((r,s)=>{let o=e[s];return(t.get(o)??0)<=1?o:r.split("/").slice(-2).join("/")})}function wG(n,e,t){let{cellWidth:r,truncate:s}=t.metrics;if(e<=0)return"";if(r(n)<=e)return n;let o=n.slice(n.lastIndexOf("/")+1);if(o!==n&&r(o)<=e)return o;let i=o.length<n.length?o:n;for(let a=1;a<i.length;a++){let d=`\u2026${i.slice(a)}`;if(r(d)<=e)return d}return s(i,e)}function P_(n){if(n<1024)return`${Math.max(0,Math.round(n))}B`;let e=n/(1024*1024);return e<1?`${Math.round(n/1024)}K`:e<1024?e<10?`${e.toFixed(1)}M`:`${Math.round(e)}M`:`${(e/1024).toFixed(1)}G`}function __(n){if(n===void 0)return"\u2013".padStart(M_);let e=n*100;return(e<100?`${e.toFixed(1)}%`:`${Math.round(e)}%`).padStart(M_)}var Bi,T_,cG,lG,uG,fG,pG,mG,gG,yG,bG,M_,kG,vG,SG,xG,IG,CG,F_,L_=j(()=>{"use strict";nS();Bi=5;T_=5e3,cG={id:"activity",relevant:()=>!0,versionKey:n=>n.busySince!==null?`busy:${Math.floor((n.now-n.busySince)/1e3)}`:n.armedSince!==null?`running:${Math.floor((n.now-n.armedSince)/1e3)}`:n.lastTurnEndedAt!==null?`idle:${A_(n.now-n.lastTurnEndedAt,T_)}`:"fresh",render:(n,e)=>n.busySince!==null?[Kr(Is("\u25CF thinking",Sf(n.now-n.busySince),e),"status-active")]:n.armedSince!==null?[Kr(Is("\u25D0 waiting",Sf(n.now-n.armedSince),e),"status-active")]:n.lastTurnEndedAt!==null?[Kr(Is("\u25CB idle",Sf(A_(n.now-n.lastTurnEndedAt,T_)),e),"status-idle")]:[Kr("\u25CB ready","status-idle")]},lG={id:"tasks",title:"tasks",relevant:n=>n.armedTasks.length>0,versionKey:(n,e)=>{let t=n.armedTasks.slice(0,Bi);return`${e.width}|${n.armedTasks.length}|`+t.map(r=>{let s=Math.floor(Math.max(0,n.now-r.since)/1e3);return`${r.taskId??r.label}:${s}`}).join("\0")},render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=[];for(let o of n.armedTasks.slice(0,Bi)){let i=Sf(Math.max(0,n.now-o.since)),a="\u25D0 ",d=e.width-r(a)-r(i)-1,c=o.label.length>0?o.label:o.taskType??"background task",l=d<4?a.trim():`${a}${t(c,d)}`;s.push(Kr(Is(l,i,e),"status-active"))}return n.armedTasks.length>Bi&&s.push(Kr(` +${n.armedTasks.length-Bi} more`,"muted")),s}},uG={id:"tools",title:"tools",relevant:n=>n.running.length>0,versionKey:(n,e)=>{let t=n.running.slice(0,eS);return`${e.width}|${n.running.length}|`+t.map(r=>{let s=r.startedAt===void 0?"":Math.floor(Math.max(0,n.now-r.startedAt)/1e3);return`${r.verb}:${r.detail??""}:${s}`}).join("\0")},render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=[],o=n.running.slice(0,eS);for(let i of o){let a=i.startedAt===void 0?"":Sf(Math.max(0,n.now-i.startedAt)),d=`\u25B8 ${i.verb}`,c=e.width-r(d)-(a===""?0:r(a)+1)-1,l=i.detail===void 0||c<4?"":` ${t(i.detail,c)}`,u=`${d}${l}`,f=a===""?u:Is(u,a,e),p={body:f,bodyStyle:"tool-status-running",openPath:i.path};if(i.path!==void 0){let m=i.path.slice(i.path.lastIndexOf("/")+1),b=m.length>0?f.indexOf(m):-1;b!==-1&&(p.openSpan={start:b,end:b+m.length})}s.push(p)}return n.running.length>o.length&&s.push(Kr(` +${n.running.length-o.length} more`,"muted")),s}},fG={id:"context",title:"context",relevant:n=>n.usage.used!==void 0||n.usage.costAmount!==void 0,versionKey:(n,e)=>`${n.usage.used??""}/${n.usage.size??""}/${n.usage.costAmount??""}/${e.width}`,render:(n,e)=>{let t=[],{used:r,size:s,costAmount:o,costCurrency:i}=n.usage;if(r!==void 0&&s!==void 0&&s>0){let a=r/s;t.push(Kr(Is(`${rS(r)}/${rS(s)}`,`${Math.round(a*100)}%`,e),a>=.9?"meter-warn":"metric")),t.push(Kr(dG(a,e.width),a>=.9?"meter-warn":"meter-fill"))}else r!==void 0&&t.push(Kr(Is("tokens",rS(r),e),"metric"));if(o!==void 0){let a=i==="USD"||i===void 0?"$":`${i} `;t.push(Kr(Is("cost",`${a}${o.toFixed(2)}`,e),"muted"))}return t}},pG={id:"queue",relevant:n=>n.queued>0,versionKey:(n,e)=>`${n.queued}/${e.width}`,render:(n,e)=>[Kr(Is("queued",String(n.queued),e),"status-queued")]};mG={id:"todo",title:"todo",pageSize:Bi,relevant:n=>n.plan.length>0,titleNote:n=>`${n.plan.filter(e=>e.status==="completed").length}/${n.plan.length}`,versionKey:(n,e)=>`${e.width}|`+n.plan.map(t=>`${t.status}:${t.content}`).join("\0"),render:(n,e)=>{let{truncate:t}=e.metrics,r=[];for(let s of hG(n.plan)){let o=s.status==="completed"?"\u2713":s.status==="in_progress"?"\u25B8":"\xB7",i=s.status==="completed"?"plan-done":s.status==="in_progress"?"plan":"plan-pending";r.push({body:t(`${o} ${s.content}`,e.width),bodyStyle:i,item:!0})}return r}};gG={id:"files",title:"edited",pageSize:Bi,relevant:n=>n.editedFiles.length>0,titleNote:n=>n.editedFiles.length>1?`${n.editedFiles.length} files`:void 0,versionKey:(n,e)=>`${e.width}|`+n.editedFiles.map(t=>`${t.path}:${t.added??""}:${t.removed??""}`).join("\0"),render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=[...n.editedFiles].reverse(),o=[],i=O_(s.map(a=>a.path));return s.forEach((a,d)=>{let c=a.added!==void 0||a.removed!==void 0?`+${a.added??0} -${a.removed??0}`:"",l=e.width-(c?r(c)+1:0),u=t(i[d],Math.max(1,l));o.push($_(c?Is(u,c,e):u,a.path,"file-path",u))}),o}},yG={id:"git",title:"git",pageSize:Bi,relevant:n=>n.git!==null&&(n.git.staged>0||n.git.unstaged>0||n.git.untracked>0||n.git.ahead>0||n.git.behind>0),titleNote:n=>n.git!==null&&n.git.files.length>1?`${n.git.files.length} files`:void 0,versionKey:(n,e)=>{let t=n.git;if(t===null)return"none";let r=t.files.map(s=>`${s.state}:${s.path}`).join("\0");return`${e.width}|${t.branch}|${t.staged}|${t.unstaged}|${t.untracked}|${t.ahead}|${t.behind}|${r}`},render:(n,e)=>{let t=n.git;if(t===null)return[];let{truncate:r,cellWidth:s}=e.metrics,o=[];if(t.branch!==null){let d=(t.ahead>0?`\u2191${t.ahead}`:"")+(t.behind>0?`\u2193${t.behind}`:"");o.push(d?Pg(r(t.branch,e.width-d.length-1),d,e):{body:r(t.branch,e.width)})}let i=t.files,a=O_(i.map(d=>d.path));return i.forEach((d,c)=>{let l=d.state==="staged"?"git-staged":d.state==="dirty"?"git-dirty":"git-untracked",u=e.width-s(d.state)-1,f=r(a[c],Math.max(1,u));o.push($_(Is(f,d.state,e),d.path,l,f))}),o}};bG={id:"info",title:"info",relevant:n=>n.agent!==null||n.model!==null||n.sessionId!==null||n.workspace!==null,versionKey:(n,e)=>`${e.width}|${n.agent}|${n.model}|${n.mode}|${n.configOptions.map(t=>`${t.id}=${t.value}`).join(",")}|${n.sessionId}|${n.host}|${n.workspace?.label??""}`,render:(n,e)=>{let{cellWidth:t}=e.metrics,r=[],s=(c,l,u)=>{let f=e.width-t(c)-1,p=Pg(c,wG(l,f,e),e);r.push(u===void 0?p:{...p,doubleAction:u})},o=c=>n.configOptions.find(l=>l.id===c)?.value??null,i=n.agent??o("agent");i!==null&&s("agent",i,{action:"choose-agent",value:"agent"});let a=n.model??o("model");a!==null&&s("model",a,{action:"choose-model",value:"model"});let d=n.mode??o("mode");d!==null&&s("session mode",d,{action:"choose-mode",value:"mode"});for(let c of n.configOptions)c.id==="agent"||c.id==="model"||c.id==="mode"||s(c.name.toLowerCase(),c.value,{action:"choose-config",value:c.id});if(n.host!==null&&s("host",n.host,{action:"copy",value:n.host}),n.sessionId!==null&&s("id",n.sessionId,{action:"copy",value:n.sessionId}),n.workspace!==null){let c=Pg("workspace",n.workspace.label,e);r.push({...c,openPath:n.workspace.path})}return r}};M_=5;kG="\u25CF",vG="\u25D0",SG="\u25CB",xG="\u25E6",IG={id:"sessions",title:"sessions",pageSize:Bi,relevant:n=>n.liveSessions.length>0,titleNote:(n,e,t)=>{if(!t)return;let r=n.liveSessions.filter(s=>s.blocked).length;return r>0?`${r} blocked`:`${n.liveSessions.length} live`},versionKey:(n,e)=>`${e.width}|`+n.liveSessions.map(t=>`${t.blocked?"w":""}${t.busy?"b":""}${t.armed?"r":""}:${t.sessionId}:${t.label}`).join("\0"),render:(n,e)=>{let{truncate:t,cellWidth:r}=e.metrics,s=i=>(i.blocked?0:3)+(i.busy?0:i.armed?1:2);return[...n.liveSessions].sort((i,a)=>s(i)-s(a)).map(i=>{let a=i.busy||i.armed,d=`${i.blocked?xG:" "}${i.busy?kG:i.armed?vG:SG}`,c=r(d),l=t(i.label,Math.max(1,e.width-c-1)),u=Math.max(1,e.width-r(l)-c);return{prefix:`${l}${" ".repeat(u)}`,prefixStyle:a?"status-active":"sidebar-value",body:d,bodyStyle:a?"status-active":i.blocked?"status-blocked":"status-idle",doubleAction:{action:"open-session",value:i.sessionId},item:!0}})}},CG={id:"resources",title:"resources",relevant:n=>n.resources.length>0,versionKey:(n,e)=>`${e.width}|`+n.resources.map(t=>`${t.label}:${P_(t.rssBytes)}:${__(t.cpuFraction)}:${t.processes}`).join("\0"),render:(n,e)=>{let{cellWidth:t,truncate:r}=e.metrics;return n.resources.map(s=>{let o=`${P_(s.rssBytes)} ${__(s.cpuFraction)}`,i=s.processes>1?`${s.label} \xD7${s.processes}`:s.label,a=e.width-t(o)-1;return Pg(r(i,Math.max(1,a)),o,e)})}},F_=[cG,lG,fG,pG,mG,gG,yG,IG,CG,bG,uG]});function AG(n){let e="",t=[],r=0;for(;r<n.length;){let s=n[r];if(s==="["){let o=n.indexOf("]",r+1);if(o!==-1&&n[o+1]==="("&&o>r+1){let i=-1,a=1,d=o+2;for(;d<n.length;){let c=n[d];if(c==="\\"&&d+1<n.length){d+=2;continue}if(c==="(")a+=1;else if(c===")"&&(a-=1,a===0)){i=d;break}d+=1}if(i!==-1&&i>o+2){let c=n.slice(r+1,o),l=n.slice(o+2,i),u=e.length;e+=c,t.push({start:u,end:e.length,url:l}),r=i+1;continue}}}e+=s,r+=1}return{body:e,links:t}}function N_(n){let e=Gt(n).trim();return e.length===0?null:e}function TG(n){return typeof n!="string"}function Mg(n){return typeof n=="string"?n:n.id}function _g(n){return n.filter(TG)}function sS(n,e){let t=new Map;for(let r of _g(n)){let s=r.refreshMs??e,o=t.get(r.script);t.set(r.script,o===void 0?s:Math.min(o,s))}return t}function D_(n){return{id:n.id,title:n.title??n.id,relevant:e=>e.processOutputs.has(n.script),versionKey:(e,t)=>`${t.width}:${e.processOutputs.get(n.script)??""}`,render:(e,t)=>{let r=e.processOutputs.get(n.script);if(r===void 0)return[];let{truncate:s}=t.metrics,o=r.split(`
259
259
  `).filter(d=>d.length>0),i=n.cap??RG,a=o.slice(0,i).map(d=>{let{body:c,links:l}=AG(d),u=s(c,t.width),f=l.filter(p=>p.start<u.length).map(p=>({...p,end:Math.min(p.end,u.length)}));return f.length>0?{body:u,links:f}:{body:u}});return o.length>i&&a.push({body:` +${o.length-i} more`,bodyStyle:"muted"}),a}}}var RG,$g=j(()=>{"use strict";Ho();RG=6});function oS(n){return n==="frame"}function H_(n=0){return{now:n,busySince:null,lastTurnEndedAt:null,armedSince:null,armedTasks:[],queued:0,usage:{},plan:[],editedFiles:[],running:[],git:null,liveSessions:[],resources:[],sessionId:null,host:null,agent:null,model:null,mode:null,configOptions:[],workspace:null,processOutputs:new Map}}var iS=j(()=>{"use strict"});function PG(n){let e=EG[n]??n;return F_.find(t=>t.id===e)}function lS(n){if(!n.some(o=>o===aS))return n;let e=new Set;for(let o of n)o!==aS&&e.add(Mg(o));let t=cS.filter(o=>!e.has(o)),r=[],s=!1;for(let o of n){if(o===aS){s||(r.push(...t),s=!0);continue}r.push(o)}return r}function dS(n,e){return{body:"\u2500".repeat(Math.max(0,n)),bodyStyle:"sidebar-rule",gutter:e}}function FG(n,e,t,r){if(r<=0||!Number.isFinite(r))return e;let s=Og(e);if(s<=r)return e;let o=Math.ceil(s/r),i=t.pages?.[n.id]??0,a=Math.max(0,Math.min(o-1,i)),d=a*r,c=d+r,l=[],u=0;for(let C of e){if(C.item!==!0){l.push(C);continue}let $=u++;$>=d&&$<c&&l.push(C)}if(n.title===void 0||l.length===0)return l;let{cellWidth:f,truncate:p}=t.metrics,m=`${$G} ${a+1}/${o} ${OG}`,b=f(m),g=t.width-b-1;if(g<1)return l;let h=p(n.title,g),y=t.width-f(h)-b,k=`${h}${" ".repeat(Math.max(1,y))}${m}`,S=f(k)-b+1,I=f(k),x=[];for(let C of l[0].actions??[])"collapse"in C&&S>2&&x.push({...C,start:1,end:S-2});return a>0&&x.push({start:S,end:S,page:{gadget:n.id,index:a-1}}),a<o-1&&x.push({start:I,end:I,page:{gadget:n.id,index:a+1}}),l[0]={...l[0],body:k,actions:x},l}function Og(n){return n.reduce((e,t)=>e+(t.item===!0?1:0),0)}function U_(n,e,t,r){let s=n.title??"",o=n.titleNote?.(e,t,r),i=r?o===void 0||o.length===0?B_:`${o} ${B_}`:o,a={start:1,end:t.width,collapse:{gadget:n.id}};if(i===void 0||i.length===0)return{body:s,bodyStyle:"sidebar-title",actions:[a]};let{cellWidth:d,truncate:c}=t.metrics,l=d(i),u=t.width-l-1;if(u<1)return{body:c(s,t.width),bodyStyle:"sidebar-title",actions:[a]};let f=c(s,u),p=t.width-d(f)-l;return{body:`${f}${" ".repeat(Math.max(1,p))}${i}`,bodyStyle:"sidebar-title",actions:[a]}}function LG(n,e,t,r){let s=n.map((c,l)=>e[l]?Og(c):0),o=n.reduce((c,l,u)=>c+(e[u]?0:Og(l)),0),i=c=>t+o+s.reduce((l,u)=>l+Math.min(u,c),0),a=Math.max(0,...s);if(i(a)<=r)return Number.POSITIVE_INFINITY;let d=1;for(let c=1;c<=a&&i(c)<=r;c++)d=c;return d}var cS,EG,aS,MG,_G,B_,$G,OG,Fg,uS=j(()=>{"use strict";L_();$g();iS();cS=["activity","sessions","tasks","context","queue","todo","files","git","resources","info","tools"],EG={session:"info"};aS="...";MG=Object.freeze({body:""}),_G=Object.freeze({body:"",gutter:"\u2502"});B_="+",$G="\u2039",OG="\u203A";Fg=class{cache=new Map;extraGadgets=new Map;rules=null;gadgets=[];configuredGadgetIds=cS;constructor(e=cS){this.setGadgets(e)}setGadgets(e){this.configuredGadgetIds=e;let t=e.map(s=>this.extraGadgets.get(s)??PG(s)).filter(s=>s!==void 0);(t.length!==this.gadgets.length||t.some((s,o)=>s!==this.gadgets[o]))&&(this.gadgets=t,this.cache.clear())}setProcessGadgets(e){this.extraGadgets=new Map(e.map(t=>[t.id,t])),this.setGadgets(this.configuredGadgetIds)}configuredIds(){return this.gadgets.map(e=>e.id)}isConfigured(e){return this.gadgets.some(t=>t.id===e)}invalidate(){this.cache.clear()}render(e,t){if(t.width<=0)return[];let r=[],s=[];for(let f of this.gadgets){if(!f.relevant(e))continue;let p=f.title!==void 0&&t.collapsed?.has(f.id)===!0,m=`${t.border}|${p?"c":"e"}|${f.versionKey(e,t)}`,b=this.cache.get(f.id),g;if(b!==void 0&&b.key===m)g=b.lines;else if(p){let h=U_(f,e,t,!0);g=[t.border==="none"?h:{...h,gutter:"\u2502"}],this.cache.set(f.id,{key:m,lines:g})}else{let h=f.render(e,t),y=f.title===void 0?h:[U_(f,e,t,!1),...h];g=h.length===0?[]:t.border==="none"?y:y.map(k=>({...k,gutter:"\u2502"})),this.cache.set(f.id,{key:m,lines:g})}g.length!==0&&(r.push(g),s.push(p?null:f))}if(r.length===0)return[];let o=oS(t.border)?r.length+1:Math.max(0,r.length-1),i=s.map(f=>f!==null&&f.pageSize!==void 0&&f.pageSize>0),a=o+r.reduce((f,p)=>f+p.length-Og(p),0),d;t.maxRows===void 0?d=Number.NaN:d=LG(r,i,a,t.maxRows);let c=r.map((f,p)=>{let m=s[p],b=m?.pageSize;if(m==null||b===void 0)return f;let g=Number.isNaN(d)?b:d;return FG(m,f,t,g)});r.length=0,r.push(...c);let l=[];if(oS(t.border)){this.rules?.width!==t.width&&(this.rules={width:t.width,lines:{"\u250C":dS(t.width,"\u250C"),"\u251C":dS(t.width,"\u251C"),"\u2514":dS(t.width,"\u2514")}});let f=this.rules.lines;return l.push(f["\u250C"]),r.forEach((p,m)=>{m>0&&l.push(f["\u251C"]),l.push(...p)}),l.push(f["\u2514"]),l}let u=t.border==="rule"?_G:MG;return r.forEach((f,p)=>{p>0&&l.push(u),l.push(...f)}),l}}});import*as j_ from"path";function DG(n){n==="unknown"||sd!==null||(Lg=n,sd=setTimeout(()=>{sd=null,Lg=null,xf()},NG),sd.unref?.())}function q_(){sd!==null&&(clearTimeout(sd),sd=null),Lg=null}function z_(){if(nt.permission)return"blocked";switch(nt.status){case"busy":case"cancelling":return"working";case"ready":return"idle";case"disconnected":case"cold":return Lg??"unknown";default:return"unknown"}}function HG(n){return typeof n!="number"||!Number.isFinite(n)||n<=0?null:`$${n.toFixed(2)}`}function BG(){let n=nt.cwd?.trim();return n?j_.basename(n)||n:null}function K_(){return nt.title?.trim()||BG()}function UG(){return{state:z_(),sessionId:nt.sessionId??null,title:K_(),cwd:nt.cwd?.trim()||null,agent:nt.agent??null,model:nt.model??null,cost:HG(nt.costAmount),queued:nt.queued??null,turnOrigin:nt.turnOrigin,turnLabel:nt.turnLabel}}function xf(){let n=dn();if(!n||!nt.sessionId||(nt.suspended?lf(ug,{transient:!0}):lf(K_()),nt.suspended)||!n.caps.report)return;let e=UG(),t=JSON.stringify(e);Ui!==t&&(Ui=t,Promise.resolve(n.report(e)).catch(()=>{Ui=null}))}function G_(n){dn()&&(n.sessionId!==nt.sessionId&&(nt.turnOrigin=null,nt.turnLabel=null),nt.sessionId=n.sessionId,nt.agent=n.agent,nt.title=n.title,nt.model=n.model,nt.costAmount=n.costAmount,nt.cwd=n.cwd,xf())}function J_(n){if(!dn())return;let e=W_.has(nt.status??""),t=W_.has(n.status??"");t&&!e?DG(z_()):t||q_(),nt.status=n.status,nt.queued=n.queued,xf()}function V_(n){dn()&&(nt.turnOrigin=n.origin,nt.turnLabel=n.label??null)}function fS(n){if(!(!dn()||nt.suspended===n)){if(nt.suspended=n,n){WG();return}Ui=null,xf()}}function WG(){let n=dn();n&&(lf(ug,{transient:!0}),Ui!==null&&(Ui=null,n.caps.report&&Promise.resolve(n.release()).catch(()=>{})))}function Y_(n){dn()&&(nt.permission=n,xf())}async function Q_(){let n=dn();if(n&&(await MM(),q_(),Ui!==null)){Ui=null,nt.sessionId=void 0,nt.turnOrigin=null,nt.turnLabel=null;try{await n.release()}catch{}}}var nt,Ui,NG,W_,Lg,sd,pS=j(()=>{"use strict";td();Av();nt={permission:!1,turnOrigin:null,turnLabel:null,suspended:!1},Ui=null,NG=1e4,W_=new Set(["disconnected","cold"]),Lg=null,sd=null});import{spawnSync as jG}from"child_process";import*as Yo from"fs";import*as yl from"path";function Z_(n,e){let t=Buffer.from(e,"utf8").toString("base64");process.stdout.write(`${X_}1337;SetUserVar=${n}=${t}${qG}`)}function KG(){if(!process.stdin.isTTY)return null;let n=t=>{try{let r=Yo.readlinkSync(t);return r.startsWith("/dev/")&&r!=="/dev/tty"?yl.basename(r):null}catch{return null}},e=n("/proc/self/fd/0")??n("/dev/fd/0");if(e)return e;try{let t=jG("tty",[],{encoding:"utf8",timeout:500});if(t.status!==0)return null;let r=t.stdout.trim();return!r.startsWith("/dev/")||r==="/dev/tty"?null:yl.basename(r)}catch{return null}}function e$(){return hS===void 0&&(hS=KG()),hS}function GG(n){let e=e$();if(e)try{Yo.mkdirSync(D.ttySessionDir(),{recursive:!0});let t=`${process.pid}:${process.ppid}:${n}
260
260
  `;Yo.writeFileSync(D.ttySessionFile(e),t,{mode:384})}catch{}}function JG(n){let e=n.trim();if(e.length===0)return null;if(!e.includes(":"))return{hydraPid:0,parentPid:0,sessionId:e};let t=e.split(":");if(t.length<3)return null;let r=Number.parseInt(t[0],10),s=Number.parseInt(t[1],10),o=t.slice(2).join(":");return!Number.isFinite(r)||!Number.isFinite(s)||o.length===0?null:{hydraPid:r,parentPid:s,sessionId:o}}function VG(){let n=e$();if(!n)return null;try{let e=Yo.readFileSync(D.ttySessionFile(n),"utf8");return JG(e)}catch{return null}}function YG(){let n=VG();return!n||n.parentPid>0&&n.parentPid!==process.ppid?null:n.sessionId}function mS(n){!yl.isAbsolute(n)||!process.stdout.isTTY||process.stdout.write(`${X_}7;${LE(n)}${zG}`)}function t$(){let n;try{n=process.cwd()}catch{return}mS(n)}function gS(n){Z_("hydra_session",n),GG(n)}function n$(){Z_("hydra_session","")}function r$(){return YG()}var X_,qG,zG,hS,yS=j(()=>{"use strict";Se();Ko();X_="\x1B]",qG="\x07",zG="\x1B\\"});import QG from"string-width";function s$(n,e){if(!n||e<=0)return 0;let t=0;for(let r of XG.segment(n)){let s=QG(r.segment);if(e<t+s)return r.index;if(t+=s,e===t)return r.index+r.segment.length}return n.length}function o$(n,e){if(e<=0)return 0;let t=0,r=0;for(let s of n)if(s.width>0&&e<t+s.width||(t+=s.width,r+=s.text.length,s.width>0&&e===t))return r;return r}var XG,i$=j(()=>{"use strict";XG=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function e4(n){return(n.split(/[/\\]/).pop()??n).replace(/\.exe$/i,"").toLowerCase()}function a$(n,e,t){let[r,...s]=n;if(!r)return null;let o=t===null?"":String(t),i=!1,a=!1,d=[];for(let l of s)l.includes("%f")&&(i=!0),!(l.includes("%n")&&(a=!0,o===""))&&d.push(l.replaceAll("%f",e).replaceAll("%n",o));if(i)return{program:r,args:d};let c=o===""||a?void 0:ZG[e4(r)];return c==="plus"?d.push(`+${o}`,e):c==="colon"?d.push(`${e}:${o}`):d.push(e),{program:r,args:d}}var ZG,d$=j(()=>{"use strict";ZG={vi:"plus",vim:"plus","vim.basic":"plus","vim.tiny":"plus",vimdiff:"plus",view:"plus",ex:"plus",nvim:"plus",nvimdiff:"plus",gvim:"plus",mvim:"plus",nano:"plus",pico:"plus",micro:"plus",kak:"plus",joe:"plus",emacs:"plus",emacsclient:"plus",hx:"colon",helix:"colon"}});function t4(){If===0&&be(EP),If++}function n4(){If!==0&&(If--,If===0&&be(PP))}function mt(n){t4();try{n()}finally{n4()}}var If,wS=j(()=>{"use strict";Va();If=0});function r4(n=bS){let e=`
261
261
  \r`+c$;for(let t of n)e+=t+c$;return e+"\r\x1B[K"}function s4(n){let e=[],t=/\u001b\[(\d+);(\d+)R/g,r;for(;(r=t.exec(n))!==null;)e.push([Number(r[1]),Number(r[2])]);return e}function l$(n){return/\u001b\[\d+;\d+R/.test(n)}function u$(n){return n.replace(/\u001b\[\d+;\d+R/g,"")}function o4(n,e=bS){if(n.length<e.length+1)return;let t={};for(let r=0;r<e.length;r++){let[s,o]=n[r],[i,a]=n[r+1];if(i!==s)return;let d=a-o;if(d!==1&&d!==2)return;t[e[r]]=d}return t}function i4(n){let e=Object.values(n);return e.length===0?!1:e.filter(r=>r===2).length>e.length/2}async function f$(n={input:process.stdin,output:process.stdout},e=200,t=bS){let{input:r,output:s}=n;if(!(r.isTTY!==!0||s.isTTY!==!0)&&!((s.columns??80)<t.length+2))return await new Promise(o=>{let i="",a=!1,d=r.isPaused?.()??!1,c,l=f=>{if(!a){a=!0,c!==void 0&&clearTimeout(c);try{(r.off??r.removeListener)?.call(r,"data",u),r.setRawMode?.(!1),d&&r.pause?.()}catch{}o(f)}},u=f=>{i+=typeof f=="string"?f:f.toString("latin1");let p=s4(i);if(p.length<t.length+1)return;let m=o4(p,t);l(m===void 0?void 0:{wide:i4(m),widths:m})};try{r.setRawMode?.(!0),r.resume?.(),r.on("data",u),s.write(r4(t))}catch{l(void 0);return}c=setTimeout(()=>l(void 0),e),c.unref?.()})}var c$,bS,kS=j(()=>{"use strict";c$="\x1B[6n",bS=["\u2500","\u2502","\xB7","\u258F","\u2026","\u2713","\u25B8"]});function c4(){let n="\x1B]10;?\x07\x1B]11;?\x07";for(let e=0;e<16;e++)n+=`\x1B]4;${e};?\x07`;return n}function p$(n){let e=/\u001b\]11;([^\u0007\u001b]*)(?:\u0007|\u001b\\)/.exec(n);return e===null?void 0:vS(e[1])}function l4(n){let e=/\u001b\]10;([^\u0007\u001b]*)(?:\u0007|\u001b\\)/.exec(n);return e===null?void 0:vS(e[1])}function u4(n){let e=new Map;for(let t of n.matchAll(/\u001b\]4;(\d+);([^\u0007\u001b]*)(?:\u0007|\u001b\\)/g)){let r=Number(t[1]);if(!Number.isInteger(r)||r<0||r>15)continue;let s=vS(t[2]);s!==void 0&&e.set(r,s)}return e}function vS(n){let e=n.trim();if(/^#[0-9a-f]+$/i.test(e))return gi(e)??void 0;let t=/^rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i.exec(e);if(t===null)return;let r=a=>{if(!(a.length===0||a.length>4))return Math.round(parseInt(a,16)/(16**a.length-1)*255)},s=r(t[1]),o=r(t[2]),i=r(t[3]);if(!(s===void 0||o===void 0||i===void 0))return Un(s,o,i)}function f4(n){return n.replace(/\u001b\](?:10|11|4);[^\u0007\u001b]*(?:\u0007|\u001b\\)/g,"")}function p4(n){return/\u001b\](?:10|11|4);/.test(n)}async function h$(n={input:process.stdin,output:process.stdout},e=a4){let{input:t,output:r}=n;return t.isTTY!==!0||r.isTTY!==!0?{palette:new Map}:await new Promise(s=>{let o="",i=!1,a=t.isPaused?.()??!1,d,c,l=()=>({foreground:l4(o),background:p$(o),palette:u4(o)}),u=p=>{o+=typeof p=="string"?p:p.toString("latin1");let m=l();if(m.foreground!==void 0&&m.background!==void 0&&m.palette.size===16){f();return}c!==void 0&&clearTimeout(c),c=setTimeout(f,d4),c.unref?.()},f=()=>{if(i)return;i=!0;for(let m of[d,c])m!==void 0&&clearTimeout(m);let p=l();try{(t.off??t.removeListener)?.call(t,"data",u),t.setRawMode?.(!1),a&&t.pause?.()}catch{}s(p)};try{t.setRawMode?.(!0),t.resume?.(),t.on("data",u),r.write(c4())}catch{f();return}d=setTimeout(f,e),d.unref?.()})}function h4(n){let e=/\u001b\[\?997;([12])n/.exec(n);if(e!==null)return e[1]==="1"?"dark":"light"}function m4(n){return n.replace(/\u001b\[\?997;\d+n/g,"")}function y$(n){return n==="dark"?Un(0,0,0):Un(255,255,255)}function w$(n,e={}){if(n===null||typeof n!="object")return;let t=n,r=t.onStdin;typeof r=="function"&&(t.onStdin=function(o){let i=o.toString("latin1");if(!p4(i)&&!/\u001b\[\?997;/.test(i)&&!l$(i)){r.call(this,o);return}let a=p$(i),d=h4(i),c=u$(m4(f4(i)));c.length>0&&r.call(this,Buffer.from(c,"latin1")),a!==void 0&&e.onBackground?.(a),d!==void 0&&e.onScheme?.(d)})}var a4,d4,m$,g$,SS=j(()=>{"use strict";ic();kS();a4=200,d4=50;m$="\x1B[?2031h",g$="\x1B[?2031l"});import{spawn as g4}from"child_process";import{statSync as Cf}from"fs";import{homedir as Ng}from"os";import{isAbsolute as Dg,join as b$,resolve as k$,sep as Hg}from"path";import E$ from"string-width";import y4 from"wrap-ansi";function H4(n){let e=n.replace(/\r\n?$|\n$/,"");return D4.test(e)?e:null}function B4(n,e){return!n||typeof n!="object"?!1:n[e]===!0}function U4(n){return n.includes("LEFT")?"left":n.includes("RIGHT")?"right":n.includes("MIDDLE")?"middle":n==="MOUSE_DRAG"||n==="MOUSE_BUTTON_RELEASED"?"left":"other"}function W4(n,e){if(n.body!==e.body||(n.prefix??"")!==(e.prefix??"")||(n.bodyStyle??"")!==(e.bodyStyle??"")||(n.prefixStyle??"")!==(e.prefixStyle??"")||!!n.ansi!=!!e.ansi||!!n.fillRow!=!!e.fillRow||!!n.collapsed!=!!e.collapsed||(n.blockKey??"")!==(e.blockKey??"")||(n.hoverSubKey??"")!==(e.hoverSubKey??"")||(n.maxWrapRows??0)!==(e.maxWrapRows??0)||(n.hangingIndent??0)!==(e.hangingIndent??0))return!1;let t=n.links,r=e.links;if(t===void 0!=(r===void 0))return!1;if(t&&r){if(t.length!==r.length)return!1;for(let s=0;s<t.length;s++){let o=t[s],i=r[s];if(o.start!==i.start||o.end!==i.end||o.url!==i.url)return!1}}return!0}function PS(n,e,t,r=null,s=null,o=null){let i=s===null?"":`a${s}`,a=o===null?"":`s${o.start}:${o.end}${o.toEndOfLine?"f":""}`;return t?`${n}|${e}|${t.prefix??""}|${t.prefixStyle??""}|${t.body}|${t.bodyStyle??""}|${t.ansi?"1":"0"}|${t.fillRow?"1":"0"}|${r??""}|${i}|${a}`:`${n}|${e}|empty|${r??""}|${i}|${a}`}function Cs(n,e){let t=[];for(let r=0;r<n.length;r++){let s=n[r]??"";if(s.length===0){t.push({bufferIdx:r,startCol:0,endCol:0});continue}let o=0;for(;o<s.length;){if(s.length-o<=e){t.push({bufferIdx:r,startCol:o,endCol:s.length}),o=s.length;break}let i=-1;for(let a=o+e-1;a>=o;a--){let d=s[a];if(d===" "||d===" "){i=a+1;break}}i===-1&&(i=o+e),t.push({bufferIdx:r,startCol:o,endCol:i}),o=i}}return t.length===0&&t.push({bufferIdx:0,startCol:0,endCol:0}),t}function go(n,e,t){let r=0,s=0,o=-1;for(let d=0;d<n.length;d++){let c=n[d];if(!(!c||c.bufferIdx!==e.row)&&(o=d,e.col>=c.startCol&&e.col<c.endCol)){r=d,s=e.col-c.startCol,o=-1;break}}if(o!==-1){let d=n[o];d&&(r=o,s=e.col-d.startCol)}let i=Math.min(t,Math.max(1,n.length)),a=0;return n.length>i&&(a=Math.max(0,Math.min(n.length-i,r-(i-1))),r<a&&(a=r),r>=a+i&&(a=r-i+1)),{cursorVisualRow:r,cursorVisualCol:s,windowStart:a,rendered:i}}function P$(n,e){if(e.length===0)return[];if(!n.includes("\x1B")){let c=[],l=n.toLowerCase(),u=0;for(;u<l.length;){let f=l.indexOf(e,u);if(f===-1)break;c.push({start:f,end:f+e.length}),u=f+e.length}return c}let t="",r=[],s=[],o=0;for(;o<n.length;){let c=Gr(n,o);if(c!==null&&c.width===0){o+=c.text.length;continue}t+=n[o],r.push(o),s.push(o+1),o+=1}let i=[],a=t.toLowerCase(),d=0;for(;d<a.length;){let c=a.indexOf(e,d);if(c===-1)break;let l=c+e.length-1;i.push({start:r[c],end:s[l]}),d=c+e.length}return i}function j4(n,e,t,r,s=null,o=0,i=!1){if(e.length===0)return;if(r.length===0){mo(n,e,t,i);return}let a=0;for(let d of P$(e,r)){if(d.start<a)continue;d.start>a&&mo(n,e.slice(a,d.start),t,i);let c=s!==null&&d.start===s;mo(n,Wg(e.slice(d.start,d.end)),c?"search-highlight-active":"search-highlight",i),a=d.end}a<e.length&&mo(n,e.slice(a),t,i)}function Af(n){return YI(n)}function mo(n,e,t,r=!1){if(e.length===0)return;let s=ac(n),o=(r?QI(t,s):void 0)??lc(t,s),i=o.transform?o.transform(e):e;s==="none"&&(i=i.replace(b4,""));let a=d=>{d.length>0&&n.noFormat(d)};a(o.open),n.noFormat(i),o.inlineSgr&&w4.test(i)&&a(fs),a(o.close)}function q4(n,e){return e<=0?[n]:n.length===0?[""]:y4(n,e,{hard:!0,trim:!1}).split(`
262
262
  `)}function $$(n){_$=n}function O$(n,e,t){if(n==="wide")return!0;if(n==="narrow")return!1;if(t!==void 0)return t;let r=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!/^(ja|ko|zh)(_|\.|@|$)/i.test(r)}function $t(n){return E$(n,{ambiguousIsNarrow:!_$})}function z4(n,e){if(!n.startsWith("\x1B]8;",e))return null;for(let t=e+4;t<n.length;t++){if(n[t]==="\x07")return n.slice(e,t+1);if(n[t]==="\x1B"&&n[t+1]==="\\")return n.slice(e,t+2)}return null}function K4(n,e){if(!n.startsWith("\x1B[",e))return null;let t=e+2;for(;t<n.length;){let s=n.charCodeAt(t);if(s<48||s>63)break;t+=1}for(;t<n.length;){let s=n.charCodeAt(t);if(s<32||s>47)break;t+=1}if(t>=n.length)return null;let r=n.charCodeAt(t);return r<64||r>126?null:n.slice(e,t+1)}function Gr(n,e){if(n.charCodeAt(e)===27){let t=z4(n,e);if(t!==null)return{text:t,width:0};let r=K4(n,e);return r!==null?{text:r,width:0}:null}return null}function Ug(n){let e=new Array(n.length+1).fill(0),t="",r=0;for(;r<n.length;){e[r]=t.length;let s=Gr(n,r);if(s){s.width>0&&(t+="^");for(let o=1;o<s.text.length;o++)e[r+o]=t.length;r+=s.text.length;continue}t+=n[r],r+=1}return e[n.length]=t.length,{clean:t,rawToClean:e}}function G4(n){let{clean:e,rawToClean:t}=Ug(n),r=new Array(e.length+1).fill(n.length);for(let s=n.length;s>=0;s--){let o=t[s];o!==void 0&&(r[o]=s)}return r}function MS(n,e,t){let r=0,s=e;for(;s<t;){let o=Gr(n,s);if(o){s+=o.text.length,o.width>0&&(r+=1);continue}r+=1,s+=1}return r}function _S(n,e,t){let r=e;for(;t>0&&r<n.length;){let s=Gr(n,r);if(s){r+=s.text.length,s.width>0&&(t-=1);continue}r+=1,t-=1}return r}function Wg(n){if(!n.includes("\x1B"))return n;let e="",t=0;for(;t<n.length;){let r=Gr(n,t);if(r){r.width>0&&(e+="^"),t+=r.text.length;continue}e+=n[t],t+=1}return e}function J4(n){if(!n.includes("\x1B"))return"";let e="",t=0;for(;t<n.length;){let r=Gr(n,t);if(r){if(r.width===0){let s=r.text.charCodeAt(0);(s===94||s===27&&r.text.charCodeAt(1)===91)&&(e+=r.text)}t+=r.text.length;continue}t+=1}return e}function F$(n){if(!n.includes("\x1B"))return!1;for(let e=0;e<n.length;e++)if(Gr(n,e))return!0;return!1}function C$(n,e){return n.indexOf("\x1B",e)}function*LS(n){let e=0;for(;e<n.length;){let t=Gr(n,e);if(t){yield{text:t.text,width:t.width},e+=t.text.length;continue}let r=n.length,s=C$(n,e);for(;s!==-1&&s<n.length;){if(Gr(n,s)){r=s;break}s=C$(n,s+1)}if(r===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:o}of FS.segment(n.slice(e,r)))yield{text:o,width:$t(o)};e=r}}function V4(n,e,t={}){if(e<=0)return[n];if(n.length===0)return[""];let r=t.escapeAware===!0&&F$(n);return!r&&!M$.test(n)?Y4(n,e):Q4(n,e,r)}function Y4(n,e){let t=[],r=n;for(;r.length>e;){let s=r.slice(0,e+1),o=-1;for(let i=Math.min(e,s.length-1);i>=0;i--)if(s[i]===" "){o=i;break}o<=0?(t.push(r.slice(0,e)),r=r.slice(e)):(t.push(r.slice(0,o)),r=r.slice(o+1))}return t.push(r),t}function Q4(n,e,t){let r=[],s=t?[...LS(n)]:X4(n),o=0;for(;o<s.length;){let i="",a=0,d=-1,c="";for(;o<s.length;){let l=s[o];if(a+l.width>e){l.text===" "&&l.width===1&&(d=o,c=i);break}l.text===" "&&l.width===1&&(d=o,c=i),i+=l.text,a+=l.width,o+=1}if(o>=s.length){r.push(i);break}d>=0?(r.push(c),o=d+1):i.length===0?(r.push(s[o].text),o+=1):r.push(i)}return r}function X4(n){let e=[];for(let{segment:t}of FS.segment(n))e.push({text:t,width:$t(t)});return e}function mn(n,e,t={}){if(e<=0)return"";let r=t.escapeAware===!0&&F$(n);if(!r&&n.length<=e&&!M$.test(n))return n;if(!r)return $t(n)<=e?n:e<=1?OS(n,e):OS(n,e-1)+"\u2026";let s=[...LS(n)],o=0;for(let i of s)o+=i.width;return o<=e?n:e<=1?R$(s,e):R$(s,e-1)+"\u2026"}function OS(n,e){if(e<=0)return"";let t="",r=0;for(let{segment:s}of FS.segment(n)){let o=$t(s);if(r+o>e)break;t+=s,r+=o}return t}function R$(n,e){if(e<=0)return"";let t="",r=0;for(let s of n){if(r+s.width>e)break;t+=s.text,r+=s.width}return t}function Z4(n,e,t){if(n<=t||t<=0)return 0;let r=Math.floor((t-1)/2);return Math.max(0,Math.min(e-r,n-t))}function eJ(n,e,t,r){if(e<=r||r<=0)return 0;let s=e-r,o=Math.max(0,Math.min(n,s));return t<o?o=t:t>o+r-1&&(o=t-r+1),Math.max(0,Math.min(o,s))}function $S(n,e){let t=Math.max(0,e-1),r=[],s=" \xB7 ",o="";for(let i of n){let a=o.length===0?i.label:`${s}${i.label}`;if(1+$t(o)+$t(a)>t)break;let d=1+$t(o)+$t(a)-$t(i.label)+1;o+=a,i.action!==void 0&&r.push({start:d,end:d+$t(i.label)-1,action:i.action})}return{text:o,spans:r}}function A$(n,e,t,r){let s=Math.max(0,e-1),o=n.rows.length>1,i=o?Math.max(...n.rows.map((c,l)=>`${l+1}. `.length)):0,a=Math.max(0,...n.rows.map(c=>$t(c.kind==="text"?`${c.label} `:c.label))),d=[];for(let c=t;c<Math.min(n.rows.length,t+r);c++){let l=n.rows[c];if(!l)continue;let u=c===n.selectedIndex,f=u?"\u276F":" ",p=o?`${c+1}. `.padStart(i):"";if(l.kind==="text"){let k=mn(` ${f} ${p}${l.label} `,s),{field:S,caretOffset:I,fieldStart:x}=rJ(l.text,l.cursor,s-$t(k));d.push({kind:"text",index:c,selected:u,body:"",prefix:k,field:S,fieldStart:x,caretCol:1+$t(k)+I,sig:`form|r|${e}|${c}|${u?1:0}|text|${k}|${S}`});continue}let m=` ${f} ${p}`,b=l.kind==="choice"?l.current===!0?"\u2022 ":" ":"",g=l.kind==="select"?l.value:l.note??"",h=g.length>0?`${b}${nJ(l.label,a)} ${g}`:`${b}${l.label}`,y=`${m}${mn(h,s-$t(m))}`;d.push({kind:l.kind,index:c,selected:u,body:y,prefix:"",field:"",fieldStart:0,caretCol:1,sig:`form|r|${e}|${c}|${u?1:0}|${l.kind}|${y}`})}return d}function nJ(n,e){let t=e-$t(n);return t>0?n+" ".repeat(t):n}function rJ(n,e,t){if(t<=0)return{field:"",caretOffset:0,fieldStart:0};let r=Math.max(0,Math.min(e,n.length));if($t(n)+1<=t)return{field:n,caretOffset:$t(n.slice(0,r)),fieldStart:0};let s=r,o=1;for(;s>0;){let i=$t(n[s-1]??"");if(o+i>t)break;o+=i,s-=1}return{field:OS(n.slice(s),t),caretOffset:$t(n.slice(s,r)),fieldStart:s}}function sJ(n){let e=n.indexOf(`
263
- `);return e===-1?n:`${n.slice(0,e)} \u21B5`}function qg(n){switch(n){case"ENTER":case"KP_ENTER":return"enter";case"ALT_ENTER":case"META_ENTER":return"alt-enter";case"SHIFT_ENTER":return"shift-enter";case"CTRL_ENTER":return"ctrl-enter";case"CTRL_J":return"ctrl-enter";case"ALT_B":case"META_B":return"alt-b";case"ALT_F":case"META_F":return"alt-f";case"ALT_N":case"META_N":return"alt-n";case"ALT_P":case"META_P":return"alt-p";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"ALT_BACKSPACE":case"META_BACKSPACE":return"alt-backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_Q":return"ctrl-q";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_X_CTRL_E":return"ctrl-x-ctrl-e";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function Wi(){let n=[fs,ol,il,IP,al,CP,dv,Jo,Ga,Ja,Ka,za,"\x1B>",rf,Vm,Ym,g$,"\x1B]9;4;0\x07",bP].join("");try{be(n)}catch{}}function L$(n){let e=[["width",80],["height",24]];for(let[t,r]of e){let s=Object.getOwnPropertyDescriptor(n,t);if(s&&s.get)continue;let o=Symbol(`raw-${t}`),i=n;i[o]=s?s.value:void 0,Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){let a=this[o];return typeof a=="number"&&Number.isFinite(a)&&a>0?a:r},set(a){this[o]=a}})}}function T$(n,e){let t={97:"ctrl-a",98:"ctrl-b",99:"ctrl-c",100:"ctrl-d",101:"ctrl-e",102:"ctrl-f",103:"ctrl-g",104:"backspace",105:"tab",106:"ctrl-enter",107:"ctrl-k",108:"ctrl-l",109:"enter",110:"ctrl-n",111:"ctrl-o",112:"ctrl-p",113:"ctrl-q",114:"ctrl-r",115:"ctrl-s",116:"ctrl-t",117:"ctrl-u",118:"ctrl-v",119:"ctrl-w",120:"ctrl-x",121:"ctrl-y"};return e===5?t[n]??null:n===27?"escape":n===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:n===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:n===127&&e===1?"backspace":n===127&&e===3||n===8&&e===3?"alt-backspace":(n===95||n===47)&&e===5?"ctrl-underscore":(n===95||n===47)&&e===7?"alt-underscore":e===3?n===98||n===66?"alt-b":n===102||n===70?"alt-f":n===110||n===78?"alt-n":n===112||n===80?"alt-p":n===95?"alt-underscore":null:null}var w4,b4,wl,bl,k4,od,v$,xS,IS,v4,S$,S4,Ot,Bt,x4,Ut,Bg,x$,I4,Rf,CS,C4,R4,RS,A4,T4,I$,E4,P4,M4,_4,AS,TS,ES,$4,O4,F4,L4,N4,D4,jg,M$,FS,_$,tJ,NS=j(()=>{"use strict";Gv();Tg();Zv();Eg();yg();et();uS();$g();iS();Se();mr();wg();pS();yS();Ko();Sg();of();i$();vg();zv();d$();wS();xn();SS();ya();ma();Va();w4=/\x1b\[[0-9;]*m/,b4=/\x1b\[[0-9;]*m/g,wl=500,bl=1,k4=700,od=/[A-Za-z0-9_:\-]/,v$=/[:\-]/,xS=/[A-Za-z0-9_./\-~+@]/,IS=/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%\-]/,v4=/[.,;:!?)\]}'"]/,S$=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,S4=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,Ot=1,Bt=0,x4=1,Ut=1,Bg=8,x$=20,I4=36,Rf=2,CS=1,C4=80,R4=12,RS=5,A4=12,T4=12,I$=350,E4=[{label:"\u2191/\u2193 choose"},{label:"\u23CE submit",action:"commit"},{label:"Esc cancel",action:"cancel"},{label:"1-9 quick-pick"}],P4=[{label:"\u2191/\u2193 choose"},{label:"\u23CE submit",action:"commit"},{label:"Esc cancel",action:"cancel"},{label:"y/n quick-pick"}],M4=3,_4=30,AS=6,TS=4,ES=2,$4=1e3,O4=1e4,F4=30,L4=.45,N4=2,D4=/^(https?|ftp):\/\/\S+$/;jg=class n{term;dispatcher;onKey;onSidebarCollapseChange;onBlockClick;onHydraLinkClick;onMouse;onHoverRun;onBlockVisible;onSuspend;onLayoutChange;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;contentRepaintThrottleMs;painter;scheduler;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;sidebarVisible=!1;sidebarConfiguredWidth=null;sidebarRenderer=new Fg;sidebarBorder="frame";sidebarSnapshot=H_();sidebarRowPaths=new Map;sidebarRowDoubleActions=new Map;sidebarRowLinks=new Map;sidebarRowActions=new Map;sidebarPages={};sidebarCollapsed=new Set;lastSidebarClick=null;sidebarScrollOffset=0;sidebarOverflowRows=0;permissionPrompt=null;formPrompt=null;formRowHits=new Map;formHintHits=[];formRegion=null;formPressHit=null;formWindowTop=0;formWindowKey=null;permissionRowHits=new Map;permissionHintHits=[];permissionRegion=null;permissionPressHit=null;permissionArmedAt=0;confirmPrompt=null;compactionPrompt=null;compactionRowHits=new Map;compactionHintHits=[];compactionRegion=null;compactionPressHit=null;compactionArmedAt=0;helpRegion=null;helpPressed=!1;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;slideTarget=0;slideTimer=null;slideEnabled;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;workspaceIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayScroll=0;btwOverlayRegion=null;btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:Dv,queued:0};barHits=new Map;hoveredBarHit=null;composerBottomRow=null;hintZoneStart=null;hintHoverReveal=!1;hintHoverHideTimer=null;hintKeyReveal=!1;barPressHit=null;lastBarClick=null;onBarAction;onFormClick;onPermissionClick;onCompactionClick;onHelpClick;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};barConfig={composer:{top:{left:ca,right:la},bottom:{left:zd,right:Kd}},sessionbar:{left:Gd,right:Jd}};scriptOutputs=new Map;lastWindowTitle=null;lastReportedCwd=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;pendingClickCount=1;doubleClickPending=!1;selectionGranularity="char";selectionAnchorWordBounds=null;selectionAnchorLineId=null;promptSelectionAnchor=null;promptSelectionDragStarted=!1;promptSelection=null;promptSelectionGranularity="char";promptSelectionAnchorWordBounds=null;promptSelectionAnchorLineRow=null;promptDoubleClickPending=!1;promptPendingClickCount=1;promptLastLeftClick=null;lastLeftClick=null;autoscrollTimer=null;autoscrollCell=null;autoscrollDir=1;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;chordMatcher=new Fi(p_);mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;openFileForeground;runForeground;foregroundChildActive=!1;progressIndicatorEnabled;emergencyCleanupInstalled=!1;onProcessExit=null;onProcessSignal=null;onProcessUncaught=null;selectiveMouseSupported=!1;selectiveMouseProbing=!1;selectiveMouseProbeTimer=null;lastProgressState=0;readonly;constructor(e){this.term=e.term,this.dispatcher=e.dispatcher;let t=e.onKey;this.onKey=o=>{this.selection!==null&&o.length>0&&this.clearSelection(),this.promptSelection!==null&&o.length>0&&this.clearPromptSelection(),t(o)},this.onBlockClick=e.onBlockClick,this.onSidebarCollapseChange=e.onSidebarCollapseChange,this.onHydraLinkClick=e.onHydraLinkClick,this.onMouse=e.onMouse,this.onBarAction=e.onBarAction,this.onFormClick=e.onFormClick,this.onPermissionClick=e.onPermissionClick,this.onCompactionClick=e.onCompactionClick,this.onHelpClick=e.onHelpClick,this.onHoverRun=e.onHoverRun,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.onLayoutChange=e.onLayoutChange,this.contentRepaintThrottleMs=e.repaintThrottleMs??$4,this.painter=new gl(this.term),this.scheduler=new Cg({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??O4,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both";let r=e.openFileCommand,s=typeof r=="string"?r.split(/\s+/).filter(o=>o.length>0):r;this.openFileCommand=s&&s.length>0?s:null,this.openFileForeground=e.openFileInTerminal??e.openFileSource==="env",this.runForeground=e.runForeground??xg,this.progressIndicatorEnabled=e.progressIndicator??!0,this.slideEnabled=e.turnSlide??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>{this.painter.clearCache(),this.sidebarRenderer.invalidate(),this.onLayoutChange?.(),this.repaint()},this.keyHandler=(o,i,a)=>this.handleKey(o,a),this.mouseHandler=(o,i)=>this.handleMouse(o,i),this.rawStdinHandler=o=>this.handleRawStdin(o)}start(e={}){this.started||(this.started=!0,fS(!1),e.skipFullscreen||this.term.fullscreen(!0),this.painter.clearCache(),this.lastWindowTitle=null,be(av),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),we({src:"grab",site:"screen.start",on:!0}),this.term.hideCursor(!1),this.term.on("key",this.keyHandler),this.mouseEnabled&&this.term.on("mouse",this.mouseHandler),this.term.on("resize",this.resizeHandler),this.installBracketedPaste(),this.installSelectiveMouseReporting(),this.installEmergencyCleanup(),this.lastProgressState=0,this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.repaint())}stop(e={}){this.started&&(fS(!0),this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.cancelHintHoverHide(),this.cancelSlide(),this.scheduler.cancel(),this.cancelPendingBlockClick(),this.stopAutoscroll(),this.uninstallSelectiveMouseReporting(),this.uninstallBracketedPaste(),this.uninstallEmergencyCleanup(),this.term.off("key",this.keyHandler),this.mouseEnabled&&this.term.off("mouse",this.mouseHandler),this.term.off("resize",this.resizeHandler),this.term.grabInput(!1),we({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(be(Ym),this.currentPointerShape="default"),e.keepFullscreen||be(rf),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(Wi(),this.term.fullscreen(!1),this.term(`
263
+ `);return e===-1?n:`${n.slice(0,e)} \u21B5`}function qg(n){switch(n){case"ENTER":case"KP_ENTER":return"enter";case"ALT_ENTER":case"META_ENTER":return"alt-enter";case"SHIFT_ENTER":return"shift-enter";case"CTRL_ENTER":return"ctrl-enter";case"CTRL_J":return"ctrl-enter";case"ALT_B":case"META_B":return"alt-b";case"ALT_F":case"META_F":return"alt-f";case"ALT_N":case"META_N":return"alt-n";case"ALT_P":case"META_P":return"alt-p";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"ALT_BACKSPACE":case"META_BACKSPACE":return"alt-backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_Q":return"ctrl-q";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_X_CTRL_E":return"ctrl-x-ctrl-e";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function Wi(){let n=[fs,ol,il,IP,al,CP,dv,Jo,Ga,Ja,Ka,za,"\x1B>",rf,Vm,Ym,g$,"\x1B]9;4;0\x07",bP].join("");try{be(n)}catch{}}function L$(n){let e=[["width",80],["height",24]];for(let[t,r]of e){let s=Object.getOwnPropertyDescriptor(n,t);if(s&&s.get)continue;let o=Symbol(`raw-${t}`),i=n;i[o]=s?s.value:void 0,Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get(){let a=this[o];return typeof a=="number"&&Number.isFinite(a)&&a>0?a:r},set(a){this[o]=a}})}}function T$(n,e){let t={97:"ctrl-a",98:"ctrl-b",99:"ctrl-c",100:"ctrl-d",101:"ctrl-e",102:"ctrl-f",103:"ctrl-g",104:"backspace",105:"tab",106:"ctrl-enter",107:"ctrl-k",108:"ctrl-l",109:"enter",110:"ctrl-n",111:"ctrl-o",112:"ctrl-p",113:"ctrl-q",114:"ctrl-r",115:"ctrl-s",116:"ctrl-t",117:"ctrl-u",118:"ctrl-v",119:"ctrl-w",120:"ctrl-x",121:"ctrl-y"};return e===5?t[n]??null:n===27?"escape":n===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:n===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:n===127&&e===1?"backspace":n===127&&e===3||n===8&&e===3?"alt-backspace":(n===95||n===47)&&e===5?"ctrl-underscore":(n===95||n===47)&&e===7?"alt-underscore":e===3?n===98||n===66?"alt-b":n===102||n===70?"alt-f":n===110||n===78?"alt-n":n===112||n===80?"alt-p":n===95?"alt-underscore":null:null}var w4,b4,wl,bl,k4,od,v$,xS,IS,v4,S$,S4,Ot,Bt,x4,Ut,Bg,x$,I4,Rf,CS,C4,R4,RS,A4,T4,I$,E4,P4,M4,_4,AS,TS,ES,$4,O4,F4,L4,N4,D4,jg,M$,FS,_$,tJ,NS=j(()=>{"use strict";Gv();Tg();Zv();Eg();yg();et();uS();$g();iS();Se();mr();wg();pS();yS();Ko();Sg();of();i$();vg();zv();d$();wS();xn();SS();ya();ma();Va();w4=/\x1b\[[0-9;]*m/,b4=/\x1b\[[0-9;]*m/g,wl=500,bl=1,k4=700,od=/[A-Za-z0-9_:\-]/,v$=/[:\-]/,xS=/[A-Za-z0-9_./\-~+@]/,IS=/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%\-]/,v4=/[.,;:!?)\]}'"]/,S$=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,S4=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,Ot=1,Bt=0,x4=1,Ut=1,Bg=8,x$=20,I4=36,Rf=2,CS=1,C4=80,R4=12,RS=5,A4=12,T4=12,I$=350,E4=[{label:"\u2191/\u2193 choose"},{label:"\u23CE submit",action:"commit"},{label:"Esc cancel",action:"cancel"},{label:"1-9 quick-pick"}],P4=[{label:"\u2191/\u2193 choose"},{label:"\u23CE submit",action:"commit"},{label:"Esc cancel",action:"cancel"},{label:"y/n quick-pick"}],M4=3,_4=30,AS=6,TS=4,ES=2,$4=1e3,O4=1e4,F4=30,L4=.45,N4=2,D4=/^(https?|ftp):\/\/\S+$/;jg=class n{term;dispatcher;onKey;onSidebarCollapseChange;onBlockClick;onHydraLinkClick;onMouse;onHoverRun;onBlockVisible;onSuspend;onLayoutChange;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;contentRepaintThrottleMs;painter;scheduler;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;uncachedWrap=new WeakSet;wrapOrigin=new WeakMap;sidebarVisible=!1;sidebarConfiguredWidth=null;sidebarRenderer=new Fg;sidebarBorder="frame";sidebarSnapshot=H_();sidebarRowPaths=new Map;sidebarRowDoubleActions=new Map;sidebarRowLinks=new Map;sidebarRowActions=new Map;sidebarPages={};sidebarCollapsed=new Set;lastSidebarClick=null;sidebarScrollOffset=0;sidebarOverflowRows=0;permissionPrompt=null;formPrompt=null;formRowHits=new Map;formHintHits=[];formRegion=null;formPressHit=null;formWindowTop=0;formWindowKey=null;permissionRowHits=new Map;permissionHintHits=[];permissionRegion=null;permissionPressHit=null;permissionArmedAt=0;confirmPrompt=null;compactionPrompt=null;compactionRowHits=new Map;compactionHintHits=[];compactionRegion=null;compactionPressHit=null;compactionArmedAt=0;helpRegion=null;helpPressed=!1;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;slideTarget=0;slideTimer=null;slideEnabled;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;workspaceIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayScroll=0;btwOverlayRegion=null;btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:Dv,queued:0};barHits=new Map;hoveredBarHit=null;composerBottomRow=null;hintZoneStart=null;hintHoverReveal=!1;hintHoverHideTimer=null;hintKeyReveal=!1;barPressHit=null;lastBarClick=null;onBarAction;onFormClick;onPermissionClick;onCompactionClick;onHelpClick;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};barConfig={composer:{top:{left:ca,right:la},bottom:{left:zd,right:Kd}},sessionbar:{left:Gd,right:Jd}};scriptOutputs=new Map;lastWindowTitle=null;lastReportedCwd=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;pendingClickCount=1;doubleClickPending=!1;selectionGranularity="char";selectionAnchorWordBounds=null;selectionAnchorLineId=null;promptSelectionAnchor=null;promptSelectionDragStarted=!1;promptSelection=null;promptSelectionGranularity="char";promptSelectionAnchorWordBounds=null;promptSelectionAnchorLineRow=null;promptDoubleClickPending=!1;promptPendingClickCount=1;promptLastLeftClick=null;lastLeftClick=null;autoscrollTimer=null;autoscrollCell=null;autoscrollDir=1;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;chordMatcher=new Fi(p_);mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;openFileForeground;runForeground;foregroundChildActive=!1;progressIndicatorEnabled;emergencyCleanupInstalled=!1;onProcessExit=null;onProcessSignal=null;onProcessUncaught=null;selectiveMouseSupported=!1;selectiveMouseProbing=!1;selectiveMouseProbeTimer=null;lastProgressState=0;readonly;constructor(e){this.term=e.term,this.dispatcher=e.dispatcher;let t=e.onKey;this.onKey=o=>{this.selection!==null&&o.length>0&&this.clearSelection(),this.promptSelection!==null&&o.length>0&&this.clearPromptSelection(),t(o)},this.onBlockClick=e.onBlockClick,this.onSidebarCollapseChange=e.onSidebarCollapseChange,this.onHydraLinkClick=e.onHydraLinkClick,this.onMouse=e.onMouse,this.onBarAction=e.onBarAction,this.onFormClick=e.onFormClick,this.onPermissionClick=e.onPermissionClick,this.onCompactionClick=e.onCompactionClick,this.onHelpClick=e.onHelpClick,this.onHoverRun=e.onHoverRun,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.onLayoutChange=e.onLayoutChange,this.contentRepaintThrottleMs=e.repaintThrottleMs??$4,this.painter=new gl(this.term),this.scheduler=new Cg({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??O4,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both";let r=e.openFileCommand,s=typeof r=="string"?r.split(/\s+/).filter(o=>o.length>0):r;this.openFileCommand=s&&s.length>0?s:null,this.openFileForeground=e.openFileInTerminal??e.openFileSource==="env",this.runForeground=e.runForeground??xg,this.progressIndicatorEnabled=e.progressIndicator??!0,this.slideEnabled=e.turnSlide??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>{this.painter.clearCache(),this.sidebarRenderer.invalidate(),this.onLayoutChange?.(),this.repaint()},this.keyHandler=(o,i,a)=>this.handleKey(o,a),this.mouseHandler=(o,i)=>this.handleMouse(o,i),this.rawStdinHandler=o=>this.handleRawStdin(o)}start(e={}){this.started||(this.started=!0,fS(!1),e.skipFullscreen||this.term.fullscreen(!0),this.painter.clearCache(),this.lastWindowTitle=null,be(av),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),we({src:"grab",site:"screen.start",on:!0}),this.term.hideCursor(!1),this.term.on("key",this.keyHandler),this.mouseEnabled&&this.term.on("mouse",this.mouseHandler),this.term.on("resize",this.resizeHandler),this.installBracketedPaste(),this.installSelectiveMouseReporting(),this.installEmergencyCleanup(),this.lastProgressState=0,this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.repaint())}stop(e={}){this.started&&(fS(!0),this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.cancelHintHoverHide(),this.cancelSlide(),this.scheduler.cancel(),this.cancelPendingBlockClick(),this.stopAutoscroll(),this.uninstallSelectiveMouseReporting(),this.uninstallBracketedPaste(),this.uninstallEmergencyCleanup(),this.term.off("key",this.keyHandler),this.mouseEnabled&&this.term.off("mouse",this.mouseHandler),this.term.off("resize",this.resizeHandler),this.term.grabInput(!1),we({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(be(Ym),this.currentPointerShape="default"),e.keepFullscreen||be(rf),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(Wi(),this.term.fullscreen(!1),this.term(`
264
264
  `)))}installBracketedPaste(){be(Jm),be(SP),be(xP),be(vP),be(Qm);let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.on("data",this.rawStdinHandler))}uninstallBracketedPaste(){be(Jo),be(Ga),be(Ja),be(Ka),be(sf),be(za),be("\x1B>");let e=this.term;!e.stdin||this.terminalKitStdinHandler===null||(e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.terminalKitStdinHandler),this.terminalKitStdinHandler=null,this.pasteActive=!1,this.pasteBuffer="")}installSelectiveMouseReporting(){this.mouseEnabled||this.selectiveMouseProbing||this.selectiveMouseSupported||(this.selectiveMouseProbing=!0,be(RP),this.selectiveMouseProbeTimer=setTimeout(()=>{this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer=null},250))}uninstallSelectiveMouseReporting(){this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseProbing=!1,this.selectiveMouseSupported&&(be(dv),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>Wi(),this.onProcessSignal=e=>{Wi(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{Wi(),process.stderr.write(`
265
265
  uncaught: ${e.stack??e.message}
266
266
  `),process.exit(1)},process.on("exit",this.onProcessExit),process.on("SIGTERM",this.onProcessSignal),process.on("SIGHUP",this.onProcessSignal),process.on("uncaughtException",this.onProcessUncaught))}uninstallEmergencyCleanup(){this.emergencyCleanupInstalled&&(this.emergencyCleanupInstalled=!1,this.onProcessExit&&(process.off("exit",this.onProcessExit),this.onProcessExit=null),this.onProcessSignal&&(process.off("SIGTERM",this.onProcessSignal),process.off("SIGHUP",this.onProcessSignal),this.onProcessSignal=null),this.onProcessUncaught&&(process.off("uncaughtException",this.onProcessUncaught),this.onProcessUncaught=null))}consumeSelectiveMouseSequences(e){if(!e.includes("\x1B["))return e;if(this.selectiveMouseProbing){let a=/\x1b\[\?(\d+);(\d+) w/.exec(e);a&&(this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseSupported=!0,be(AP),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let t=/\x1b\[<(64|65);\d+;\d+M/g,r="",s=0,o;for(;(o=t.exec(e))!==null;)r+=e.slice(s,o.index),o[1]==="64"?this.scrollBy(3):this.scrollBy(-3),s=o.index+o[0].length;return r+=e.slice(s),r}handleRawStdin(e){if(process.env.HYDRA_TUI_KEY_TRACE){let r=Array.from(e).map(s=>"0x"+s.toString(16).padStart(2,"0")).join(" ");we({tag:"raw",bytes:r,len:e.length})}let t=e.toString("binary");if(t=this.consumeSelectiveMouseSequences(t),t.includes("\x1B[I")||t.includes("\x1B[O")){let r=this.terminalFocused;for(;;){let s=t.indexOf("\x1B[I"),o=t.indexOf("\x1B[O"),i=s===-1?o:o===-1?s:Math.min(s,o);if(i===-1)break;let a=i===s;this.terminalFocused=a,a&&(this.lastFocusInAt=Date.now()),t=t.slice(0,i)+t.slice(i+"\x1B[I".length)}this.terminalFocused!==r&&this.scheduleRepaint()}if(t.length!==0){if(this.pasteActive){this.handleRawStdinSegment(t);return}if(t===""&&this.onSuspend){this.onSuspend();return}if(this.onSuspend&&(t==="\x1B[27;5;122~"||t==="\x1B[122;5u")){this.onSuspend();return}if(t===""){this.onKey([{type:"key",name:"ctrl-underscore"}]);return}if(t==="\x1B"||t==="\x1B_"){this.onKey([{type:"key",name:"alt-underscore"}]);return}if(t==="\x1B\x7F"||t==="\x1B\b"){this.onKey([{type:"key",name:"alt-backspace"}]);return}if(t.startsWith("\x1B\x7F")||t.startsWith("\x1B\b")){this.onKey([{type:"key",name:"alt-backspace"}]),this.handleRawStdin(Buffer.from(t.slice(2),"binary"));return}if(/\x1b\[27;\d+;\d+~/.test(t)){this.handleCsi27Stdin(t);return}if(t.includes(sl)){this.handleRawStdinSegment(t);return}if(t.includes(`
267
267
  `)){let r=t.split(`
268
268
  `);if(r.filter(o=>o.length>0).length>1){this.onKey([{type:"paste",text:t.replace(/\r/g,"")}]);return}for(let o=0;o<r.length;o++)r[o].length>0&&this.handleRawStdin(Buffer.from(r[o],"binary")),o<r.length-1&&this.onKey([{type:"key",name:"ctrl-enter"}]);return}if(t.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(t)){this.handleCsiUStdin(t);return}this.handleRawStdinSegment(t)}}handleCsi27Stdin(e){let t=/\x1b\[27;(\d+);(\d+)~/g,r=0,s;for(;(s=t.exec(e))!==null;){s.index>r&&this.handleRawStdin(Buffer.from(e.slice(r,s.index),"binary"));let o=parseInt(s[1],10),i=parseInt(s[2],10),a=T$(i,o);a!==null?this.dispatchKeyName(a):(o===1||o===2)&&i>=32&&i<127&&this.handleRawStdinSegment(String.fromCharCode(i)),r=s.index+s[0].length}r<e.length&&this.handleRawStdin(Buffer.from(e.slice(r),"binary"))}handleCsiUStdin(e){let t=/\x1b\[(\d+)(?:;(\d+))?u/g,r=0,s;for(;(s=t.exec(e))!==null;){s.index>r&&this.handleRawStdin(Buffer.from(e.slice(r,s.index),"binary"));let o=parseInt(s[1],10),i=s[2]!==void 0?parseInt(s[2],10):1,a=T$(o,i);a!==null&&this.dispatchKeyName(a),r=s.index+s[0].length}r<e.length&&this.handleRawStdin(Buffer.from(e.slice(r),"binary"))}handleRawStdinSegment(e){let t=sl,r=nf;for(;e.length>0;){if(this.pasteActive){let o=e.indexOf(r);if(o===-1){this.pasteBuffer+=e;return}this.pasteBuffer+=e.slice(0,o),e=e.slice(o+r.length),this.pasteActive=!1;let i=Buffer.from(this.pasteBuffer,"binary").toString("utf-8").replace(/\r\n?/g,`
269
269
  `);this.pasteBuffer="";let a=a_(i);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:i}]);continue}let s=e.indexOf(t);if(s===-1){let o=H4(e);o!==null?this.onKey([{type:"paste",text:o}]):this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e,"binary"));return}s>0&&this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e.slice(0,s),"binary")),e=e.slice(s+t.length),this.pasteActive=!0}}width(){return this.contentWidth()}termWidth(){return this.term.width||0}sidebarReserved(){if(!this.sidebarVisible)return 0;let e=this.term.width||0;if(e<C4)return 0;let t=this.sidebarConfiguredWidth??Math.min(I4,Math.max(x$,Math.floor(e*.28))),r=e-R4-Rf-CS;return Math.min(t,Math.max(x$,r))+Rf+CS}sidebarOverlay(){let e=this.sidebarReserved();return e>0&&e*2>(this.term.width||0)}sidebarColumnStart(){let e=this.sidebarReserved();return e===0?0:(this.term.width||0)-e+1}contentWidth(){let e=this.term.width||0;return this.sidebarOverlay()?e:Math.max(0,e-this.sidebarReserved())}transcriptVisibleWidth(){let e=this.sidebarColumnStart();return e===0?this.contentWidth():e-1}sidebarBodyWidth(){let e=this.sidebarReserved();return e===0?0:e-Rf-CS}isSidebarVisible(){return this.sidebarVisible}isSidebarSuppressed(){return this.sidebarVisible&&this.sidebarReserved()===0}isSidebarOverlay(){return this.sidebarOverlay()}setSidebarVisible(e){this.sidebarVisible!==e&&(this.sidebarVisible=e,this.lastSidebarClick=null,this.sidebarRowPaths.clear(),this.sidebarRowDoubleActions.clear(),this.sidebarRowActions.clear(),this.sidebarRowLinks.clear(),this.sidebarPages={},this.sidebarScrollOffset=0,this.sidebarOverflowRows=0,this.sidebarRenderer.invalidate(),this.painter.clearCache())}toggleSidebar(){return this.setSidebarVisible(!this.sidebarVisible),this.sidebarVisible}setSidebarGadgets(e){this.sidebarRenderer.setGadgets(e),this.scheduleRepaint()}setSidebarProcessGadgets(e){this.sidebarRenderer.setProcessGadgets(e.map(D_)),this.scheduleRepaint()}isSidebarGadgetConfigured(e){return this.sidebarRenderer.isConfigured(e)}isSidebarGadgetActive(e){return this.sidebarRenderer.isConfigured(e)&&!this.sidebarCollapsed.has(e)}toggleSidebarGadgetCollapsed(e){let t=!this.sidebarCollapsed.has(e);return t?this.sidebarCollapsed.add(e):this.sidebarCollapsed.delete(e),this.sidebarRenderer.invalidate(),this.onSidebarCollapseChange?.(e,t),t}setSidebarCollapsed(e){this.sidebarCollapsed=new Set(e),this.sidebarRenderer.invalidate()}sidebarCollapsedIds(){return[...this.sidebarCollapsed]}setSidebarBorder(e){this.sidebarBorder!==e&&(this.sidebarBorder=e,this.sidebarRenderer.invalidate(),this.painter.clearCache(),this.scheduleRepaint())}setSidebarWidth(e){this.sidebarConfiguredWidth=e,this.painter.clearCache()}setSidebarSnapshot(e){this.sidebarSnapshot={...this.sidebarSnapshot,...e},this.sidebarVisible&&this.scheduleRepaint()}setScriptOutput(e,t){if(t===null){if(!this.scriptOutputs.has(e))return;this.scriptOutputs.delete(e)}else{if(this.scriptOutputs.get(e)===t)return;this.scriptOutputs.set(e,t)}this.scheduleRepaint()}setProcessOutput(e,t){let r=this.sidebarSnapshot.processOutputs.get(e);if(t===null){if(r===void 0)return;let s=new Map(this.sidebarSnapshot.processOutputs);s.delete(e),this.sidebarSnapshot={...this.sidebarSnapshot,processOutputs:s}}else{if(r===t)return;let s=new Map(this.sidebarSnapshot.processOutputs);s.set(e,t),this.sidebarSnapshot={...this.sidebarSnapshot,processOutputs:s}}this.sidebarVisible&&this.scheduleRepaint()}appendLines(e){e.length!==0&&(this.streamingActive=!1,this.lines.push(...e),this.trackLines(e),this.adjustScrollForRowChange(this.wrappedRowsOfMany(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint())}appendLine(e){this.streamingActive=!1,this.lines.push(e),this.trackLine(e),this.adjustScrollForRowChange(this.wrappedRowsOf(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}adjustScrollForRowChange(e){if(e!==0){if(this.scrollOffset>0){this.cancelSlide(!0),this.scrollOffset=Math.max(0,this.scrollOffset+e);return}this.slideTimer!==null&&(this.slideTarget=Math.max(0,this.slideTarget+e))}}wrappedRowsOf(e){let t=this.contentWidth();return this.wrapCacheWidth!==t&&(this.wrapCache.clear(),this.wrapCacheWidth=t),this.wrapOne(e,t).length}wrappedRowsOfMany(e){let t=0;for(let r of e)t+=this.wrappedRowsOf(r);return t}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let t of e)this.trackLine(t)}forgetLine(e){let t=this.lineIds.get(e);t!==void 0&&this.wrapCache.delete(t)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let t=this.lines.splice(0,e);for(let r of t)this.forgetLine(r);this.invalidateSelectionIfTouches(t);for(let[r,s]of[...this.keyedBlocks.entries()])s.start-=e,s.start<0&&this.keyedBlocks.delete(r)}upsertLine(e,t){this.upsertLines(e,[t])}upsertLines(e,t){if(t.length===0)return;for(let i of t)i.blockKey=e;let r=this.keyedBlocks.get(e),s=!1,o=0;if(r){let i=r.start+r.count;s=i>=this.lines.length;let a=this.wrappedRowsOfMany(this.lines.slice(r.start,i)),d=t.length-r.count,c=this.lines.slice(r.start,i),l=new Array(t.length),u=[];for(let f=0;f<t.length;f++){let p=c[f],m=t[f];p!==void 0&&W4(p,m)?l[f]=p:(p!==void 0&&u.push(p),l[f]=m)}for(let f=t.length;f<c.length;f++)u.push(c[f]);this.lines.splice(r.start,r.count,...l);for(let f of u)this.forgetLine(f);for(let f of l)this.lineIds.has(f)||this.trackLine(f);if(this.invalidateSelectionIfTouches(u),r.count=t.length,d!==0)for(let[f,p]of this.keyedBlocks)f!==e&&p.start>r.start&&(p.start+=d);o=this.wrappedRowsOfMany(t)-a}else s=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:t.length}),this.lines.push(...t),this.trackLines(t),o=this.wrappedRowsOfMany(t);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(o),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,t,r,s){if(e.length===0)return;let o=e.split(`
270
- `),[i,...a]=o,d=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let u=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=i??"",d+=this.wrappedRowsOf(l)-u}}else{if(this.lines.length>0){let u=this.lines[this.lines.length-1];if(!(u&&u.body===""&&(!u.prefix||u.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),d+=this.wrappedRowsOf(p)}}let l={prefix:t,body:i??"",bodyStyle:r};s!==void 0&&(l.prefixStyle=s),this.lines.push(l),this.trackLine(l),d+=this.wrappedRowsOf(l)}let c=" ".repeat(t.length);for(let l of a){let u={prefix:c,body:l,bodyStyle:r};this.lines.push(u),this.trackLine(u),d+=this.wrappedRowsOf(u)}this.streamingActive=!0,this.adjustScrollForRowChange(d),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setBarConfig(e){this.barConfig=vf(e),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.syncReportedCwd(),G_({sessionId:this.sessionbar.sessionId,agent:this.sessionbar.agent,title:this.sessionbar.title,model:this.sessionbar.model,costAmount:this.sessionbar.usage?.costAmount,cwd:this.sessionbar.cwd}),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),t=e&&e.length>0?e:"New Hydra Session",s=(this.readonly?`${t} [VIEW ONLY]`:t).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);s!==this.lastWindowTitle&&(this.lastWindowTitle=s,be(`\x1B]0;${s}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,be("\x1B]0;\x1B\\")}syncReportedCwd(){let e=this.sessionbar.cwd?.trim();e&&e!==this.lastReportedCwd&&(this.lastReportedCwd=e,mS(e))}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),J_({status:this.banner.status,queued:this.banner.queued}),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&mt(()=>{this.term.hideCursor(),e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}sessionTitle(){return this.sessionbar.title}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,t=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},t),this.syncedPartialRepaint(()=>this.drawBanner())}setCompactionIndicator(e){this.compactionIndicator!==e&&(this.compactionIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setSynthesisIndicator(e){this.synthesisIndicator!==e&&(this.synthesisIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setWorkspaceIndicator(e){this.workspaceIndicator!==e&&(this.workspaceIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setMouseEnabled(e){this.mouseEnabled!==e&&(this.mouseEnabled=e,this.started&&(e?(this.term.grabInput({mouse:"drag"}),this.term.on("mouse",this.mouseHandler)):(this.term.off("mouse",this.mouseHandler),this.term.grabInput(!0)),we({src:"grab",site:"setMouseEnabled",on:!0,mouse:e}),this.reclaimStdinAfterGrabInput()))}reclaimStdinAfterGrabInput(){if(this.terminalKitStdinHandler===null)return;let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.rawStdinHandler))}isMouseEnabled(){return this.mouseEnabled}setInAppSelectionEnabled(e){this.inAppSelectionEnabled=e}isInAppSelectionEnabled(){return this.inAppSelectionEnabled}setSelection(e,t){let r=this.lineIndexById(e.sourceLineId),s=this.lineIndexById(t.sourceLineId),o=r<s||r===s&&e.offset<=t.offset,i=o?e:t,a=o?t:e;if(i.sourceLineId===a.sourceLineId&&i.offset===a.offset){this.clearSelection();return}let d={startLineId:i.sourceLineId,startOffset:i.offset,endLineId:a.sourceLineId,endOffset:a.offset},c=this.selection;c&&c.startLineId===d.startLineId&&c.startOffset===d.startOffset&&c.endLineId===d.endLineId&&c.endOffset===d.endOffset||(this.selection=d,this.repaint())}clearSelection(){this.selection!==null&&(this.selection=null,this.repaint())}hasSelection(){return this.selection!==null}getSelection(){return this.selection===null?null:{start:{sourceLineId:this.selection.startLineId,offset:this.selection.startOffset},end:{sourceLineId:this.selection.endLineId,offset:this.selection.endOffset}}}farEndpointFrom(e){if(this.selection===null)return null;let t=this.selection,r=this.lineIndexById(e.sourceLineId),s=this.lineIndexById(t.startLineId),o=this.lineIndexById(t.endLineId);if(r<0||s<0||o<0)return null;let i=(u,f,p,m)=>u!==p?u-p:f-m,a=i(r,e.offset,s,t.startOffset),d=i(r,e.offset,o,t.endOffset);if(a<=0)return{sourceLineId:t.endLineId,offset:t.endOffset};if(d>=0)return{sourceLineId:t.startLineId,offset:t.startOffset};let c=Math.abs(r-s)*1e6+Math.abs(e.offset-t.startOffset);return Math.abs(r-o)*1e6+Math.abs(e.offset-t.endOffset)>=c?{sourceLineId:t.endLineId,offset:t.endOffset}:{sourceLineId:t.startLineId,offset:t.startOffset}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let t=[];for(let r=e.loIdx;r<=e.hiIdx;r++){let s=this.lines[r];if(!s)continue;let o=this.lineIds.get(s),i=o===void 0?void 0:e.byId.get(o);if(!i)continue;let d=(s.body??"").slice(i.start,i.end);(Af(s.bodyStyle)||s.ansi)&&(d=Wg(d)),t.push(d)}return t.join(`
271
- `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let t=this.lineIndexById(e.startLineId),r=this.lineIndexById(e.endLineId);if(t===-1||r===-1)return null;let s=t,o=r,i=e.startOffset,a=e.endOffset;t>r&&(s=r,o=t,i=e.endOffset,a=e.startOffset);let d=new Map,c=-1;for(let l=o;l>=s;l--){let u=this.lines[l];if(u&&!this.isHiddenLine(u)){c=l;break}}for(let l=s;l<=o;l++){let u=this.lines[l];if(!u||this.isHiddenLine(u))continue;let f=this.lineIds.get(u);if(f===void 0)continue;let p=(u.body??"").length,m=l===s?Math.max(0,Math.min(p,i)):0,b=l===o?Math.max(0,Math.min(p,a)):p;d.set(f,{start:m,end:b,toEnd:l<c})}return{loIdx:s,hiIdx:o,byId:d}}selectionRangeForChunk(e){if(this.selection===null)return null;let t=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(t===null)return null;let r=this.wrapOrigin.get(e);if(!r)return null;let s=t.get(r.sourceLineId);if(!s)return null;let o=r.sourceColOffset,i=r.bodyDisplayShift??0,a=r.sourceColEnd??o+e.body.length-i,d=Math.max(s.start,o),c=Math.min(s.end,a);if(c<=d)return null;let l,u;if(r.sourceColEnd!==void 0){let f=this.sourceBodyForId(r.sourceLineId);if(f===null)return null;let p=MS(f,o,d),m=MS(f,d,c);l=_S(e.body,i,p),u=_S(e.body,l,m)}else l=d-o+i,u=c-o+i;return{start:l,end:u,toEndOfLine:s.toEnd||s.end>a}}sourceBodyForId(e){let t=this.lineIndexById(e);return t===-1?null:this.lines[t]?.body??null}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,t=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${t}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:this.workspaceIndicator!==null?{text:this.workspaceIndicator,kind:"workspace"}:this.synthesisIndicator!==null?{text:this.synthesisIndicator,kind:"synthesis"}:this.compactionIndicator!==null?{text:this.compactionIndicator,kind:"compaction"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.selection!==null&&(this.selection=null),this.repaint()}invalidateSelectionIfTouches(e){if(this.selection!==null)for(let t of e){let r=this.lineIds.get(t);if(r!==void 0&&(r===this.selection.startLineId||r===this.selection.endLineId)){this.selection=null;return}}}setHideThoughts(e){this.hideThoughts!==e&&(this.hideThoughts=e,this.repaint())}clearKey(e){this.keyedBlocks.delete(e)}hasKey(e){return this.keyedBlocks.has(e)}removeKey(e){let t=this.keyedBlocks.get(e);if(!t)return;let r=t.start+t.count,s=r>=this.lines.length,o=this.wrappedRowsOfMany(this.lines.slice(t.start,r)),i=this.lines.splice(t.start,t.count);for(let a of i)this.forgetLine(a);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[a,d]of this.keyedBlocks)a!==e&&d.start>t.start&&(d.start-=t.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-o),this.moveStickyToEnd(),this.scheduleRepaint()}setStickyBottomKey(e){this.stickyBottomKey=e,this.moveStickyToEnd(),this.scheduleRepaint()}moveStickyToEnd(){if(this.stickyBottomKey===null)return;let e=this.keyedBlocks.get(this.stickyBottomKey);if(!e)return;let t=e.start+e.count;if(t>=this.lines.length)return;let r=this.lines.splice(e.start,e.count);for(let[s,o]of this.keyedBlocks)s!==this.stickyBottomKey&&o.start>=t&&(o.start-=e.count);e.start=this.lines.length,this.lines.push(...r),this.streamingActive=!1}removeBlock(e){let t=this.keyedBlocks.get(e);if(!t)return;let r=t.start+t.count>=this.lines.length,s=this.wrappedRowsOfMany(this.lines.slice(t.start,t.start+t.count)),o=this.lines.splice(t.start,t.count);for(let i of o)this.forgetLine(i);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[,i]of this.keyedBlocks)i.start>t.start&&(i.start-=t.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-s),this.scheduleRepaint()}contiguousRun(e,t){if(!this.keyedBlocks.has(e))return[];let r=[...t].map(d=>{let c=this.keyedBlocks.get(d);return c?{key:d,start:c.start,count:c.count}:null}).filter(d=>d!==null).sort((d,c)=>d.start-c.start),s=r.findIndex(d=>d.key===e);if(s<0)return[];let o=(d,c)=>{for(let[l,u]of this.keyedBlocks)if(!t.has(l)&&u.start>=d&&u.start<c)return!0;return!1},i=s;for(;i>0&&!o(r[i-1].start+r[i-1].count,r[i].start);)i--;let a=s;for(;a<r.length-1&&!o(r[a].start+r[a].count,r[a+1].start);)a++;return r.slice(i,a+1).map(d=>d.key)}setRunCollapsed(e,t,r){if(e.length===0)return;let s=e[0];if(!this.keyedBlocks.has(s))return;this.upsertLines(s,r);let o=this.keyedBlocks.get(s),i=o.start+o.count;for(let a of e){let d=this.keyedBlocks.get(a);d&&(i=Math.max(i,d.start+d.count))}for(let a=o.start+o.count;a<i;a++){let d=this.lines[a];d&&(d.collapsed=t)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,be(av),this.term.clear(),this.repaint()}pauseRepaint(){this.repaintPaused+=1}resumeRepaint(){this.repaintPaused!==0&&(this.repaintPaused-=1,this.repaintPaused===0&&this.repaintPending&&(this.repaintPending=!1,this.repaint()))}setQueuedPrompts(e){this.queuedTexts=[...e],this.lastQueueEditingIndex=this.dispatcher.state().queueIndex,this.repaint()}repaintNow(){this.repaint()}setPermissionPrompt(e){e!==null&&this.permissionPrompt===null&&(this.clearSelection(),this.permissionArmedAt=Date.now()),this.permissionPrompt=e?{...e}:null,e===null&&(this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion=null,this.permissionPressHit=null),Y_(this.permissionPrompt!==null),this.repaint()}setFormPrompt(e){e!==null&&this.formPrompt===null&&this.clearSelection(),this.formPrompt=e?{...e,rows:e.rows.map(t=>({...t}))}:null,e===null&&(this.clearFormHits(),this.formWindowKey=null,this.formWindowTop=0),this.repaint()}clearFormHits(){this.formRowHits.clear(),this.formHintHits=[],this.formRegion=null,this.formPressHit=null}isFormPromptActive(){return this.formPrompt!==null}setConfirmPrompt(e){e!==null&&this.confirmPrompt===null&&this.clearSelection(),this.confirmPrompt=e?{...e}:null,this.repaint()}isCompactionPromptActive(){return this.compactionPrompt!==null}compactionPromptSpec(){return this.compactionPrompt?{...this.compactionPrompt}:null}setCompactionPrompt(e){e!==null&&this.compactionPrompt===null&&(this.clearSelection(),this.compactionArmedAt=Date.now()),this.compactionPrompt=e?{...e}:null,e===null&&(this.compactionRowHits.clear(),this.compactionHintHits=[],this.compactionRegion=null,this.compactionPressHit=null),this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,e===null&&(this.helpRegion=null,this.helpPressed=!1),this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}openBtwOverlay(e){let t=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=t,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlayScroll=0,this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let t=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,t=!0),e.usage!==void 0){let r=this.btwOverlayUsage,s=e.usage;(!r||r.used!==s.used||r.size!==s.size||r.costAmount!==s.costAmount||r.costCurrency!==s.costCurrency)&&(this.btwOverlayUsage={...s},t=!0)}t&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let r=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){r=!1;break}if(r)return}let t=this.btwOverlayLines.length;if(this.btwOverlayLines=[...e],this.btwOverlayScroll>0&&e.length>t){let r=this.term.width,s=0;for(let o=t;o<this.btwOverlayLines.length;o++)s+=r>4?this.wrapOne(this.btwOverlayLines[o],r).length:1;this.btwOverlayScroll+=s}this.scheduleRepaint()}setBtwOverlayStatus(e){let t=this.btwOverlayLabel===e.label,r=this.btwOverlayStatus===e.style;t&&r||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.btwOverlayRegion=null,this.focusedPane="main",this.scheduleRepaint())}reopenBtwOverlay(){return this.btwOverlayOpen?!0:this.btwOverlayLines.length===0?!1:(this.btwOverlayOpen=!0,this.focusedPane="btw",this.scheduleRepaint(),!0)}hasBtwOverlayHistory(){return this.btwOverlayLines.length>0}toggleFocusedPane(){this.focusedPane=this.focusedPane==="main"?"btw":"main",this.scheduleRepaint()}getFocusedPane(){return this.focusedPane}isOverlayOpen(){return this.btwOverlayOpen}setCompletions(e){e.length===this.completions.length&&e.every((r,s)=>{let o=this.completions[s];return o!==void 0&&o.name===r.name&&o.description===r.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let t=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,r=t!==void 0&&t.start+t.count===this.lines.length,s=r?t.start-1:this.lines.length-1;if(s<0)return;let o=this.lines[s];if(o&&o.body===""&&(o.prefix===void 0||o.prefix===""))return;let i={body:""};e!==void 0&&(i.bodyStyle=e),r?(this.lines.splice(t.start,0,i),t.start+=1):this.lines.push(i),this.trackLine(i),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(i)),this.trimScrollback(),this.scheduleRepaint()}refreshPrompt(){if(this.promptRows()!==this.lastPromptRows){this.repaint();return}this.syncedPartialRepaint(()=>{let e=this.dispatcher.state().queueIndex;e!==this.lastQueueEditingIndex&&(this.lastQueueEditingIndex=e,this.drawQueuedZone()),this.drawPrompt()})}handleKey(e,t){if(process.env.HYDRA_TUI_KEY_TRACE&&we({tag:"key",name:e,isChar:!!t.isCharacter}),t.isCharacter){this.chordMatcher.clear(),this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.chordMatcher.clear(),this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.chordMatcher.clear(),this.scrollBy(-this.scrollPageSize());return}if(e==="ALT_PAGE_UP"){this.chordMatcher.clear(),this.scrollToPrevTurn();return}if(e==="ALT_PAGE_DOWN"){this.chordMatcher.clear(),this.scrollToNextTurn();return}let r=qg(e);if(r){this.dispatchKeyName(r);return}e.startsWith("CTRL_")&&(this.chordMatcher.clear(),this.revealHints())}dispatchKeyName(e){let t=this.chordMatcher.feed(e);switch(t.kind){case"pass":this.onKey([{type:"key",name:t.token}]);return;case"armed":return;case"aborted":this.revealHints();return}}handleMouse(e,t){if(e==="MOUSE_WHEEL_UP"||e==="MOUSE_WHEEL_DOWN"){let u=e==="MOUSE_WHEEL_UP"?3:-3,f=this.mouseCell(t);if(f!==null&&this.isFormCell(f.y)){this.stepFormCursor(e==="MOUSE_WHEEL_UP"?-3:3);return}if(f!==null&&this.isCompactionCell(f.y)){this.stepCompactionCursor(e==="MOUSE_WHEEL_UP"?-1:1);return}if(f!==null&&this.isSidebarCell(f.x,f.y)&&this.scrollSidebarBy(u)||f!==null&&this.isBtwOverlayCell(f.y)&&this.scrollBtwOverlayBy(u))return;this.scrollBy(u);return}let s=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||s)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let i=this.mouseCell(t),a=U4(e),d=null;e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?d="move":e.endsWith("_PRESSED")?d="press":e.endsWith("_RELEASED")&&(d="release"),d!==null&&i!==null&&this.onMouse&&this.onMouse({kind:d,button:a,x:i.x,y:i.y,name:e});let c=i!==null?this.barHitAt(i.x,i.y):null;if(d==="move"){let u=c?.id??null,f=i!==null&&i.y===this.composerBottomRow&&this.hintZoneStart!==null&&i.x>=this.hintZoneStart,p=this.trackHintHover(f);if((u!==this.hoveredBarHit||p)&&(this.hoveredBarHit=u,this.syncedPartialRepaint(()=>this.drawBars())),c!==null&&this.setPointerShape(c.action!=="none"||c.doubleAction!=="none"?"pointer":"default"),i!==null&&this.isPermissionCell(i.y)){let m=this.permissionHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="option"&&this.permissionPrompt!==null&&m.index!==this.permissionPrompt.selectedIndex&&this.onPermissionClick?.({kind:"option",index:m.index,select:!0})}if(i!==null&&this.isCompactionCell(i.y)){let m=this.compactionHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="option"&&this.compactionPrompt!==null&&m.index!==this.compactionPrompt.selectedIndex&&this.onCompactionClick?.({kind:"option",index:m.index,select:!0})}if(i!==null&&this.isFormCell(i.y)){let m=this.formHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="row"&&this.formPrompt!==null&&m.row!==this.formPrompt.selectedIndex&&this.onFormClick?.({kind:"row",row:m.row,select:!0})}}let l=i!==null&&c===null&&this.barHits.get(i.y)===void 0&&i.x>=1&&i.x<=this.transcriptVisibleWidth();if(i!==null&&l&&d!=="release"){let u=this.keyAndSubAtRow(i.y),f=u!==null&&u.key.startsWith("agent:")?null:u;if(f===null&&d==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let p=this.nearestKeyAboveRow(i.y),m=this.nearestKeyBelowRow(i.y);p!==null&&m!==null&&this.hoveredRunKeys.has(p)&&this.hoveredRunKeys.has(m)&&(f={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(f!==null?"pointer":"default"),d==="move"){let p=f?.key??null,m=f?.sub??null;(p!==this.hoveredBlockKey||m!==this.hoveredSubKey)&&(this.hoveredBlockKey=p,this.hoveredSubKey=m,this.hoveredRunKeys=p!==null&&this.onHoverRun?this.onHoverRun(p)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else d==="move"&&(i!==null&&!l&&this.setPointerShape("default"),(this.hoveredBlockKey!==null||this.hoveredSubKey!==null||this.hoveredRunKeys!==null)&&(this.hoveredBlockKey=null,this.hoveredSubKey=null,this.hoveredRunKeys=null,this.syncedPartialRepaint(()=>this.drawScrollback())));if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let u=this.lastLeftClick;if(u!==null&&i!==null&&Math.abs(i.x-u.x)<=bl&&Math.abs(i.y-u.y)<=bl&&Date.now()-u.t<=wl||this.flushPendingBlockClick(),i!==null&&this.handleBarPress(i)){this.pressCell=null;return}if(i!==null&&this.handlePermissionPress(i)){this.pressCell=null;return}if(i!==null&&this.handleCompactionPress(i)){this.pressCell=null;return}if(i!==null&&this.handleHelpPress(i)){this.pressCell=null;return}if(i!==null&&this.handleFormPress(i)){this.pressCell=null;return}if(this.handleSidebarPress(i)){this.pressCell=null,this.clearSelection();return}if(this.pressCell=i,i!==null&&this.handlePromptSelectionPress(i)){this.lastLeftClick=null;return}this.handleSelectionPress(i,B4(t,"shift"));return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),!(e==="MOUSE_RIGHT_BUTTON_PRESSED"&&i!==null&&this.extendSelectionByClick(i))){if(e==="MOUSE_DRAG"&&i!==null){if(this.promptSelectionAnchor!==null){this.handlePromptSelectionDrag(i);return}this.handleSelectionDrag(i);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_RIGHT_BUTTON_RELEASED"||e==="MOUSE_MIDDLE_BUTTON_RELEASED"||e==="MOUSE_OTHER_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){if(this.handleBarRelease(i)){this.pressCell=null;return}if(this.handlePermissionRelease(i)){this.pressCell=null;return}if(this.handleCompactionRelease(i)){this.pressCell=null;return}if(this.handleHelpRelease(i)){this.pressCell=null;return}if(this.handleFormRelease(i)){this.pressCell=null;return}let u=this.pressCell;if(this.pressCell=null,this.promptSelectionAnchor!==null){this.handlePromptSelectionRelease(i);return}let f=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(u!==null&&i!==null&&i.x===u.x&&i.y===u.y&&!f&&this.onBlockClick){let p=this.keyAndSubAtRow(i.y),m=p?.key??null;if(m!==null){let b=i.y;for(;b>1&&this.keyAtRow(b-1)===m;)b-=1;this.schedulePendingBlockClick(m,i.y-b,p?.sub??null)}}(i===null||!this.isSidebarCell(i.x,i.y))&&this.handleSelectionRelease(i)}}}handleSelectionPress(e,t=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,this.selectionGranularity="char",this.selectionAnchorWordBounds=null,this.selectionAnchorLineId=null,!this.inAppSelectionEnabled||e===null)return;let r=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(r===null){this.lastLeftClick=null;return}if(t&&this.selection!==null&&this.extendSelectionByClickResolved(r)){this.lastLeftClick=null;return}this.selectionAnchor=r;let s=Date.now(),o=this.lastLeftClick,i=o!==null&&s-o.t<=wl&&Math.abs(e.x-o.x)<=bl&&Math.abs(e.y-o.y)<=bl&&o.sourceLineId!==null&&o.sourceLineId===r.sourceLineId;if(i&&o.count===2&&e.x===o.x&&e.y===o.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(r.sourceLineId),this.selectionGranularity="line",this.selectionAnchorLineId=r.sourceLineId,this.doubleClickPending=!0;return}if(i&&o.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.tryOpenLinkAt(r,e?.y??null)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenFileAt(r)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(r)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let c=this.wordBoundsAt(r);c!==null&&(this.setSelection({sourceLineId:r.sourceLineId,offset:c.start},{sourceLineId:r.sourceLineId,offset:c.end}),this.doubleClickPending=!0,this.selectionGranularity="word",this.selectionAnchorWordBounds={sourceLineId:r.sourceLineId,start:c.start,end:c.end})}}selectWholeSourceLine(e){let t=this.lineById(e);if(t===null)return;let r=(t.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:r})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null)return;this.extendSelectionForGesture(e);let t=this.scrollbackVisibleRows();e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=t&&this.scrollOffset>0?this.startAutoscroll(e,-1):this.stopAutoscroll()}extendSelectionForGesture(e){this.selectionGranularity==="word"?this.extendWordSelectionToCell(e):this.selectionGranularity==="line"?this.extendLineSelectionToCell(e):this.extendSelectionToCell(e)}extendWordSelectionToCell(e){if(this.selectionAnchorWordBounds===null)return;let t=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(t===null)return;let r=this.selectionAnchorWordBounds,s=this.lineIndexById(r.sourceLineId),o=this.lineIndexById(t.sourceLineId);if(s<0||o<0)return;let i=o<s||o===s&&t.offset<r.start,a=o>s||o===s&&t.offset>r.end,d={sourceLineId:r.sourceLineId,offset:r.start},c={sourceLineId:r.sourceLineId,offset:r.end};if(i){let l=this.wordBoundsAt(t);d=l!==null?{sourceLineId:t.sourceLineId,offset:l.start}:t}else if(a){let l=this.wordBoundsAt(t);c=l!==null?{sourceLineId:t.sourceLineId,offset:l.end}:t}this.selectionDragStarted=!0,this.setSelection(d,c)}extendLineSelectionToCell(e){if(this.selectionAnchorLineId===null)return;let t=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(t===null)return;let r=this.lineIndexById(this.selectionAnchorLineId),s=this.lineIndexById(t.sourceLineId);if(r<0||s<0)return;let o=s<=r?t.sourceLineId:this.selectionAnchorLineId,i=s<=r?this.selectionAnchorLineId:t.sourceLineId,a=this.lineById(i);a!==null&&(this.selectionDragStarted=!0,this.setSelection({sourceLineId:o,offset:0},{sourceLineId:i,offset:(a.body??"").length}))}extendSelectionByClick(e){if(!this.inAppSelectionEnabled||this.selection===null)return!1;let r=this.resolveEdgeSource(e.y)??this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);return r===null?!1:this.extendSelectionByClickResolved(r)}resolveEdgeSource(e){let t=this.scrollbackVisibleRows();if(t<=0||this.lines.length===0)return null;let r=this.contentWidth(),{rows:s}=this.wrapTail(r,t+this.scrollOffset),o=s.length-this.scrollOffset,i=Math.max(0,o-t),a=s.slice(i,o),d=Math.max(0,t-a.length),c=e-1,l=this.scrollOffset<this.maxScrollOffset(),u=this.scrollOffset>0,f=c<d;if(c===0&&l||f){let p=this.lines[0];if(p){let m=this.lineIds.get(p);if(m!==void 0)return{sourceLineId:m,offset:0}}}if(c>=t-1&&u){let p=this.lines[this.lines.length-1];if(p){let m=this.lineIds.get(p);if(m!==void 0)return{sourceLineId:m,offset:(p.body??"").length}}}return null}resolveNearestSource(e,t){let r=this.scrollbackVisibleRows();if(r<=0)return null;let s=Math.max(1,Math.min(this.transcriptVisibleWidth(),e));for(let o=1;o<r;o++){let i=t-o;if(i>=1){let d=this.resolveCellToSource(s,i);if(d!==null){let c=this.lineById(d.sourceLineId);return c?{sourceLineId:d.sourceLineId,offset:(c.body??"").length}:d}}let a=t+o;if(a<=r){let d=this.resolveCellToSource(s,a);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let t=this.farEndpointFrom(e);return t===null?!1:(this.selectionAnchor=t,this.selectionDragStarted=!0,this.setSelection(t,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let t=this.resolveCellToSource(e.x,e.y);t!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,t))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,t){if(this.autoscrollTimer!==null&&this.autoscrollDir===t){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=t,this.autoscrollTimer=setInterval(()=>{if(this.selectionAnchor===null||this.autoscrollCell===null){this.stopAutoscroll();return}let r=this.scrollOffset;if(this.scrollBy(this.autoscrollDir),this.scrollOffset===r){this.stopAutoscroll();return}this.extendSelectionForGesture(this.autoscrollCell)},n.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let t=this.selectionDragStarted,r=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let s=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:s?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(t||r){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let t=this.lineById(e.sourceLineId);if(t===null)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=Ug(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length,a=Math.max(0,Math.min(s.length-1,i));if(i>=s.length&&(a=s.length-1),!od.test(s[a])&&!IS.test(s[a]))return null;let d=a;for(;d>0&&IS.test(s[d-1]);)d--;let c=a+1;for(;c<s.length&&IS.test(s[c]);)c++;for(;c>d+1&&v4.test(s[c-1]);)c--;if(s.slice(d,c).includes("://")){let p=d,m=c;return this.projectCleanRangeToRaw(o,r.length,p,m)}if(!od.test(s[a]))return null;let u=a;for(;u>0&&od.test(s[u-1]);)u--;let f=a+1;for(;f<s.length&&od.test(s[f]);)f++;for(;f>u+1&&v$.test(s[f-1]);)f--;for(;u<f-1&&v$.test(s[u]);)u++;return this.projectCleanRangeToRaw(o,r.length,u,f)}projectCleanRangeToRaw(e,t,r,s){let o=t,i=t;for(let a=0;a<e.length;a++)if(e[a]===r&&o===t&&(o=a),e[a]===s&&i===t){i=a;break}return{start:o,end:i}}pathTokenAt(e){let t=this.lineById(e.sourceLineId);if(t===null||t.ansi)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=Ug(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length;if(t.links){for(let p of t.links)if(i>=p.start&&i<p.end){let m=p.url,b=m.startsWith("file://")?m.slice(7):m,g=null,h=b.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return h&&(b=h[1],g=Number.parseInt(h[2],10)),{raw:b,line:g}}}let a=Math.max(0,Math.min(s.length-1,i));if(i>=s.length&&(a=s.length-1),!xS.test(s[a]))return null;let d=a;for(;d>0&&xS.test(s[d-1]);)d--;let c=a+1;for(;c<s.length&&xS.test(s[c]);)c++;let l=s.slice(d,c);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let u=null,f=s.slice(c).match(/^:(\d+)(?::\d+)?/);return f&&(u=Number.parseInt(f[1],10)),{raw:l,line:u}}findLinkUrlAt(e){let t=this.lineById(e.sourceLineId);if(t===null||!t.links||t.ansi)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=Ug(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length;for(let a of t.links)if(i>=a.start&&i<a.end)return a.url;return null}osc8UrlFor(e){if(S$.test(e))return null;if(e.startsWith("file://"))return pl(this.sessionbar)?null:e;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))return e;if(pl(this.sessionbar))return null;let t=e.indexOf("#"),r=t===-1?e:e.slice(0,t),s=t===-1?"":e.slice(t);if(r.length===0)return null;let o=r;return r==="~"||r.startsWith("~/")?o=r==="~"?Ng():`${Ng()}/${r.slice(2)}`:Dg(r)||(o=k$(this.sessionbar.cwd,r)),Hk(o+s)}linkSpansForWindow(e,t,r,s,o){let i=G4(e),a=[];for(let d of t){let c=this.osc8UrlFor(d.url);if(c===null)continue;let l=i[d.start]??e.length,u=i[d.end]??e.length,f=Math.max(l,r),p=Math.min(u,s);p>f&&a.push({start:f-r+o,end:p-r+o,url:c})}return a.length>0?a:null}resolvePathToken(e){let t=e;(t==="~"||t.startsWith("~/"))&&(t=t==="~"?Ng():`${Ng()}/${t.slice(2)}`);let r=Dg(t)||e.startsWith("~"),s=Dg(t)?t:k$(this.sessionbar.cwd,t);if(r)return s;try{if(Cf(s).isFile())return s}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let r=t.line===null?"":`:${t.line}`;return this.tryOpenPathString(t.raw+r)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let r=t.raw;if(!S4.test(r))return!1;let s=r.startsWith(Yt)?[r]:[Yt+r,r],o=null;for(let i of s)try{if(Cf(D.sessionFile(i)).isFile()){o=i;break}}catch{}return o===null?!1:this.onHydraLinkClick(o)}dispatchLinkUrl(e){let t=e.match(S$);if(t){let o=t[1]??null;return o!==null&&this.onHydraLinkClick!==void 0?this.onHydraLinkClick(o):!1}if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)&&!e.startsWith("file://"))return!1;let r=e;if(r.startsWith("file://")){let o=r.slice(7),i=o.indexOf("/");r=i===-1?"":o.slice(i);try{r=decodeURIComponent(r)}catch{}}if(r.length===0)return!1;let s=r.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return s?this.tryOpenPathString(`${s[1]}:${s[2]}`):this.tryOpenPathString(r)}tryOpenLinkAt(e,t){let r=this.findLinkUrlAt(e);if(r!==null)return this.dispatchLinkUrl(r);let o=this.lineById(e.sourceLineId)?.links?.[0]?.url;if(o!==void 0)return this.dispatchLinkUrl(o);if(t!==null){let i=this.blockLinkUrlAt(t);if(i!==null)return this.dispatchLinkUrl(i)}return!1}reconcileWorkspacePath(e){let t=b$(D.home(),"workspaces")+Hg;if(!e.startsWith(t))return e;let s=this.sessionbar.cwd;if(s.length>0&&(e===s||e.startsWith(s+Hg)))return e;let o=!1;try{Cf(e),o=!0}catch{o=!1}if(o)return this.notify("opening a file in a workspace this session left \u2014 edits there will not reach your project",5e3),e;let i=e.slice(t.length).split(Hg).slice(2).join(Hg);if(i.length>0&&s.length>0){let a=b$(s,i);try{if(Cf(a).isFile())return this.notify("that workspace is gone \u2014 opened the file in your project instead",4e3),a}catch{}}return this.notify("that file was in a workspace that no longer exists",4e3),null}tryOpenPathString(e){if(pl(this.sessionbar))return this.notify(`can't open \u2014 this session's files are on ${this.sessionbar.remote}`,4e3),!0;if(this.openFileCommand===null)return!1;let t=e,r=null,s=e.match(/^(.*?):(\d+)(?::\d+)?$/);s&&(t=s[1],r=Number.parseInt(s[2],10));let o=this.resolvePathToken(t);if(o===null)return!1;let i=this.reconcileWorkspacePath(o);if(i===null)return!1;let a=a$(this.openFileCommand,i,r);if(a===null)return!1;let d=r===null?i:`${i}:${r}`;if(this.openFileForeground)return this.openInForeground(a,d),!0;try{let c=g4(a.program,a.args,{detached:!0,stdio:"ignore",cwd:this.spawnCwd()});c.on("error",l=>{this.notify(`open file failed: ${l.message}`)}),c.unref(),this.notify(`opening ${d}`)}catch(c){this.notify(`open file failed: ${c.message}`)}return!0}spawnCwd(){let e=this.sessionbar.cwd;if(!(!e||!Dg(e)))try{return Cf(e).isDirectory()?e:void 0}catch{return}}openInForeground(e,t){this.foregroundChildActive||(this.foregroundChildActive=!0,this.runForeground({program:e.program,args:e.args,cwd:this.spawnCwd(),banner:`\u2500 ${e.program} ${t} \u2014 quit the editor to return to hydra \u2500
272
- `},{suspend:()=>this.stop(),resume:()=>this.start(),notify:r=>this.notify(r)}).finally(()=>{this.foregroundChildActive=!1}))}schedulePendingBlockClick(e,t,r){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,t,r);return}this.cancelPendingBlockClick();let s=this.onBlockClick,o=setTimeout(()=>{this.pendingBlockClick=null,s(e,t,r)},wl);typeof o.unref=="function"&&o.unref(),this.pendingBlockClick={timer:o,key:e,rowOffset:t,subKey:r}}cancelPendingBlockClick(){this.pendingBlockClick!==null&&(clearTimeout(this.pendingBlockClick.timer),this.pendingBlockClick=null)}flushPendingBlockClick(){let e=this.pendingBlockClick;e!==null&&(clearTimeout(e.timer),this.pendingBlockClick=null,this.onBlockClick&&this.onBlockClick(e.key,e.rowOffset,e.subKey))}lineById(e){for(let t of this.lines)if(this.lineIds.get(t)===e)return t;return null}lineIndexById(e){for(let t=0;t<this.lines.length;t++){let r=this.lines[t];if(r&&this.lineIds.get(r)===e)return t}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&ml(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let r=e.length;this.notify(`copied ${r} char${r===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${t.reason}`)},t=>{this.notify(`clipboard copy failed: ${t.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let t=e,r=Number(t.x),s=Number(t.y);return!Number.isFinite(r)||!Number.isFinite(s)?null:{x:r,y:s}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,be(e==="pointer"?TP:Ym))}blockLinkUrlAt(e){let t=this.keyAtRow(e);if(t===null||t.startsWith("agent:"))return null;let r=this.contentWidth(),s=1,o=this.scrollbackVisibleRows();if(o<=0)return null;let{rows:i}=this.wrapTail(r,o+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-o),c=i.slice(d,a),l=Math.max(0,o-c.length),u=e-s-l,f=d+u,p=null,m=1/0;for(let b=0;b<i.length;b++){let g=i[b];if(g.blockKey!==t||g.linkSpans===void 0||g.linkSpans.length===0)continue;let h=Math.abs(b-f);h<m&&(m=h,p=g.linkSpans[0]?.url??null)}return p}keyAtRow(e){let t=this.contentWidth(),r=1,s=this.scrollbackVisibleRows();if(s<=0)return null;let o=e-r;if(o<0||o>=s)return null;let{rows:i}=this.wrapTail(t,s+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-s),c=i.slice(d,a),l=Math.max(0,s-c.length),u=o-l;return u<0||u>=c.length?null:c[u]?.blockKey??null}nearestKeyAboveRow(e){for(let t=e-1;t>=1;t--){let r=this.keyAtRow(t);if(r!==null)return r}return null}nearestKeyBelowRow(e){let r=this.scrollbackVisibleRows();for(let s=e+1;s<=r;s++){let o=this.keyAtRow(s);if(o!==null)return o}return null}keyAndSubAtRow(e){let t=this.contentWidth(),r=1,s=this.scrollbackVisibleRows();if(s<=0)return null;let o=e-r;if(o<0||o>=s)return null;let{rows:i}=this.wrapTail(t,s+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-s),c=i.slice(d,a),l=Math.max(0,s-c.length),u=o-l;if(u<0||u>=c.length)return null;let f=c[u];return f?.blockKey?{key:f.blockKey,sub:f.hoverSubKey??null}:null}resolveCellToSource(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return null;let r=this.contentWidth(),s=1,o=this.scrollbackVisibleRows();if(o<=0)return null;let i=t-s;if(i<0||i>=o||e<1||e>this.transcriptVisibleWidth())return null;let{rows:a}=this.wrapTail(r,o+this.scrollOffset),d=a.length-this.scrollOffset,c=Math.max(0,d-o),l=a.slice(c,d),u=Math.max(0,o-l.length),f=i-u;if(f<0||f>=l.length)return null;let p=l[f];if(!p)return null;let m=this.wrapOrigin.get(p);if(!m)return null;let b=$t(p.prefix??""),g=m.bodyDisplayShift??0,h=e-1-b;if(h<g)return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset};let y=h,S=Af(p.bodyStyle)||p.ansi===!0?o$(LS(p.body),y):s$(p.body,y);if(m.sourceColEnd!==void 0){let I=this.sourceBodyForId(m.sourceLineId);if(I!==null){let x=MS(p.body,g,S),C=_S(I,m.sourceColOffset,x);return{sourceLineId:m.sourceLineId,offset:C}}}return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset+S-g}}scrollBy(e){if(e===0)return;this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=this.maxScrollOffset(),r=Math.min(t,Math.max(0,this.scrollOffset+e));r!==this.scrollOffset&&(this.scrollOffset=r,this.repaint())}scrollToBottom(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}scrollToPrevTurn(){if(this.pageWhenNoTurns(1))return;let e=this.turnStops(),t=this.settledScrollOffset(),r=e.find(s=>s>t);this.stepToTurnStop(r??this.maxScrollOffset())}scrollToNextTurn(){if(this.pageWhenNoTurns(-1))return;let e=this.turnStops(),t=this.settledScrollOffset(),r=0;for(let s of e){if(s>=t)break;r=s}this.stepToTurnStop(r)}pageWhenNoTurns(e){return this.turnScrollOffsets().length>0?!1:(this.scrollBy(e*this.scrollPageSize()),!0)}settledScrollOffset(){return this.slideTimer!==null?this.slideTarget:this.scrollOffset}stepToTurnStop(e){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.slideScrollTo(e),this.notifyTurnPosition(e)}turnStops(){let e=this.maxScrollOffset(),t=[0,...this.turnScrollOffsets(),e].filter(r=>r>=0&&r<=e).sort((r,s)=>r-s);return t.filter((r,s)=>s===0||r!==t[s-1])}notifyTurnPosition(e){let t=this.turnScrollOffsets();if(t.length===0)return;let r=t.findIndex(o=>o>=e),s=r===-1?1:t.length-r;this.notify(`turn ${s}/${t.length}`,1500)}turnScrollOffsets(){return this.turnAnchors().map(e=>e.offset)}turnAnchors(){let e=this.contentWidth(),t=this.scrollbackVisibleRows();if(t<=0)return[];let r=[],s=0,o=null;for(let i=this.lines.length-1;i>=0;i--){let a=this.lines[i];if(!(!a||this.isHiddenLine(a))){if(s+=this.wrapOne(a,e).length,a.bodyStyle==="user"){o={offset:Math.max(0,s-t),lineIndex:i,recordedAt:a.recordedAt};continue}o!==null&&(r.push(o),o=null)}}return o!==null&&r.push(o),r}scrollToTurnAt(e){let t=this.turnAnchors();if(t.length===0)return;let r=t.find(s=>s.recordedAt!==void 0&&s.recordedAt<=e)??t[t.length-1];this.setScrollOffset(r.offset),this.notifyTurnPosition(r.offset)}slideScrollTo(e){this.cancelSlide();let t=Math.min(this.maxScrollOffset(),Math.max(0,e)),r=Math.abs(t-this.scrollOffset);if(r!==0){if(r<=N4||!this.slideEnabled){this.setScrollOffset(t);return}this.slideTarget=t,this.slideTimer=setInterval(()=>{let s=this.slideTarget-this.scrollOffset,o=Math.sign(s)*Math.max(1,Math.round(Math.abs(s)*L4)),i=Math.abs(s)<=Math.abs(o)?this.slideTarget:this.scrollOffset+o;this.scrollOffset=i,this.syncedPartialRepaint(()=>this.drawScrollback()),i===this.slideTarget&&this.cancelSlide()},F4)}}cancelSlide(e=!1){this.slideTimer!==null&&(clearInterval(this.slideTimer),this.slideTimer=null,e&&this.scrollOffset!==this.slideTarget&&(this.scrollOffset=Math.min(this.maxScrollOffset(),Math.max(0,this.slideTarget)),this.syncedPartialRepaint(()=>this.drawScrollback())))}setScrollOffset(e){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=Math.min(this.maxScrollOffset(),Math.max(0,e));t!==this.scrollOffset&&(this.scrollOffset=t,this.repaint())}isScrolledBack(){return this.scrollOffset>0}isScrollbackSearchActive(){return this.scrollbackSearch!==null}enterScrollbackSearch(){this.scrollbackSearch===null&&(this.scrollbackSearch={term:"",matchIndex:0,matches:[],baselineScroll:this.scrollOffset},this.scrollbackHighlight=null,this.repaint())}updateScrollbackSearchTerm(e){if(this.scrollbackSearch===null)return;let t=e.toLowerCase(),r=[];if(t.length>0)for(let s=this.lines.length-1;s>=0;s--){let o=this.lines[s];if(!o||o.body.length===0||o.ansi)continue;let i=P$(o.body,t);for(let a=i.length-1;a>=0;a--)r.push({lineIdx:s,col:i[a].start})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=r,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=t.length>0?t:null,r.length>0&&this.scrollToMatch(r[0]),this.repaint()}advanceScrollbackSearch(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return;let e=Math.min(this.scrollbackSearch.matches.length-1,this.scrollbackSearch.matchIndex+1);e!==this.scrollbackSearch.matchIndex&&(this.scrollbackSearch.matchIndex=e,this.scrollToMatch(this.scrollbackSearch.matches[e]),this.repaint())}retreatScrollbackSearch(){this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0||this.scrollbackSearch.matchIndex!==0&&(this.scrollbackSearch.matchIndex-=1,this.scrollToMatch(this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex]),this.repaint())}acceptScrollbackSearch(){this.scrollbackSearch!==null&&(this.scrollbackSearch=null,this.scrollbackHighlight=null,this.repaint())}cancelScrollbackSearch(){if(this.scrollbackSearch===null)return;let e=this.scrollbackSearch.baselineScroll;this.scrollbackSearch=null,this.scrollbackHighlight=null,this.scrollOffset=e,this.repaint()}scrollbackSearchTerm(){return this.scrollbackSearch?.term??""}currentMatchInfo(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return null;let e=this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex];if(!e)return null;let t=this.lines[e.lineIdx];if(!t)return null;let r=this.lineIds.get(t);return r===void 0?null:{lineId:r,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,t){if(!e||t===null)return null;let r=this.wrapOrigin.get(e);if(!r||r.sourceLineId!==t.lineId)return null;let s=r.bodyDisplayShift??0,o=t.col-r.sourceColOffset+s;return o<s||o>=e.body.length?null:o}scrollToMatch(e){let t=this.contentWidth(),r=this.scrollbackVisibleRows();if(r<=0)return;let s=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(s+=this.wrapOne(u,t).length)}let o=this.lines[e.lineIdx],i=0;if(o){let l=this.wrapOne(o,t),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let m=p.body.length;if(e.col<u+m){i=l.length-1-f;break}u+=m}}let a=s+i,d=Math.max(0,a-Math.floor(r/2)),c=this.maxScrollOffset();this.scrollOffset=Math.min(c,d)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let t=this.term.height-this.promptRows()-Ot-Ut-Bt-x4-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,t-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.contentWidth(),Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){this.scheduler.schedule()}paintRow(e,t,r,s){return this.started?this.painter.paintRow(e,t,r,s):!1}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,t=this.term.height;e<20||t<8||(this.painter.ensureSize(e,t),this.barHits.clear(),mt(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawSidebar(1,this.scrollbackVisibleRows()),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let r=this.promptRows(),s=t-r-Bt-Ut-Ot;this.drawBar("composerTop",s),this.drawPrompt(),this.drawBar("composerBottom",t-Ot),this.drawBar("sessionbar",this.term.height),this.placeCursor(),(this.permissionPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=r}))}barContext(){return{scope:"session",session:this.sessionbar,banner:this.banner,scrollOffset:this.scrollOffset,transient:this.bannerRightContent(),hovered:this.terminalFocused?this.hoveredBarHit:null,hintsRevealed:this.hintsRevealed(),scriptOutputs:this.scriptOutputs}}trackHintHover(e){return e?(this.cancelHintHoverHide(),this.hintHoverReveal?!1:(this.hintHoverReveal=!0,!0)):(!this.hintHoverReveal||this.hintHoverHideTimer!==null||(this.hintHoverHideTimer=setTimeout(()=>{this.hintHoverHideTimer=null,this.hintHoverReveal=!1,this.syncedPartialRepaint(()=>this.drawBars())},k4)),!1)}cancelHintHoverHide(){this.hintHoverHideTimer!==null&&(clearTimeout(this.hintHoverHideTimer),this.hintHoverHideTimer=null)}hintsRevealed(){return this.terminalFocused?this.hintHoverReveal||this.hintKeyReveal:!1}revealHints(){this.hintKeyReveal||(this.hintKeyReveal=!0,this.syncedPartialRepaint(()=>this.drawBars()))}clearHintReveal(){this.cancelHintHoverHide(),!(!this.hintKeyReveal&&!this.hintHoverReveal)&&(this.hintKeyReveal=!1,this.hintHoverReveal=!1,this.syncedPartialRepaint(()=>this.drawBars()))}btwContext(){let e=this.btwOverlayStatus==="busy"?"busy":this.btwOverlayStatus==="done"?"ready":"disconnected";return{scope:"btw",statusLabel:"By the way",session:{...this.sessionbar,sessionId:this.btwOverlaySessionId??"",...this.btwOverlayUsage!==void 0?{usage:this.btwOverlayUsage}:{usage:void 0}},banner:{status:e,currentMode:void 0,hint:[],queued:0},scrollOffset:0,transient:null,hovered:this.terminalFocused?this.hoveredBarHit:null,hintsRevealed:!1,scriptOutputs:this.scriptOutputs}}drawBar(e,t){let r=Xv[e],s=e==="sessionbar"?Math.max(1,this.term.width-1):this.term.width,o=e==="sessionbar"?this.barConfig.sessionbar:e==="composerBottom"?this.barConfig.composer.bottom:this.barConfig.composer.top;e==="composerBottom"&&(this.composerBottomRow=t);let i=e==="btw"?this.btwContext():this.barContext(),a=e==="composerBottom"?v_(i):null,d=a!==null?[a]:kf(e,o.right,i),c=Jv(s,kf(e,o.left,i),d,r);e==="composerBottom"&&(this.hintZoneStart=this.hintZoneStartFor(s,o,i,a,c));let l=this.terminalFocused?this.hoveredBarHit:null,u=`${e}|${s}|${l??""}|${c.signature}`;this.paintRow(t,u,()=>{for(let f of c.chunks){let p=f.id!==void 0&&f.id===l?"hint-hover":f.token;H(this.term,p,f.text)}}),this.barHits.set(t,c.hits)}hintZoneStartFor(e,t,r,s,o){if(s!==null)return null;if(r.hintsRevealed)return o.rightStart;let i={...r,hintsRevealed:!0};return Jv(e,kf("composerBottom",t.left,i),kf("composerBottom",t.right,i),Xv.composerBottom).rightStart}barHitAt(e,t){let r=this.barHits.get(t);return r===void 0?null:r.find(s=>e>=s.start&&e<=s.end)??null}bannerHitAt(e,t){let r=this.barHitAt(e,t);if(r===null)return null;let s=r.id.slice(r.id.indexOf(":")+1);return Dv.some(o=>o.id===s)?s:null}stepFormCursor(e){let t=this.formPrompt;if(t===null||t.rows.length===0)return;let r=Math.max(0,Math.min(t.rows.length-1,t.selectedIndex+e));r!==t.selectedIndex&&this.onFormClick?.({kind:"row",row:r,select:!0})}isFormCell(e){let t=this.formRegion;return this.formPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}formHitAt(e,t){if(!this.isFormCell(t))return null;for(let s of this.formHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.formRowHits.get(t);if(r===void 0)return null;if(r.field!==void 0&&e>=r.field.startCol){let{slice:s,sliceStart:o,startCol:i}=r.field,a=o,d=i;for(let c of s){let l=d+$t(c);if(e<l)break;d=l,a+=c.length}return{kind:"row",row:r.row,caretOffset:a}}return{kind:"row",row:r.row}}handleFormPress(e){return this.isFormCell(e.y)?(this.formPressHit=this.formHitAt(e.x,e.y),!0):(this.formPressHit=null,!1)}handleFormRelease(e){let t=this.formPressHit;if(this.formPressHit=null,t===null||e===null||!this.isFormCell(e.y))return t!==null;let r=this.formHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="row"&&t.kind==="row"&&r.row!==t.row||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action||this.onFormClick?.(r),!0}handleBarPress(e){let t=this.barHitAt(e.x,e.y);if(t===null)return this.barPressHit=null,!1;let r=Date.now(),s=this.lastBarClick;return s!==null&&s.id===t.id&&r-s.t<=wl&&t.doubleAction!=="none"?(this.lastBarClick=null,this.barPressHit=null,this.dispatchBarAction(t.doubleAction,t.value),!0):(this.lastBarClick={id:t.id,t:r},this.barPressHit=t,!0)}handleBarRelease(e){let t=this.barPressHit;if(this.barPressHit=null,t===null||e===null)return!1;let r=this.barHitAt(e.x,e.y);return r===null||r.id!==t.id?!1:(r.action==="none"||this.dispatchBarAction(r.action,r.value),!0)}dispatchBarAction(e,t){if(e!=="none"){if(e==="copy"){ml(t,{target:this.selectionClipboard}).then(r=>{this.notify(r.ok?`copied ${t}`:`clipboard copy failed: ${r.reason}`)},r=>{this.notify(`clipboard copy failed: ${r.message}`)});return}if(e==="open-session"){this.onHydraLinkClick?.(t);return}if(e==="open"){this.tryOpenPathString(t)||this.notify(this.hasOpenFileCommand()?`can't open ${t}`:"no tui.openFileCommand configured");return}this.onBarAction?.(e,t)}}drawScrollback(){let e=this.contentWidth(),t=this.sidebarReserved()>0&&!this.sidebarOverlay(),r=this.sidebarBodyWidth()>0,s=1,o=this.scrollbackVisibleRows();if(o<=0)return;let{rows:i,exhausted:a}=this.wrapTail(e,o+this.scrollOffset);if(a){let g=Math.max(0,i.length-o);this.scrollOffset>g&&(this.scrollOffset=g)}let d=i.length-this.scrollOffset,c=Math.max(0,d-o),l=i.slice(c,d),u=Math.max(0,o-l.length),f=this.currentMatchInfo(),p=f?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let m=-1,b=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let g=0;g<l.length;g++){let h=l[g]?.blockKey;h===void 0||!(h===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(h))||(m===-1&&(m=g),b=g)}for(let g=0;g<o;g++){let h=s+g,y=g-u,k=y>=0?l[y]:void 0,S=this.activeMatchCol(k,f),I=k?this.selectionRangeForChunk(k):null,x=k!==void 0&&k.blockKey!==void 0&&(k.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(k.blockKey)),C=k!==void 0&&k.blockKey===void 0&&m!==-1&&y>=m&&y<=b,$=x||C,E=this.terminalFocused&&$&&(this.hoveredSubKey===null||(k.hoverSubKey??null)===this.hoveredSubKey),M=PS("sb",e,k,this.scrollbackHighlight,S,I)+(E?"|H":"");this.paintRow(h,M,()=>{k?this.writeFormattedLine(k,e,S,p,I,E,t,k.linkSpans??null):t&&this.term(" ".repeat(e))},t?{erase:!1}:void 0)&&r&&this.painter.invalidate("sidebar",h)}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let g=new Set;for(let y of l)y.blockKey!==void 0&&g.add(y.blockKey);let h=[];for(let y of this.pendingVisibleKeys)g.has(y)&&h.push(y);for(let y of h)this.pendingVisibleKeys.delete(y),this.onBlockVisible(y)}}drawSidebar(e,t){let r=this.sidebarBodyWidth();if(r<=0||t<=0){this.sidebarOverflowRows=0;return}let s=this.sidebarColumnStart(),o={metrics:{cellWidth:$t,truncate:mn},width:r,border:this.sidebarBorder,pages:this.sidebarPages,collapsed:this.sidebarCollapsed,maxRows:t},i={...this.sidebarSnapshot,now:Date.now()},a=this.sidebarRenderer.render(i,o);this.sidebarOverflowRows=Math.max(0,a.length-t),this.sidebarScrollOffset>this.sidebarOverflowRows&&(this.sidebarScrollOffset=this.sidebarOverflowRows);let d=this.sidebarScrollOffset;this.sidebarRowPaths.clear(),this.sidebarRowDoubleActions.clear(),this.sidebarRowActions.clear(),this.sidebarRowLinks.clear();let c=s+Rf;for(let l=0;l<t;l++){let u=e+l,f=l+d,p=a[f];p?.openPath!==void 0&&this.sidebarRowPaths.set(u,p.openPath),p?.doubleAction!==void 0&&this.sidebarRowDoubleActions.set(u,p.doubleAction),p?.links!==void 0&&p.links.length>0&&this.sidebarRowLinks.set(u,p.links.map(h=>({start:c+h.start,end:c+h.end,url:h.url}))),p?.actions!==void 0&&p.actions.length>0&&this.sidebarRowActions.set(u,p.actions.map(h=>({start:c+h.start-1,end:c+h.end-1,..."page"in h?{gadget:h.page.gadget,index:h.page.index}:{gadget:h.collapse.gadget,collapse:!0}})));let m=l===0&&d>0?"\u25B2":l===t-1&&d<this.sidebarOverflowRows?"\u25BC":p?.gutter??" ",b=(()=>{let h=[];if(p?.openPath!==void 0&&p.openPath.startsWith("/")&&p.openSpan!==void 0&&h.push({...p.openSpan,url:Hk(p.openPath)}),p?.links!==void 0){let y=this.linkSpansForWindow(p.body,p.links,0,p.body.length,0);y!==null&&h.push(...y)}return h.length>0?h:null})(),g=PS("sbar",r,p,null,null,null)+`|${m}|${b===null?"":b.map(h=>`${h.start}:${h.end}:${h.url}`).join(",")}`;this.paintRow(u,g,()=>{this.term(" ".repeat(Math.max(0,Rf-1))),m===" "?this.term(" "):mo(this.term,m,"sidebar-rule",!1),p?this.writeFormattedLine(p,r,null,0,null,!1,!0,b):this.term(" ".repeat(r))},{region:"sidebar",column:s})}}scrollSidebarBy(e){if(this.sidebarOverflowRows<=0)return!1;let t=Math.max(0,Math.min(this.sidebarOverflowRows,this.sidebarScrollOffset-e));return t===this.sidebarScrollOffset||(this.sidebarScrollOffset=t,this.repaintNow()),!0}sidebarPageState(){return this.sidebarPages}sidebarScrollState(){return{offset:this.sidebarScrollOffset,overflow:this.sidebarOverflowRows}}isSidebarCell(e,t){let r=this.sidebarColumnStart();return r===0?!1:e>=r&&e<=(this.term.width||0)&&t>=1&&t<=this.scrollbackVisibleRows()}handleSidebarPress(e){if(e===null||!this.isSidebarCell(e.x,e.y))return!1;for(let o of this.sidebarRowActions.get(e.y)??[])if(!(e.x<o.start||e.x>o.end))return o.collapse===!0?this.toggleSidebarGadgetCollapsed(o.gadget):this.sidebarPages={...this.sidebarPages,[o.gadget]:o.index??0},this.lastSidebarClick=null,this.repaintNow(),!0;let t=Date.now(),r=this.lastSidebarClick;if(r!==null&&t-r.t<=wl&&e.y===r.y){this.lastSidebarClick=null;let o=this.sidebarRowDoubleActions.get(e.y);if(o!==void 0)return this.dispatchBarAction(o.action,o.value),!0;let a=this.sidebarRowLinks.get(e.y)?.find(c=>e.x>=c.start&&e.x<c.end);if(a!==void 0)return this.dispatchLinkUrl(a.url),!0;let d=this.sidebarRowPaths.get(e.y);return d!==void 0&&!this.dispatchLinkUrl(d)&&this.notify(this.hasOpenFileCommand()?`can't open ${d}`:"no tui.openFileCommand configured"),!0}return this.lastSidebarClick={x:e.x,y:e.y,t},!0}hasOpenFileCommand(){return this.openFileCommand!==null}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(RS,this.queuedTexts.length)}chipRows(){return Math.min(TS,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((t,r)=>t===e[r])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(AS,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),s=this.term.height-r-Ot-Ut-Bt,o=this.queuedRows(),i=this.chipRows(),d=s-1-o-i-e+1,c=0;for(let l of this.completions.slice(0,e))l.name.length>c&&(c=l.name.length);for(let l=0;l<e;l++){let u=d+l,f=this.completions[l],p=l===e-1&&this.completions.length>AS,m=this.completions.length-AS+1,b=f?p?`comp|${t}|overflow|${m}`:`comp|${t}|${c}|${f.name}|${f.description??""}`:`comp|${t}|empty`;this.paintRow(u,b,()=>{if(!f)return;if(p){H(this.term,"modal-hint",` + ${m} more match(es)`);return}let g=f.name.padEnd(c),h=f.description??"",y=t-g.length-4,k=y>0?mn(h,y):"";this.term.noFormat(" "),H(this.term,"completion-name",g),k.length>0&&(this.term.noFormat(" "),H(this.term,"completion-desc",k))})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),i=this.term.height-r-Ot-Ut-Bt-1-e+1;for(let a=0;a<e;a++){let d=i+a,c=a===e-1&&this.attachments.length>TS,l=this.attachments.length-TS,u=this.attachments[a],f=u?`${u.name??"image"} \xB7 ${zr(u.sizeBytes)}`:"",p=c?`chip|${t}|overflow|${l}`:u?`chip|${t}|${f}`:`chip|${t}|empty`;this.paintRow(d,p,()=>{if(c){H(this.term,"modal-hint",` \u{1F4CE} + ${l+1} more attached`);return}u&&(this.term.noFormat(" "),H(this.term,"attachment",`\u{1F4CE} ${f}`))})}}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),s=this.term.height-r-Ot-Ut-Bt,o=this.chipRows(),a=s-1-o-e+1,d=this.dispatcher.state().queueIndex;for(let c=0;c<e;c++){let l=a+c,u=this.queuedTexts[c],f=c===e-1&&this.queuedTexts.length>RS,p=this.queuedTexts.length-RS,m=u===void 0?"":f?`+ ${p+1} more queued`:mn(sJ(u),t-4),b=!f&&c===d,g=u===void 0?`queued|${t}|empty`:`queued|${t}|${b?"edit":f?"ovf":"row"}|${m}`;this.paintRow(l,g,()=>{if(u===void 0)return;let h=`\u23F3 ${m}`,y=h+" ".repeat(Math.max(0,t-1-h.length));b?H(this.term,"queue-cursor","\u25B8"):H(this.term,"queue-blank"," "),H(this.term,"queue-row",y)})}}promptVisualLayout(){if(this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt||this.scrollbackSearch||this.readonly)return null;let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=Cs(r.buffer,t),o=go(s,r,Bg);return{top:this.term.height-o.rendered-Bt-Ut-Ot+1,layout:o,visualRows:s}}resolveCellToPromptOffset(e,t){let r=this.promptVisualLayout();if(r===null)return null;let{top:s,layout:o,visualRows:i}=r,a=t-s;if(a<0||a>=o.rendered||e<1||e>this.term.width)return null;let d=i[o.windowStart+a];if(!d)return null;let l=Math.max(0,Math.min(d.endCol-d.startCol,e-1-2));return{row:d.bufferIdx,col:d.startCol+l}}setPromptSelection(e,t){let r=e.row<t.row||e.row===t.row&&e.col<=t.col,s=r?e:t,o=r?t:e;if(s.row===o.row&&s.col===o.col){this.clearPromptSelection();return}let i={startRow:s.row,startCol:s.col,endRow:o.row,endCol:o.col},a=this.promptSelection;a&&a.startRow===i.startRow&&a.startCol===i.startCol&&a.endRow===i.endRow&&a.endCol===i.endCol||(this.promptSelection=i,this.syncedPartialRepaint(()=>this.drawPrompt()))}clearPromptSelection(){this.promptSelection!==null&&(this.promptSelection=null,this.syncedPartialRepaint(()=>this.drawPrompt()))}getPromptSelectionText(){if(this.promptSelection===null)return"";let{startRow:e,startCol:t,endRow:r,endCol:s}=this.promptSelection,o=this.dispatcher.state().buffer;if(e===r)return(o[e]??"").slice(t,s);let i=[(o[e]??"").slice(t)];for(let a=e+1;a<r;a++)i.push(o[a]??"");return i.push((o[r]??"").slice(0,s)),i.join(`
273
- `)}promptWordBoundsAt(e){let t=this.dispatcher.state().buffer[e.row]??"";if(t.length===0)return null;let r=Math.max(0,Math.min(t.length-1,e.col));if(!od.test(t[r]))return null;let s=r;for(;s>0&&od.test(t[s-1]);)s--;let o=r+1;for(;o<t.length&&od.test(t[o]);)o++;return{start:s,end:o}}selectPromptWholeLine(e){let t=this.dispatcher.state().buffer[e]??"";this.setPromptSelection({row:e,col:0},{row:e,col:t.length})}extendPromptWordSelectionTo(e){let t=this.promptSelectionAnchorWordBounds;if(t===null)return;let r=e.row<t.row||e.row===t.row&&e.col<t.start,s=e.row>t.row||e.row===t.row&&e.col>t.end,o={row:t.row,col:t.start},i={row:t.row,col:t.end};if(r){let a=this.promptWordBoundsAt(e);o=a!==null?{row:e.row,col:a.start}:e}else if(s){let a=this.promptWordBoundsAt(e);i=a!==null?{row:e.row,col:a.end}:e}this.setPromptSelection(o,i)}extendPromptLineSelectionTo(e){let t=this.promptSelectionAnchorLineRow;if(t===null)return;let r=Math.min(t,e.row),s=Math.max(t,e.row),o=this.dispatcher.state().buffer[s]??"";this.setPromptSelection({row:r,col:0},{row:s,col:o.length})}handlePromptSelectionPress(e){if(!this.inAppSelectionEnabled)return!1;let t=this.resolveCellToPromptOffset(e.x,e.y);if(t===null)return!1;this.promptSelectionAnchor=t,this.promptSelectionDragStarted=!1,this.promptDoubleClickPending=!1,this.promptPendingClickCount=1,this.promptSelectionGranularity="char",this.promptSelectionAnchorWordBounds=null,this.promptSelectionAnchorLineRow=null,this.clearPromptSelection();let r=Date.now(),s=this.promptLastLeftClick,o=s!==null&&r-s.t<=wl&&Math.abs(e.x-s.x)<=bl&&Math.abs(e.y-s.y)<=bl&&s.row!==null&&s.row===t.row;if(o&&s.count===2&&e.x===s.x&&e.y===s.y)return this.promptPendingClickCount=3,this.selectPromptWholeLine(t.row),this.promptSelectionGranularity="line",this.promptSelectionAnchorLineRow=t.row,this.promptDoubleClickPending=!0,!0;if(o&&s.count===1){this.promptPendingClickCount=2;let d=this.promptWordBoundsAt(t);d!==null&&(this.setPromptSelection({row:t.row,col:d.start},{row:t.row,col:d.end}),this.promptDoubleClickPending=!0,this.promptSelectionGranularity="word",this.promptSelectionAnchorWordBounds={row:t.row,start:d.start,end:d.end})}return!0}handlePromptSelectionDrag(e){if(this.promptSelectionAnchor===null)return;let t=this.promptVisualLayout();if(t===null)return;let r=Math.max(1,Math.min(this.term.width,e.x)),s=Math.max(t.top,Math.min(t.top+t.layout.rendered-1,e.y)),o=this.resolveCellToPromptOffset(r,s);o!==null&&(this.promptSelectionDragStarted=!0,this.promptSelectionGranularity==="word"?this.extendPromptWordSelectionTo(o):this.promptSelectionGranularity==="line"?this.extendPromptLineSelectionTo(o):this.setPromptSelection(this.promptSelectionAnchor,o))}handlePromptSelectionRelease(e){let t=this.promptSelectionDragStarted,r=this.promptDoubleClickPending;if(this.promptSelectionAnchor=null,this.promptSelectionDragStarted=!1,this.promptDoubleClickPending=!1,e!==null){let s=this.resolveCellToPromptOffset(e.x,e.y);this.promptLastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.promptPendingClickCount,row:s?.row??null}}if(this.promptPendingClickCount=1,t||r){this.finalizePromptSelection();return}this.clearPromptSelection()}finalizePromptSelection(){let e=this.getPromptSelectionText();e.length!==0&&ml(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let r=e.length;this.notify(`copied ${r} char${r===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${t.reason}`)},t=>{this.notify(`clipboard copy failed: ${t.message}`)})}drawPrompt(){if((this.permissionPrompt||this.formPrompt||this.confirmPrompt)&&(this.compactionRegion=null),(this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.compactionPrompt)&&(this.helpRegion=null),this.permissionPrompt){this.drawPermissionPrompt();return}if(this.formPrompt){this.drawFormPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.compactionPrompt){this.drawCompactionPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=Cs(r.buffer,t),o=go(s,r,Bg),i=this.term.height-o.rendered-Bt-Ut-Ot+1,a=!1;for(let d=0;d<o.rendered;d++){let c=s[o.windowStart+d],l=i+d,u="wrap",f="";c&&(c.bufferIdx===0&&c.startCol===0?u="first":c.startCol===0&&(u="newline"),f=(r.buffer[c.bufferIdx]??"").slice(c.startCol,c.endCol));let p=-1,m=-1;if(c&&this.promptSelection!==null){let g=this.promptSelection;if(c.bufferIdx>=g.startRow&&c.bufferIdx<=g.endRow){let h=c.bufferIdx===g.startRow?g.startCol:c.startCol,y=c.bufferIdx===g.endRow?g.endCol:c.endCol,k=Math.max(h,c.startCol),S=Math.min(y,c.endCol);S>k&&(p=k-c.startCol,m=S-c.startCol)}}let b=c?`prompt|${this.term.width}|${u}|${f}|${p}:${m}`:`prompt|${this.term.width}|empty`;this.paintRow(l,b,()=>{c&&(u==="first"?a?H(this.term,"composer-inactive","> "):H(this.term,"composer-gutter","> "):u==="newline"?H(this.term,"composer-continuation","\xB7 "):this.term(" "),a?H(this.term,"composer-inactive",f):p>=0&&m>p?(p>0&&H(this.term,"content",f.slice(0,p)),H(this.term,"selection-highlight",f.slice(p,m)),m<f.length&&H(this.term,"content",f.slice(m))):H(this.term,"content",f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let t=this.term.width,r=this.term.height-ES-Bt-Ut-Ot+1;this.paintRow(r,`confirm|q|${t}|${e.question}`,()=>{H(this.term,"prompt-text",` ? ${mn(e.question,t-4)}`)}),this.paintRow(r+1,`confirm|h|${t}|${e.hint}`,()=>{H(this.term,"modal-hint",` ${mn(e.hint,t-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let t=this.term.width,r=this.compactionRows(),s=this.term.height-r-Bt-Ut-Ot+1,o=s;this.compactionRowHits.clear(),this.compactionHintHits=[],this.compactionRegion={top:s,bottom:s+r-1};let i=(c,l)=>{o>=s+r||(this.paintRow(o,c,l),o+=1)};i(`cpct|msg|${t}|${e.message}`,()=>{H(this.term,"prompt-text",` ${mn(e.message,t-2)}`)}),i(`cpct|q|${t}`,()=>{H(this.term,"content"," Compact now to reduce future per-turn token cost?")});for(let c=0;c<e.options.length&&!(o>=s+r-1);c++){let l=e.options[c];if(!l)continue;let u=c===e.selectedIndex,p=` ${u?"\u276F":" "} ${c+1}. ${mn(l.label,t-8)}`;this.compactionRowHits.set(o,c),i(`cpct|o|${t}|${c}|${u?"1":"0"}|${l.label}`,()=>{u?H(this.term,"modal-option-selected",p):H(this.term,"modal-option",p)})}let a=$S(P4,t),d=o;for(let c of a.spans)(c.action==="commit"||c.action==="cancel")&&this.compactionHintHits.push({row:d,start:c.start,end:c.end,action:c.action});i(`cpct|hint|${t}|${a.text}`,()=>{H(this.term,"modal-hint",` ${a.text}`)})}isCompactionCell(e){let t=this.compactionRegion;return this.compactionPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}compactionHitAt(e,t){if(!this.isCompactionCell(t))return null;for(let s of this.compactionHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.compactionRowHits.get(t);return r===void 0?null:{kind:"option",index:r}}stepCompactionCursor(e){let t=this.compactionPrompt;if(t===null||t.options.length===0)return;let r=Math.max(0,Math.min(t.options.length-1,t.selectedIndex+e));r!==t.selectedIndex&&this.onCompactionClick?.({kind:"option",index:r,select:!0})}handleCompactionPress(e){return this.isCompactionCell(e.y)?(this.compactionPressHit=this.compactionHitAt(e.x,e.y),!0):(this.compactionPressHit=null,!1)}handleCompactionRelease(e){let t=this.compactionPressHit;if(this.compactionPressHit=null,t===null||e===null||!this.isCompactionCell(e.y))return t!==null;let r=this.compactionHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="option"&&t.kind==="option"&&r.index!==t.index||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action?!0:Date.now()-this.compactionArmedAt<I$?(this.notify("compaction prompt just appeared, click again to confirm"),!0):(this.onCompactionClick?.(r),!0)}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let t=this.term.width,r=this.helpRows(),s=this.term.height-r-Bt-Ut-Ot+1,o=s;this.helpRegion={top:s,bottom:s+r-1};let i=(d,c)=>{o>=s+r||(this.paintRow(o,d,c),o+=1)};i(`help|t|${t}|${e.title}`,()=>{H(this.term,"prompt-text",` \u2753 ${mn(e.title,t-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(d=>d===null?0:d[0].length),4));for(let d of e.entries){if(o>=s+r-1)break;if(d===null){i(`help|sep|${t}|${o}`,()=>{});continue}let[c,l]=d,u=c.padEnd(a);i(`help|e|${t}|${c}|${l}`,()=>{this.term(" "),H(this.term,"modal-key",u),H(this.term,"content",` ${mn(l,t-2-a-1)}`)})}i(`help|hint|${t}|${e.hint}`,()=>{H(this.term,"modal-hint",` ${mn(e.hint,t-2)}`)})}helpRows(){return this.helpPrompt?Math.min(_4,2+this.helpPrompt.entries.length):0}isHelpCell(e){let t=this.helpRegion;return this.helpPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}handleHelpPress(e){return this.isHelpCell(e.y)?(this.helpPressed=!0,!0):(this.helpPressed=!1,!1)}handleHelpRelease(e){let t=this.helpPressed;return this.helpPressed=!1,t?(e!==null&&this.isHelpCell(e.y)&&this.onHelpClick?.(),!0):!1}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let t=this.term.width,r=this.permissionRows(),s=this.term.height-r-Bt-Ut-Ot+1,o=s;this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion={top:s,bottom:s+r-1};let i=(l,u)=>{o>=s+r||(this.paintRow(o,l,u),o+=1)};i(`perm|t|${t}|${e.title}`,()=>{H(this.term,"prompt-text",` \u{1F512} ${mn(e.title,t-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";i(`perm|sub|${t}|${a}`,()=>{H(this.term,"modal-hint",` ${mn(a,t-2)}`)}),i(`perm|q|${t}`,()=>{H(this.term,"content"," Do you want to proceed?")});for(let l=0;l<e.options.length&&!(o>=s+r-1);l++){let u=e.options[l];if(!u)continue;let f=l===e.selectedIndex,m=` ${f?"\u276F":" "} ${l+1}. ${mn(u.label,t-8)}`;this.permissionRowHits.set(o,l),i(`perm|o|${t}|${l}|${f?"1":"0"}|${u.label}`,()=>{f?H(this.term,"modal-option-selected",m):H(this.term,"modal-option",m)})}let d=$S(E4,t),c=o;for(let l of d.spans)(l.action==="commit"||l.action==="cancel")&&this.permissionHintHits.push({row:c,start:l.start,end:l.end,action:l.action});i(`perm|hint|${t}|${d.text}`,()=>{H(this.term,"modal-hint",` ${d.text}`)})}isPermissionCell(e){let t=this.permissionRegion;return this.permissionPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}permissionHitAt(e,t){if(!this.isPermissionCell(t))return null;for(let s of this.permissionHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.permissionRowHits.get(t);return r===void 0?null:{kind:"option",index:r}}handlePermissionPress(e){return this.isPermissionCell(e.y)?(this.permissionPressHit=this.permissionHitAt(e.x,e.y),!0):(this.permissionPressHit=null,!1)}handlePermissionRelease(e){let t=this.permissionPressHit;if(this.permissionPressHit=null,t===null||e===null||!this.isPermissionCell(e.y))return t!==null;let r=this.permissionHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="option"&&t.kind==="option"&&r.index!==t.index||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action?!0:Date.now()-this.permissionArmedAt<I$?(this.notify("permission prompt just appeared, click again to confirm"),!0):(this.onPermissionClick?.(r),!0)}computeBannerPrefixText(){let e=[];return this.banner.queued>0&&e.push(`${this.banner.queued} queued`),this.scrollOffset>0&&e.push(`\u2191 ${this.scrollOffset}`),e.length>0?e.join(" \xB7 ")+" \xB7 ":""}drawBanner(){let e=this.term.height,t=this.promptRows(),r=e-t-Bt-Ut-Ot;this.drawBar("composerTop",r),this.drawBar("composerBottom",e-Ot)}drawBars(){this.drawBanner(),this.drawBar("sessionbar",this.term.height)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-Bt-Ut-Ot+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Bt-Ut-Ot;this.term.moveTo(2,Math.min(f,p));return}if(this.formPrompt){let l=this.formPrompt,u=this.formWindowSize(),f=this.formWindowTop,p=this.formTop()+1+(l.selectedIndex-f),m=this.term.height-Bt-Ut-Ot,b=Math.min(p,m),h=A$(l,this.term.width,f,u).find(y=>y.selected);if(h?.kind!=="text"){this.term.hideCursor(!0);return}this.term.hideCursor(!1),this.term.moveTo(Math.min(h.caretCol,this.term.width),b);return}if(this.confirmPrompt){let l=this.term.height-ES-Bt-Ut-Ot+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-Bt-Ut-Ot+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Bt-Ut-Ot;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-Bt-Ut-Ot+1;this.term.moveTo(2,u);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=Cs(r.buffer,t),o=go(s,r,Bg),a=this.term.height-o.rendered-Bt-Ut-Ot+1+Math.max(0,o.cursorVisualRow-o.windowStart),d=o.cursorVisualCol+3,c=this.term.height-Bt-Ut-Ot;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.formPrompt)return this.formRows();if(this.confirmPrompt)return ES;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=Cs(r.buffer,t);return Math.min(Bg,Math.max(1,s.length))}permissionRows(){return this.permissionPrompt?Math.min(A4,4+this.permissionPrompt.options.length):0}formRows(){return this.formPrompt?Math.min(Math.max(M4,this.formPrompt.maxRows??T4),2+this.formPrompt.rows.length):0}formWindowSize(){return Math.max(1,this.formRows()-2)}formTop(){return this.term.height-this.formRows()-Bt-Ut-Ot+1}drawFormPrompt(){let e=this.formPrompt;if(!e)return;let t=this.term.width,r=this.formRows(),s=this.formTop(),o=this.formWindowSize(),i=`${e.title}|${e.rows.length}|${o}`;i!==this.formWindowKey?(this.formWindowKey=i,this.formWindowTop=Z4(e.rows.length,e.selectedIndex,o)):this.formWindowTop=eJ(this.formWindowTop,e.rows.length,e.selectedIndex,o);let a=this.formWindowTop;this.clearFormHits(),this.formRegion={top:s,bottom:s+r-1};let d=s,c=(b,g)=>{d>=s+r||(this.paintRow(d,b,g),d+=1)},l=e.rows.length>o?` (${e.selectedIndex+1}/${e.rows.length})`:"";c(`form|t|${t}|${e.title}|${l}`,()=>{H(this.term,"prompt-text",` \u2699 ${mn(`${e.title}${l}`,t-5)}`)});let u=A$(e,t,a,o);for(let b of u){if(d>=s+r-1)break;this.formRowHits.set(d,{row:b.index,...b.kind==="text"?{field:{startCol:1+$t(b.prefix),slice:b.field,sliceStart:b.fieldStart}}:{}}),c(b.sig,()=>{if(b.kind==="text"){H(this.term,b.selected?"modal-option-selected":"modal-option",b.prefix),H(this.term,"content",b.field);return}H(this.term,b.selected?"modal-option-selected":"modal-option",b.body)})}let f=e.hints??tJ,p=d,m=$S(f,t);for(let b of m.spans)this.formHintHits.push({row:p,...b});c(`form|hint|${t}|${m.text}`,()=>{H(this.term,"modal-hint",` ${m.text}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),t=this.term.width,r=this.wrapBtwWindow(t,e,0).rows.length;return Math.min(this.btwOverlayMaxHeight,1+r)}wrapBtwWindow(e,t,r){let s=this.btwOverlayLines.length;if(t<=0||s===0)return{rows:[],offset:0,more:!1};if(e<=4){let f=Math.min(Math.max(0,r),Math.max(0,s-t)),p=s-f,m=Math.max(0,p-t);return{rows:this.btwOverlayLines.slice(m,p),offset:f,more:m>0}}let o=Math.max(0,r),i=[],a=0;for(let f=s-1;f>=0;f--){let p=this.btwOverlayLines[f],m=this.wrapOne(p,e);if(i.push(m),a+=m.length,a>t+o)break}let d=[];for(let f=i.length-1;f>=0;f--)d.push(...i[f]);let c=Math.min(o,Math.max(0,d.length-t)),l=d.length-c,u=Math.max(0,l-t);return{rows:d.slice(u,l),offset:c,more:u>0}}scrollBtwOverlayBy(e){let t=this.btwOverlayRegion;if(!this.btwOverlayOpen||t===null||t.contentRows<=0)return!1;let r=Math.max(0,this.btwOverlayScroll+e),s=this.wrapBtwWindow(this.term.width,t.contentRows,r);return!s.more&&s.offset===0?!1:(s.offset===this.btwOverlayScroll||(this.btwOverlayScroll=s.offset,this.repaintNow()),!0)}isBtwOverlayCell(e){let t=this.btwOverlayRegion;return t!==null&&e>=t.top&&e<=t.bottom}btwOverlayScrollState(){let t=this.btwOverlayRegion?.contentRows??0;return{offset:this.btwOverlayScroll,more:this.wrapBtwWindow(this.term.width,t,this.btwOverlayScroll).more}}drawBtwOverlay(){if(!this.btwOverlayOpen){this.btwOverlayRegion=null;return}let e=this.btwOverlayRows();if(e===0){this.btwOverlayRegion=null;return}let t=this.term.width,s=this.term.height-this.promptRows()-Bt-Ut-Ot,o=this.chipRows()+this.queuedRows()+this.completionRows(),i=s-1-o,a=i-e+1,d=e-1,c=a;this.btwOverlayRegion={top:c,bottom:i,contentRows:d},this.drawBar("btw",c);let l=this.wrapBtwWindow(t,d,this.btwOverlayScroll);this.btwOverlayScroll=l.offset;let u=l.rows;for(let f=0;f<d;f++){let p=c+1+f,m=u.length-d+f,b=m>=0?u[m]:void 0,g=PS(`btw|c${f}`,t,b);this.paintRow(p,g,()=>{b?this.writeFormattedLine(b,t):this.term.noFormat(" ".repeat(t))})}}isHiddenLine(e){return e.collapsed===!0||this.hideThoughts&&e.bodyStyle==="thought"}wrapTail(e,t){if(e<=4){let d=[];for(let l of this.lines)this.isHiddenLine(l)||d.push(l);let c=Math.min(t,d.length);return{rows:d.slice(d.length-c),exhausted:t>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),t<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],s=0,o=0,i=!1;for(let d=this.lines.length-1;d>=0;d--){let c=this.lines[d];if(this.isHiddenLine(c)){d===0&&(i=!0);continue}let l=this.wrapOne(c,e);if(r.push(l),s+=l.length,o=d,s>=t)break}let a=[];for(let d=r.length-1;d>=0;d--)a.push(...r[d]);return{rows:a,exhausted:o===0||i}}wrapOne(e,t){let r=this.lineIds.get(e);if(r!==void 0){let g=this.wrapCache.get(r);if(g)return g}let s=e.prefix??"",o=$t(s),i=Math.max(1,t-o-1),a=Math.max(0,Math.min(e.hangingIndent??0,i-1)),d=Math.max(1,i-a),c=Af(e.bodyStyle),l=e.ansi?q4(e.body,a>0?d:i):V4(e.body,a>0?d:i,{escapeAware:c}),u=e.ansi?0:e.maxWrapRows??0,f=u>0&&l.length>u;f&&(l.length=u);let p=[],m=0,b=0;for(let g=0;g<l.length;g++){let h=l[g]??"",y=g===0||a===0?h:" ".repeat(a)+h;f&&g===l.length-1&&(y=mn(`${y}\u2026`,i,{escapeAware:c}));let k={prefix:g===0?e.prefix:" ".repeat(o),body:y};if(e.prefixStyle!==void 0&&(k.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(k.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(k.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(k.hoverSubKey=e.hoverSubKey),e.fillRow&&(k.fillRow=!0),e.ansi&&(k.ansi=!0),r!==void 0&&h.length>0)if(e.ansi){let S=m,I=0;for(let E=0;E<h.length;){let M=Gr(h,E);if(M){E+=M.text.length,M.width>0&&(I+=1);continue}I+=1,E+=1}let x=I;for(;x>0&&m<e.body.length;){let E=Gr(e.body,m);if(E){m+=E.text.length,E.width>0&&(x-=1);continue}m+=1,x-=1}let C=m;if(g===l.length-1){for(;C<e.body.length;){let E=Gr(e.body,C);if(!E)break;C+=E.text.length}m=C}let $={sourceLineId:r,sourceColOffset:S,sourceColEnd:C};if(g>0&&a>0&&($.bodyDisplayShift=a),this.wrapOrigin.set(k,$),e.links!==void 0){let E=this.linkSpansForWindow(e.body,e.links,S,C,g===0||a===0?0:a);E!==null&&(k.linkSpans=E)}}else{let S=e.body.indexOf(h,b),I=S===-1?b:S,x={sourceLineId:r,sourceColOffset:I};if(g>0&&a>0&&(x.bodyDisplayShift=a),this.wrapOrigin.set(k,x),e.links!==void 0){let C=this.linkSpansForWindow(e.body,e.links,I,I+h.length,g===0||a===0?0:a);C!==null&&(k.linkSpans=C)}b=I+h.length}p.push(k)}return r!==void 0&&this.wrapCache.set(r,p),p}writeFormattedLine(e,t,r=null,s=0,o=null,i=!1,a=!1,d=null){e.prefix&&mo(this.term,e.prefix,e.prefixStyle??e.bodyStyle,i);let c=Math.max(0,t-$t(e.prefix??"")),l=Af(e.bodyStyle),u=e.ansi?e.body:mn(e.body,c,{escapeAware:l}),f=d===null||d.length===0?null:d.map(b=>({start:Math.max(0,Math.min(u.length,b.start)),end:Math.max(0,Math.min(u.length,b.end)),url:b.url})).filter(b=>b.end>b.start).sort((b,g)=>b.start-g.start),p=(b,g,h)=>{if(f===null){h(b,g);return}let y=g+b.length,k=g;for(let S of f){if(S.end<=k||S.start>=y)continue;let I=Math.max(S.start,k),x=Math.min(S.end,y);I>k&&h(b.slice(k-g,I-g),k),process.stdout.write(`\x1B]8;;${S.url}\x1B\\`),h(b.slice(I-g,x-g),I),process.stdout.write("\x1B]8;;\x1B\\"),k=x}k<y&&h(b.slice(k-g),k)},m=(b,g)=>{b.length!==0&&p(b,g,(h,y)=>{if(this.scrollbackHighlight!==null&&!e.ansi){let k=r!==null&&r>=y?r-y:null;j4(this.term,h,e.bodyStyle,this.scrollbackHighlight,k,s,i)}else mo(this.term,h,e.bodyStyle,i)})};if(o!==null){let b=Math.max(0,Math.min(u.length,o.start)),g=Math.max(b,Math.min(u.length,o.end)),h=Af(e.bodyStyle)||e.ansi===!0;if(m(u.slice(0,b),0),g>b){let k=u.slice(b,g);h&&(k=Wg(k)),h?mo(this.term,k,"selection-highlight",i):p(k,b,S=>{mo(this.term,S,"selection-highlight",i)})}let y=u.slice(g);if(h&&g>b){let k=J4(u.slice(0,g));k.length>0&&(y=k+y)}m(y,g)}else m(u,0);if(e.fillRow||i||a){let b=e.ansi?E$(u):$t(l?Wg(u):u),g=c-b;if(g>0){let h=o!==null&&o.toEndOfLine?"selection-highlight":e.fillRow||i?e.bodyStyle:void 0;mo(this.term," ".repeat(g),h,i)}}(e.ansi||e.body.includes("\x1B"))&&this.term.styleReset()}};M$=/[^\x20-\x7e]/,FS=new Intl.Segmenter(void 0,{granularity:"grapheme"}),_$=!1;tJ=[{label:"\u2191/\u2193 choose"},{label:"\u23CE this session",action:"commit"},{label:"s save default",action:"save"},{label:"Esc close",action:"close"}]});function oJ(n,e,t=Qo){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let r=t[n];return r?{kind:"resolve",action:r.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,n-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(e.kind==="char"){let r=e.ch.toLowerCase();if(r==="n")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(r==="p")return{kind:"continue",selected:Math.max(0,n-1)};let s=t.findIndex(o=>o.hotkey.toLowerCase()===r);if(s>=0){let o=t[s];if(o)return{kind:"resolve",action:o.key}}}return{kind:"continue",selected:n}}async function N$(n,e){kr();let t=Qe(e.sessionId),r=e.importedFromMachine??"another machine",s=V(e.cwd),o=Qo.findIndex(p=>p.key==="view");o<0&&(o=0);let i=null,a=null,d=()=>{let m=7+Qo.length*2+2,b=zn(n,{contentHeight:m,title:"Imported session"}),g=b.contentW,h=[{label:"session: ",value:t},{label:"from: ",value:r},{label:"cwd: ",value:s}],y=0;for(let S of h)n.moveTo(b.contentX,b.contentY+y),H(n,"modal-label",` ${S.label}`),H(n,"content",At(S.value,g-S.label.length-2)),y++;y++;let k=D$(n,b,y,{intro:"What do you want to do?",choices:Qo,selected:o,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"});return i=b,a=k.firstChoiceRow,b},c=()=>{let p=i,m=a;if(!(p===null||m===null))for(let b=0;b<Qo.length;b++){let g=Qo[b];g&&DS(n,p,m+b*2,g.label,b===o)}},l=p=>{p<0||p>=Qo.length||p===o||(o=p,c())},u=null,f=H$({choiceCount:Qo.length,layout:()=>i,firstChoiceRow:()=>a,selected:()=>o,select:l,commit:p=>{let m=Qo[p];m&&u?.(m.key)},back:()=>u?.("back")});return qr({term:n,render:d,onKey:(p,m,b,g)=>{let h=iJ(p,b);if(!h)return;let y=oJ(o,h);if(y.kind==="cancel"){g("cancel");return}if(y.kind==="back"){g("back");return}if(y.kind==="resolve"){g(y.action);return}l(y.selected)},onMouse:(p,m,b)=>{u=b,f(p,m)}})}function D$(n,e,t,r){let s=t;n.moveTo(e.contentX,e.contentY+s),H(n,"content",` ${r.intro}`),s+=2;let o=e.contentY+s;for(let i=0;i<r.choices.length;i++){let a=r.choices[i];a&&(DS(n,e,e.contentY+s,a.label,i===r.selected),s++,n.moveTo(e.contentX,e.contentY+s),H(n,"list-description",` ${a.description}`),s++)}return s++,n.moveTo(e.contentX,e.contentY+s),H(n,"modal-hint",` ${r.footer}`),{firstChoiceRow:o}}function H$(n){let e=null,t=r=>{let s=n.firstChoiceRow();if(s===null)return null;let o=r-s;if(o<0)return null;let i=Math.floor(o/2);return i<n.choiceCount?i:null};return(r,s)=>{if(r==="MOUSE_WHEEL_UP"){n.select(n.selected()-1);return}if(r==="MOUSE_WHEEL_DOWN"){n.select(n.selected()+1);return}if(r==="MOUSE_LEFT_BUTTON_PRESSED"){e={x:s?.x??-1,y:s?.y??-1};return}let o=s?.y;if(typeof o!="number")return;if(r==="MOUSE_MOTION"){let l=t(o);l!==null&&n.select(l);return}if(r!=="MOUSE_LEFT_BUTTON_RELEASED")return;let i=s?.x,a=e!==null&&i===e.x&&o===e.y;if(e=null,!a)return;let d=n.layout();if(d!==null&&typeof i=="number"&&(i<d.x||i>=d.x+d.w||o<d.y||o>=d.y+d.h)){n.back();return}let c=t(o);c!==null&&n.commit(c)}}function DS(n,e,t,r,s){let i=ks(` ${s?"\u276F":" "} ${r}`,e.contentW);n.moveTo(e.contentX,t),H(n,s?"list-selected":"content",i)}function iJ(n,e){return n==="UP"?{kind:"up"}:n==="DOWN"?{kind:"down"}:n==="ENTER"||n==="KP_ENTER"?{kind:"enter"}:n==="ESCAPE"?{kind:"back"}:n==="CTRL_C"||n==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:n}:null}async function B$(n,e,t){let r=Qe(e.sessionId),s=e.title??V(e.cwd),o=1,i=[{key:"launch",label:"Launch",hotkey:"l",description:"start a new agent session"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=null,d=null,c=()=>{let f=zn(n,{contentHeight:11,title:"Open session",overlay:!0}),p=f.contentW,m=0;n.moveTo(f.contentX,f.contentY+m),H(n,"modal-label"," session: "),H(n,"content",At(r,p-10)),m++,n.moveTo(f.contentX,f.contentY+m),H(n,"content"," "+At(s,p-2)),m++,m++;let b=D$(n,f,m,{intro:"What do you want to do?",choices:i,selected:o,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"});a=f,d=b.firstChoiceRow},l=()=>{let f=a,p=d;if(!(f===null||p===null))for(let m=0;m<i.length;m++){let b=i[m];b&&DS(n,f,p+m*2,b.label,m===o)}},u=f=>{f<0||f>=i.length||f===o||(o=f,l())};return c(),n.hideCursor(),await new Promise(f=>{let p=!1,m=()=>{p=!0},b=y=>{m(),t.pop(),f(y)},g=(y,k,S)=>{if(y==="CTRL_C"||y==="CTRL_D"){b("cancel");return}if(y==="ESCAPE"){b("back");return}if(y==="ENTER"||y==="KP_ENTER"){b(i[o]?.key??"view");return}if(y==="UP"||y==="SHIFT_TAB"){u(o-1);return}if(y==="DOWN"||y==="TAB"){u(o+1);return}if(S?.isCharacter){let I=y.toLowerCase();if(I==="l"){b("launch");return}if(I==="v"){b("view");return}if(I==="n"){u(o+1);return}if(I==="p"){u(o-1);return}}},h=H$({choiceCount:i.length,layout:()=>a,firstChoiceRow:()=>d,selected:()=>o,select:u,commit:y=>{let k=i[y];k&&b(k.key)},back:()=>b("back")});t.push({onKey:(y,k,S)=>{p||g(y,k,S)},onMouse:(y,k)=>{p||h(y,k)},onResize:()=>{p||c()}})})}var Qo,HS=j(()=>{"use strict";Se();mr();Li();xn();Qo=[{key:"fork-local",label:"Fork locally",hotkey:"f",description:"spawn a local fork \u2014 original imported copy stays as-is"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}]});function Ef(n){if(n.length===0)return"";let e=n[0]??"";for(let t=1;t<n.length;t++){let r=n[t]??"",s=0;for(;s<e.length&&s<r.length&&e[s]===r[s];)s+=1;if(e=e.slice(0,s),e.length===0)break}return e}function U$(n){let{matches:e,firstLine:t}=n;if(e.length===0)return null;let r=t.indexOf(" "),s=r===-1?t:t.slice(0,r),o=r===-1?"":t.slice(r);if(e.length===1){let a=e[0]??"",d=o.startsWith(" ")?"":" ";return a+d+o}let i=Ef(e);return i.length<=s.length?null:i+o}var zg=j(()=>{"use strict"});import*as W$ from"os";async function ad(n,e,t={}){let r=t.defaultCwd??(e?await NM(e.cwd):void 0)??W$.homedir();kr();let s=t.title??"Fork locally \u2014 choose cwd",o=t.intro??"Pick a local cwd for this session:",i=e?[{label:"session: ",value:Qe(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:V(e.cwd)}]:[],a=new Hi(r.endsWith("/")?r:r+"/"),d=()=>{let M=FM(a.text);M>0&&a.setText(a.text.slice(M))},c=null,l=!1,u=null,f=null,p=null,m=null,b=" Enter accept \xB7 Esc back",g="Enter accept",h="Esc back",y=b.indexOf(g),k=b.indexOf(h),S=()=>{let M=i.length+6;u=zn(n,{contentHeight:M,title:s,overlay:t.overlay===!0});let F=u.contentW,K=0;for(let z of i)n.moveTo(u.contentX,u.contentY+K),H(n,"modal-label",` ${z.label}`),H(n,"content",At(z.value,F-z.label.length-2)),K++;K++,n.moveTo(u.contentX,u.contentY+K),H(n,"content",` ${o}`),K+=2,C(K),K+=2;let Y=u.contentY+K;c!==null?(n.moveTo(u.contentX,Y),H(n,"input-error",` ${At(c,F-2)}`),f=null,p=null,m=null):(n.moveTo(u.contentX,Y),H(n,"modal-hint",b),f=Y,p={start:u.contentX+y,end:u.contentX+y+g.length-1},m={start:u.contentX+k,end:u.contentX+k+h.length-1})},I=()=>i.length+3,x=0,C=M=>{if(!u)return;let F=M??I();n.moveTo(u.contentX,u.contentY+F).eraseLineAfter(),n.moveTo(u.x+u.w-1,u.contentY+F),H(n,"box-border","\u2502"),n.moveTo(u.contentX,u.contentY+F),n.noFormat(" ");let Y=Math.max(1,u.contentW-1-2),z=a.text,re=a.cursor;re<x&&(x=re),re-x>=Y&&(x=re-Y+1),x<0&&(x=0);let Q=z.slice(x,x+Y);x>0&&Q.length>0&&(Q="\u2026"+Q.slice(1));let ke=_v(z),xe=(Ge,ue)=>{if(ue.length===0)return;let oe=Ge+ue.length;if(ke<=Ge)H(n,"content",ue);else if(ke>=oe)H(n,"modal-hint",ue);else{let $e=ke-Ge;H(n,"modal-hint",ue.slice(0,$e)),H(n,"content",ue.slice($e))}},je=re-x;if(l){xe(x,Q);return}je>=Q.length?(xe(x,Q),H(n,"input-cursor"," ")):(xe(x,Q.slice(0,je)),H(n,"input-cursor",Q[je]??" "),xe(x+je+1,Q.slice(je+1)))},$=()=>{if(C(),!u)return;let M=I()+2;n.moveTo(u.contentX,u.contentY+M).eraseLineAfter(),n.moveTo(u.x+u.w-1,u.contentY+M),H(n,"box-border","\u2502");let F=u.contentY+M;n.moveTo(u.contentX,F),c!==null?(H(n,"input-error",` ${At(c,u.contentW-2)}`),f=null,p=null,m=null):(H(n,"modal-hint",b),f=F,p={start:u.contentX+y,end:u.contentX+y+g.length-1},m={start:u.contentX+k,end:u.contentX+k+h.length-1})},E=M=>{if(l)return;let F=a.text;l=!0,c=null,$(),mf(F).then(K=>{if(l=!1,K.ok){M({kind:"ok",path:K.path});return}c=K.reason,$()})};return qr({term:n,render:S,overlay:t.overlay===!0,onKey:(M,F,K,Y)=>{if(!l){if(M==="ENTER"||M==="KP_ENTER"){E(Y);return}if(M==="ESCAPE"){Y({kind:"back"});return}if(M==="CTRL_C"||M==="CTRL_D"){Y({kind:"cancel"});return}if(M==="TAB"){l=!0,DM(a.text).then(z=>{if(l=!1,z.matches.length===0)return;let re;if(z.matches.length===1)re=z.prefix+z.matches[0];else{let Q=Ef(z.matches);if(Q.length<=z.basePrefix.length)return;re=z.prefix+Q}re!==a.text&&(a.setText(re,{recordUndo:!0}),d(),c=null,$())});return}if(a.handleKey(M,K?.isCharacter===!0)){d(),c=null,$();return}}},onMouse:(M,F,K)=>{if(l||M!=="MOUSE_LEFT_BUTTON_PRESSED")return;let Y=F?.x,z=F?.y;if(!(typeof Y!="number"||typeof z!="number")){if(u!==null&&(Y<u.x||Y>=u.x+u.w||z<u.y||z>=u.y+u.h)){K({kind:"back"});return}if(f!==null&&z===f){if(p!==null&&Y>=p.start&&Y<=p.end){E(K);return}if(m!==null&&Y>=m.start&&Y<=m.end){K({kind:"back"});return}}}}})}var BS=j(()=>{"use strict";Se();mr();$v();zg();Li();mg();xn()});import*as q$ from"fs";import*as z$ from"os";import*as Kg from"path";function Gg(n,e){let t=e;for(;t>0;){let r=n[t-1]??"";if(/\s/.test(r)){if(r===" "&&n[t-2]==="\\"){t-=2;continue}break}t-=1}return t===e?null:{token:n.slice(t,e),start:t}}function aJ(n){return n.length===0?!1:n.includes("/")?!0:n==="~"||n==="."||n===".."}function dJ(n){return n.replace(/\\ /g," ")}function j$(n){return n.replace(/ /g,"\\ ")}function cJ(n){let e=n.lastIndexOf("/");return e===-1?{dirPrefix:"",base:n}:{dirPrefix:n.slice(0,e+1),base:n.slice(e+1)}}function lJ(n,e){let t=n.length===0?".":n;return(t==="~"||t.startsWith("~/"))&&(t=z$.homedir()+t.slice(1)),Kg.isAbsolute(t)?t:Kg.resolve(e,t)}function uJ(n){let e;try{e=q$.readdirSync(n,{withFileTypes:!0})}catch{return null}return e.map(t=>({name:t.name,isDir:t.isDirectory()}))}function Jg(n,e,t=uJ){let r=dJ(n),{dirPrefix:s,base:o}=cJ(r);if(s.length===0&&!aJ(n)&&o.length===0)return null;let i=lJ(s,e),a=t(i);if(a===null)return null;let d=o.startsWith("."),c=a.filter(f=>f.name.startsWith(o)&&(d||!f.name.startsWith(".")));if(c.length===0)return null;let l=c.map(f=>f.isDir?f.name+"/":f.name);if(c.length===1){let f=c[0],p=f.isDir?f.name+"/":f.name;return{replacement:j$(s+p),candidates:l}}let u=Ef(c.map(f=>f.name));return{replacement:j$(s+u),candidates:l}}var US=j(()=>{"use strict";zg()});import{spawn as fJ}from"child_process";function pJ(n,e){let t="";for(let r=0;r<n.length;r++){let s=n[r];if(s!=="%"||r===n.length-1){t+=s;continue}switch(n[r+1]){case"%":t+="%",r++;break;case"s":t+=e.sessionId,r++;break;case"c":t+=e.cwd,r++;break;case"a":t+=e.agentId,r++;break;case"u":t+=e.baseUrl,r++;break;case"t":t+=e.tokenFile,r++;break;default:t+=s;break}}return t}function hJ(n){if(Array.isArray(n))return[...n];let e=n;return e.trim().length===0?[]:e.trim().split(/\s+/)}function mJ(n,e){let t=hJ(n.command);if(t.length===0)return null;let r=t.map(a=>Ze(pJ(a,e))),[s,...o]=r;if(!s)return null;let i={HYDRA_SESSION_ID:e.sessionId,HYDRA_CWD:e.cwd,HYDRA_AGENT:e.agentId,HYDRA_BASE_URL:e.baseUrl,HYDRA_TOKEN_FILE:e.tokenFile};return{program:s,args:o,env:i}}function gJ(n){let e={stdout:"",stderr:"",bytes:0,truncated:!1},t=(r,s)=>{if(e.truncated)return;let o=n-e.bytes;if(o<=0){e.truncated=!0;return}let i=r.length<=o?r.toString("utf8"):r.subarray(0,o).toString("utf8");r.length>o&&(e.truncated=!0),e[s]+=i,e.bytes+=Math.min(r.length,o)};return{onStdout:r=>t(r,"stdout"),onStderr:r=>t(r,"stderr"),onExit:(r,s)=>{let o=[],i=(a,d)=>{let c=a.split(/\r?\n/);for(;c.length>0&&c[c.length-1]==="";)c.pop();for(let l of c)o.push({text:l,style:d})};return e.stdout&&i(e.stdout,"stdout"),e.stderr&&i(e.stderr,"stderr"),e.truncated&&o.push({text:`[output truncated at ${n} bytes]`,style:"meta"}),s?o.push({text:`[killed by ${s}]`,style:"error"}):typeof r=="number"&&r!==0&&o.push({text:`[exit ${r}]`,style:"error"}),o}}}function Vg(n,e,t){let r=mJ(n,e);if(r===null){t.notify("hotkey: empty command");return}let s=gJ(t.maxOutputBytes??yJ),o=t.spawnFn??fJ,i;try{i=o(r.program,r.args,{cwd:t.cwd,env:{...t.parentEnv??process.env,...r.env},stdio:["ignore","pipe","pipe"]})}catch(a){t.emitLines([{text:`[hotkey spawn failed: ${a.message}]`,style:"error"}]);return}i.stdout?.on("data",s.onStdout),i.stderr?.on("data",s.onStderr),i.on("error",a=>{t.emitLines([{text:`[hotkey spawn error: ${a.message}]`,style:"error"}])}),i.on("close",(a,d)=>{t.emitLines(s.onExit(a,d))})}var yJ,WS=j(()=>{"use strict";et();yJ=16*1024});function wJ(n){process.stdout.write(`\x1B]9;4;${n}\x1B\\`)}function bJ(n,e,t){let r=`${t.agentId}@${t.version}`;if(t.source==="npm")return t.phase==="install_start"||t.phase==="download_start"?`${n} installing ${r} via npm\u2026`:t.phase==="installed"?`${n} ${r} installed`:`${n} installing ${r} via npm\u2026`;if(t.phase==="download_start"||t.phase==="download_progress"){let s=t.receivedBytes??0,o=t.totalBytes??0,i=(s/1e6).toFixed(1);if(o>0){let a=(o/1e6).toFixed(1),d=Math.min(100,Math.floor(s/o*100));return`${n} downloading ${r} ${i}/${a} MB (${d}%)`}return`${n} downloading ${r} ${i} MB`}return t.phase==="download_done"?`${n} downloaded ${r}, verifying\u2026`:t.phase==="extract"?`${n} extracting ${r}\u2026`:t.phase==="installed"?`${n} ${r} installed`:e||n}function Yg(n,e){let t=!1,r="",s=!1,o=n,i=a=>{t||a===3&&s||a===0&&!s||(s=a===3,wJ(a))};return{write(a){t||(o=a,r=a,e.write(a))},applyProgress(a){if(t)return;a.phase==="download_start"||a.phase==="download_progress"||a.phase==="install_start"||a.phase==="extract"||a.phase==="download_done"?i(3):a.phase==="installed"&&i(0);let c=bJ(o,r,a);r=c,e.write(c)},finalize(){t||(t=!0,i(0),e.finalize())}}}function K$(n){let e=!1;return{write(t){e||(process.stdout.write("\r"),n.eraseLineAfter(),H(n,"status-active",t))},finalize(){e||(e=!0,process.stdout.write(`
274
- `))}}}var jS=j(()=>{"use strict";xn()});function zS(n="local"){let e={filters:{cwdOnly:!1,hostFilter:n==="all"?"__all":"__local",includeNonInteractive:!1}};return n!=="local"&&n!=="all"&&(e.pendingDefaultHost=n),e}function dd(){return dn()?.id??"terminal"}function SJ(){if(!uf())return J$;let n=[];for(let e of J$)n.push(e),e?.[0]==="*"&&n.push(["^t",pg()?"go to selected session's tab (opening one if needed), or send the composer to a new one":"new tab: selected session, or send the composer to a new one"]);return n}async function KS(n,e){let t=()=>{be(fs),be(Ka),be(Jo),be(Ga),be(Ja),be(ol),be(il),be(al),be(za),be("\x1B>")};t();let r=e.prefs??zS();if(e.prefs===void 0&&e.currentSessionId!==void 0){let P=e.sessions.find(_=>_.sessionId===e.currentSessionId);(P?.importedFromMachine||P?.remote)&&(r.filters.hostFilter="__all")}if(r.pendingDefaultHost!==void 0){let P=RJ(r.pendingDefaultHost,e.sessions);r.filters.hostFilter=P,P!=="__local"&&(r.pendingDefaultHost=void 0)}let s=e.cwd,o=Xg(e.sessions,s),i,a=P=>{let _=P;return r.filters.cwdOnly&&(_=_.filter(W=>W.cwd===s)),r.filters.includeNonInteractive||(_=_.filter(W=>W.interactive===!0)),_=CJ(_,r.filters.hostFilter),_},d=a(o),c={columns:Hr,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},l=d.map(P=>ws(P,Date.now()));c.columns=V$(l,e.config.tui.sessionColumns);let u=lo(l,c),f=1+d.length,p=0,m=0;if(e.currentSessionId!==void 0){let P=d.findIndex(_=>_.sessionId===e.currentSessionId);P>=0&&(p=P+1)}let b=!1,g="",h=120,y=!1,k=0,S="normal",I=null,x=!1,C="input",$=new Vo({history:[],collapsePastes:!1}),E=[],M=!1,F=0,K=0,Y=null,z=!1,re=new Map,Q=lo([],c),ke="",xe=P=>re.get(P)??null,je=()=>{let P=Date.now(),_=new Map(d.map(se=>[se.sessionId,se])),W=[];re=new Map;for(let se of E){let ae=_.get(se.sessionId);if(!ae)continue;let ge=ws(ae,P);re.set(se.sessionId,ge),W.push(ge)}Q=lo(W,c);let J=Math.max(20,Cn(n)-Qg);ke=wr(jo,Q,J,c).padEnd(J)},Ge=null,ue=null,oe=null,$e=null,lt=()=>{if($e!==null){let P=$e;return{plain:P,render:()=>{H(n,"status-active",` ${P}`)}}}if(b){let P=d.length===0?"no matches":`${d.length} match${d.length===1?"":"es"}`;return{plain:`/${g}\u2589 ${P} \xB7 ^c clears`,render:()=>{H(n,"prompt-text",` /${g}`),H(n,"prompt-cursor"," "),H(n,"modal-hint",` ${P} \xB7 ^c clears`)}}}return oe!==null?{plain:oe,render:()=>{H(n,"modal-hint",` ${oe}`)}}:null},Tt=!1,Me=new Vo({history:[]});if(e.initialPrompt&&Me.setBuffer(e.initialPrompt),e.initialAttachments)for(let P of e.initialAttachments)Me.addAttachment(P);let Jt=e.config.tui.promptHistoryMaxEntries;Pu(D.globalTuiHistoryFile()).then(P=>{let _=P.length>Jt?P.slice(P.length-Jt):P;Me.setHistory(_)}).catch(()=>{});let Ye=new gl(n),As=Gl(e.config),Ki=e.config.tui.selectionClipboard,Kn=null,Ts=!1,Ht=null,X="char",Et=null,Sr=null,gn=!1,Yr=1,Xo=null,ay=500,vl=1,Es=/[A-Za-z0-9_:\-]/,Zo=uo(n),Wt=Cn(n),it=0,ud="",or=0,Gn=[],yn=1,yo=0,Gi=0,Sl=0,fd="",wo=[],On=1,Hf=0,Xe=[],wn=1,Ji=0,Vi=0,bo=0,Yi=()=>{Zo=uo(n),Wt=Cn(n);let P=Math.max(10,Wt-Qg-1);or=Math.max(10,Wt-G$);let _=Math.max(10,Wt-8),W=Me.state().attachments.length,J=W>0?` \xB7 \u{1F4CE}\xD7${W}`:"",se=Math.max(10,_-J.length);ud=xJ(s,se)+J;let ae=Me.state();Gn=Cs(ae.buffer,or);let ge=go(Gn,ae,Pf);yn=ge.rendered,yo=ge.windowStart,Gi=ge.cursorVisualRow,Sl=ge.cursorVisualCol;let ut=6+yn,St=Math.max(3,Zo-ut);it=Math.min(d.length,St),fd=wr(jo,u,P,c).padEnd(P),wo=l.map(en=>wr(en,u,P,c).padEnd(P))},pd=()=>{l=d.map(P=>ws(P,Date.now())),c.columns=V$(l,e.config.tui.sessionColumns),u=lo(l,c),f=1+d.length,Yi()},Rn=()=>{let P=a(o);b&&g.length>0?d=P.filter(_=>TJ(_,g)):d=P,pd(),b?(m=0,p=d.length>0?1:0):p>f-1&&(p=Math.max(0,f-1)),m+it>d.length&&(m=Math.max(0,d.length-it)),Qr()},Ps=P=>{if(P===null){p=0,m=0;return}if(P!==void 0){let _=d.findIndex(W=>W.sessionId===P);if(_>=0){p=_+1,Qr();return}}p=d.length>0?1:0,m=0,Qr()},Qr=()=>{if(p===0)return;let P=p-1;P<m?m=P:P>=m+it?m=P-it+1:m+it>d.length&&(m=Math.max(0,d.length-it))},me=()=>Math.max(2,Wt-3),Rt=!1,rt=!0,Xt=!1,Bf=[],Zt=e.composerAgentId,bn=e.composerModel,ko=e.composerHost,ei=!1,xl=()=>{let P=Zt;if(!P)return"";let _=bn;return _?`${P}\u2022${_}`:P},Ms=null,Fn=null,_s=null,kn=null,hd=()=>{let P=me(),_=`\u2500 ${ud} `,W=xl(),J="";if(W.length>0){let zt=`\u2500 ${W} `;zt.length+_.length+1<=P&&(J=zt)}let se="";if((e.availableHosts?.length??0)>0){let zt=`\u2500 ${ko??"local"} `;zt.length+J.length+_.length+1<=P&&(se=zt)}let ae=Math.max(1,P-_.length-se.length-J.length),ge="\u2500".repeat(ae),ut=(p===0||Rt)&&rt;if(Ms=_.length>0?{start:2,end:1+_.length}:null,se.length>0){let zt=1+_.length+ae+1;_s={start:zt,end:zt+se.length-1}}else _s=null;if(J.length>0){let zt=1+_.length+ae+se.length+1;Fn={start:zt,end:zt+J.length-1}}else Fn=null;let St=ut?"box-border-focused":"box-border",en=ut?"box-border-focused-hover":"box-border-hover",tn=(zt,ci)=>{H(n,ci?en:St,zt)};H(n,St,"\u256D"),tn(_,kn==="cwd"),H(n,St,ge),se&&tn(se,kn==="host"),J&&tn(J,kn==="agent"),H(n,St,"\u256E")},md=()=>{let P=me(),_="\u2500".repeat(P);(p===0||Rt)&&rt?H(n,"box-border-focused",`\u2570${_}\u256F`):H(n,"box-border",`\u2570${_}\u256F`)},gd=()=>{let P=lt();if(P===null)return;let _=Math.max(0,Cn(n)-2);if(P.plain.length>_){let W=P.plain.slice(0,Math.max(0,_-1))+"\u2026";H(n,"modal-hint",` ${W}`);return}P.render()},ti=P=>{let _=Gn[P];return _?(Me.state().buffer[_.bufferIdx]??"").slice(_.startCol,_.endCol):""},yd=P=>{if(Ht===null)return null;let _=Gn[P];if(!_)return null;let W=Ht;if(_.bufferIdx<W.startRow||_.bufferIdx>W.endRow)return null;let J=_.bufferIdx===W.startRow?W.startCol:_.startCol,se=_.bufferIdx===W.endRow?W.endCol:_.endCol,ae=Math.max(J,_.startCol),ge=Math.min(se,_.endCol);return ge<=ae?null:{start:ae-_.startCol,end:ge-_.startCol}},xr=P=>{let _=me(),W=ti(P),J=Math.max(0,_-1-W.length),se=" ".repeat(J),ae=yd(P),ge=()=>{if(ae===null){H(n,"content",` ${W}${se}`);return}H(n,"content"," "),ae.start>0&&H(n,"content",W.slice(0,ae.start)),H(n,"selection-highlight",W.slice(ae.start,ae.end)),ae.end<W.length&&H(n,"content",W.slice(ae.end)),H(n,"content",se)};(p===0||Rt)&&rt?(H(n,"box-border-focused","\u2502"),ge(),H(n,"box-border-focused","\u2502")):(H(n,"box-border","\u2502"),ge(),H(n,"box-border","\u2502"))},ni=P=>{let _=wo[P]??"",W=d[P],J=W&&W.priority&&W.priority>0?"* ":" ";p===P+1&&!Rt&&rt?H(n,"list-selected",`${J}${_}`):H(n,"content",`${J}${_}`)},Qi=()=>{let P=m,_=Math.max(0,d.length-m-it),W=[];return r.filters.cwdOnly&&W.push({kind:"plain",text:"cwd-only"}),r.filters.hostFilter!=="__all"&&W.push({kind:"host",text:AJ(r.filters.hostFilter)}),r.filters.includeNonInteractive&&W.push({kind:"plain",text:"+non-interactive"}),P>0&&W.push({kind:"plain",text:`\u2191 ${P} above`}),_>0&&W.push({kind:"plain",text:`\u2193 ${_} below`}),W},Il=()=>{let P=Qi();return P.length===0?"":` ${P.map(_=>_.text).join(" \xB7 ")}`},$s=P=>Qe(P),Uf=()=>{let P=I?`${I.sessionId}|${I.status}`:"";return["ind",S,P,Ge?`${Ge.text}${Ge.cursor}`:"",ue??"",b?`1|${g}|${d.length}`:"0",Il(),di?"h1":"h0",ea?"ho1":"ho0"].join("")},Ne=()=>{mt(()=>{Ye.paintRow(Xr(),Uf(),()=>{let P=()=>{Eo=null,rs=null};if(S==="confirm-kill"&&I)P(),H(n,"prompt-text",` kill ${$s(I.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&I)P(),I.status==="warm"?H(n,"prompt-destructive",` kill + delete ${$s(I.sessionId)}? [y/N]`):H(n,"prompt-destructive",` delete ${$s(I.sessionId)}? [y/N]`);else if(S==="busy"&&I)P(),H(n,"modal-status",` working on ${$s(I.sessionId)}\u2026`);else if(S==="rename"&&I&&Ge){P();let _=Ge.text,W=Ge.cursor;H(n,"prompt-text"," title: "),H(n,"prompt-text",_.slice(0,W)),W<_.length?(H(n,"prompt-cursor",_[W]??" "),H(n,"prompt-text",_.slice(W+1))):H(n,"prompt-cursor"," "),H(n,"modal-hint"," Enter saves \xB7 Esc cancels")}else if(ue!==null)P(),H(n,"modal-status",` ${ue}`);else{let _=Qi(),W=Il(),J="Esc \xB7 Go Back",se=J.length,ae=5,ge=W.length,ut=Math.max(1,Wt-ge-se-ae);if(rs=null,_.length>0){H(n,"modal-hint"," ");let St=3;for(let en=0;en<_.length;en++){let tn=_[en];en>0&&(H(n,"modal-hint"," \xB7 "),St+=3),tn.kind==="host"?(rs={start:St,end:St+tn.text.length-1},ea?H(n,"content",tn.text):H(n,"modal-hint",tn.text)):H(n,"modal-hint",tn.text),St+=tn.text.length}}H(n,"modal-hint"," ".repeat(ut)),di?H(n,"content",J):H(n,"modal-hint",J),Eo={start:Wt-ae-se+1,end:Wt-ae}}})})},Ln=P=>On+1+P,Jn=()=>On+yn+1,Le=()=>On+yn+3,Wf=P=>Le()+1+(P-m),Xr=()=>Le()+1+it,cn=()=>{let P=Gi-yo;if(P<0||P>=yn)return;let _=3+Sl;n.moveTo(_,Ln(P))},Zr=(P,_)=>{let W=_-(On+1);if(W<0||W>=yn)return null;let J=Gn[yo+W];if(!J)return null;let se=Math.max(0,Math.min(J.endCol-J.startCol,P-3));return{row:J.bufferIdx,col:J.startCol+se}},vo=()=>{Ht!==null&&(Ht=null,To())},Os=(P,_)=>{let W=P.row<_.row||P.row===_.row&&P.col<=_.col,J=W?P:_,se=W?_:P;if(J.row===se.row&&J.col===se.col){vo();return}let ae={startRow:J.row,startCol:J.col,endRow:se.row,endCol:se.col},ge=Ht;ge&&ge.startRow===ae.startRow&&ge.startCol===ae.startCol&&ge.endRow===ae.endRow&&ge.endCol===ae.endCol||(Ht=ae,To())},A=()=>{if(Ht===null)return"";let{startRow:P,startCol:_,endRow:W,endCol:J}=Ht,se=Me.state().buffer;if(P===W)return(se[P]??"").slice(_,J);let ae=[(se[P]??"").slice(_)];for(let ge=P+1;ge<W;ge++)ae.push(se[ge]??"");return ae.push((se[W]??"").slice(0,J)),ae.join(`
275
- `)},jf=()=>{let P=A();P.length!==0&&ml(P,{target:Ki}).then(_=>{let W=P.length;oe=_.ok?`copied ${W} char${W===1?"":"s"} to clipboard`:`clipboard copy failed: ${_.reason}`,Ir()},_=>{oe=`clipboard copy failed: ${_.message}`,Ir()})},Cl=P=>{let _=Me.state().buffer[P.row]??"";if(_.length===0)return null;let W=Math.max(0,Math.min(_.length-1,P.col));if(!Es.test(_[W]))return null;let J=W;for(;J>0&&Es.test(_[J-1]);)J--;let se=W+1;for(;se<_.length&&Es.test(_[se]);)se++;return{start:J,end:se}},qf=P=>{let _=Me.state().buffer[P]??"";Os({row:P,col:0},{row:P,col:_.length})},zf=P=>{let _=Et;if(_===null)return;let W=P.row<_.row||P.row===_.row&&P.col<_.start,J=P.row>_.row||P.row===_.row&&P.col>_.end,se={row:_.row,col:_.start},ae={row:_.row,col:_.end};if(W){let ge=Cl(P);se=ge!==null?{row:P.row,col:ge.start}:P}else if(J){let ge=Cl(P);ae=ge!==null?{row:P.row,col:ge.end}:P}Os(se,ae)},wd=P=>{let _=Sr;if(_===null)return;let W=Math.min(_,P.row),J=Math.max(_,P.row),se=Me.state().buffer[J]??"";Os({row:W,col:0},{row:J,col:se.length})},ri=P=>{if(!As)return;let _=Zr(P.x,P.y);if(_===null)return;Kn=_,Ts=!1,gn=!1,Yr=1,X="char",Et=null,Sr=null,vo();let W=Date.now(),J=Xo,se=J!==null&&W-J.t<=ay&&Math.abs(P.x-J.x)<=vl&&Math.abs(P.y-J.y)<=vl&&J.row!==null&&J.row===_.row;if(se&&J.count===2&&P.x===J.x&&P.y===J.y){Yr=3,qf(_.row),X="line",Sr=_.row,gn=!0;return}if(se&&J.count===1){Yr=2;let ut=Cl(_);ut!==null&&(Os({row:_.row,col:ut.start},{row:_.row,col:ut.end}),gn=!0,X="word",Et={row:_.row,start:ut.start,end:ut.end})}},es=P=>{if(Kn===null)return;let _=Math.max(1,Math.min(Wt,P.x)),W=Math.max(On+1,Math.min(On+yn,P.y)),J=Zr(_,W);J!==null&&(Ts=!0,X==="word"?zf(J):X==="line"?wd(J):Os(Kn,J))},dy=P=>{let _=Ts,W=gn;if(Kn=null,Ts=!1,gn=!1,P!==null){let J=Zr(P.x,P.y);Xo={x:P.x,y:P.y,t:Date.now(),count:Yr,row:J?.row??null}}if(Yr=1,_||W){jf();return}vo()},bd=()=>rt?p===0?"f":Rt?"h":"u":"x",So=()=>`ct|${bd()}|${me()}|${ud}|${xl()}|${ko??""}|${kn??""}`,Rl=()=>`cb|${bd()}|${me()}`,Kf=()=>$e!==null?`cs|i|${$e}`:b?`cs|s|${g}|${d.length}`:oe!==null?`cs|h|${oe}`:"blank",Al=P=>{let _=yd(P),W=_===null?"":`${_.start}:${_.end}`;return`cbb|${bd()}|${me()}|${ti(P)}|${W}`},Gf=()=>`h|${fd}`,kd=P=>{let _=d[P],W=_&&_.priority&&_.priority>0?"* ":" ",J=wo[P]??"";return`sr|${p===P+1&&!Rt&&rt?"1":"0"}|${W}${J}`},Pt=()=>{mt(()=>{n.hideCursor(),Yi(),Qr(),On=1,Ye.ensureSize(Wt,Zo),Ye.paintRow(On,So(),()=>{hd()});for(let P=0;P<yn;P++){let _=yo+P;Ye.paintRow(Ln(P),Al(_),()=>{xr(_)})}Ye.paintRow(Jn(),Rl(),()=>{md()}),Ye.paintRow(Jn()+1,Kf(),()=>gd()),Ye.paintRow(Le(),Gf(),()=>{H(n,"list-header",` ${fd}`)});for(let P=0;P<it;P++){let _=m+P,W=Le()+1+P;_<d.length?Ye.paintRow(W,kd(_),()=>{ni(_)}):Ye.paintRow(W,"blank",()=>{})}Ne();for(let P=Xr()+1;P<=Zo;P++)Ye.paintRow(P,"blank",()=>{});p===0&&(cn(),n.hideCursor(!1))})},Jf=()=>{Ye.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),Pt()},Vf=()=>{mt(()=>{n.hideCursor(),Ye.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),H(n,"modal-title"," Picker hotkeys"),n.noFormat(`
270
+ `),[i,...a]=o,d=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let u=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=i??"",d+=this.wrappedRowsOf(l)-u}}else{if(this.lines.length>0){let u=this.lines[this.lines.length-1];if(!(u&&u.body===""&&(!u.prefix||u.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),d+=this.wrappedRowsOf(p)}}let l={prefix:t,body:i??"",bodyStyle:r};s!==void 0&&(l.prefixStyle=s),this.lines.push(l),this.trackLine(l),d+=this.wrappedRowsOf(l)}let c=" ".repeat(t.length);for(let l of a){let u={prefix:c,body:l,bodyStyle:r};this.lines.push(u),this.trackLine(u),d+=this.wrappedRowsOf(u)}this.streamingActive=!0,this.adjustScrollForRowChange(d),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setBarConfig(e){this.barConfig=vf(e),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.syncReportedCwd(),G_({sessionId:this.sessionbar.sessionId,agent:this.sessionbar.agent,title:this.sessionbar.title,model:this.sessionbar.model,costAmount:this.sessionbar.usage?.costAmount,cwd:this.sessionbar.cwd}),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),t=e&&e.length>0?e:"New Hydra Session",s=(this.readonly?`${t} [VIEW ONLY]`:t).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);s!==this.lastWindowTitle&&(this.lastWindowTitle=s,be(`\x1B]0;${s}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,be("\x1B]0;\x1B\\")}syncReportedCwd(){let e=this.sessionbar.cwd?.trim();e&&e!==this.lastReportedCwd&&(this.lastReportedCwd=e,mS(e))}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),J_({status:this.banner.status,queued:this.banner.queued}),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&mt(()=>{this.term.hideCursor(),e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}sessionTitle(){return this.sessionbar.title}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,t=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},t),this.syncedPartialRepaint(()=>this.drawBanner())}setCompactionIndicator(e){this.compactionIndicator!==e&&(this.compactionIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setSynthesisIndicator(e){this.synthesisIndicator!==e&&(this.synthesisIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setWorkspaceIndicator(e){this.workspaceIndicator!==e&&(this.workspaceIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setMouseEnabled(e){this.mouseEnabled!==e&&(this.mouseEnabled=e,this.started&&(e?(this.term.grabInput({mouse:"drag"}),this.term.on("mouse",this.mouseHandler)):(this.term.off("mouse",this.mouseHandler),this.term.grabInput(!0)),we({src:"grab",site:"setMouseEnabled",on:!0,mouse:e}),this.reclaimStdinAfterGrabInput()))}reclaimStdinAfterGrabInput(){if(this.terminalKitStdinHandler===null)return;let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.rawStdinHandler))}isMouseEnabled(){return this.mouseEnabled}setInAppSelectionEnabled(e){this.inAppSelectionEnabled=e}isInAppSelectionEnabled(){return this.inAppSelectionEnabled}setSelection(e,t){let r=this.lineIndexById(e.sourceLineId),s=this.lineIndexById(t.sourceLineId),o=r<s||r===s&&e.offset<=t.offset,i=o?e:t,a=o?t:e;if(i.sourceLineId===a.sourceLineId&&i.offset===a.offset){this.clearSelection();return}let d={startLineId:i.sourceLineId,startOffset:i.offset,endLineId:a.sourceLineId,endOffset:a.offset},c=this.selection;c&&c.startLineId===d.startLineId&&c.startOffset===d.startOffset&&c.endLineId===d.endLineId&&c.endOffset===d.endOffset||(this.selection=d,this.repaint())}clearSelection(){this.selection!==null&&(this.selection=null,this.repaint())}hasSelection(){return this.selection!==null}getSelection(){return this.selection===null?null:{start:{sourceLineId:this.selection.startLineId,offset:this.selection.startOffset},end:{sourceLineId:this.selection.endLineId,offset:this.selection.endOffset}}}farEndpointFrom(e){if(this.selection===null)return null;let t=this.selection,r=this.lineIndexById(e.sourceLineId),s=this.lineIndexById(t.startLineId),o=this.lineIndexById(t.endLineId);if(r<0||s<0||o<0)return null;let i=(u,f,p,m)=>u!==p?u-p:f-m,a=i(r,e.offset,s,t.startOffset),d=i(r,e.offset,o,t.endOffset);if(a<=0)return{sourceLineId:t.endLineId,offset:t.endOffset};if(d>=0)return{sourceLineId:t.startLineId,offset:t.startOffset};let c=Math.abs(r-s)*1e6+Math.abs(e.offset-t.startOffset);return Math.abs(r-o)*1e6+Math.abs(e.offset-t.endOffset)>=c?{sourceLineId:t.endLineId,offset:t.endOffset}:{sourceLineId:t.startLineId,offset:t.startOffset}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let t=[];for(let r=e.loIdx;r<=e.hiIdx;r++){let s=this.displayLineAt(r);if(!s)continue;let o=this.lineIds.get(s),i=o===void 0?void 0:e.byId.get(o);if(!i)continue;let d=(s.body??"").slice(i.start,i.end);(Af(s.bodyStyle)||s.ansi)&&(d=Wg(d)),t.push(d)}return t.join(`
271
+ `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let t=this.lineIndexById(e.startLineId),r=this.lineIndexById(e.endLineId);if(t===-1||r===-1)return null;let s=t,o=r,i=e.startOffset,a=e.endOffset;t>r&&(s=r,o=t,i=e.endOffset,a=e.startOffset);let d=new Map,c=-1;for(let l=o;l>=s;l--){let u=this.displayLineAt(l);if(u&&!this.isHiddenDisplayLine(l,u)){c=l;break}}for(let l=s;l<=o;l++){let u=this.displayLineAt(l);if(!u||this.isHiddenDisplayLine(l,u))continue;let f=this.lineIds.get(u);if(f===void 0)continue;let p=(u.body??"").length,m=l===s?Math.max(0,Math.min(p,i)):0,b=l===o?Math.max(0,Math.min(p,a)):p;d.set(f,{start:m,end:b,toEnd:l<c})}return{loIdx:s,hiIdx:o,byId:d}}selectionRangeForChunk(e){if(this.selection===null)return null;let t=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(t===null)return null;let r=this.wrapOrigin.get(e);if(!r)return null;let s=t.get(r.sourceLineId);if(!s)return null;let o=r.sourceColOffset,i=r.bodyDisplayShift??0,a=r.sourceColEnd??o+e.body.length-i,d=Math.max(s.start,o),c=Math.min(s.end,a);if(c<=d)return null;let l,u;if(r.sourceColEnd!==void 0){let f=this.sourceBodyForId(r.sourceLineId);if(f===null)return null;let p=MS(f,o,d),m=MS(f,d,c);l=_S(e.body,i,p),u=_S(e.body,l,m)}else l=d-o+i,u=c-o+i;return{start:l,end:u,toEndOfLine:s.toEnd||s.end>a}}sourceBodyForId(e){let t=this.lineIndexById(e);return t===-1?null:this.displayLineAt(t)?.body??null}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,t=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${t}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:this.workspaceIndicator!==null?{text:this.workspaceIndicator,kind:"workspace"}:this.synthesisIndicator!==null?{text:this.synthesisIndicator,kind:"synthesis"}:this.compactionIndicator!==null?{text:this.compactionIndicator,kind:"compaction"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.selection!==null&&(this.selection=null),this.repaint()}invalidateSelectionIfTouches(e){if(this.selection!==null)for(let t of e){let r=this.lineIds.get(t);if(r!==void 0&&(r===this.selection.startLineId||r===this.selection.endLineId)){this.selection=null;return}}}setHideThoughts(e){this.hideThoughts!==e&&(this.hideThoughts=e,this.repaint())}clearKey(e){this.keyedBlocks.delete(e)}hasKey(e){return this.keyedBlocks.has(e)}removeKey(e){let t=this.keyedBlocks.get(e);if(!t)return;let r=t.start+t.count,s=r>=this.lines.length,o=this.wrappedRowsOfMany(this.lines.slice(t.start,r)),i=this.lines.splice(t.start,t.count);for(let a of i)this.forgetLine(a);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[a,d]of this.keyedBlocks)a!==e&&d.start>t.start&&(d.start-=t.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-o),this.moveStickyToEnd(),this.scheduleRepaint()}setStickyBottomKey(e){this.stickyBottomKey=e,this.moveStickyToEnd(),this.scheduleRepaint()}moveStickyToEnd(){if(this.stickyBottomKey===null)return;let e=this.keyedBlocks.get(this.stickyBottomKey);if(!e)return;let t=e.start+e.count;if(t>=this.lines.length)return;let r=this.lines.splice(e.start,e.count);for(let[s,o]of this.keyedBlocks)s!==this.stickyBottomKey&&o.start>=t&&(o.start-=e.count);e.start=this.lines.length,this.lines.push(...r),this.streamingActive=!1}removeBlock(e){let t=this.keyedBlocks.get(e);if(!t)return;let r=t.start+t.count>=this.lines.length,s=this.wrappedRowsOfMany(this.lines.slice(t.start,t.start+t.count)),o=this.lines.splice(t.start,t.count);for(let i of o)this.forgetLine(i);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[,i]of this.keyedBlocks)i.start>t.start&&(i.start-=t.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-s),this.scheduleRepaint()}contiguousRun(e,t){if(!this.keyedBlocks.has(e))return[];let r=[...t].map(d=>{let c=this.keyedBlocks.get(d);return c?{key:d,start:c.start,count:c.count}:null}).filter(d=>d!==null).sort((d,c)=>d.start-c.start),s=r.findIndex(d=>d.key===e);if(s<0)return[];let o=(d,c)=>{for(let[l,u]of this.keyedBlocks)if(!t.has(l)&&u.start>=d&&u.start<c)return!0;return!1},i=s;for(;i>0&&!o(r[i-1].start+r[i-1].count,r[i].start);)i--;let a=s;for(;a<r.length-1&&!o(r[a].start+r[a].count,r[a+1].start);)a++;return r.slice(i,a+1).map(d=>d.key)}setRunCollapsed(e,t,r){if(e.length===0)return;let s=e[0];if(!this.keyedBlocks.has(s))return;this.upsertLines(s,r);let o=this.keyedBlocks.get(s),i=o.start+o.count;for(let a of e){let d=this.keyedBlocks.get(a);d&&(i=Math.max(i,d.start+d.count))}for(let a=o.start+o.count;a<i;a++){let d=this.lines[a];d&&(d.collapsed=t)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,be(av),this.term.clear(),this.repaint()}pauseRepaint(){this.repaintPaused+=1}resumeRepaint(){this.repaintPaused!==0&&(this.repaintPaused-=1,this.repaintPaused===0&&this.repaintPending&&(this.repaintPending=!1,this.repaint()))}setQueuedPrompts(e){this.queuedTexts=[...e],this.lastQueueEditingIndex=this.dispatcher.state().queueIndex,this.repaint()}repaintNow(){this.repaint()}setPermissionPrompt(e){e!==null&&this.permissionPrompt===null&&(this.clearSelection(),this.permissionArmedAt=Date.now()),this.permissionPrompt=e?{...e}:null,e===null&&(this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion=null,this.permissionPressHit=null),Y_(this.permissionPrompt!==null),this.repaint()}setFormPrompt(e){e!==null&&this.formPrompt===null&&this.clearSelection(),this.formPrompt=e?{...e,rows:e.rows.map(t=>({...t}))}:null,e===null&&(this.clearFormHits(),this.formWindowKey=null,this.formWindowTop=0),this.repaint()}clearFormHits(){this.formRowHits.clear(),this.formHintHits=[],this.formRegion=null,this.formPressHit=null}isFormPromptActive(){return this.formPrompt!==null}setConfirmPrompt(e){e!==null&&this.confirmPrompt===null&&this.clearSelection(),this.confirmPrompt=e?{...e}:null,this.repaint()}isCompactionPromptActive(){return this.compactionPrompt!==null}compactionPromptSpec(){return this.compactionPrompt?{...this.compactionPrompt}:null}setCompactionPrompt(e){e!==null&&this.compactionPrompt===null&&(this.clearSelection(),this.compactionArmedAt=Date.now()),this.compactionPrompt=e?{...e}:null,e===null&&(this.compactionRowHits.clear(),this.compactionHintHits=[],this.compactionRegion=null,this.compactionPressHit=null),this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,e===null&&(this.helpRegion=null,this.helpPressed=!1),this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}openBtwOverlay(e){let t=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=t,this.focusedPane="btw",this.invalidateSelectionIfTouches(this.btwOverlayLines),this.btwOverlayLines=[],this.btwOverlayScroll=0,this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let t=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,t=!0),e.usage!==void 0){let r=this.btwOverlayUsage,s=e.usage;(!r||r.used!==s.used||r.size!==s.size||r.costAmount!==s.costAmount||r.costCurrency!==s.costCurrency)&&(this.btwOverlayUsage={...s},t=!0)}t&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let o=!0;for(let i=0;i<e.length;i++)if(this.btwOverlayLines[i]!==e[i]){o=!1;break}if(o)return}let t=this.btwOverlayLines.length,r=this.btwOverlayLines;this.btwOverlayLines=[...e];for(let o of this.btwOverlayLines)this.lineIds.get(o)===void 0&&(this.trackLine(o),this.uncachedWrap.add(o));let s=new Set(this.btwOverlayLines);if(this.invalidateSelectionIfTouches(r.filter(o=>!s.has(o))),this.btwOverlayScroll>0&&e.length>t){let o=this.term.width,i=0;for(let a=t;a<this.btwOverlayLines.length;a++)i+=o>4?this.wrapOne(this.btwOverlayLines[a],o).length:1;this.btwOverlayScroll+=i}this.scheduleRepaint()}setBtwOverlayStatus(e){let t=this.btwOverlayLabel===e.label,r=this.btwOverlayStatus===e.style;t&&r||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.invalidateSelectionIfTouches(this.btwOverlayLines),this.btwOverlayRegion=null,this.focusedPane="main",this.scheduleRepaint())}reopenBtwOverlay(){return this.btwOverlayOpen?!0:this.btwOverlayLines.length===0?!1:(this.btwOverlayOpen=!0,this.focusedPane="btw",this.scheduleRepaint(),!0)}hasBtwOverlayHistory(){return this.btwOverlayLines.length>0}toggleFocusedPane(){this.focusedPane=this.focusedPane==="main"?"btw":"main",this.scheduleRepaint()}getFocusedPane(){return this.focusedPane}isOverlayOpen(){return this.btwOverlayOpen}setCompletions(e){e.length===this.completions.length&&e.every((r,s)=>{let o=this.completions[s];return o!==void 0&&o.name===r.name&&o.description===r.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let t=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,r=t!==void 0&&t.start+t.count===this.lines.length,s=r?t.start-1:this.lines.length-1;if(s<0)return;let o=this.lines[s];if(o&&o.body===""&&(o.prefix===void 0||o.prefix===""))return;let i={body:""};e!==void 0&&(i.bodyStyle=e),r?(this.lines.splice(t.start,0,i),t.start+=1):this.lines.push(i),this.trackLine(i),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(i)),this.trimScrollback(),this.scheduleRepaint()}refreshPrompt(){if(this.promptRows()!==this.lastPromptRows){this.repaint();return}this.syncedPartialRepaint(()=>{let e=this.dispatcher.state().queueIndex;e!==this.lastQueueEditingIndex&&(this.lastQueueEditingIndex=e,this.drawQueuedZone()),this.drawPrompt()})}handleKey(e,t){if(process.env.HYDRA_TUI_KEY_TRACE&&we({tag:"key",name:e,isChar:!!t.isCharacter}),t.isCharacter){this.chordMatcher.clear(),this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.chordMatcher.clear(),this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.chordMatcher.clear(),this.scrollBy(-this.scrollPageSize());return}if(e==="ALT_PAGE_UP"){this.chordMatcher.clear(),this.scrollToPrevTurn();return}if(e==="ALT_PAGE_DOWN"){this.chordMatcher.clear(),this.scrollToNextTurn();return}let r=qg(e);if(r){this.dispatchKeyName(r);return}e.startsWith("CTRL_")&&(this.chordMatcher.clear(),this.revealHints())}dispatchKeyName(e){let t=this.chordMatcher.feed(e);switch(t.kind){case"pass":this.onKey([{type:"key",name:t.token}]);return;case"armed":return;case"aborted":this.revealHints();return}}handleMouse(e,t){if(e==="MOUSE_WHEEL_UP"||e==="MOUSE_WHEEL_DOWN"){let u=e==="MOUSE_WHEEL_UP"?3:-3,f=this.mouseCell(t);if(f!==null&&this.isFormCell(f.y)){this.stepFormCursor(e==="MOUSE_WHEEL_UP"?-3:3);return}if(f!==null&&this.isCompactionCell(f.y)){this.stepCompactionCursor(e==="MOUSE_WHEEL_UP"?-1:1);return}if(f!==null&&this.isSidebarCell(f.x,f.y)&&this.scrollSidebarBy(u)||f!==null&&this.isBtwOverlayCell(f.y)&&this.scrollBtwOverlayBy(u))return;this.scrollBy(u);return}let s=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||s)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let i=this.mouseCell(t),a=U4(e),d=null;e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?d="move":e.endsWith("_PRESSED")?d="press":e.endsWith("_RELEASED")&&(d="release"),d!==null&&i!==null&&this.onMouse&&this.onMouse({kind:d,button:a,x:i.x,y:i.y,name:e});let c=i!==null?this.barHitAt(i.x,i.y):null;if(d==="move"){let u=c?.id??null,f=i!==null&&i.y===this.composerBottomRow&&this.hintZoneStart!==null&&i.x>=this.hintZoneStart,p=this.trackHintHover(f);if((u!==this.hoveredBarHit||p)&&(this.hoveredBarHit=u,this.syncedPartialRepaint(()=>this.drawBars())),c!==null&&this.setPointerShape(c.action!=="none"||c.doubleAction!=="none"?"pointer":"default"),i!==null&&this.isPermissionCell(i.y)){let m=this.permissionHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="option"&&this.permissionPrompt!==null&&m.index!==this.permissionPrompt.selectedIndex&&this.onPermissionClick?.({kind:"option",index:m.index,select:!0})}if(i!==null&&this.isCompactionCell(i.y)){let m=this.compactionHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="option"&&this.compactionPrompt!==null&&m.index!==this.compactionPrompt.selectedIndex&&this.onCompactionClick?.({kind:"option",index:m.index,select:!0})}if(i!==null&&this.isFormCell(i.y)){let m=this.formHitAt(i.x,i.y);this.setPointerShape(m!==null?"pointer":"default"),m!==null&&m.kind==="row"&&this.formPrompt!==null&&m.row!==this.formPrompt.selectedIndex&&this.onFormClick?.({kind:"row",row:m.row,select:!0})}}let l=i!==null&&c===null&&this.barHits.get(i.y)===void 0&&i.x>=1&&i.x<=this.transcriptVisibleWidth();if(i!==null&&l&&d!=="release"){let u=this.keyAndSubAtRow(i.y),f=u!==null&&u.key.startsWith("agent:")?null:u;if(f===null&&d==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let p=this.nearestKeyAboveRow(i.y),m=this.nearestKeyBelowRow(i.y);p!==null&&m!==null&&this.hoveredRunKeys.has(p)&&this.hoveredRunKeys.has(m)&&(f={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(f!==null?"pointer":"default"),d==="move"){let p=f?.key??null,m=f?.sub??null;(p!==this.hoveredBlockKey||m!==this.hoveredSubKey)&&(this.hoveredBlockKey=p,this.hoveredSubKey=m,this.hoveredRunKeys=p!==null&&this.onHoverRun?this.onHoverRun(p)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else d==="move"&&(i!==null&&!l&&this.setPointerShape("default"),(this.hoveredBlockKey!==null||this.hoveredSubKey!==null||this.hoveredRunKeys!==null)&&(this.hoveredBlockKey=null,this.hoveredSubKey=null,this.hoveredRunKeys=null,this.syncedPartialRepaint(()=>this.drawScrollback())));if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let u=this.lastLeftClick;if(u!==null&&i!==null&&Math.abs(i.x-u.x)<=bl&&Math.abs(i.y-u.y)<=bl&&Date.now()-u.t<=wl||this.flushPendingBlockClick(),i!==null&&this.handleBarPress(i)){this.pressCell=null;return}if(i!==null&&this.handlePermissionPress(i)){this.pressCell=null;return}if(i!==null&&this.handleCompactionPress(i)){this.pressCell=null;return}if(i!==null&&this.handleHelpPress(i)){this.pressCell=null;return}if(i!==null&&this.handleFormPress(i)){this.pressCell=null;return}if(this.handleSidebarPress(i)){this.pressCell=null,this.clearSelection();return}if(this.pressCell=i,i!==null&&this.handlePromptSelectionPress(i)){this.lastLeftClick=null;return}this.handleSelectionPress(i,B4(t,"shift"));return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),!(e==="MOUSE_RIGHT_BUTTON_PRESSED"&&i!==null&&this.extendSelectionByClick(i))){if(e==="MOUSE_DRAG"&&i!==null){if(this.promptSelectionAnchor!==null){this.handlePromptSelectionDrag(i);return}this.handleSelectionDrag(i);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_RIGHT_BUTTON_RELEASED"||e==="MOUSE_MIDDLE_BUTTON_RELEASED"||e==="MOUSE_OTHER_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){if(this.handleBarRelease(i)){this.pressCell=null;return}if(this.handlePermissionRelease(i)){this.pressCell=null;return}if(this.handleCompactionRelease(i)){this.pressCell=null;return}if(this.handleHelpRelease(i)){this.pressCell=null;return}if(this.handleFormRelease(i)){this.pressCell=null;return}let u=this.pressCell;if(this.pressCell=null,this.promptSelectionAnchor!==null){this.handlePromptSelectionRelease(i);return}let f=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(u!==null&&i!==null&&i.x===u.x&&i.y===u.y&&!f&&this.onBlockClick){let p=this.keyAndSubAtRow(i.y),m=p?.key??null;if(m!==null){let b=i.y;for(;b>1&&this.keyAtRow(b-1)===m;)b-=1;this.schedulePendingBlockClick(m,i.y-b,p?.sub??null)}}(i===null||!this.isSidebarCell(i.x,i.y))&&this.handleSelectionRelease(i)}}}handleSelectionPress(e,t=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,this.selectionGranularity="char",this.selectionAnchorWordBounds=null,this.selectionAnchorLineId=null,!this.inAppSelectionEnabled||e===null)return;let r=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(r===null){this.lastLeftClick=null;return}if(t&&this.selection!==null&&this.extendSelectionByClickResolved(r)){this.lastLeftClick=null;return}this.selectionAnchor=r;let s=Date.now(),o=this.lastLeftClick,i=o!==null&&s-o.t<=wl&&Math.abs(e.x-o.x)<=bl&&Math.abs(e.y-o.y)<=bl&&o.sourceLineId!==null&&o.sourceLineId===r.sourceLineId;if(i&&o.count===2&&e.x===o.x&&e.y===o.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(r.sourceLineId),this.selectionGranularity="line",this.selectionAnchorLineId=r.sourceLineId,this.doubleClickPending=!0;return}if(i&&o.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.tryOpenLinkAt(r,e?.y??null)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenFileAt(r)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(r)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let c=this.wordBoundsAt(r);c!==null&&(this.setSelection({sourceLineId:r.sourceLineId,offset:c.start},{sourceLineId:r.sourceLineId,offset:c.end}),this.doubleClickPending=!0,this.selectionGranularity="word",this.selectionAnchorWordBounds={sourceLineId:r.sourceLineId,start:c.start,end:c.end})}}selectWholeSourceLine(e){let t=this.lineById(e);if(t===null)return;let r=(t.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:r})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null)return;this.extendSelectionForGesture(e);let t=this.scrollbackVisibleRows();if(this.isBtwOverlayCell(e.y)){this.stopAutoscroll();return}e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=t&&this.scrollOffset>0?this.startAutoscroll(e,-1):this.stopAutoscroll()}extendSelectionForGesture(e){this.selectionGranularity==="word"?this.extendWordSelectionToCell(e):this.selectionGranularity==="line"?this.extendLineSelectionToCell(e):this.extendSelectionToCell(e)}extendWordSelectionToCell(e){if(this.selectionAnchorWordBounds===null)return;let t=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(t===null)return;let r=this.selectionAnchorWordBounds,s=this.lineIndexById(r.sourceLineId),o=this.lineIndexById(t.sourceLineId);if(s<0||o<0)return;let i=o<s||o===s&&t.offset<r.start,a=o>s||o===s&&t.offset>r.end,d={sourceLineId:r.sourceLineId,offset:r.start},c={sourceLineId:r.sourceLineId,offset:r.end};if(i){let l=this.wordBoundsAt(t);d=l!==null?{sourceLineId:t.sourceLineId,offset:l.start}:t}else if(a){let l=this.wordBoundsAt(t);c=l!==null?{sourceLineId:t.sourceLineId,offset:l.end}:t}this.selectionDragStarted=!0,this.setSelection(d,c)}extendLineSelectionToCell(e){if(this.selectionAnchorLineId===null)return;let t=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(t===null)return;let r=this.lineIndexById(this.selectionAnchorLineId),s=this.lineIndexById(t.sourceLineId);if(r<0||s<0)return;let o=s<=r?t.sourceLineId:this.selectionAnchorLineId,i=s<=r?this.selectionAnchorLineId:t.sourceLineId,a=this.lineById(i);a!==null&&(this.selectionDragStarted=!0,this.setSelection({sourceLineId:o,offset:0},{sourceLineId:i,offset:(a.body??"").length}))}extendSelectionByClick(e){if(!this.inAppSelectionEnabled||this.selection===null)return!1;let r=this.resolveEdgeSource(e.y)??this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);return r===null?!1:this.extendSelectionByClickResolved(r)}resolveEdgeSource(e){let t=this.scrollbackVisibleRows();if(t<=0||this.lines.length===0)return null;let r=this.contentWidth(),{rows:s}=this.wrapTail(r,t+this.scrollOffset),o=s.length-this.scrollOffset,i=Math.max(0,o-t),a=s.slice(i,o),d=Math.max(0,t-a.length),c=e-1,l=this.scrollOffset<this.maxScrollOffset(),u=this.scrollOffset>0,f=c<d;if(c===0&&l||f){let p=this.lines[0];if(p){let m=this.lineIds.get(p);if(m!==void 0)return{sourceLineId:m,offset:0}}}if(c>=t-1&&u){let p=this.lines[this.lines.length-1];if(p){let m=this.lineIds.get(p);if(m!==void 0)return{sourceLineId:m,offset:(p.body??"").length}}}return null}resolveNearestSource(e,t){let r=this.scrollbackVisibleRows();if(r<=0)return null;let s=Math.max(1,Math.min(this.transcriptVisibleWidth(),e));for(let o=1;o<r;o++){let i=t-o;if(i>=1){let d=this.resolveCellToSource(s,i);if(d!==null){let c=this.lineById(d.sourceLineId);return c?{sourceLineId:d.sourceLineId,offset:(c.body??"").length}:d}}let a=t+o;if(a<=r){let d=this.resolveCellToSource(s,a);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let t=this.farEndpointFrom(e);return t===null?!1:(this.selectionAnchor=t,this.selectionDragStarted=!0,this.setSelection(t,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let t=this.resolveCellToSource(e.x,e.y);t!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,t))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,t){if(this.autoscrollTimer!==null&&this.autoscrollDir===t){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=t,this.autoscrollTimer=setInterval(()=>{if(this.selectionAnchor===null||this.autoscrollCell===null){this.stopAutoscroll();return}let r=this.scrollOffset;if(this.scrollBy(this.autoscrollDir),this.scrollOffset===r){this.stopAutoscroll();return}this.extendSelectionForGesture(this.autoscrollCell)},n.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let t=this.selectionDragStarted,r=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let s=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:s?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(t||r){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let t=this.lineById(e.sourceLineId);if(t===null)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=Ug(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length,a=Math.max(0,Math.min(s.length-1,i));if(i>=s.length&&(a=s.length-1),!od.test(s[a])&&!IS.test(s[a]))return null;let d=a;for(;d>0&&IS.test(s[d-1]);)d--;let c=a+1;for(;c<s.length&&IS.test(s[c]);)c++;for(;c>d+1&&v4.test(s[c-1]);)c--;if(s.slice(d,c).includes("://")){let p=d,m=c;return this.projectCleanRangeToRaw(o,r.length,p,m)}if(!od.test(s[a]))return null;let u=a;for(;u>0&&od.test(s[u-1]);)u--;let f=a+1;for(;f<s.length&&od.test(s[f]);)f++;for(;f>u+1&&v$.test(s[f-1]);)f--;for(;u<f-1&&v$.test(s[u]);)u++;return this.projectCleanRangeToRaw(o,r.length,u,f)}projectCleanRangeToRaw(e,t,r,s){let o=t,i=t;for(let a=0;a<e.length;a++)if(e[a]===r&&o===t&&(o=a),e[a]===s&&i===t){i=a;break}return{start:o,end:i}}pathTokenAt(e){let t=this.lineById(e.sourceLineId);if(t===null||t.ansi)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=Ug(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length;if(t.links){for(let p of t.links)if(i>=p.start&&i<p.end){let m=p.url,b=m.startsWith("file://")?m.slice(7):m,g=null,h=b.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return h&&(b=h[1],g=Number.parseInt(h[2],10)),{raw:b,line:g}}}let a=Math.max(0,Math.min(s.length-1,i));if(i>=s.length&&(a=s.length-1),!xS.test(s[a]))return null;let d=a;for(;d>0&&xS.test(s[d-1]);)d--;let c=a+1;for(;c<s.length&&xS.test(s[c]);)c++;let l=s.slice(d,c);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let u=null,f=s.slice(c).match(/^:(\d+)(?::\d+)?/);return f&&(u=Number.parseInt(f[1],10)),{raw:l,line:u}}findLinkUrlAt(e){let t=this.lineById(e.sourceLineId);if(t===null||!t.links||t.ansi)return null;let r=t.body??"";if(r.length===0)return null;let{clean:s,rawToClean:o}=Ug(r);if(s.length===0)return null;let i=o[Math.min(e.offset,o.length-1)]??s.length;for(let a of t.links)if(i>=a.start&&i<a.end)return a.url;return null}osc8UrlFor(e){if(S$.test(e))return null;if(e.startsWith("file://"))return pl(this.sessionbar)?null:e;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))return e;if(pl(this.sessionbar))return null;let t=e.indexOf("#"),r=t===-1?e:e.slice(0,t),s=t===-1?"":e.slice(t);if(r.length===0)return null;let o=r;return r==="~"||r.startsWith("~/")?o=r==="~"?Ng():`${Ng()}/${r.slice(2)}`:Dg(r)||(o=k$(this.sessionbar.cwd,r)),Hk(o+s)}linkSpansForWindow(e,t,r,s,o){let i=G4(e),a=[];for(let d of t){let c=this.osc8UrlFor(d.url);if(c===null)continue;let l=i[d.start]??e.length,u=i[d.end]??e.length,f=Math.max(l,r),p=Math.min(u,s);p>f&&a.push({start:f-r+o,end:p-r+o,url:c})}return a.length>0?a:null}resolvePathToken(e){let t=e;(t==="~"||t.startsWith("~/"))&&(t=t==="~"?Ng():`${Ng()}/${t.slice(2)}`);let r=Dg(t)||e.startsWith("~"),s=Dg(t)?t:k$(this.sessionbar.cwd,t);if(r)return s;try{if(Cf(s).isFile())return s}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let r=t.line===null?"":`:${t.line}`;return this.tryOpenPathString(t.raw+r)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let r=t.raw;if(!S4.test(r))return!1;let s=r.startsWith(Yt)?[r]:[Yt+r,r],o=null;for(let i of s)try{if(Cf(D.sessionFile(i)).isFile()){o=i;break}}catch{}return o===null?!1:this.onHydraLinkClick(o)}dispatchLinkUrl(e){let t=e.match(S$);if(t){let o=t[1]??null;return o!==null&&this.onHydraLinkClick!==void 0?this.onHydraLinkClick(o):!1}if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)&&!e.startsWith("file://"))return!1;let r=e;if(r.startsWith("file://")){let o=r.slice(7),i=o.indexOf("/");r=i===-1?"":o.slice(i);try{r=decodeURIComponent(r)}catch{}}if(r.length===0)return!1;let s=r.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return s?this.tryOpenPathString(`${s[1]}:${s[2]}`):this.tryOpenPathString(r)}tryOpenLinkAt(e,t){let r=this.findLinkUrlAt(e);if(r!==null)return this.dispatchLinkUrl(r);let o=this.lineById(e.sourceLineId)?.links?.[0]?.url;if(o!==void 0)return this.dispatchLinkUrl(o);if(t!==null){let i=this.blockLinkUrlAt(t);if(i!==null)return this.dispatchLinkUrl(i)}return!1}reconcileWorkspacePath(e){let t=b$(D.home(),"workspaces")+Hg;if(!e.startsWith(t))return e;let s=this.sessionbar.cwd;if(s.length>0&&(e===s||e.startsWith(s+Hg)))return e;let o=!1;try{Cf(e),o=!0}catch{o=!1}if(o)return this.notify("opening a file in a workspace this session left \u2014 edits there will not reach your project",5e3),e;let i=e.slice(t.length).split(Hg).slice(2).join(Hg);if(i.length>0&&s.length>0){let a=b$(s,i);try{if(Cf(a).isFile())return this.notify("that workspace is gone \u2014 opened the file in your project instead",4e3),a}catch{}}return this.notify("that file was in a workspace that no longer exists",4e3),null}tryOpenPathString(e){if(pl(this.sessionbar))return this.notify(`can't open \u2014 this session's files are on ${this.sessionbar.remote}`,4e3),!0;if(this.openFileCommand===null)return!1;let t=e,r=null,s=e.match(/^(.*?):(\d+)(?::\d+)?$/);s&&(t=s[1],r=Number.parseInt(s[2],10));let o=this.resolvePathToken(t);if(o===null)return!1;let i=this.reconcileWorkspacePath(o);if(i===null)return!1;let a=a$(this.openFileCommand,i,r);if(a===null)return!1;let d=r===null?i:`${i}:${r}`;if(this.openFileForeground)return this.openInForeground(a,d),!0;try{let c=g4(a.program,a.args,{detached:!0,stdio:"ignore",cwd:this.spawnCwd()});c.on("error",l=>{this.notify(`open file failed: ${l.message}`)}),c.unref(),this.notify(`opening ${d}`)}catch(c){this.notify(`open file failed: ${c.message}`)}return!0}spawnCwd(){let e=this.sessionbar.cwd;if(!(!e||!Dg(e)))try{return Cf(e).isDirectory()?e:void 0}catch{return}}openInForeground(e,t){this.foregroundChildActive||(this.foregroundChildActive=!0,this.runForeground({program:e.program,args:e.args,cwd:this.spawnCwd(),banner:`\u2500 ${e.program} ${t} \u2014 quit the editor to return to hydra \u2500
272
+ `},{suspend:()=>this.stop(),resume:()=>this.start(),notify:r=>this.notify(r)}).finally(()=>{this.foregroundChildActive=!1}))}schedulePendingBlockClick(e,t,r){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,t,r);return}this.cancelPendingBlockClick();let s=this.onBlockClick,o=setTimeout(()=>{this.pendingBlockClick=null,s(e,t,r)},wl);typeof o.unref=="function"&&o.unref(),this.pendingBlockClick={timer:o,key:e,rowOffset:t,subKey:r}}cancelPendingBlockClick(){this.pendingBlockClick!==null&&(clearTimeout(this.pendingBlockClick.timer),this.pendingBlockClick=null)}flushPendingBlockClick(){let e=this.pendingBlockClick;e!==null&&(clearTimeout(e.timer),this.pendingBlockClick=null,this.onBlockClick&&this.onBlockClick(e.key,e.rowOffset,e.subKey))}displayLineCount(){return this.lines.length+this.displayOverlayCount()}displayOverlayCount(){return this.btwOverlayOpen?this.btwOverlayLines.length:0}displayLineAt(e){if(e<this.lines.length)return this.lines[e];if(this.btwOverlayOpen)return this.btwOverlayLines[e-this.lines.length]}isHiddenDisplayLine(e,t){return e<this.lines.length&&this.isHiddenLine(t)}lineById(e){let t=this.displayLineCount();for(let r=0;r<t;r++){let s=this.displayLineAt(r);if(s&&this.lineIds.get(s)===e)return s}return null}lineIndexById(e){let t=this.displayLineCount();for(let r=0;r<t;r++){let s=this.displayLineAt(r);if(s&&this.lineIds.get(s)===e)return r}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&ml(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let r=e.length;this.notify(`copied ${r} char${r===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${t.reason}`)},t=>{this.notify(`clipboard copy failed: ${t.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let t=e,r=Number(t.x),s=Number(t.y);return!Number.isFinite(r)||!Number.isFinite(s)?null:{x:r,y:s}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,be(e==="pointer"?TP:Ym))}blockLinkUrlAt(e){let t=this.keyAtRow(e);if(t===null||t.startsWith("agent:"))return null;let r=this.contentWidth(),s=1,o=this.scrollbackVisibleRows();if(o<=0)return null;let{rows:i}=this.wrapTail(r,o+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-o),c=i.slice(d,a),l=Math.max(0,o-c.length),u=e-s-l,f=d+u,p=null,m=1/0;for(let b=0;b<i.length;b++){let g=i[b];if(g.blockKey!==t||g.linkSpans===void 0||g.linkSpans.length===0)continue;let h=Math.abs(b-f);h<m&&(m=h,p=g.linkSpans[0]?.url??null)}return p}keyAtRow(e){let t=this.contentWidth(),r=1,s=this.scrollbackVisibleRows();if(s<=0)return null;let o=e-r;if(o<0||o>=s)return null;let{rows:i}=this.wrapTail(t,s+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-s),c=i.slice(d,a),l=Math.max(0,s-c.length),u=o-l;return u<0||u>=c.length?null:c[u]?.blockKey??null}nearestKeyAboveRow(e){for(let t=e-1;t>=1;t--){let r=this.keyAtRow(t);if(r!==null)return r}return null}nearestKeyBelowRow(e){let r=this.scrollbackVisibleRows();for(let s=e+1;s<=r;s++){let o=this.keyAtRow(s);if(o!==null)return o}return null}keyAndSubAtRow(e){let t=this.contentWidth(),r=1,s=this.scrollbackVisibleRows();if(s<=0)return null;let o=e-r;if(o<0||o>=s)return null;let{rows:i}=this.wrapTail(t,s+this.scrollOffset),a=i.length-this.scrollOffset,d=Math.max(0,a-s),c=i.slice(d,a),l=Math.max(0,s-c.length),u=o-l;if(u<0||u>=c.length)return null;let f=c[u];return f?.blockKey?{key:f.blockKey,sub:f.hoverSubKey??null}:null}resolveCellToSource(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return null;let r=this.resolveBtwOverlayCell(e,t);if(r!==null)return r;let s=this.contentWidth(),o=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let a=t-o;if(a<0||a>=i||e<1||e>this.transcriptVisibleWidth())return null;let{rows:d}=this.wrapTail(s,i+this.scrollOffset),c=d.length-this.scrollOffset,l=Math.max(0,c-i),u=d.slice(l,c),f=Math.max(0,i-u.length),p=a-f;if(p<0||p>=u.length)return null;let m=u[p];return m?this.resolveChunkColumn(m,e):null}resolveChunkColumn(e,t){let r=this.wrapOrigin.get(e);if(!r)return null;let s=$t(e.prefix??""),o=r.bodyDisplayShift??0,i=t-1-s;if(i<o)return{sourceLineId:r.sourceLineId,offset:r.sourceColOffset};let a=i,c=Af(e.bodyStyle)||e.ansi===!0?o$(LS(e.body),a):s$(e.body,a);if(r.sourceColEnd!==void 0){let l=this.sourceBodyForId(r.sourceLineId);if(l!==null){let u=MS(e.body,o,c),f=_S(l,r.sourceColOffset,u);return{sourceLineId:r.sourceLineId,offset:f}}}return{sourceLineId:r.sourceLineId,offset:r.sourceColOffset+c-o}}scrollBy(e){if(e===0)return;this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=this.maxScrollOffset(),r=Math.min(t,Math.max(0,this.scrollOffset+e));r!==this.scrollOffset&&(this.scrollOffset=r,this.repaint())}scrollToBottom(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}scrollToPrevTurn(){if(this.pageWhenNoTurns(1))return;let e=this.turnStops(),t=this.settledScrollOffset(),r=e.find(s=>s>t);this.stepToTurnStop(r??this.maxScrollOffset())}scrollToNextTurn(){if(this.pageWhenNoTurns(-1))return;let e=this.turnStops(),t=this.settledScrollOffset(),r=0;for(let s of e){if(s>=t)break;r=s}this.stepToTurnStop(r)}pageWhenNoTurns(e){return this.turnScrollOffsets().length>0?!1:(this.scrollBy(e*this.scrollPageSize()),!0)}settledScrollOffset(){return this.slideTimer!==null?this.slideTarget:this.scrollOffset}stepToTurnStop(e){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.slideScrollTo(e),this.notifyTurnPosition(e)}turnStops(){let e=this.maxScrollOffset(),t=[0,...this.turnScrollOffsets(),e].filter(r=>r>=0&&r<=e).sort((r,s)=>r-s);return t.filter((r,s)=>s===0||r!==t[s-1])}notifyTurnPosition(e){let t=this.turnScrollOffsets();if(t.length===0)return;let r=t.findIndex(o=>o>=e),s=r===-1?1:t.length-r;this.notify(`turn ${s}/${t.length}`,1500)}turnScrollOffsets(){return this.turnAnchors().map(e=>e.offset)}turnAnchors(){let e=this.contentWidth(),t=this.scrollbackVisibleRows();if(t<=0)return[];let r=[],s=0,o=null;for(let i=this.lines.length-1;i>=0;i--){let a=this.lines[i];if(!(!a||this.isHiddenLine(a))){if(s+=this.wrapOne(a,e).length,a.bodyStyle==="user"){o={offset:Math.max(0,s-t),lineIndex:i,recordedAt:a.recordedAt};continue}o!==null&&(r.push(o),o=null)}}return o!==null&&r.push(o),r}scrollToTurnAt(e){let t=this.turnAnchors();if(t.length===0)return;let r=t.find(s=>s.recordedAt!==void 0&&s.recordedAt<=e)??t[t.length-1];this.setScrollOffset(r.offset),this.notifyTurnPosition(r.offset)}slideScrollTo(e){this.cancelSlide();let t=Math.min(this.maxScrollOffset(),Math.max(0,e)),r=Math.abs(t-this.scrollOffset);if(r!==0){if(r<=N4||!this.slideEnabled){this.setScrollOffset(t);return}this.slideTarget=t,this.slideTimer=setInterval(()=>{let s=this.slideTarget-this.scrollOffset,o=Math.sign(s)*Math.max(1,Math.round(Math.abs(s)*L4)),i=Math.abs(s)<=Math.abs(o)?this.slideTarget:this.scrollOffset+o;this.scrollOffset=i,this.syncedPartialRepaint(()=>this.drawScrollback()),i===this.slideTarget&&this.cancelSlide()},F4)}}cancelSlide(e=!1){this.slideTimer!==null&&(clearInterval(this.slideTimer),this.slideTimer=null,e&&this.scrollOffset!==this.slideTarget&&(this.scrollOffset=Math.min(this.maxScrollOffset(),Math.max(0,this.slideTarget)),this.syncedPartialRepaint(()=>this.drawScrollback())))}setScrollOffset(e){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=Math.min(this.maxScrollOffset(),Math.max(0,e));t!==this.scrollOffset&&(this.scrollOffset=t,this.repaint())}isScrolledBack(){return this.scrollOffset>0}isScrollbackSearchActive(){return this.scrollbackSearch!==null}enterScrollbackSearch(){this.scrollbackSearch===null&&(this.scrollbackSearch={term:"",matchIndex:0,matches:[],baselineScroll:this.scrollOffset},this.scrollbackHighlight=null,this.repaint())}updateScrollbackSearchTerm(e){if(this.scrollbackSearch===null)return;let t=e.toLowerCase(),r=[];if(t.length>0)for(let s=this.lines.length-1;s>=0;s--){let o=this.lines[s];if(!o||o.body.length===0||o.ansi)continue;let i=P$(o.body,t);for(let a=i.length-1;a>=0;a--)r.push({lineIdx:s,col:i[a].start})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=r,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=t.length>0?t:null,r.length>0&&this.scrollToMatch(r[0]),this.repaint()}advanceScrollbackSearch(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return;let e=Math.min(this.scrollbackSearch.matches.length-1,this.scrollbackSearch.matchIndex+1);e!==this.scrollbackSearch.matchIndex&&(this.scrollbackSearch.matchIndex=e,this.scrollToMatch(this.scrollbackSearch.matches[e]),this.repaint())}retreatScrollbackSearch(){this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0||this.scrollbackSearch.matchIndex!==0&&(this.scrollbackSearch.matchIndex-=1,this.scrollToMatch(this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex]),this.repaint())}acceptScrollbackSearch(){this.scrollbackSearch!==null&&(this.scrollbackSearch=null,this.scrollbackHighlight=null,this.repaint())}cancelScrollbackSearch(){if(this.scrollbackSearch===null)return;let e=this.scrollbackSearch.baselineScroll;this.scrollbackSearch=null,this.scrollbackHighlight=null,this.scrollOffset=e,this.repaint()}scrollbackSearchTerm(){return this.scrollbackSearch?.term??""}currentMatchInfo(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return null;let e=this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex];if(!e)return null;let t=this.lines[e.lineIdx];if(!t)return null;let r=this.lineIds.get(t);return r===void 0?null:{lineId:r,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,t){if(!e||t===null)return null;let r=this.wrapOrigin.get(e);if(!r||r.sourceLineId!==t.lineId)return null;let s=r.bodyDisplayShift??0,o=t.col-r.sourceColOffset+s;return o<s||o>=e.body.length?null:o}scrollToMatch(e){let t=this.contentWidth(),r=this.scrollbackVisibleRows();if(r<=0)return;let s=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(s+=this.wrapOne(u,t).length)}let o=this.lines[e.lineIdx],i=0;if(o){let l=this.wrapOne(o,t),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let m=p.body.length;if(e.col<u+m){i=l.length-1-f;break}u+=m}}let a=s+i,d=Math.max(0,a-Math.floor(r/2)),c=this.maxScrollOffset();this.scrollOffset=Math.min(c,d)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let t=this.term.height-this.promptRows()-Ot-Ut-Bt-x4-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,t-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.contentWidth(),Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){this.scheduler.schedule()}paintRow(e,t,r,s){return this.started?this.painter.paintRow(e,t,r,s):!1}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,t=this.term.height;e<20||t<8||(this.painter.ensureSize(e,t),this.barHits.clear(),mt(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawSidebar(1,this.scrollbackVisibleRows()),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let r=this.promptRows(),s=t-r-Bt-Ut-Ot;this.drawBar("composerTop",s),this.drawPrompt(),this.drawBar("composerBottom",t-Ot),this.drawBar("sessionbar",this.term.height),this.placeCursor(),(this.permissionPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=r}))}barContext(){return{scope:"session",session:this.sessionbar,banner:this.banner,scrollOffset:this.scrollOffset,transient:this.bannerRightContent(),hovered:this.terminalFocused?this.hoveredBarHit:null,hintsRevealed:this.hintsRevealed(),scriptOutputs:this.scriptOutputs}}trackHintHover(e){return e?(this.cancelHintHoverHide(),this.hintHoverReveal?!1:(this.hintHoverReveal=!0,!0)):(!this.hintHoverReveal||this.hintHoverHideTimer!==null||(this.hintHoverHideTimer=setTimeout(()=>{this.hintHoverHideTimer=null,this.hintHoverReveal=!1,this.syncedPartialRepaint(()=>this.drawBars())},k4)),!1)}cancelHintHoverHide(){this.hintHoverHideTimer!==null&&(clearTimeout(this.hintHoverHideTimer),this.hintHoverHideTimer=null)}hintsRevealed(){return this.terminalFocused?this.hintHoverReveal||this.hintKeyReveal:!1}revealHints(){this.hintKeyReveal||(this.hintKeyReveal=!0,this.syncedPartialRepaint(()=>this.drawBars()))}clearHintReveal(){this.cancelHintHoverHide(),!(!this.hintKeyReveal&&!this.hintHoverReveal)&&(this.hintKeyReveal=!1,this.hintHoverReveal=!1,this.syncedPartialRepaint(()=>this.drawBars()))}btwContext(){let e=this.btwOverlayStatus==="busy"?"busy":this.btwOverlayStatus==="done"?"ready":"disconnected";return{scope:"btw",statusLabel:"By the way",session:{...this.sessionbar,sessionId:this.btwOverlaySessionId??"",...this.btwOverlayUsage!==void 0?{usage:this.btwOverlayUsage}:{usage:void 0}},banner:{status:e,currentMode:void 0,hint:[],queued:0},scrollOffset:0,transient:null,hovered:this.terminalFocused?this.hoveredBarHit:null,hintsRevealed:!1,scriptOutputs:this.scriptOutputs}}drawBar(e,t){let r=Xv[e],s=e==="sessionbar"?Math.max(1,this.term.width-1):this.term.width,o=e==="sessionbar"?this.barConfig.sessionbar:e==="composerBottom"?this.barConfig.composer.bottom:this.barConfig.composer.top;e==="composerBottom"&&(this.composerBottomRow=t);let i=e==="btw"?this.btwContext():this.barContext(),a=e==="composerBottom"?v_(i):null,d=a!==null?[a]:kf(e,o.right,i),c=Jv(s,kf(e,o.left,i),d,r);e==="composerBottom"&&(this.hintZoneStart=this.hintZoneStartFor(s,o,i,a,c));let l=this.terminalFocused?this.hoveredBarHit:null,u=`${e}|${s}|${l??""}|${c.signature}`;this.paintRow(t,u,()=>{for(let f of c.chunks){let p=f.id!==void 0&&f.id===l?"hint-hover":f.token;H(this.term,p,f.text)}}),this.barHits.set(t,c.hits)}hintZoneStartFor(e,t,r,s,o){if(s!==null)return null;if(r.hintsRevealed)return o.rightStart;let i={...r,hintsRevealed:!0};return Jv(e,kf("composerBottom",t.left,i),kf("composerBottom",t.right,i),Xv.composerBottom).rightStart}barHitAt(e,t){let r=this.barHits.get(t);return r===void 0?null:r.find(s=>e>=s.start&&e<=s.end)??null}bannerHitAt(e,t){let r=this.barHitAt(e,t);if(r===null)return null;let s=r.id.slice(r.id.indexOf(":")+1);return Dv.some(o=>o.id===s)?s:null}stepFormCursor(e){let t=this.formPrompt;if(t===null||t.rows.length===0)return;let r=Math.max(0,Math.min(t.rows.length-1,t.selectedIndex+e));r!==t.selectedIndex&&this.onFormClick?.({kind:"row",row:r,select:!0})}isFormCell(e){let t=this.formRegion;return this.formPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}formHitAt(e,t){if(!this.isFormCell(t))return null;for(let s of this.formHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.formRowHits.get(t);if(r===void 0)return null;if(r.field!==void 0&&e>=r.field.startCol){let{slice:s,sliceStart:o,startCol:i}=r.field,a=o,d=i;for(let c of s){let l=d+$t(c);if(e<l)break;d=l,a+=c.length}return{kind:"row",row:r.row,caretOffset:a}}return{kind:"row",row:r.row}}handleFormPress(e){return this.isFormCell(e.y)?(this.formPressHit=this.formHitAt(e.x,e.y),!0):(this.formPressHit=null,!1)}handleFormRelease(e){let t=this.formPressHit;if(this.formPressHit=null,t===null||e===null||!this.isFormCell(e.y))return t!==null;let r=this.formHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="row"&&t.kind==="row"&&r.row!==t.row||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action||this.onFormClick?.(r),!0}handleBarPress(e){let t=this.barHitAt(e.x,e.y);if(t===null)return this.barPressHit=null,!1;let r=Date.now(),s=this.lastBarClick;return s!==null&&s.id===t.id&&r-s.t<=wl&&t.doubleAction!=="none"?(this.lastBarClick=null,this.barPressHit=null,this.dispatchBarAction(t.doubleAction,t.value),!0):(this.lastBarClick={id:t.id,t:r},this.barPressHit=t,!0)}handleBarRelease(e){let t=this.barPressHit;if(this.barPressHit=null,t===null||e===null)return!1;let r=this.barHitAt(e.x,e.y);return r===null||r.id!==t.id?!1:(r.action==="none"||this.dispatchBarAction(r.action,r.value),!0)}dispatchBarAction(e,t){if(e!=="none"){if(e==="copy"){ml(t,{target:this.selectionClipboard}).then(r=>{this.notify(r.ok?`copied ${t}`:`clipboard copy failed: ${r.reason}`)},r=>{this.notify(`clipboard copy failed: ${r.message}`)});return}if(e==="open-session"){this.onHydraLinkClick?.(t);return}if(e==="open"){this.tryOpenPathString(t)||this.notify(this.hasOpenFileCommand()?`can't open ${t}`:"no tui.openFileCommand configured");return}this.onBarAction?.(e,t)}}drawScrollback(){let e=this.contentWidth(),t=this.sidebarReserved()>0&&!this.sidebarOverlay(),r=this.sidebarBodyWidth()>0,s=1,o=this.scrollbackVisibleRows();if(o<=0)return;let{rows:i,exhausted:a}=this.wrapTail(e,o+this.scrollOffset);if(a){let g=Math.max(0,i.length-o);this.scrollOffset>g&&(this.scrollOffset=g)}let d=i.length-this.scrollOffset,c=Math.max(0,d-o),l=i.slice(c,d),u=Math.max(0,o-l.length),f=this.currentMatchInfo(),p=f?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let m=-1,b=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let g=0;g<l.length;g++){let h=l[g]?.blockKey;h===void 0||!(h===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(h))||(m===-1&&(m=g),b=g)}for(let g=0;g<o;g++){let h=s+g,y=g-u,k=y>=0?l[y]:void 0,S=this.activeMatchCol(k,f),I=k?this.selectionRangeForChunk(k):null,x=k!==void 0&&k.blockKey!==void 0&&(k.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(k.blockKey)),C=k!==void 0&&k.blockKey===void 0&&m!==-1&&y>=m&&y<=b,$=x||C,P=this.terminalFocused&&$&&(this.hoveredSubKey===null||(k.hoverSubKey??null)===this.hoveredSubKey),M=PS("sb",e,k,this.scrollbackHighlight,S,I)+(P?"|H":"");this.paintRow(h,M,()=>{k?this.writeFormattedLine(k,e,S,p,I,P,t,k.linkSpans??null):t&&this.term(" ".repeat(e))},t?{erase:!1}:void 0)&&r&&this.painter.invalidate("sidebar",h)}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let g=new Set;for(let y of l)y.blockKey!==void 0&&g.add(y.blockKey);let h=[];for(let y of this.pendingVisibleKeys)g.has(y)&&h.push(y);for(let y of h)this.pendingVisibleKeys.delete(y),this.onBlockVisible(y)}}drawSidebar(e,t){let r=this.sidebarBodyWidth();if(r<=0||t<=0){this.sidebarOverflowRows=0;return}let s=this.sidebarColumnStart(),o={metrics:{cellWidth:$t,truncate:mn},width:r,border:this.sidebarBorder,pages:this.sidebarPages,collapsed:this.sidebarCollapsed,maxRows:t},i={...this.sidebarSnapshot,now:Date.now()},a=this.sidebarRenderer.render(i,o);this.sidebarOverflowRows=Math.max(0,a.length-t),this.sidebarScrollOffset>this.sidebarOverflowRows&&(this.sidebarScrollOffset=this.sidebarOverflowRows);let d=this.sidebarScrollOffset;this.sidebarRowPaths.clear(),this.sidebarRowDoubleActions.clear(),this.sidebarRowActions.clear(),this.sidebarRowLinks.clear();let c=s+Rf;for(let l=0;l<t;l++){let u=e+l,f=l+d,p=a[f];p?.openPath!==void 0&&this.sidebarRowPaths.set(u,p.openPath),p?.doubleAction!==void 0&&this.sidebarRowDoubleActions.set(u,p.doubleAction),p?.links!==void 0&&p.links.length>0&&this.sidebarRowLinks.set(u,p.links.map(h=>({start:c+h.start,end:c+h.end,url:h.url}))),p?.actions!==void 0&&p.actions.length>0&&this.sidebarRowActions.set(u,p.actions.map(h=>({start:c+h.start-1,end:c+h.end-1,..."page"in h?{gadget:h.page.gadget,index:h.page.index}:{gadget:h.collapse.gadget,collapse:!0}})));let m=l===0&&d>0?"\u25B2":l===t-1&&d<this.sidebarOverflowRows?"\u25BC":p?.gutter??" ",b=(()=>{let h=[];if(p?.openPath!==void 0&&p.openPath.startsWith("/")&&p.openSpan!==void 0&&h.push({...p.openSpan,url:Hk(p.openPath)}),p?.links!==void 0){let y=this.linkSpansForWindow(p.body,p.links,0,p.body.length,0);y!==null&&h.push(...y)}return h.length>0?h:null})(),g=PS("sbar",r,p,null,null,null)+`|${m}|${b===null?"":b.map(h=>`${h.start}:${h.end}:${h.url}`).join(",")}`;this.paintRow(u,g,()=>{this.term(" ".repeat(Math.max(0,Rf-1))),m===" "?this.term(" "):mo(this.term,m,"sidebar-rule",!1),p?this.writeFormattedLine(p,r,null,0,null,!1,!0,b):this.term(" ".repeat(r))},{region:"sidebar",column:s})}}scrollSidebarBy(e){if(this.sidebarOverflowRows<=0)return!1;let t=Math.max(0,Math.min(this.sidebarOverflowRows,this.sidebarScrollOffset-e));return t===this.sidebarScrollOffset||(this.sidebarScrollOffset=t,this.repaintNow()),!0}sidebarPageState(){return this.sidebarPages}sidebarScrollState(){return{offset:this.sidebarScrollOffset,overflow:this.sidebarOverflowRows}}isSidebarCell(e,t){let r=this.sidebarColumnStart();return r===0?!1:e>=r&&e<=(this.term.width||0)&&t>=1&&t<=this.scrollbackVisibleRows()}handleSidebarPress(e){if(e===null||!this.isSidebarCell(e.x,e.y))return!1;for(let o of this.sidebarRowActions.get(e.y)??[])if(!(e.x<o.start||e.x>o.end))return o.collapse===!0?this.toggleSidebarGadgetCollapsed(o.gadget):this.sidebarPages={...this.sidebarPages,[o.gadget]:o.index??0},this.lastSidebarClick=null,this.repaintNow(),!0;let t=Date.now(),r=this.lastSidebarClick;if(r!==null&&t-r.t<=wl&&e.y===r.y){this.lastSidebarClick=null;let o=this.sidebarRowDoubleActions.get(e.y);if(o!==void 0)return this.dispatchBarAction(o.action,o.value),!0;let a=this.sidebarRowLinks.get(e.y)?.find(c=>e.x>=c.start&&e.x<c.end);if(a!==void 0)return this.dispatchLinkUrl(a.url),!0;let d=this.sidebarRowPaths.get(e.y);return d!==void 0&&!this.dispatchLinkUrl(d)&&this.notify(this.hasOpenFileCommand()?`can't open ${d}`:"no tui.openFileCommand configured"),!0}return this.lastSidebarClick={x:e.x,y:e.y,t},!0}hasOpenFileCommand(){return this.openFileCommand!==null}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(RS,this.queuedTexts.length)}chipRows(){return Math.min(TS,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((t,r)=>t===e[r])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(AS,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),s=this.term.height-r-Ot-Ut-Bt,o=this.queuedRows(),i=this.chipRows(),d=s-1-o-i-e+1,c=0;for(let l of this.completions.slice(0,e))l.name.length>c&&(c=l.name.length);for(let l=0;l<e;l++){let u=d+l,f=this.completions[l],p=l===e-1&&this.completions.length>AS,m=this.completions.length-AS+1,b=f?p?`comp|${t}|overflow|${m}`:`comp|${t}|${c}|${f.name}|${f.description??""}`:`comp|${t}|empty`;this.paintRow(u,b,()=>{if(!f)return;if(p){H(this.term,"modal-hint",` + ${m} more match(es)`);return}let g=f.name.padEnd(c),h=f.description??"",y=t-g.length-4,k=y>0?mn(h,y):"";this.term.noFormat(" "),H(this.term,"completion-name",g),k.length>0&&(this.term.noFormat(" "),H(this.term,"completion-desc",k))})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),i=this.term.height-r-Ot-Ut-Bt-1-e+1;for(let a=0;a<e;a++){let d=i+a,c=a===e-1&&this.attachments.length>TS,l=this.attachments.length-TS,u=this.attachments[a],f=u?`${u.name??"image"} \xB7 ${zr(u.sizeBytes)}`:"",p=c?`chip|${t}|overflow|${l}`:u?`chip|${t}|${f}`:`chip|${t}|empty`;this.paintRow(d,p,()=>{if(c){H(this.term,"modal-hint",` \u{1F4CE} + ${l+1} more attached`);return}u&&(this.term.noFormat(" "),H(this.term,"attachment",`\u{1F4CE} ${f}`))})}}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let t=this.term.width,r=this.promptRows(),s=this.term.height-r-Ot-Ut-Bt,o=this.chipRows(),a=s-1-o-e+1,d=this.dispatcher.state().queueIndex;for(let c=0;c<e;c++){let l=a+c,u=this.queuedTexts[c],f=c===e-1&&this.queuedTexts.length>RS,p=this.queuedTexts.length-RS,m=u===void 0?"":f?`+ ${p+1} more queued`:mn(sJ(u),t-4),b=!f&&c===d,g=u===void 0?`queued|${t}|empty`:`queued|${t}|${b?"edit":f?"ovf":"row"}|${m}`;this.paintRow(l,g,()=>{if(u===void 0)return;let h=`\u23F3 ${m}`,y=h+" ".repeat(Math.max(0,t-1-h.length));b?H(this.term,"queue-cursor","\u25B8"):H(this.term,"queue-blank"," "),H(this.term,"queue-row",y)})}}promptVisualLayout(){if(this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt||this.scrollbackSearch||this.readonly)return null;let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=Cs(r.buffer,t),o=go(s,r,Bg);return{top:this.term.height-o.rendered-Bt-Ut-Ot+1,layout:o,visualRows:s}}resolveCellToPromptOffset(e,t){let r=this.promptVisualLayout();if(r===null)return null;let{top:s,layout:o,visualRows:i}=r,a=t-s;if(a<0||a>=o.rendered||e<1||e>this.term.width)return null;let d=i[o.windowStart+a];if(!d)return null;let l=Math.max(0,Math.min(d.endCol-d.startCol,e-1-2));return{row:d.bufferIdx,col:d.startCol+l}}setPromptSelection(e,t){let r=e.row<t.row||e.row===t.row&&e.col<=t.col,s=r?e:t,o=r?t:e;if(s.row===o.row&&s.col===o.col){this.clearPromptSelection();return}let i={startRow:s.row,startCol:s.col,endRow:o.row,endCol:o.col},a=this.promptSelection;a&&a.startRow===i.startRow&&a.startCol===i.startCol&&a.endRow===i.endRow&&a.endCol===i.endCol||(this.promptSelection=i,this.syncedPartialRepaint(()=>this.drawPrompt()))}clearPromptSelection(){this.promptSelection!==null&&(this.promptSelection=null,this.syncedPartialRepaint(()=>this.drawPrompt()))}getPromptSelectionText(){if(this.promptSelection===null)return"";let{startRow:e,startCol:t,endRow:r,endCol:s}=this.promptSelection,o=this.dispatcher.state().buffer;if(e===r)return(o[e]??"").slice(t,s);let i=[(o[e]??"").slice(t)];for(let a=e+1;a<r;a++)i.push(o[a]??"");return i.push((o[r]??"").slice(0,s)),i.join(`
273
+ `)}promptWordBoundsAt(e){let t=this.dispatcher.state().buffer[e.row]??"";if(t.length===0)return null;let r=Math.max(0,Math.min(t.length-1,e.col));if(!od.test(t[r]))return null;let s=r;for(;s>0&&od.test(t[s-1]);)s--;let o=r+1;for(;o<t.length&&od.test(t[o]);)o++;return{start:s,end:o}}selectPromptWholeLine(e){let t=this.dispatcher.state().buffer[e]??"";this.setPromptSelection({row:e,col:0},{row:e,col:t.length})}extendPromptWordSelectionTo(e){let t=this.promptSelectionAnchorWordBounds;if(t===null)return;let r=e.row<t.row||e.row===t.row&&e.col<t.start,s=e.row>t.row||e.row===t.row&&e.col>t.end,o={row:t.row,col:t.start},i={row:t.row,col:t.end};if(r){let a=this.promptWordBoundsAt(e);o=a!==null?{row:e.row,col:a.start}:e}else if(s){let a=this.promptWordBoundsAt(e);i=a!==null?{row:e.row,col:a.end}:e}this.setPromptSelection(o,i)}extendPromptLineSelectionTo(e){let t=this.promptSelectionAnchorLineRow;if(t===null)return;let r=Math.min(t,e.row),s=Math.max(t,e.row),o=this.dispatcher.state().buffer[s]??"";this.setPromptSelection({row:r,col:0},{row:s,col:o.length})}handlePromptSelectionPress(e){if(!this.inAppSelectionEnabled)return!1;let t=this.resolveCellToPromptOffset(e.x,e.y);if(t===null)return!1;this.promptSelectionAnchor=t,this.promptSelectionDragStarted=!1,this.promptDoubleClickPending=!1,this.promptPendingClickCount=1,this.promptSelectionGranularity="char",this.promptSelectionAnchorWordBounds=null,this.promptSelectionAnchorLineRow=null,this.clearPromptSelection();let r=Date.now(),s=this.promptLastLeftClick,o=s!==null&&r-s.t<=wl&&Math.abs(e.x-s.x)<=bl&&Math.abs(e.y-s.y)<=bl&&s.row!==null&&s.row===t.row;if(o&&s.count===2&&e.x===s.x&&e.y===s.y)return this.promptPendingClickCount=3,this.selectPromptWholeLine(t.row),this.promptSelectionGranularity="line",this.promptSelectionAnchorLineRow=t.row,this.promptDoubleClickPending=!0,!0;if(o&&s.count===1){this.promptPendingClickCount=2;let d=this.promptWordBoundsAt(t);d!==null&&(this.setPromptSelection({row:t.row,col:d.start},{row:t.row,col:d.end}),this.promptDoubleClickPending=!0,this.promptSelectionGranularity="word",this.promptSelectionAnchorWordBounds={row:t.row,start:d.start,end:d.end})}return!0}handlePromptSelectionDrag(e){if(this.promptSelectionAnchor===null)return;let t=this.promptVisualLayout();if(t===null)return;let r=Math.max(1,Math.min(this.term.width,e.x)),s=Math.max(t.top,Math.min(t.top+t.layout.rendered-1,e.y)),o=this.resolveCellToPromptOffset(r,s);o!==null&&(this.promptSelectionDragStarted=!0,this.promptSelectionGranularity==="word"?this.extendPromptWordSelectionTo(o):this.promptSelectionGranularity==="line"?this.extendPromptLineSelectionTo(o):this.setPromptSelection(this.promptSelectionAnchor,o))}handlePromptSelectionRelease(e){let t=this.promptSelectionDragStarted,r=this.promptDoubleClickPending;if(this.promptSelectionAnchor=null,this.promptSelectionDragStarted=!1,this.promptDoubleClickPending=!1,e!==null){let s=this.resolveCellToPromptOffset(e.x,e.y);this.promptLastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.promptPendingClickCount,row:s?.row??null}}if(this.promptPendingClickCount=1,t||r){this.finalizePromptSelection();return}this.clearPromptSelection()}finalizePromptSelection(){let e=this.getPromptSelectionText();e.length!==0&&ml(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let r=e.length;this.notify(`copied ${r} char${r===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${t.reason}`)},t=>{this.notify(`clipboard copy failed: ${t.message}`)})}drawPrompt(){if((this.permissionPrompt||this.formPrompt||this.confirmPrompt)&&(this.compactionRegion=null),(this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.compactionPrompt)&&(this.helpRegion=null),this.permissionPrompt){this.drawPermissionPrompt();return}if(this.formPrompt){this.drawFormPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.compactionPrompt){this.drawCompactionPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=Cs(r.buffer,t),o=go(s,r,Bg),i=this.term.height-o.rendered-Bt-Ut-Ot+1,a=!1;for(let d=0;d<o.rendered;d++){let c=s[o.windowStart+d],l=i+d,u="wrap",f="";c&&(c.bufferIdx===0&&c.startCol===0?u="first":c.startCol===0&&(u="newline"),f=(r.buffer[c.bufferIdx]??"").slice(c.startCol,c.endCol));let p=-1,m=-1;if(c&&this.promptSelection!==null){let g=this.promptSelection;if(c.bufferIdx>=g.startRow&&c.bufferIdx<=g.endRow){let h=c.bufferIdx===g.startRow?g.startCol:c.startCol,y=c.bufferIdx===g.endRow?g.endCol:c.endCol,k=Math.max(h,c.startCol),S=Math.min(y,c.endCol);S>k&&(p=k-c.startCol,m=S-c.startCol)}}let b=c?`prompt|${this.term.width}|${u}|${f}|${p}:${m}`:`prompt|${this.term.width}|empty`;this.paintRow(l,b,()=>{c&&(u==="first"?a?H(this.term,"composer-inactive","> "):H(this.term,"composer-gutter","> "):u==="newline"?H(this.term,"composer-continuation","\xB7 "):this.term(" "),a?H(this.term,"composer-inactive",f):p>=0&&m>p?(p>0&&H(this.term,"content",f.slice(0,p)),H(this.term,"selection-highlight",f.slice(p,m)),m<f.length&&H(this.term,"content",f.slice(m))):H(this.term,"content",f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let t=this.term.width,r=this.term.height-ES-Bt-Ut-Ot+1;this.paintRow(r,`confirm|q|${t}|${e.question}`,()=>{H(this.term,"prompt-text",` ? ${mn(e.question,t-4)}`)}),this.paintRow(r+1,`confirm|h|${t}|${e.hint}`,()=>{H(this.term,"modal-hint",` ${mn(e.hint,t-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let t=this.term.width,r=this.compactionRows(),s=this.term.height-r-Bt-Ut-Ot+1,o=s;this.compactionRowHits.clear(),this.compactionHintHits=[],this.compactionRegion={top:s,bottom:s+r-1};let i=(c,l)=>{o>=s+r||(this.paintRow(o,c,l),o+=1)};i(`cpct|msg|${t}|${e.message}`,()=>{H(this.term,"prompt-text",` ${mn(e.message,t-2)}`)}),i(`cpct|q|${t}`,()=>{H(this.term,"content"," Compact now to reduce future per-turn token cost?")});for(let c=0;c<e.options.length&&!(o>=s+r-1);c++){let l=e.options[c];if(!l)continue;let u=c===e.selectedIndex,p=` ${u?"\u276F":" "} ${c+1}. ${mn(l.label,t-8)}`;this.compactionRowHits.set(o,c),i(`cpct|o|${t}|${c}|${u?"1":"0"}|${l.label}`,()=>{u?H(this.term,"modal-option-selected",p):H(this.term,"modal-option",p)})}let a=$S(P4,t),d=o;for(let c of a.spans)(c.action==="commit"||c.action==="cancel")&&this.compactionHintHits.push({row:d,start:c.start,end:c.end,action:c.action});i(`cpct|hint|${t}|${a.text}`,()=>{H(this.term,"modal-hint",` ${a.text}`)})}isCompactionCell(e){let t=this.compactionRegion;return this.compactionPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}compactionHitAt(e,t){if(!this.isCompactionCell(t))return null;for(let s of this.compactionHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.compactionRowHits.get(t);return r===void 0?null:{kind:"option",index:r}}stepCompactionCursor(e){let t=this.compactionPrompt;if(t===null||t.options.length===0)return;let r=Math.max(0,Math.min(t.options.length-1,t.selectedIndex+e));r!==t.selectedIndex&&this.onCompactionClick?.({kind:"option",index:r,select:!0})}handleCompactionPress(e){return this.isCompactionCell(e.y)?(this.compactionPressHit=this.compactionHitAt(e.x,e.y),!0):(this.compactionPressHit=null,!1)}handleCompactionRelease(e){let t=this.compactionPressHit;if(this.compactionPressHit=null,t===null||e===null||!this.isCompactionCell(e.y))return t!==null;let r=this.compactionHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="option"&&t.kind==="option"&&r.index!==t.index||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action?!0:Date.now()-this.compactionArmedAt<I$?(this.notify("compaction prompt just appeared, click again to confirm"),!0):(this.onCompactionClick?.(r),!0)}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let t=this.term.width,r=this.helpRows(),s=this.term.height-r-Bt-Ut-Ot+1,o=s;this.helpRegion={top:s,bottom:s+r-1};let i=(d,c)=>{o>=s+r||(this.paintRow(o,d,c),o+=1)};i(`help|t|${t}|${e.title}`,()=>{H(this.term,"prompt-text",` \u2753 ${mn(e.title,t-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(d=>d===null?0:d[0].length),4));for(let d of e.entries){if(o>=s+r-1)break;if(d===null){i(`help|sep|${t}|${o}`,()=>{});continue}let[c,l]=d,u=c.padEnd(a);i(`help|e|${t}|${c}|${l}`,()=>{this.term(" "),H(this.term,"modal-key",u),H(this.term,"content",` ${mn(l,t-2-a-1)}`)})}i(`help|hint|${t}|${e.hint}`,()=>{H(this.term,"modal-hint",` ${mn(e.hint,t-2)}`)})}helpRows(){return this.helpPrompt?Math.min(_4,2+this.helpPrompt.entries.length):0}isHelpCell(e){let t=this.helpRegion;return this.helpPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}handleHelpPress(e){return this.isHelpCell(e.y)?(this.helpPressed=!0,!0):(this.helpPressed=!1,!1)}handleHelpRelease(e){let t=this.helpPressed;return this.helpPressed=!1,t?(e!==null&&this.isHelpCell(e.y)&&this.onHelpClick?.(),!0):!1}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let t=this.term.width,r=this.permissionRows(),s=this.term.height-r-Bt-Ut-Ot+1,o=s;this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion={top:s,bottom:s+r-1};let i=(l,u)=>{o>=s+r||(this.paintRow(o,l,u),o+=1)};i(`perm|t|${t}|${e.title}`,()=>{H(this.term,"prompt-text",` \u{1F512} ${mn(e.title,t-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";i(`perm|sub|${t}|${a}`,()=>{H(this.term,"modal-hint",` ${mn(a,t-2)}`)}),i(`perm|q|${t}`,()=>{H(this.term,"content"," Do you want to proceed?")});for(let l=0;l<e.options.length&&!(o>=s+r-1);l++){let u=e.options[l];if(!u)continue;let f=l===e.selectedIndex,m=` ${f?"\u276F":" "} ${l+1}. ${mn(u.label,t-8)}`;this.permissionRowHits.set(o,l),i(`perm|o|${t}|${l}|${f?"1":"0"}|${u.label}`,()=>{f?H(this.term,"modal-option-selected",m):H(this.term,"modal-option",m)})}let d=$S(E4,t),c=o;for(let l of d.spans)(l.action==="commit"||l.action==="cancel")&&this.permissionHintHits.push({row:c,start:l.start,end:l.end,action:l.action});i(`perm|hint|${t}|${d.text}`,()=>{H(this.term,"modal-hint",` ${d.text}`)})}isPermissionCell(e){let t=this.permissionRegion;return this.permissionPrompt!==null&&t!==null&&e>=t.top&&e<=t.bottom}permissionHitAt(e,t){if(!this.isPermissionCell(t))return null;for(let s of this.permissionHintHits)if(s.row===t&&e>=s.start&&e<=s.end)return{kind:"hint",action:s.action};let r=this.permissionRowHits.get(t);return r===void 0?null:{kind:"option",index:r}}handlePermissionPress(e){return this.isPermissionCell(e.y)?(this.permissionPressHit=this.permissionHitAt(e.x,e.y),!0):(this.permissionPressHit=null,!1)}handlePermissionRelease(e){let t=this.permissionPressHit;if(this.permissionPressHit=null,t===null||e===null||!this.isPermissionCell(e.y))return t!==null;let r=this.permissionHitAt(e.x,e.y);return r===null||r.kind!==t.kind||r.kind==="option"&&t.kind==="option"&&r.index!==t.index||r.kind==="hint"&&t.kind==="hint"&&r.action!==t.action?!0:Date.now()-this.permissionArmedAt<I$?(this.notify("permission prompt just appeared, click again to confirm"),!0):(this.onPermissionClick?.(r),!0)}computeBannerPrefixText(){let e=[];return this.banner.queued>0&&e.push(`${this.banner.queued} queued`),this.scrollOffset>0&&e.push(`\u2191 ${this.scrollOffset}`),e.length>0?e.join(" \xB7 ")+" \xB7 ":""}drawBanner(){let e=this.term.height,t=this.promptRows(),r=e-t-Bt-Ut-Ot;this.drawBar("composerTop",r),this.drawBar("composerBottom",e-Ot)}drawBars(){this.drawBanner(),this.drawBar("sessionbar",this.term.height)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-Bt-Ut-Ot+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Bt-Ut-Ot;this.term.moveTo(2,Math.min(f,p));return}if(this.formPrompt){let l=this.formPrompt,u=this.formWindowSize(),f=this.formWindowTop,p=this.formTop()+1+(l.selectedIndex-f),m=this.term.height-Bt-Ut-Ot,b=Math.min(p,m),h=A$(l,this.term.width,f,u).find(y=>y.selected);if(h?.kind!=="text"){this.term.hideCursor(!0);return}this.term.hideCursor(!1),this.term.moveTo(Math.min(h.caretCol,this.term.width),b);return}if(this.confirmPrompt){let l=this.term.height-ES-Bt-Ut-Ot+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-Bt-Ut-Ot+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Bt-Ut-Ot;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-Bt-Ut-Ot+1;this.term.moveTo(2,u);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=Cs(r.buffer,t),o=go(s,r,Bg),a=this.term.height-o.rendered-Bt-Ut-Ot+1+Math.max(0,o.cursorVisualRow-o.windowStart),d=o.cursorVisualCol+3,c=this.term.height-Bt-Ut-Ot;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.formPrompt)return this.formRows();if(this.confirmPrompt)return ES;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,t=Math.max(1,e-2),r=this.dispatcher.state(),s=Cs(r.buffer,t);return Math.min(Bg,Math.max(1,s.length))}permissionRows(){return this.permissionPrompt?Math.min(A4,4+this.permissionPrompt.options.length):0}formRows(){return this.formPrompt?Math.min(Math.max(M4,this.formPrompt.maxRows??T4),2+this.formPrompt.rows.length):0}formWindowSize(){return Math.max(1,this.formRows()-2)}formTop(){return this.term.height-this.formRows()-Bt-Ut-Ot+1}drawFormPrompt(){let e=this.formPrompt;if(!e)return;let t=this.term.width,r=this.formRows(),s=this.formTop(),o=this.formWindowSize(),i=`${e.title}|${e.rows.length}|${o}`;i!==this.formWindowKey?(this.formWindowKey=i,this.formWindowTop=Z4(e.rows.length,e.selectedIndex,o)):this.formWindowTop=eJ(this.formWindowTop,e.rows.length,e.selectedIndex,o);let a=this.formWindowTop;this.clearFormHits(),this.formRegion={top:s,bottom:s+r-1};let d=s,c=(b,g)=>{d>=s+r||(this.paintRow(d,b,g),d+=1)},l=e.rows.length>o?` (${e.selectedIndex+1}/${e.rows.length})`:"";c(`form|t|${t}|${e.title}|${l}`,()=>{H(this.term,"prompt-text",` \u2699 ${mn(`${e.title}${l}`,t-5)}`)});let u=A$(e,t,a,o);for(let b of u){if(d>=s+r-1)break;this.formRowHits.set(d,{row:b.index,...b.kind==="text"?{field:{startCol:1+$t(b.prefix),slice:b.field,sliceStart:b.fieldStart}}:{}}),c(b.sig,()=>{if(b.kind==="text"){H(this.term,b.selected?"modal-option-selected":"modal-option",b.prefix),H(this.term,"content",b.field);return}H(this.term,b.selected?"modal-option-selected":"modal-option",b.body)})}let f=e.hints??tJ,p=d,m=$S(f,t);for(let b of m.spans)this.formHintHits.push({row:p,...b});c(`form|hint|${t}|${m.text}`,()=>{H(this.term,"modal-hint",` ${m.text}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),t=this.term.width,r=this.wrapBtwWindow(t,e,0).rows.length;return Math.min(this.btwOverlayMaxHeight,1+r)}wrapBtwWindow(e,t,r){let s=this.btwOverlayLines.length;if(t<=0||s===0)return{rows:[],offset:0,more:!1};if(e<=4){let f=Math.min(Math.max(0,r),Math.max(0,s-t)),p=s-f,m=Math.max(0,p-t);return{rows:this.btwOverlayLines.slice(m,p),offset:f,more:m>0}}let o=Math.max(0,r),i=[],a=0;for(let f=s-1;f>=0;f--){let p=this.btwOverlayLines[f],m=this.wrapOne(p,e);if(i.push(m),a+=m.length,a>t+o)break}let d=[];for(let f=i.length-1;f>=0;f--)d.push(...i[f]);let c=Math.min(o,Math.max(0,d.length-t)),l=d.length-c,u=Math.max(0,l-t);return{rows:d.slice(u,l),offset:c,more:u>0}}scrollBtwOverlayBy(e){let t=this.btwOverlayRegion;if(!this.btwOverlayOpen||t===null||t.contentRows<=0)return!1;let r=Math.max(0,this.btwOverlayScroll+e),s=this.wrapBtwWindow(this.term.width,t.contentRows,r);return!s.more&&s.offset===0?!1:(s.offset===this.btwOverlayScroll||(this.btwOverlayScroll=s.offset,this.repaintNow()),!0)}resolveBtwOverlayCell(e,t){let r=this.btwOverlayRegion;if(!this.btwOverlayOpen||r===null||r.contentRows<=0)return null;let s=t-(r.top+1);if(s<0||s>=r.contentRows)return null;let o=this.term.width;if(e<1||e>o)return null;let i=this.wrapBtwWindow(o,r.contentRows,this.btwOverlayScroll),a=i.rows.length-r.contentRows+s,d=a>=0?i.rows[a]:void 0;return d?this.resolveChunkColumn(d,e):null}isBtwOverlayCell(e){let t=this.btwOverlayRegion;return t!==null&&e>=t.top&&e<=t.bottom}btwOverlayScrollState(){let t=this.btwOverlayRegion?.contentRows??0;return{offset:this.btwOverlayScroll,more:this.wrapBtwWindow(this.term.width,t,this.btwOverlayScroll).more}}drawBtwOverlay(){if(!this.btwOverlayOpen){this.btwOverlayRegion=null;return}let e=this.btwOverlayRows();if(e===0){this.btwOverlayRegion=null;return}let t=this.term.width,s=this.term.height-this.promptRows()-Bt-Ut-Ot,o=this.chipRows()+this.queuedRows()+this.completionRows(),i=s-1-o,a=i-e+1,d=e-1,c=a;this.btwOverlayRegion={top:c,bottom:i,contentRows:d},this.drawBar("btw",c);let l=this.wrapBtwWindow(t,d,this.btwOverlayScroll);this.btwOverlayScroll=l.offset;let u=l.rows;for(let f=0;f<d;f++){let p=c+1+f,m=u.length-d+f,b=m>=0?u[m]:void 0,g=b?this.selectionRangeForChunk(b):null,h=PS(`btw|c${f}`,t,b,null,null,g);this.paintRow(p,h,()=>{b?this.writeFormattedLine(b,t,null,0,g):this.term.noFormat(" ".repeat(t))})}}isHiddenLine(e){return e.collapsed===!0||this.hideThoughts&&e.bodyStyle==="thought"}wrapTail(e,t){if(e<=4){let d=[];for(let l of this.lines)this.isHiddenLine(l)||d.push(l);let c=Math.min(t,d.length);return{rows:d.slice(d.length-c),exhausted:t>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),t<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],s=0,o=0,i=!1;for(let d=this.lines.length-1;d>=0;d--){let c=this.lines[d];if(this.isHiddenLine(c)){d===0&&(i=!0);continue}let l=this.wrapOne(c,e);if(r.push(l),s+=l.length,o=d,s>=t)break}let a=[];for(let d=r.length-1;d>=0;d--)a.push(...r[d]);return{rows:a,exhausted:o===0||i}}wrapOne(e,t){let r=this.lineIds.get(e),s=r!==void 0&&!this.uncachedWrap.has(e);if(s){let h=this.wrapCache.get(r);if(h)return h}let o=e.prefix??"",i=$t(o),a=Math.max(1,t-i-1),d=Math.max(0,Math.min(e.hangingIndent??0,a-1)),c=Math.max(1,a-d),l=Af(e.bodyStyle),u=e.ansi?q4(e.body,d>0?c:a):V4(e.body,d>0?c:a,{escapeAware:l}),f=e.ansi?0:e.maxWrapRows??0,p=f>0&&u.length>f;p&&(u.length=f);let m=[],b=0,g=0;for(let h=0;h<u.length;h++){let y=u[h]??"",k=h===0||d===0?y:" ".repeat(d)+y;p&&h===u.length-1&&(k=mn(`${k}\u2026`,a,{escapeAware:l}));let S={prefix:h===0?e.prefix:" ".repeat(i),body:k};if(e.prefixStyle!==void 0&&(S.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(S.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(S.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(S.hoverSubKey=e.hoverSubKey),e.fillRow&&(S.fillRow=!0),e.ansi&&(S.ansi=!0),r!==void 0&&y.length>0)if(e.ansi){let I=b,x=0;for(let M=0;M<y.length;){let F=Gr(y,M);if(F){M+=F.text.length,F.width>0&&(x+=1);continue}x+=1,M+=1}let C=x;for(;C>0&&b<e.body.length;){let M=Gr(e.body,b);if(M){b+=M.text.length,M.width>0&&(C-=1);continue}b+=1,C-=1}let $=b;if(h===u.length-1){for(;$<e.body.length;){let M=Gr(e.body,$);if(!M)break;$+=M.text.length}b=$}let P={sourceLineId:r,sourceColOffset:I,sourceColEnd:$};if(h>0&&d>0&&(P.bodyDisplayShift=d),this.wrapOrigin.set(S,P),e.links!==void 0){let M=this.linkSpansForWindow(e.body,e.links,I,$,h===0||d===0?0:d);M!==null&&(S.linkSpans=M)}}else{let I=e.body.indexOf(y,g),x=I===-1?g:I,C={sourceLineId:r,sourceColOffset:x};if(h>0&&d>0&&(C.bodyDisplayShift=d),this.wrapOrigin.set(S,C),e.links!==void 0){let $=this.linkSpansForWindow(e.body,e.links,x,x+y.length,h===0||d===0?0:d);$!==null&&(S.linkSpans=$)}g=x+y.length}m.push(S)}return s&&this.wrapCache.set(r,m),m}writeFormattedLine(e,t,r=null,s=0,o=null,i=!1,a=!1,d=null){e.prefix&&mo(this.term,e.prefix,e.prefixStyle??e.bodyStyle,i);let c=Math.max(0,t-$t(e.prefix??"")),l=Af(e.bodyStyle),u=e.ansi?e.body:mn(e.body,c,{escapeAware:l}),f=d===null||d.length===0?null:d.map(b=>({start:Math.max(0,Math.min(u.length,b.start)),end:Math.max(0,Math.min(u.length,b.end)),url:b.url})).filter(b=>b.end>b.start).sort((b,g)=>b.start-g.start),p=(b,g,h)=>{if(f===null){h(b,g);return}let y=g+b.length,k=g;for(let S of f){if(S.end<=k||S.start>=y)continue;let I=Math.max(S.start,k),x=Math.min(S.end,y);I>k&&h(b.slice(k-g,I-g),k),process.stdout.write(`\x1B]8;;${S.url}\x1B\\`),h(b.slice(I-g,x-g),I),process.stdout.write("\x1B]8;;\x1B\\"),k=x}k<y&&h(b.slice(k-g),k)},m=(b,g)=>{b.length!==0&&p(b,g,(h,y)=>{if(this.scrollbackHighlight!==null&&!e.ansi){let k=r!==null&&r>=y?r-y:null;j4(this.term,h,e.bodyStyle,this.scrollbackHighlight,k,s,i)}else mo(this.term,h,e.bodyStyle,i)})};if(o!==null){let b=Math.max(0,Math.min(u.length,o.start)),g=Math.max(b,Math.min(u.length,o.end)),h=Af(e.bodyStyle)||e.ansi===!0;if(m(u.slice(0,b),0),g>b){let k=u.slice(b,g);h&&(k=Wg(k)),h?mo(this.term,k,"selection-highlight",i):p(k,b,S=>{mo(this.term,S,"selection-highlight",i)})}let y=u.slice(g);if(h&&g>b){let k=J4(u.slice(0,g));k.length>0&&(y=k+y)}m(y,g)}else m(u,0);if(e.fillRow||i||a){let b=e.ansi?E$(u):$t(l?Wg(u):u),g=c-b;if(g>0){let h=o!==null&&o.toEndOfLine?"selection-highlight":e.fillRow||i?e.bodyStyle:void 0;mo(this.term," ".repeat(g),h,i)}}(e.ansi||e.body.includes("\x1B"))&&this.term.styleReset()}};M$=/[^\x20-\x7e]/,FS=new Intl.Segmenter(void 0,{granularity:"grapheme"}),_$=!1;tJ=[{label:"\u2191/\u2193 choose"},{label:"\u23CE this session",action:"commit"},{label:"s save default",action:"save"},{label:"Esc close",action:"close"}]});function oJ(n,e,t=Qo){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let r=t[n];return r?{kind:"resolve",action:r.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,n-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(e.kind==="char"){let r=e.ch.toLowerCase();if(r==="n")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(r==="p")return{kind:"continue",selected:Math.max(0,n-1)};let s=t.findIndex(o=>o.hotkey.toLowerCase()===r);if(s>=0){let o=t[s];if(o)return{kind:"resolve",action:o.key}}}return{kind:"continue",selected:n}}async function N$(n,e){kr();let t=Qe(e.sessionId),r=e.importedFromMachine??"another machine",s=V(e.cwd),o=Qo.findIndex(p=>p.key==="view");o<0&&(o=0);let i=null,a=null,d=()=>{let m=7+Qo.length*2+2,b=zn(n,{contentHeight:m,title:"Imported session"}),g=b.contentW,h=[{label:"session: ",value:t},{label:"from: ",value:r},{label:"cwd: ",value:s}],y=0;for(let S of h)n.moveTo(b.contentX,b.contentY+y),H(n,"modal-label",` ${S.label}`),H(n,"content",At(S.value,g-S.label.length-2)),y++;y++;let k=D$(n,b,y,{intro:"What do you want to do?",choices:Qo,selected:o,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"});return i=b,a=k.firstChoiceRow,b},c=()=>{let p=i,m=a;if(!(p===null||m===null))for(let b=0;b<Qo.length;b++){let g=Qo[b];g&&DS(n,p,m+b*2,g.label,b===o)}},l=p=>{p<0||p>=Qo.length||p===o||(o=p,c())},u=null,f=H$({choiceCount:Qo.length,layout:()=>i,firstChoiceRow:()=>a,selected:()=>o,select:l,commit:p=>{let m=Qo[p];m&&u?.(m.key)},back:()=>u?.("back")});return qr({term:n,render:d,onKey:(p,m,b,g)=>{let h=iJ(p,b);if(!h)return;let y=oJ(o,h);if(y.kind==="cancel"){g("cancel");return}if(y.kind==="back"){g("back");return}if(y.kind==="resolve"){g(y.action);return}l(y.selected)},onMouse:(p,m,b)=>{u=b,f(p,m)}})}function D$(n,e,t,r){let s=t;n.moveTo(e.contentX,e.contentY+s),H(n,"content",` ${r.intro}`),s+=2;let o=e.contentY+s;for(let i=0;i<r.choices.length;i++){let a=r.choices[i];a&&(DS(n,e,e.contentY+s,a.label,i===r.selected),s++,n.moveTo(e.contentX,e.contentY+s),H(n,"list-description",` ${a.description}`),s++)}return s++,n.moveTo(e.contentX,e.contentY+s),H(n,"modal-hint",` ${r.footer}`),{firstChoiceRow:o}}function H$(n){let e=null,t=r=>{let s=n.firstChoiceRow();if(s===null)return null;let o=r-s;if(o<0)return null;let i=Math.floor(o/2);return i<n.choiceCount?i:null};return(r,s)=>{if(r==="MOUSE_WHEEL_UP"){n.select(n.selected()-1);return}if(r==="MOUSE_WHEEL_DOWN"){n.select(n.selected()+1);return}if(r==="MOUSE_LEFT_BUTTON_PRESSED"){e={x:s?.x??-1,y:s?.y??-1};return}let o=s?.y;if(typeof o!="number")return;if(r==="MOUSE_MOTION"){let l=t(o);l!==null&&n.select(l);return}if(r!=="MOUSE_LEFT_BUTTON_RELEASED")return;let i=s?.x,a=e!==null&&i===e.x&&o===e.y;if(e=null,!a)return;let d=n.layout();if(d!==null&&typeof i=="number"&&(i<d.x||i>=d.x+d.w||o<d.y||o>=d.y+d.h)){n.back();return}let c=t(o);c!==null&&n.commit(c)}}function DS(n,e,t,r,s){let i=ks(` ${s?"\u276F":" "} ${r}`,e.contentW);n.moveTo(e.contentX,t),H(n,s?"list-selected":"content",i)}function iJ(n,e){return n==="UP"?{kind:"up"}:n==="DOWN"?{kind:"down"}:n==="ENTER"||n==="KP_ENTER"?{kind:"enter"}:n==="ESCAPE"?{kind:"back"}:n==="CTRL_C"||n==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:n}:null}async function B$(n,e,t){let r=Qe(e.sessionId),s=e.title??V(e.cwd),o=1,i=[{key:"launch",label:"Launch",hotkey:"l",description:"start a new agent session"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=null,d=null,c=()=>{let f=zn(n,{contentHeight:11,title:"Open session",overlay:!0}),p=f.contentW,m=0;n.moveTo(f.contentX,f.contentY+m),H(n,"modal-label"," session: "),H(n,"content",At(r,p-10)),m++,n.moveTo(f.contentX,f.contentY+m),H(n,"content"," "+At(s,p-2)),m++,m++;let b=D$(n,f,m,{intro:"What do you want to do?",choices:i,selected:o,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"});a=f,d=b.firstChoiceRow},l=()=>{let f=a,p=d;if(!(f===null||p===null))for(let m=0;m<i.length;m++){let b=i[m];b&&DS(n,f,p+m*2,b.label,m===o)}},u=f=>{f<0||f>=i.length||f===o||(o=f,l())};return c(),n.hideCursor(),await new Promise(f=>{let p=!1,m=()=>{p=!0},b=y=>{m(),t.pop(),f(y)},g=(y,k,S)=>{if(y==="CTRL_C"||y==="CTRL_D"){b("cancel");return}if(y==="ESCAPE"){b("back");return}if(y==="ENTER"||y==="KP_ENTER"){b(i[o]?.key??"view");return}if(y==="UP"||y==="SHIFT_TAB"){u(o-1);return}if(y==="DOWN"||y==="TAB"){u(o+1);return}if(S?.isCharacter){let I=y.toLowerCase();if(I==="l"){b("launch");return}if(I==="v"){b("view");return}if(I==="n"){u(o+1);return}if(I==="p"){u(o-1);return}}},h=H$({choiceCount:i.length,layout:()=>a,firstChoiceRow:()=>d,selected:()=>o,select:u,commit:y=>{let k=i[y];k&&b(k.key)},back:()=>b("back")});t.push({onKey:(y,k,S)=>{p||g(y,k,S)},onMouse:(y,k)=>{p||h(y,k)},onResize:()=>{p||c()}})})}var Qo,HS=j(()=>{"use strict";Se();mr();Li();xn();Qo=[{key:"fork-local",label:"Fork locally",hotkey:"f",description:"spawn a local fork \u2014 original imported copy stays as-is"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}]});function Ef(n){if(n.length===0)return"";let e=n[0]??"";for(let t=1;t<n.length;t++){let r=n[t]??"",s=0;for(;s<e.length&&s<r.length&&e[s]===r[s];)s+=1;if(e=e.slice(0,s),e.length===0)break}return e}function U$(n){let{matches:e,firstLine:t}=n;if(e.length===0)return null;let r=t.indexOf(" "),s=r===-1?t:t.slice(0,r),o=r===-1?"":t.slice(r);if(e.length===1){let a=e[0]??"",d=o.startsWith(" ")?"":" ";return a+d+o}let i=Ef(e);return i.length<=s.length?null:i+o}var zg=j(()=>{"use strict"});import*as W$ from"os";async function ad(n,e,t={}){let r=t.defaultCwd??(e?await NM(e.cwd):void 0)??W$.homedir();kr();let s=t.title??"Fork locally \u2014 choose cwd",o=t.intro??"Pick a local cwd for this session:",i=e?[{label:"session: ",value:Qe(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:V(e.cwd)}]:[],a=new Hi(r.endsWith("/")?r:r+"/"),d=()=>{let M=FM(a.text);M>0&&a.setText(a.text.slice(M))},c=null,l=!1,u=null,f=null,p=null,m=null,b=" Enter accept \xB7 Esc back",g="Enter accept",h="Esc back",y=b.indexOf(g),k=b.indexOf(h),S=()=>{let M=i.length+6;u=zn(n,{contentHeight:M,title:s,overlay:t.overlay===!0});let F=u.contentW,K=0;for(let z of i)n.moveTo(u.contentX,u.contentY+K),H(n,"modal-label",` ${z.label}`),H(n,"content",At(z.value,F-z.label.length-2)),K++;K++,n.moveTo(u.contentX,u.contentY+K),H(n,"content",` ${o}`),K+=2,C(K),K+=2;let Y=u.contentY+K;c!==null?(n.moveTo(u.contentX,Y),H(n,"input-error",` ${At(c,F-2)}`),f=null,p=null,m=null):(n.moveTo(u.contentX,Y),H(n,"modal-hint",b),f=Y,p={start:u.contentX+y,end:u.contentX+y+g.length-1},m={start:u.contentX+k,end:u.contentX+k+h.length-1})},I=()=>i.length+3,x=0,C=M=>{if(!u)return;let F=M??I();n.moveTo(u.contentX,u.contentY+F).eraseLineAfter(),n.moveTo(u.x+u.w-1,u.contentY+F),H(n,"box-border","\u2502"),n.moveTo(u.contentX,u.contentY+F),n.noFormat(" ");let Y=Math.max(1,u.contentW-1-2),z=a.text,re=a.cursor;re<x&&(x=re),re-x>=Y&&(x=re-Y+1),x<0&&(x=0);let Q=z.slice(x,x+Y);x>0&&Q.length>0&&(Q="\u2026"+Q.slice(1));let ke=_v(z),xe=(Ge,ue)=>{if(ue.length===0)return;let oe=Ge+ue.length;if(ke<=Ge)H(n,"content",ue);else if(ke>=oe)H(n,"modal-hint",ue);else{let $e=ke-Ge;H(n,"modal-hint",ue.slice(0,$e)),H(n,"content",ue.slice($e))}},je=re-x;if(l){xe(x,Q);return}je>=Q.length?(xe(x,Q),H(n,"input-cursor"," ")):(xe(x,Q.slice(0,je)),H(n,"input-cursor",Q[je]??" "),xe(x+je+1,Q.slice(je+1)))},$=()=>{if(C(),!u)return;let M=I()+2;n.moveTo(u.contentX,u.contentY+M).eraseLineAfter(),n.moveTo(u.x+u.w-1,u.contentY+M),H(n,"box-border","\u2502");let F=u.contentY+M;n.moveTo(u.contentX,F),c!==null?(H(n,"input-error",` ${At(c,u.contentW-2)}`),f=null,p=null,m=null):(H(n,"modal-hint",b),f=F,p={start:u.contentX+y,end:u.contentX+y+g.length-1},m={start:u.contentX+k,end:u.contentX+k+h.length-1})},P=M=>{if(l)return;let F=a.text;l=!0,c=null,$(),mf(F).then(K=>{if(l=!1,K.ok){M({kind:"ok",path:K.path});return}c=K.reason,$()})};return qr({term:n,render:S,overlay:t.overlay===!0,onKey:(M,F,K,Y)=>{if(!l){if(M==="ENTER"||M==="KP_ENTER"){P(Y);return}if(M==="ESCAPE"){Y({kind:"back"});return}if(M==="CTRL_C"||M==="CTRL_D"){Y({kind:"cancel"});return}if(M==="TAB"){l=!0,DM(a.text).then(z=>{if(l=!1,z.matches.length===0)return;let re;if(z.matches.length===1)re=z.prefix+z.matches[0];else{let Q=Ef(z.matches);if(Q.length<=z.basePrefix.length)return;re=z.prefix+Q}re!==a.text&&(a.setText(re,{recordUndo:!0}),d(),c=null,$())});return}if(a.handleKey(M,K?.isCharacter===!0)){d(),c=null,$();return}}},onMouse:(M,F,K)=>{if(l||M!=="MOUSE_LEFT_BUTTON_PRESSED")return;let Y=F?.x,z=F?.y;if(!(typeof Y!="number"||typeof z!="number")){if(u!==null&&(Y<u.x||Y>=u.x+u.w||z<u.y||z>=u.y+u.h)){K({kind:"back"});return}if(f!==null&&z===f){if(p!==null&&Y>=p.start&&Y<=p.end){P(K);return}if(m!==null&&Y>=m.start&&Y<=m.end){K({kind:"back"});return}}}}})}var BS=j(()=>{"use strict";Se();mr();$v();zg();Li();mg();xn()});import*as q$ from"fs";import*as z$ from"os";import*as Kg from"path";function Gg(n,e){let t=e;for(;t>0;){let r=n[t-1]??"";if(/\s/.test(r)){if(r===" "&&n[t-2]==="\\"){t-=2;continue}break}t-=1}return t===e?null:{token:n.slice(t,e),start:t}}function aJ(n){return n.length===0?!1:n.includes("/")?!0:n==="~"||n==="."||n===".."}function dJ(n){return n.replace(/\\ /g," ")}function j$(n){return n.replace(/ /g,"\\ ")}function cJ(n){let e=n.lastIndexOf("/");return e===-1?{dirPrefix:"",base:n}:{dirPrefix:n.slice(0,e+1),base:n.slice(e+1)}}function lJ(n,e){let t=n.length===0?".":n;return(t==="~"||t.startsWith("~/"))&&(t=z$.homedir()+t.slice(1)),Kg.isAbsolute(t)?t:Kg.resolve(e,t)}function uJ(n){let e;try{e=q$.readdirSync(n,{withFileTypes:!0})}catch{return null}return e.map(t=>({name:t.name,isDir:t.isDirectory()}))}function Jg(n,e,t=uJ){let r=dJ(n),{dirPrefix:s,base:o}=cJ(r);if(s.length===0&&!aJ(n)&&o.length===0)return null;let i=lJ(s,e),a=t(i);if(a===null)return null;let d=o.startsWith("."),c=a.filter(f=>f.name.startsWith(o)&&(d||!f.name.startsWith(".")));if(c.length===0)return null;let l=c.map(f=>f.isDir?f.name+"/":f.name);if(c.length===1){let f=c[0],p=f.isDir?f.name+"/":f.name;return{replacement:j$(s+p),candidates:l}}let u=Ef(c.map(f=>f.name));return{replacement:j$(s+u),candidates:l}}var US=j(()=>{"use strict";zg()});import{spawn as fJ}from"child_process";function pJ(n,e){let t="";for(let r=0;r<n.length;r++){let s=n[r];if(s!=="%"||r===n.length-1){t+=s;continue}switch(n[r+1]){case"%":t+="%",r++;break;case"s":t+=e.sessionId,r++;break;case"c":t+=e.cwd,r++;break;case"a":t+=e.agentId,r++;break;case"u":t+=e.baseUrl,r++;break;case"t":t+=e.tokenFile,r++;break;default:t+=s;break}}return t}function hJ(n){if(Array.isArray(n))return[...n];let e=n;return e.trim().length===0?[]:e.trim().split(/\s+/)}function mJ(n,e){let t=hJ(n.command);if(t.length===0)return null;let r=t.map(a=>Ze(pJ(a,e))),[s,...o]=r;if(!s)return null;let i={HYDRA_SESSION_ID:e.sessionId,HYDRA_CWD:e.cwd,HYDRA_AGENT:e.agentId,HYDRA_BASE_URL:e.baseUrl,HYDRA_TOKEN_FILE:e.tokenFile};return{program:s,args:o,env:i}}function gJ(n){let e={stdout:"",stderr:"",bytes:0,truncated:!1},t=(r,s)=>{if(e.truncated)return;let o=n-e.bytes;if(o<=0){e.truncated=!0;return}let i=r.length<=o?r.toString("utf8"):r.subarray(0,o).toString("utf8");r.length>o&&(e.truncated=!0),e[s]+=i,e.bytes+=Math.min(r.length,o)};return{onStdout:r=>t(r,"stdout"),onStderr:r=>t(r,"stderr"),onExit:(r,s)=>{let o=[],i=(a,d)=>{let c=a.split(/\r?\n/);for(;c.length>0&&c[c.length-1]==="";)c.pop();for(let l of c)o.push({text:l,style:d})};return e.stdout&&i(e.stdout,"stdout"),e.stderr&&i(e.stderr,"stderr"),e.truncated&&o.push({text:`[output truncated at ${n} bytes]`,style:"meta"}),s?o.push({text:`[killed by ${s}]`,style:"error"}):typeof r=="number"&&r!==0&&o.push({text:`[exit ${r}]`,style:"error"}),o}}}function Vg(n,e,t){let r=mJ(n,e);if(r===null){t.notify("hotkey: empty command");return}let s=gJ(t.maxOutputBytes??yJ),o=t.spawnFn??fJ,i;try{i=o(r.program,r.args,{cwd:t.cwd,env:{...t.parentEnv??process.env,...r.env},stdio:["ignore","pipe","pipe"]})}catch(a){t.emitLines([{text:`[hotkey spawn failed: ${a.message}]`,style:"error"}]);return}i.stdout?.on("data",s.onStdout),i.stderr?.on("data",s.onStderr),i.on("error",a=>{t.emitLines([{text:`[hotkey spawn error: ${a.message}]`,style:"error"}])}),i.on("close",(a,d)=>{t.emitLines(s.onExit(a,d))})}var yJ,WS=j(()=>{"use strict";et();yJ=16*1024});function wJ(n){process.stdout.write(`\x1B]9;4;${n}\x1B\\`)}function bJ(n,e,t){let r=`${t.agentId}@${t.version}`;if(t.source==="npm")return t.phase==="install_start"||t.phase==="download_start"?`${n} installing ${r} via npm\u2026`:t.phase==="installed"?`${n} ${r} installed`:`${n} installing ${r} via npm\u2026`;if(t.phase==="download_start"||t.phase==="download_progress"){let s=t.receivedBytes??0,o=t.totalBytes??0,i=(s/1e6).toFixed(1);if(o>0){let a=(o/1e6).toFixed(1),d=Math.min(100,Math.floor(s/o*100));return`${n} downloading ${r} ${i}/${a} MB (${d}%)`}return`${n} downloading ${r} ${i} MB`}return t.phase==="download_done"?`${n} downloaded ${r}, verifying\u2026`:t.phase==="extract"?`${n} extracting ${r}\u2026`:t.phase==="installed"?`${n} ${r} installed`:e||n}function Yg(n,e){let t=!1,r="",s=!1,o=n,i=a=>{t||a===3&&s||a===0&&!s||(s=a===3,wJ(a))};return{write(a){t||(o=a,r=a,e.write(a))},applyProgress(a){if(t)return;a.phase==="download_start"||a.phase==="download_progress"||a.phase==="install_start"||a.phase==="extract"||a.phase==="download_done"?i(3):a.phase==="installed"&&i(0);let c=bJ(o,r,a);r=c,e.write(c)},finalize(){t||(t=!0,i(0),e.finalize())}}}function K$(n){let e=!1;return{write(t){e||(process.stdout.write("\r"),n.eraseLineAfter(),H(n,"status-active",t))},finalize(){e||(e=!0,process.stdout.write(`
274
+ `))}}}var jS=j(()=>{"use strict";xn()});function zS(n="local"){let e={filters:{cwdOnly:!1,hostFilter:n==="all"?"__all":"__local",includeNonInteractive:!1}};return n!=="local"&&n!=="all"&&(e.pendingDefaultHost=n),e}function dd(){return dn()?.id??"terminal"}function SJ(){if(!uf())return J$;let n=[];for(let e of J$)n.push(e),e?.[0]==="*"&&n.push(["^t",pg()?"go to selected session's tab (opening one if needed), or send the composer to a new one":"new tab: selected session, or send the composer to a new one"]);return n}async function KS(n,e){let t=()=>{be(fs),be(Ka),be(Jo),be(Ga),be(Ja),be(ol),be(il),be(al),be(za),be("\x1B>")};t();let r=e.prefs??zS();if(e.prefs===void 0&&e.currentSessionId!==void 0){let E=e.sessions.find(_=>_.sessionId===e.currentSessionId);(E?.importedFromMachine||E?.remote)&&(r.filters.hostFilter="__all")}if(r.pendingDefaultHost!==void 0){let E=RJ(r.pendingDefaultHost,e.sessions);r.filters.hostFilter=E,E!=="__local"&&(r.pendingDefaultHost=void 0)}let s=e.cwd,o=Xg(e.sessions,s),i,a=E=>{let _=E;return r.filters.cwdOnly&&(_=_.filter(W=>W.cwd===s)),r.filters.includeNonInteractive||(_=_.filter(W=>W.interactive===!0)),_=CJ(_,r.filters.hostFilter),_},d=a(o),c={columns:Hr,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},l=d.map(E=>ws(E,Date.now()));c.columns=V$(l,e.config.tui.sessionColumns);let u=lo(l,c),f=1+d.length,p=0,m=0;if(e.currentSessionId!==void 0){let E=d.findIndex(_=>_.sessionId===e.currentSessionId);E>=0&&(p=E+1)}let b=!1,g="",h=120,y=!1,k=0,S="normal",I=null,x=!1,C="input",$=new Vo({history:[],collapsePastes:!1}),P=[],M=!1,F=0,K=0,Y=null,z=!1,re=new Map,Q=lo([],c),ke="",xe=E=>re.get(E)??null,je=()=>{let E=Date.now(),_=new Map(d.map(se=>[se.sessionId,se])),W=[];re=new Map;for(let se of P){let ae=_.get(se.sessionId);if(!ae)continue;let ge=ws(ae,E);re.set(se.sessionId,ge),W.push(ge)}Q=lo(W,c);let J=Math.max(20,Cn(n)-Qg);ke=wr(jo,Q,J,c).padEnd(J)},Ge=null,ue=null,oe=null,$e=null,lt=()=>{if($e!==null){let E=$e;return{plain:E,render:()=>{H(n,"status-active",` ${E}`)}}}if(b){let E=d.length===0?"no matches":`${d.length} match${d.length===1?"":"es"}`;return{plain:`/${g}\u2589 ${E} \xB7 ^c clears`,render:()=>{H(n,"prompt-text",` /${g}`),H(n,"prompt-cursor"," "),H(n,"modal-hint",` ${E} \xB7 ^c clears`)}}}return oe!==null?{plain:oe,render:()=>{H(n,"modal-hint",` ${oe}`)}}:null},Tt=!1,Me=new Vo({history:[]});if(e.initialPrompt&&Me.setBuffer(e.initialPrompt),e.initialAttachments)for(let E of e.initialAttachments)Me.addAttachment(E);let Jt=e.config.tui.promptHistoryMaxEntries;Pu(D.globalTuiHistoryFile()).then(E=>{let _=E.length>Jt?E.slice(E.length-Jt):E;Me.setHistory(_)}).catch(()=>{});let Ye=new gl(n),As=Gl(e.config),Ki=e.config.tui.selectionClipboard,Kn=null,Ts=!1,Ht=null,X="char",Et=null,Sr=null,gn=!1,Yr=1,Xo=null,ay=500,vl=1,Es=/[A-Za-z0-9_:\-]/,Zo=uo(n),Wt=Cn(n),it=0,ud="",or=0,Gn=[],yn=1,yo=0,Gi=0,Sl=0,fd="",wo=[],On=1,Hf=0,Xe=[],wn=1,Ji=0,Vi=0,bo=0,Yi=()=>{Zo=uo(n),Wt=Cn(n);let E=Math.max(10,Wt-Qg-1);or=Math.max(10,Wt-G$);let _=Math.max(10,Wt-8),W=Me.state().attachments.length,J=W>0?` \xB7 \u{1F4CE}\xD7${W}`:"",se=Math.max(10,_-J.length);ud=xJ(s,se)+J;let ae=Me.state();Gn=Cs(ae.buffer,or);let ge=go(Gn,ae,Pf);yn=ge.rendered,yo=ge.windowStart,Gi=ge.cursorVisualRow,Sl=ge.cursorVisualCol;let ut=6+yn,St=Math.max(3,Zo-ut);it=Math.min(d.length,St),fd=wr(jo,u,E,c).padEnd(E),wo=l.map(en=>wr(en,u,E,c).padEnd(E))},pd=()=>{l=d.map(E=>ws(E,Date.now())),c.columns=V$(l,e.config.tui.sessionColumns),u=lo(l,c),f=1+d.length,Yi()},Rn=()=>{let E=a(o);b&&g.length>0?d=E.filter(_=>TJ(_,g)):d=E,pd(),b?(m=0,p=d.length>0?1:0):p>f-1&&(p=Math.max(0,f-1)),m+it>d.length&&(m=Math.max(0,d.length-it)),Qr()},Ps=E=>{if(E===null){p=0,m=0;return}if(E!==void 0){let _=d.findIndex(W=>W.sessionId===E);if(_>=0){p=_+1,Qr();return}}p=d.length>0?1:0,m=0,Qr()},Qr=()=>{if(p===0)return;let E=p-1;E<m?m=E:E>=m+it?m=E-it+1:m+it>d.length&&(m=Math.max(0,d.length-it))},me=()=>Math.max(2,Wt-3),Rt=!1,rt=!0,Xt=!1,Bf=[],Zt=e.composerAgentId,bn=e.composerModel,ko=e.composerHost,ei=!1,xl=()=>{let E=Zt;if(!E)return"";let _=bn;return _?`${E}\u2022${_}`:E},Ms=null,Fn=null,_s=null,kn=null,hd=()=>{let E=me(),_=`\u2500 ${ud} `,W=xl(),J="";if(W.length>0){let zt=`\u2500 ${W} `;zt.length+_.length+1<=E&&(J=zt)}let se="";if((e.availableHosts?.length??0)>0){let zt=`\u2500 ${ko??"local"} `;zt.length+J.length+_.length+1<=E&&(se=zt)}let ae=Math.max(1,E-_.length-se.length-J.length),ge="\u2500".repeat(ae),ut=(p===0||Rt)&&rt;if(Ms=_.length>0?{start:2,end:1+_.length}:null,se.length>0){let zt=1+_.length+ae+1;_s={start:zt,end:zt+se.length-1}}else _s=null;if(J.length>0){let zt=1+_.length+ae+se.length+1;Fn={start:zt,end:zt+J.length-1}}else Fn=null;let St=ut?"box-border-focused":"box-border",en=ut?"box-border-focused-hover":"box-border-hover",tn=(zt,ci)=>{H(n,ci?en:St,zt)};H(n,St,"\u256D"),tn(_,kn==="cwd"),H(n,St,ge),se&&tn(se,kn==="host"),J&&tn(J,kn==="agent"),H(n,St,"\u256E")},md=()=>{let E=me(),_="\u2500".repeat(E);(p===0||Rt)&&rt?H(n,"box-border-focused",`\u2570${_}\u256F`):H(n,"box-border",`\u2570${_}\u256F`)},gd=()=>{let E=lt();if(E===null)return;let _=Math.max(0,Cn(n)-2);if(E.plain.length>_){let W=E.plain.slice(0,Math.max(0,_-1))+"\u2026";H(n,"modal-hint",` ${W}`);return}E.render()},ti=E=>{let _=Gn[E];return _?(Me.state().buffer[_.bufferIdx]??"").slice(_.startCol,_.endCol):""},yd=E=>{if(Ht===null)return null;let _=Gn[E];if(!_)return null;let W=Ht;if(_.bufferIdx<W.startRow||_.bufferIdx>W.endRow)return null;let J=_.bufferIdx===W.startRow?W.startCol:_.startCol,se=_.bufferIdx===W.endRow?W.endCol:_.endCol,ae=Math.max(J,_.startCol),ge=Math.min(se,_.endCol);return ge<=ae?null:{start:ae-_.startCol,end:ge-_.startCol}},xr=E=>{let _=me(),W=ti(E),J=Math.max(0,_-1-W.length),se=" ".repeat(J),ae=yd(E),ge=()=>{if(ae===null){H(n,"content",` ${W}${se}`);return}H(n,"content"," "),ae.start>0&&H(n,"content",W.slice(0,ae.start)),H(n,"selection-highlight",W.slice(ae.start,ae.end)),ae.end<W.length&&H(n,"content",W.slice(ae.end)),H(n,"content",se)};(p===0||Rt)&&rt?(H(n,"box-border-focused","\u2502"),ge(),H(n,"box-border-focused","\u2502")):(H(n,"box-border","\u2502"),ge(),H(n,"box-border","\u2502"))},ni=E=>{let _=wo[E]??"",W=d[E],J=W&&W.priority&&W.priority>0?"* ":" ";p===E+1&&!Rt&&rt?H(n,"list-selected",`${J}${_}`):H(n,"content",`${J}${_}`)},Qi=()=>{let E=m,_=Math.max(0,d.length-m-it),W=[];return r.filters.cwdOnly&&W.push({kind:"plain",text:"cwd-only"}),r.filters.hostFilter!=="__all"&&W.push({kind:"host",text:AJ(r.filters.hostFilter)}),r.filters.includeNonInteractive&&W.push({kind:"plain",text:"+non-interactive"}),E>0&&W.push({kind:"plain",text:`\u2191 ${E} above`}),_>0&&W.push({kind:"plain",text:`\u2193 ${_} below`}),W},Il=()=>{let E=Qi();return E.length===0?"":` ${E.map(_=>_.text).join(" \xB7 ")}`},$s=E=>Qe(E),Uf=()=>{let E=I?`${I.sessionId}|${I.status}`:"";return["ind",S,E,Ge?`${Ge.text}${Ge.cursor}`:"",ue??"",b?`1|${g}|${d.length}`:"0",Il(),di?"h1":"h0",ea?"ho1":"ho0"].join("")},Ne=()=>{mt(()=>{Ye.paintRow(Xr(),Uf(),()=>{let E=()=>{Eo=null,rs=null};if(S==="confirm-kill"&&I)E(),H(n,"prompt-text",` kill ${$s(I.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&I)E(),I.status==="warm"?H(n,"prompt-destructive",` kill + delete ${$s(I.sessionId)}? [y/N]`):H(n,"prompt-destructive",` delete ${$s(I.sessionId)}? [y/N]`);else if(S==="busy"&&I)E(),H(n,"modal-status",` working on ${$s(I.sessionId)}\u2026`);else if(S==="rename"&&I&&Ge){E();let _=Ge.text,W=Ge.cursor;H(n,"prompt-text"," title: "),H(n,"prompt-text",_.slice(0,W)),W<_.length?(H(n,"prompt-cursor",_[W]??" "),H(n,"prompt-text",_.slice(W+1))):H(n,"prompt-cursor"," "),H(n,"modal-hint"," Enter saves \xB7 Esc cancels")}else if(ue!==null)E(),H(n,"modal-status",` ${ue}`);else{let _=Qi(),W=Il(),J="Esc \xB7 Go Back",se=J.length,ae=5,ge=W.length,ut=Math.max(1,Wt-ge-se-ae);if(rs=null,_.length>0){H(n,"modal-hint"," ");let St=3;for(let en=0;en<_.length;en++){let tn=_[en];en>0&&(H(n,"modal-hint"," \xB7 "),St+=3),tn.kind==="host"?(rs={start:St,end:St+tn.text.length-1},ea?H(n,"content",tn.text):H(n,"modal-hint",tn.text)):H(n,"modal-hint",tn.text),St+=tn.text.length}}H(n,"modal-hint"," ".repeat(ut)),di?H(n,"content",J):H(n,"modal-hint",J),Eo={start:Wt-ae-se+1,end:Wt-ae}}})})},Ln=E=>On+1+E,Jn=()=>On+yn+1,Le=()=>On+yn+3,Wf=E=>Le()+1+(E-m),Xr=()=>Le()+1+it,cn=()=>{let E=Gi-yo;if(E<0||E>=yn)return;let _=3+Sl;n.moveTo(_,Ln(E))},Zr=(E,_)=>{let W=_-(On+1);if(W<0||W>=yn)return null;let J=Gn[yo+W];if(!J)return null;let se=Math.max(0,Math.min(J.endCol-J.startCol,E-3));return{row:J.bufferIdx,col:J.startCol+se}},vo=()=>{Ht!==null&&(Ht=null,To())},Os=(E,_)=>{let W=E.row<_.row||E.row===_.row&&E.col<=_.col,J=W?E:_,se=W?_:E;if(J.row===se.row&&J.col===se.col){vo();return}let ae={startRow:J.row,startCol:J.col,endRow:se.row,endCol:se.col},ge=Ht;ge&&ge.startRow===ae.startRow&&ge.startCol===ae.startCol&&ge.endRow===ae.endRow&&ge.endCol===ae.endCol||(Ht=ae,To())},A=()=>{if(Ht===null)return"";let{startRow:E,startCol:_,endRow:W,endCol:J}=Ht,se=Me.state().buffer;if(E===W)return(se[E]??"").slice(_,J);let ae=[(se[E]??"").slice(_)];for(let ge=E+1;ge<W;ge++)ae.push(se[ge]??"");return ae.push((se[W]??"").slice(0,J)),ae.join(`
275
+ `)},jf=()=>{let E=A();E.length!==0&&ml(E,{target:Ki}).then(_=>{let W=E.length;oe=_.ok?`copied ${W} char${W===1?"":"s"} to clipboard`:`clipboard copy failed: ${_.reason}`,Ir()},_=>{oe=`clipboard copy failed: ${_.message}`,Ir()})},Cl=E=>{let _=Me.state().buffer[E.row]??"";if(_.length===0)return null;let W=Math.max(0,Math.min(_.length-1,E.col));if(!Es.test(_[W]))return null;let J=W;for(;J>0&&Es.test(_[J-1]);)J--;let se=W+1;for(;se<_.length&&Es.test(_[se]);)se++;return{start:J,end:se}},qf=E=>{let _=Me.state().buffer[E]??"";Os({row:E,col:0},{row:E,col:_.length})},zf=E=>{let _=Et;if(_===null)return;let W=E.row<_.row||E.row===_.row&&E.col<_.start,J=E.row>_.row||E.row===_.row&&E.col>_.end,se={row:_.row,col:_.start},ae={row:_.row,col:_.end};if(W){let ge=Cl(E);se=ge!==null?{row:E.row,col:ge.start}:E}else if(J){let ge=Cl(E);ae=ge!==null?{row:E.row,col:ge.end}:E}Os(se,ae)},wd=E=>{let _=Sr;if(_===null)return;let W=Math.min(_,E.row),J=Math.max(_,E.row),se=Me.state().buffer[J]??"";Os({row:W,col:0},{row:J,col:se.length})},ri=E=>{if(!As)return;let _=Zr(E.x,E.y);if(_===null)return;Kn=_,Ts=!1,gn=!1,Yr=1,X="char",Et=null,Sr=null,vo();let W=Date.now(),J=Xo,se=J!==null&&W-J.t<=ay&&Math.abs(E.x-J.x)<=vl&&Math.abs(E.y-J.y)<=vl&&J.row!==null&&J.row===_.row;if(se&&J.count===2&&E.x===J.x&&E.y===J.y){Yr=3,qf(_.row),X="line",Sr=_.row,gn=!0;return}if(se&&J.count===1){Yr=2;let ut=Cl(_);ut!==null&&(Os({row:_.row,col:ut.start},{row:_.row,col:ut.end}),gn=!0,X="word",Et={row:_.row,start:ut.start,end:ut.end})}},es=E=>{if(Kn===null)return;let _=Math.max(1,Math.min(Wt,E.x)),W=Math.max(On+1,Math.min(On+yn,E.y)),J=Zr(_,W);J!==null&&(Ts=!0,X==="word"?zf(J):X==="line"?wd(J):Os(Kn,J))},dy=E=>{let _=Ts,W=gn;if(Kn=null,Ts=!1,gn=!1,E!==null){let J=Zr(E.x,E.y);Xo={x:E.x,y:E.y,t:Date.now(),count:Yr,row:J?.row??null}}if(Yr=1,_||W){jf();return}vo()},bd=()=>rt?p===0?"f":Rt?"h":"u":"x",So=()=>`ct|${bd()}|${me()}|${ud}|${xl()}|${ko??""}|${kn??""}`,Rl=()=>`cb|${bd()}|${me()}`,Kf=()=>$e!==null?`cs|i|${$e}`:b?`cs|s|${g}|${d.length}`:oe!==null?`cs|h|${oe}`:"blank",Al=E=>{let _=yd(E),W=_===null?"":`${_.start}:${_.end}`;return`cbb|${bd()}|${me()}|${ti(E)}|${W}`},Gf=()=>`h|${fd}`,kd=E=>{let _=d[E],W=_&&_.priority&&_.priority>0?"* ":" ",J=wo[E]??"";return`sr|${p===E+1&&!Rt&&rt?"1":"0"}|${W}${J}`},Pt=()=>{mt(()=>{n.hideCursor(),Yi(),Qr(),On=1,Ye.ensureSize(Wt,Zo),Ye.paintRow(On,So(),()=>{hd()});for(let E=0;E<yn;E++){let _=yo+E;Ye.paintRow(Ln(E),Al(_),()=>{xr(_)})}Ye.paintRow(Jn(),Rl(),()=>{md()}),Ye.paintRow(Jn()+1,Kf(),()=>gd()),Ye.paintRow(Le(),Gf(),()=>{H(n,"list-header",` ${fd}`)});for(let E=0;E<it;E++){let _=m+E,W=Le()+1+E;_<d.length?Ye.paintRow(W,kd(_),()=>{ni(_)}):Ye.paintRow(W,"blank",()=>{})}Ne();for(let E=Xr()+1;E<=Zo;E++)Ye.paintRow(E,"blank",()=>{});p===0&&(cn(),n.hideCursor(!1))})},Jf=()=>{Ye.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),Pt()},Vf=()=>{mt(()=>{n.hideCursor(),Ye.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),H(n,"modal-title"," Picker hotkeys"),n.noFormat(`
276
276
 
277
- `);for(let P of SJ()){if(P===null){n(`
278
- `);continue}let[_,W]=P;H(n,"modal-key",` ${_.padEnd(vJ)}`),H(n,"content",W),n.noFormat(`
277
+ `);for(let E of SJ()){if(E===null){n(`
278
+ `);continue}let[_,W]=E;H(n,"modal-key",` ${_.padEnd(vJ)}`),H(n,"content",W),n.noFormat(`
279
279
  `)}n(`
280
280
  `),H(n,"modal-hint"," press any key to dismiss"),n.noFormat(`
281
- `)})},vd=()=>wn+4,Nn=()=>wn+5,Vn=2,It=0,Yn=()=>{Zo=uo(n);let P=Math.max(2,Zo-(wn+4)-Vn);return Math.max(1,Math.floor(P/2))},xo=()=>{let P=Yn();F<It?It=F:F>=It+P&&(It=F-P+1),It+P>E.length&&(It=Math.max(0,E.length-P)),It<0&&(It=0)},Tl=P=>{Wt=Cn(n);let _=Math.max(2,Wt-3),W="\u2500 Find sessions ",J="\u2500".repeat(Math.max(1,_-W.length));P?H(n,"box-border-focused",`\u256D${W}${J}\u256E`):H(n,"box-border",`\u256D${W}${J}\u256E`),n.styleReset()},Io=()=>{Wt=Cn(n),Hf=Math.max(10,Wt-G$);let P=$.state();Xe=Cs(P.buffer,Hf);let _=go(Xe,P,kJ);wn=_.rendered,Ji=_.windowStart,Vi=_.cursorVisualRow,bo=_.cursorVisualCol},Sd=(P,_)=>{Wt=Cn(n);let W=Math.max(2,Wt-3),J=Xe[P],se="";J&&(se=($.state().buffer[J.bufferIdx]??"").slice(J.startCol,J.endCol));let ae=Math.max(0,W-1-se.length),ge=" ".repeat(ae);_?(H(n,"box-border-focused","\u2502"),H(n,"content",` ${se}${ge}`),H(n,"box-border-focused","\u2502")):(H(n,"box-border","\u2502"),H(n,"content",` ${se}${ge}`),H(n,"box-border","\u2502")),n.styleReset()},ln=P=>{Wt=Cn(n);let _=Math.max(2,Wt-3),W="\u2500".repeat(_);P?H(n,"box-border-focused",`\u2570${W}\u256F`):H(n,"box-border",`\u2570${W}\u256F`),n.styleReset()},si=()=>3+bo,Co=()=>2+(Vi-Ji),Xi=()=>{let P=C==="input";mt(()=>{P&&n.hideCursor(),n.moveTo(1,1),Tl(P);for(let _=0;_<wn;_++)n.moveTo(1,2+_),Sd(Ji+_,P);n.moveTo(1,2+wn),ln(P),P&&(n.moveTo(si(),Co()),n.hideCursor(!1))})},xd=()=>{mt(()=>{n.hideCursor();for(let P=0;P<wn;P++)n.moveTo(1,2+P),Sd(Ji+P,!0);n.moveTo(si(),Co()),n.hideCursor(!1)})},El=4,Pl=16,cy=()=>Math.max(24,Cn(n)-1-El-Pl),Yf=(P,_)=>{let W=E[P];if(!W)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let J=Cn(n),se=Math.max(20,J-Qg),ae=xe(W.sessionId),ge=ae!==null?wr(ae,Q,se,c).padEnd(se):`${Qe(W.sessionId)} ${W.status==="warm"?"warm":"cold"} ${Yu(W.title??V(W.cwd),Math.max(5,se-20))}`.padEnd(se),ut=_?K:0,St=W.snippets[ut],en=W.snippets.length>1?`[${ut+1}/${W.snippets.length}] `:W.totalMatches>W.snippets.length?`[${W.snippets.length} of ${W.totalMatches}] `:"",tn=St?.toolName?`${St.toolName} `:"",zt=`${en}${tn}`,ci=Math.max(10,J-1-El-zt.length),ta=St?Yu(St.text,ci):"",li=St?` ${zt}${ta}`:" (no snippet)";return{rowBudget:se,line1:ge,line2:li.padEnd(se+Qg),focusedRow:_}},Id=()=>{H(n,"list-header",` ${ke}`),n.styleReset()},Fs=(P,_)=>{let{line1:W,focusedRow:J}=Yf(P,_);J?H(n,"list-selected",`\u276F ${W}`):H(n,"content",` ${W}`),n.styleReset()},Cd=(P,_)=>{let{line2:W}=Yf(P,_);H(n,"list-description",W),n.styleReset()},Rd=()=>{if(z)H(n,"modal-status"," searching\u2026"),n.styleReset(),n.eraseLineAfter();else if(Y!==null)H(n,"modal-error",` ${Y}`),n.styleReset(),n.eraseLineAfter();else if(C==="input")E.length>0?H(n,"modal-hint"," Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):H(n,"modal-hint"," Enter to search \xB7 Esc cancel"),n.styleReset(),n.eraseLineAfter();else{let P=E.length,_=M?" \xB7 truncated":"",W=P>0?` ${P} ${P===1?"session":"sessions"} match${_} \xB7 `:" ";H(n,"modal-hint",`${W}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 i info \xB7 Enter open \xB7 Esc back`),n.styleReset(),n.eraseLineAfter()}},Ro=()=>{Io();let P=C==="input",_=$.state().buffer.join(`
282
- `);mt(()=>{n.hideCursor(),Ye.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),Tl(P);for(let J=0;J<wn;J++)n.moveTo(1,2+J),Sd(Ji+J,P);n.moveTo(1,2+wn),ln(P);let W=E.length;if(W===0)n.moveTo(1,Nn()),z||(Y===null&&_.trim().length===0?(H(n,"modal-hint"," type a query in the box above, then press Enter"),n.eraseLineAfter()):Y===null&&(H(n,"modal-status"," no matches"),n.eraseLineAfter())),n.moveTo(1,Nn()+1),Rd();else{xo(),n.moveTo(1,vd()),Id();let J=Yn(),se=C!=="input";for(let ae=0;ae<J;ae++){let ge=It+ae;n.moveTo(1,Nn()+ae*2),ge<W?Fs(ge,se&&ge===F):n.eraseLineAfter(),n.moveTo(1,Nn()+ae*2+1),ge<W?Cd(ge,se&&ge===F):n.eraseLineAfter()}n.moveTo(1,Nn()+J*2),Rd()}P&&(n.moveTo(si(),Co()),n.hideCursor(!1))})},Zi=(P,_)=>{let W=P-It;W<0||W>=Yn()||mt(()=>{n.moveTo(1,Nn()+W*2),Fs(P,_),n.moveTo(1,Nn()+W*2+1),Cd(P,_)})},Ls=()=>{mt(()=>{n.moveTo(1,Nn()+Yn()*2),Rd()})},Ns=()=>{mt(()=>{let P=Yn(),_=E.length,W=C!=="input";for(let J=0;J<P;J++){let se=It+J;n.moveTo(1,Nn()+J*2),se<_?Fs(se,W&&se===F):n.eraseLineAfter(),n.moveTo(1,Nn()+J*2+1),se<_?Cd(se,W&&se===F):n.eraseLineAfter()}n.moveTo(1,Nn()+P*2),Rd()})},ir=()=>$.state().buffer.join(`
283
- `),oi=P=>{let _=wn;$.feed({type:"paste",text:P}),Io(),wn!==_?Ro():xd()},Ao=async()=>{let P=ir().trim();if(P.length!==0){if(d.length===0){Y="no sessions in view to search",Ro();return}z=!0,Y=null,Ro();try{let _=await tE(e.target,P,{sessionIds:d.map(W=>W.sessionId),snippetWidth:cy()});E=_.results,je(),M=_.truncated,F=0,K=0,It=0,C=_.results.length>0?"results":"input",Io()}catch(_){Y=`search failed: ${_.message}`}finally{z=!1,Ro()}}},Qn=()=>{let P=ir();if(P.trim().length===0&&E.length===0){delete r.lastFind;return}r.lastFind={query:P,results:E,truncated:M,selectedIdx:F,snippetIdx:K,scrollOffset:It}},Ds=()=>{},Vt=()=>{mt(()=>{let P=p===0;P&&n.hideCursor(),Ye.paintRow(On,So(),()=>{hd()}),Ye.paintRow(Jn(),Rl(),()=>{md()});for(let _=0;_<yn;_++){let W=yo+_;Ye.paintRow(Ln(_),Al(W),()=>{xr(W)})}P&&(cn(),n.hideCursor(!1))})},Ir=()=>{mt(()=>{Ye.paintRow(Jn()+1,Kf(),()=>gd())})},Cr=()=>{oe!==null&&(oe=null,Ir())},Xn=P=>{let _=e.config.tui.hotkeys[P];return _?(Vg(_,{sessionId:"",cwd:s,agentId:Zt??"",baseUrl:e.target.baseUrl,tokenFile:D.authToken()},{notify:W=>{oe=W,Ir()},cwd:s,emitLines:W=>{if(W.length===0)return;let J=W[0].text;oe=W.length>1?`${J} (+${W.length-1} more)`:J,Ir()}}),!0):!1},To=()=>{mt(()=>{let P=Me.state();Gn=Cs(P.buffer,or);let _=go(Gn,P,Pf);yo=_.windowStart,Gi=_.cursorVisualRow,Sl=_.cursorVisualCol;let W=p===0;W&&n.hideCursor();for(let J=0;J<yn;J++){let se=yo+J;Ye.paintRow(Ln(J),Al(se),()=>{xr(se)})}W&&(cn(),n.hideCursor(!1))})},Ad=async()=>{let P=await kg();if(!P.ok){ue=P.reason,Ne();return}if(P.kind!=="image"){let _=Me.state(),W=[..._.buffer],J=_.row,se=_.col;Me.feed({type:"paste",text:P.text});let ae=Me.state();if(W.length!==ae.buffer.length||J!==ae.row||se!==ae.col||!W.every((ut,St)=>ut===ae.buffer[St])){let ut=Cs(ae.buffer,or);go(ut,ae,Pf).rendered!==yn?Pt():To()}return}Me.addAttachment(P.attachment),ue=`attached ${P.attachment.name??"image"}`,Pt()},Qf=async()=>{let P=await Ig(Me.expandedText(),{suspend:()=>_l?.(),resume:()=>Pd?.(),notify:_=>{ue=_,Ne()}});P!==null&&(Me.setBuffer(P,Me.state().attachments),Pt())},ly=P=>{P<m||P>=m+it||mt(()=>{Ye.paintRow(Wf(P),kd(P),()=>{ni(P)})})},ts=()=>{mt(()=>{for(let P=0;P<it;P++){let _=Le()+1+P,W=m+P;W<d.length?Ye.paintRow(_,kd(W),()=>{ni(W)}):Ye.paintRow(_,"blank",()=>{})}Ne()})},Td=()=>{mt(()=>{Ye.paintRow(Le(),Gf(),()=>{H(n,"list-header",` ${fd}`)});for(let P=0;P<it;P++){let _=Le()+1+P,W=m+P;W<d.length?Ye.paintRow(_,kd(W),()=>{ni(W)}):Ye.paintRow(_,"blank",()=>{})}Ne(),p===0&&(cn(),n.hideCursor(!1))})},ns=!1,ii="",Ml=0,uy=200,Dn=null,ai=!1,Eo=null,di=!1,rs=null,ea=!1,ar=null,Ed=null,_l=null,Pd=null,$l=!1,Ol=null,Md=P=>{let _=P.toString("binary");if(_.includes("\x1B[I")||_.includes("\x1B[O")){for(;;){let J=_.indexOf("\x1B[I"),se=_.indexOf("\x1B[O"),ae=J===-1?se:se===-1?J:Math.min(J,se);if(ae===-1)break;let ge=rt;rt=ae===J,rt&&(Ml=Date.now()),ge!==rt&&!Xt&&Bf.length<=1&&mt(()=>{Vt(),ts()}),_=_.slice(0,ae)+_.slice(ae+"\x1B[I".length)}if(_.length===0)return}if(!ns&&_===""&&Ed){Ed();return}if(!ns&&(_===""||_==="\x1B_"||_==="\x1B")){Ol?.(_);return}if(ns){let J=_.indexOf(nf);if(J===-1){ii+=_;return}ii+=_.slice(0,J),ns=!1;let se=Buffer.from(ii,"binary").toString("utf-8").replace(/\r\n?/g,`
284
- `);ii="";let ae=_.slice(J+nf.length);if(x)C==="input"&&!z&&oi(se);else if(p===0&&!b){let ge=Me.feed({type:"paste",text:se});for(let tn of ge)tn.type==="attachment-request"&&Ad();let ut=Me.state(),St=Cs(ut.buffer,or);go(St,ut,Pf).rendered!==yn?Pt():To()}ae.length>0&&ar&&ar(Buffer.from(ae,"binary"));return}let W=_.indexOf(sl);if(W===-1){ar?.(P);return}W>0&&ar?.(Buffer.from(_.slice(0,W),"binary")),_=_.slice(W+sl.length),ns=!0,_.length>0&&Md(Buffer.from(_,"binary"))};return Pt(),await new Promise(P=>{let _=null,W=!1,J=null,se=!1,ae=Bf,ge=N=>{ae.push(N)},ut=()=>{ae.pop(),Xt||ae[ae.length-1]?.onResize()},St={push:ge,pop:ut},en=()=>{let N={kind:"new",cwd:s},ee=Me.state().attachments;return ee.length>0&&(N.attachments=[...ee]),Zt&&(N.agentId=Zt),bn&&(N.model=bn),ko&&(N.host=ko),ei&&(N.agentExplicit=!0),N},tn=async()=>{if(!(ei||!e.onCwdChange))try{let N=await e.onCwdChange(s);N.agentId!==void 0&&(Zt=N.agentId,bn=N.model),N.notice!==void 0&&(ue=N.notice)}catch{}},zt=async()=>{ui(),Ye.clearCache(),ge({onKey:()=>{},onResize:()=>{}});let ee;try{ee=await ad(n,void 0,{defaultCwd:s,title:"Change cwd",intro:"New cwd for the picker and any new sessions:",overlay:!0})}finally{ut(),cr()}if(ee.kind==="ok"&&ee.path!==s){s=ee.path;let pe=p>0?d[p-1]?.sessionId:null;o=Xg(o,s),Rn(),Ps(pe),await tn()}Xt||Pt()},ci=async(N="agent")=>{let ee=e.availableAgents??[],pe=e.availableHosts??[];if(ee.length===0&&pe.length===0)return;let Z=[...new Set([e.config.sessionDefaults??{},...Object.values(e.hostInfo??{}).map(Ue=>Ue.sessionDefaults??{})].flatMap(Ue=>Object.values(Ue)).map(Ue=>Ue.model).filter(Ue=>typeof Ue=="string"))];ui(),Ye.clearCache(),ge({onKey:()=>{},onResize:()=>{}});let Be;try{Be=await s_(n,{...Zt?{agentId:Zt}:{},...bn?{model:bn}:{},...ko?{host:ko}:{}},{agents:ee,hosts:pe,...e.hostInfo?{hostInfo:e.hostInfo}:{},...e.config.defaultAgent?{localDefaultAgent:e.config.defaultAgent}:{},models:Z,defaultModelFor:(Ue,at)=>Ue===void 0?void 0:Or((at!==void 0?e.hostInfo?.[at]?.sessionDefaults:void 0)??e.config.sessionDefaults,{id:Ue.id,extendsChain:Ue.extendsChain})?.value.model},N)}finally{ut(),cr()}if(Be.kind==="apply"){let Ue=Be.config,at=Ue.agentId!==Zt||Ue.model!==bn;if(Zt=Ue.agentId,bn=Ue.model,ko=Ue.host,at&&(ei=!0,Zt!==void 0&&e.onComposerAgentChange?.(Zt,bn)),Be.persist&&Zt!==void 0)try{await hi(Zt)}catch{}}Xt||Pt()};Ds=()=>{Qn(),$=new Vo({history:[],collapsePastes:!1}),E=[],M=!1,F=0,K=0,It=0,Y=null,z=!1,C="input",x=!1,ut()};let ta=new Fi(Xm),li=(N,ee,pe)=>{if(Xf(),Ht!==null&&vo(),pe?.isCharacter){ta.clear(),ae[ae.length-1]?.onKey(N,ee,pe);return}let Z=ta.feed(N);switch(Z.kind){case"pass":ae[ae.length-1]?.onKey(Z.token,ee,pe);return;case"armed":case"aborted":return}},Fl=()=>{Xt||ae[ae.length-1]?.onResize()};Ol=N=>{Xt||(ta.clear(),ae[ae.length-1]?.onKey(N,null,{}))};let na=!1,_d=()=>{if(na)return;na=!0,ae.length=0,_&&(clearInterval(_),_=null),J&&(J.abort(),J=null,W=!1),n.off("key",li),n.off("mouse",Bs),n.off("resize",Fl),be(Jo),be(sf);let N=n;N.stdin&&ar&&(N.stdin.removeListener("data",Md),N.stdin.on("data",ar),ar=null),ns=!1,ii="",n.grabInput(!1),we({src:"grab",site:"picker.detachInput",on:!1})},Rr=()=>{Xt||(Xt=!0,_d(),n.hideCursor(!1),n.moveTo(1,Xr()+1),n(`
285
- `))},$d=()=>{if(Xt||ae.length>1||S!=="normal"||b||se||$l)return;W&&J&&(J.abort(),J=null,W=!1);let N=p>0?d[p-1]?.sessionId:void 0;W=!0;let ee=new AbortController;J=ee,nn(N,{silent:!0,signal:ee.signal}).finally(()=>{J===ee&&(J=null),W=!1})},Xf=()=>{Xt||(_&&clearInterval(_),_=setInterval($d,3e3))},Ar=()=>(_d(),Yg("",{write(ee){$e=ee,Ir()},finalize(){$e=null,Rr()}})),ra=()=>(Rr(),P({kind:Tt?"exit":"abort"}),!0),Zf=()=>{let N=l.map(ee=>`${ee.session}|${ee.upstream}|${ee.host}|${ee.state}|${ee.agent}|${ee.model}|${ee.age}|${ee.title}|${ee.cwd}|${ee.cost}`).join(`
281
+ `)})},vd=()=>wn+4,Nn=()=>wn+5,Vn=2,It=0,Yn=()=>{Zo=uo(n);let E=Math.max(2,Zo-(wn+4)-Vn);return Math.max(1,Math.floor(E/2))},xo=()=>{let E=Yn();F<It?It=F:F>=It+E&&(It=F-E+1),It+E>P.length&&(It=Math.max(0,P.length-E)),It<0&&(It=0)},Tl=E=>{Wt=Cn(n);let _=Math.max(2,Wt-3),W="\u2500 Find sessions ",J="\u2500".repeat(Math.max(1,_-W.length));E?H(n,"box-border-focused",`\u256D${W}${J}\u256E`):H(n,"box-border",`\u256D${W}${J}\u256E`),n.styleReset()},Io=()=>{Wt=Cn(n),Hf=Math.max(10,Wt-G$);let E=$.state();Xe=Cs(E.buffer,Hf);let _=go(Xe,E,kJ);wn=_.rendered,Ji=_.windowStart,Vi=_.cursorVisualRow,bo=_.cursorVisualCol},Sd=(E,_)=>{Wt=Cn(n);let W=Math.max(2,Wt-3),J=Xe[E],se="";J&&(se=($.state().buffer[J.bufferIdx]??"").slice(J.startCol,J.endCol));let ae=Math.max(0,W-1-se.length),ge=" ".repeat(ae);_?(H(n,"box-border-focused","\u2502"),H(n,"content",` ${se}${ge}`),H(n,"box-border-focused","\u2502")):(H(n,"box-border","\u2502"),H(n,"content",` ${se}${ge}`),H(n,"box-border","\u2502")),n.styleReset()},ln=E=>{Wt=Cn(n);let _=Math.max(2,Wt-3),W="\u2500".repeat(_);E?H(n,"box-border-focused",`\u2570${W}\u256F`):H(n,"box-border",`\u2570${W}\u256F`),n.styleReset()},si=()=>3+bo,Co=()=>2+(Vi-Ji),Xi=()=>{let E=C==="input";mt(()=>{E&&n.hideCursor(),n.moveTo(1,1),Tl(E);for(let _=0;_<wn;_++)n.moveTo(1,2+_),Sd(Ji+_,E);n.moveTo(1,2+wn),ln(E),E&&(n.moveTo(si(),Co()),n.hideCursor(!1))})},xd=()=>{mt(()=>{n.hideCursor();for(let E=0;E<wn;E++)n.moveTo(1,2+E),Sd(Ji+E,!0);n.moveTo(si(),Co()),n.hideCursor(!1)})},El=4,Pl=16,cy=()=>Math.max(24,Cn(n)-1-El-Pl),Yf=(E,_)=>{let W=P[E];if(!W)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let J=Cn(n),se=Math.max(20,J-Qg),ae=xe(W.sessionId),ge=ae!==null?wr(ae,Q,se,c).padEnd(se):`${Qe(W.sessionId)} ${W.status==="warm"?"warm":"cold"} ${Yu(W.title??V(W.cwd),Math.max(5,se-20))}`.padEnd(se),ut=_?K:0,St=W.snippets[ut],en=W.snippets.length>1?`[${ut+1}/${W.snippets.length}] `:W.totalMatches>W.snippets.length?`[${W.snippets.length} of ${W.totalMatches}] `:"",tn=St?.toolName?`${St.toolName} `:"",zt=`${en}${tn}`,ci=Math.max(10,J-1-El-zt.length),ta=St?Yu(St.text,ci):"",li=St?` ${zt}${ta}`:" (no snippet)";return{rowBudget:se,line1:ge,line2:li.padEnd(se+Qg),focusedRow:_}},Id=()=>{H(n,"list-header",` ${ke}`),n.styleReset()},Fs=(E,_)=>{let{line1:W,focusedRow:J}=Yf(E,_);J?H(n,"list-selected",`\u276F ${W}`):H(n,"content",` ${W}`),n.styleReset()},Cd=(E,_)=>{let{line2:W}=Yf(E,_);H(n,"list-description",W),n.styleReset()},Rd=()=>{if(z)H(n,"modal-status"," searching\u2026"),n.styleReset(),n.eraseLineAfter();else if(Y!==null)H(n,"modal-error",` ${Y}`),n.styleReset(),n.eraseLineAfter();else if(C==="input")P.length>0?H(n,"modal-hint"," Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):H(n,"modal-hint"," Enter to search \xB7 Esc cancel"),n.styleReset(),n.eraseLineAfter();else{let E=P.length,_=M?" \xB7 truncated":"",W=E>0?` ${E} ${E===1?"session":"sessions"} match${_} \xB7 `:" ";H(n,"modal-hint",`${W}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 i info \xB7 Enter open \xB7 Esc back`),n.styleReset(),n.eraseLineAfter()}},Ro=()=>{Io();let E=C==="input",_=$.state().buffer.join(`
282
+ `);mt(()=>{n.hideCursor(),Ye.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),Tl(E);for(let J=0;J<wn;J++)n.moveTo(1,2+J),Sd(Ji+J,E);n.moveTo(1,2+wn),ln(E);let W=P.length;if(W===0)n.moveTo(1,Nn()),z||(Y===null&&_.trim().length===0?(H(n,"modal-hint"," type a query in the box above, then press Enter"),n.eraseLineAfter()):Y===null&&(H(n,"modal-status"," no matches"),n.eraseLineAfter())),n.moveTo(1,Nn()+1),Rd();else{xo(),n.moveTo(1,vd()),Id();let J=Yn(),se=C!=="input";for(let ae=0;ae<J;ae++){let ge=It+ae;n.moveTo(1,Nn()+ae*2),ge<W?Fs(ge,se&&ge===F):n.eraseLineAfter(),n.moveTo(1,Nn()+ae*2+1),ge<W?Cd(ge,se&&ge===F):n.eraseLineAfter()}n.moveTo(1,Nn()+J*2),Rd()}E&&(n.moveTo(si(),Co()),n.hideCursor(!1))})},Zi=(E,_)=>{let W=E-It;W<0||W>=Yn()||mt(()=>{n.moveTo(1,Nn()+W*2),Fs(E,_),n.moveTo(1,Nn()+W*2+1),Cd(E,_)})},Ls=()=>{mt(()=>{n.moveTo(1,Nn()+Yn()*2),Rd()})},Ns=()=>{mt(()=>{let E=Yn(),_=P.length,W=C!=="input";for(let J=0;J<E;J++){let se=It+J;n.moveTo(1,Nn()+J*2),se<_?Fs(se,W&&se===F):n.eraseLineAfter(),n.moveTo(1,Nn()+J*2+1),se<_?Cd(se,W&&se===F):n.eraseLineAfter()}n.moveTo(1,Nn()+E*2),Rd()})},ir=()=>$.state().buffer.join(`
283
+ `),oi=E=>{let _=wn;$.feed({type:"paste",text:E}),Io(),wn!==_?Ro():xd()},Ao=async()=>{let E=ir().trim();if(E.length!==0){if(d.length===0){Y="no sessions in view to search",Ro();return}z=!0,Y=null,Ro();try{let _=await tE(e.target,E,{sessionIds:d.map(W=>W.sessionId),snippetWidth:cy()});P=_.results,je(),M=_.truncated,F=0,K=0,It=0,C=_.results.length>0?"results":"input",Io()}catch(_){Y=`search failed: ${_.message}`}finally{z=!1,Ro()}}},Qn=()=>{let E=ir();if(E.trim().length===0&&P.length===0){delete r.lastFind;return}r.lastFind={query:E,results:P,truncated:M,selectedIdx:F,snippetIdx:K,scrollOffset:It}},Ds=()=>{},Vt=()=>{mt(()=>{let E=p===0;E&&n.hideCursor(),Ye.paintRow(On,So(),()=>{hd()}),Ye.paintRow(Jn(),Rl(),()=>{md()});for(let _=0;_<yn;_++){let W=yo+_;Ye.paintRow(Ln(_),Al(W),()=>{xr(W)})}E&&(cn(),n.hideCursor(!1))})},Ir=()=>{mt(()=>{Ye.paintRow(Jn()+1,Kf(),()=>gd())})},Cr=()=>{oe!==null&&(oe=null,Ir())},Xn=E=>{let _=e.config.tui.hotkeys[E];return _?(Vg(_,{sessionId:"",cwd:s,agentId:Zt??"",baseUrl:e.target.baseUrl,tokenFile:D.authToken()},{notify:W=>{oe=W,Ir()},cwd:s,emitLines:W=>{if(W.length===0)return;let J=W[0].text;oe=W.length>1?`${J} (+${W.length-1} more)`:J,Ir()}}),!0):!1},To=()=>{mt(()=>{let E=Me.state();Gn=Cs(E.buffer,or);let _=go(Gn,E,Pf);yo=_.windowStart,Gi=_.cursorVisualRow,Sl=_.cursorVisualCol;let W=p===0;W&&n.hideCursor();for(let J=0;J<yn;J++){let se=yo+J;Ye.paintRow(Ln(J),Al(se),()=>{xr(se)})}W&&(cn(),n.hideCursor(!1))})},Ad=async()=>{let E=await kg();if(!E.ok){ue=E.reason,Ne();return}if(E.kind!=="image"){let _=Me.state(),W=[..._.buffer],J=_.row,se=_.col;Me.feed({type:"paste",text:E.text});let ae=Me.state();if(W.length!==ae.buffer.length||J!==ae.row||se!==ae.col||!W.every((ut,St)=>ut===ae.buffer[St])){let ut=Cs(ae.buffer,or);go(ut,ae,Pf).rendered!==yn?Pt():To()}return}Me.addAttachment(E.attachment),ue=`attached ${E.attachment.name??"image"}`,Pt()},Qf=async()=>{let E=await Ig(Me.expandedText(),{suspend:()=>_l?.(),resume:()=>Pd?.(),notify:_=>{ue=_,Ne()}});E!==null&&(Me.setBuffer(E,Me.state().attachments),Pt())},ly=E=>{E<m||E>=m+it||mt(()=>{Ye.paintRow(Wf(E),kd(E),()=>{ni(E)})})},ts=()=>{mt(()=>{for(let E=0;E<it;E++){let _=Le()+1+E,W=m+E;W<d.length?Ye.paintRow(_,kd(W),()=>{ni(W)}):Ye.paintRow(_,"blank",()=>{})}Ne()})},Td=()=>{mt(()=>{Ye.paintRow(Le(),Gf(),()=>{H(n,"list-header",` ${fd}`)});for(let E=0;E<it;E++){let _=Le()+1+E,W=m+E;W<d.length?Ye.paintRow(_,kd(W),()=>{ni(W)}):Ye.paintRow(_,"blank",()=>{})}Ne(),p===0&&(cn(),n.hideCursor(!1))})},ns=!1,ii="",Ml=0,uy=200,Dn=null,ai=!1,Eo=null,di=!1,rs=null,ea=!1,ar=null,Ed=null,_l=null,Pd=null,$l=!1,Ol=null,Md=E=>{let _=E.toString("binary");if(_.includes("\x1B[I")||_.includes("\x1B[O")){for(;;){let J=_.indexOf("\x1B[I"),se=_.indexOf("\x1B[O"),ae=J===-1?se:se===-1?J:Math.min(J,se);if(ae===-1)break;let ge=rt;rt=ae===J,rt&&(Ml=Date.now()),ge!==rt&&!Xt&&Bf.length<=1&&mt(()=>{Vt(),ts()}),_=_.slice(0,ae)+_.slice(ae+"\x1B[I".length)}if(_.length===0)return}if(!ns&&_===""&&Ed){Ed();return}if(!ns&&(_===""||_==="\x1B_"||_==="\x1B")){Ol?.(_);return}if(ns){let J=_.indexOf(nf);if(J===-1){ii+=_;return}ii+=_.slice(0,J),ns=!1;let se=Buffer.from(ii,"binary").toString("utf-8").replace(/\r\n?/g,`
284
+ `);ii="";let ae=_.slice(J+nf.length);if(x)C==="input"&&!z&&oi(se);else if(p===0&&!b){let ge=Me.feed({type:"paste",text:se});for(let tn of ge)tn.type==="attachment-request"&&Ad();let ut=Me.state(),St=Cs(ut.buffer,or);go(St,ut,Pf).rendered!==yn?Pt():To()}ae.length>0&&ar&&ar(Buffer.from(ae,"binary"));return}let W=_.indexOf(sl);if(W===-1){ar?.(E);return}W>0&&ar?.(Buffer.from(_.slice(0,W),"binary")),_=_.slice(W+sl.length),ns=!0,_.length>0&&Md(Buffer.from(_,"binary"))};return Pt(),await new Promise(E=>{let _=null,W=!1,J=null,se=!1,ae=Bf,ge=N=>{ae.push(N)},ut=()=>{ae.pop(),Xt||ae[ae.length-1]?.onResize()},St={push:ge,pop:ut},en=()=>{let N={kind:"new",cwd:s},ee=Me.state().attachments;return ee.length>0&&(N.attachments=[...ee]),Zt&&(N.agentId=Zt),bn&&(N.model=bn),ko&&(N.host=ko),ei&&(N.agentExplicit=!0),N},tn=async()=>{if(!(ei||!e.onCwdChange))try{let N=await e.onCwdChange(s);N.agentId!==void 0&&(Zt=N.agentId,bn=N.model),N.notice!==void 0&&(ue=N.notice)}catch{}},zt=async()=>{ui(),Ye.clearCache(),ge({onKey:()=>{},onResize:()=>{}});let ee;try{ee=await ad(n,void 0,{defaultCwd:s,title:"Change cwd",intro:"New cwd for the picker and any new sessions:",overlay:!0})}finally{ut(),cr()}if(ee.kind==="ok"&&ee.path!==s){s=ee.path;let pe=p>0?d[p-1]?.sessionId:null;o=Xg(o,s),Rn(),Ps(pe),await tn()}Xt||Pt()},ci=async(N="agent")=>{let ee=e.availableAgents??[],pe=e.availableHosts??[];if(ee.length===0&&pe.length===0)return;let Z=[...new Set([e.config.sessionDefaults??{},...Object.values(e.hostInfo??{}).map(Ue=>Ue.sessionDefaults??{})].flatMap(Ue=>Object.values(Ue)).map(Ue=>Ue.model).filter(Ue=>typeof Ue=="string"))];ui(),Ye.clearCache(),ge({onKey:()=>{},onResize:()=>{}});let Be;try{Be=await s_(n,{...Zt?{agentId:Zt}:{},...bn?{model:bn}:{},...ko?{host:ko}:{}},{agents:ee,hosts:pe,...e.hostInfo?{hostInfo:e.hostInfo}:{},...e.config.defaultAgent?{localDefaultAgent:e.config.defaultAgent}:{},models:Z,defaultModelFor:(Ue,at)=>Ue===void 0?void 0:Or((at!==void 0?e.hostInfo?.[at]?.sessionDefaults:void 0)??e.config.sessionDefaults,{id:Ue.id,extendsChain:Ue.extendsChain})?.value.model},N)}finally{ut(),cr()}if(Be.kind==="apply"){let Ue=Be.config,at=Ue.agentId!==Zt||Ue.model!==bn;if(Zt=Ue.agentId,bn=Ue.model,ko=Ue.host,at&&(ei=!0,Zt!==void 0&&e.onComposerAgentChange?.(Zt,bn)),Be.persist&&Zt!==void 0)try{await hi(Zt)}catch{}}Xt||Pt()};Ds=()=>{Qn(),$=new Vo({history:[],collapsePastes:!1}),P=[],M=!1,F=0,K=0,It=0,Y=null,z=!1,C="input",x=!1,ut()};let ta=new Fi(Xm),li=(N,ee,pe)=>{if(Xf(),Ht!==null&&vo(),pe?.isCharacter){ta.clear(),ae[ae.length-1]?.onKey(N,ee,pe);return}let Z=ta.feed(N);switch(Z.kind){case"pass":ae[ae.length-1]?.onKey(Z.token,ee,pe);return;case"armed":case"aborted":return}},Fl=()=>{Xt||ae[ae.length-1]?.onResize()};Ol=N=>{Xt||(ta.clear(),ae[ae.length-1]?.onKey(N,null,{}))};let na=!1,_d=()=>{if(na)return;na=!0,ae.length=0,_&&(clearInterval(_),_=null),J&&(J.abort(),J=null,W=!1),n.off("key",li),n.off("mouse",Bs),n.off("resize",Fl),be(Jo),be(sf);let N=n;N.stdin&&ar&&(N.stdin.removeListener("data",Md),N.stdin.on("data",ar),ar=null),ns=!1,ii="",n.grabInput(!1),we({src:"grab",site:"picker.detachInput",on:!1})},Rr=()=>{Xt||(Xt=!0,_d(),n.hideCursor(!1),n.moveTo(1,Xr()+1),n(`
285
+ `))},$d=()=>{if(Xt||ae.length>1||S!=="normal"||b||se||$l)return;W&&J&&(J.abort(),J=null,W=!1);let N=p>0?d[p-1]?.sessionId:void 0;W=!0;let ee=new AbortController;J=ee,nn(N,{silent:!0,signal:ee.signal}).finally(()=>{J===ee&&(J=null),W=!1})},Xf=()=>{Xt||(_&&clearInterval(_),_=setInterval($d,3e3))},Ar=()=>(_d(),Yg("",{write(ee){$e=ee,Ir()},finalize(){$e=null,Rr()}})),ra=()=>(Rr(),E({kind:Tt?"exit":"abort"}),!0),Zf=()=>{let N=l.map(ee=>`${ee.session}|${ee.upstream}|${ee.host}|${ee.state}|${ee.agent}|${ee.model}|${ee.age}|${ee.title}|${ee.cwd}|${ee.cost}`).join(`
286
286
  `);return`${p}:${m}:${ue??""}
287
- ${N}`},fy=(N,ee)=>{o=Xg(J0(o,N,ee),s),i=N.cursor},Od=0,Fd=async()=>{if(!e.target.isLocal)return!1;try{let N=await an(await He());return N.baseUrl===e.target.baseUrl&&N.wsUrl===e.target.wsUrl&&N.token===e.target.token?!1:(e.target.baseUrl=N.baseUrl,e.target.wsUrl=N.wsUrl,e.target.display=N.display,e.target.token=N.token,!0)}catch{return!1}},nn=async(N,ee={})=>{let pe=async()=>{let Z=ee.silent?Zf():"",_e=f,Be=i!==void 0,Ue=await Rk(e.target,{includeNonInteractive:!0,since:i,signal:ee.signal}),at=N??(p>0?d[p-1]?.sessionId:void 0);if(fy(Ue,Be),Rn(),at!==void 0){let vn=d.findIndex(ce=>ce.sessionId===at);vn>=0?p=vn+1:p=0}p>f-1&&(p=Math.max(0,f-1)),m+it>d.length&&(m=Math.max(0,d.length-it)),Qr(),!(ee.silent&&Zf()===Z)&&(f===_e?Td():Pt())};try{await pe(),Od=0}catch(Z){let _e=Z;if(await Fd())try{await pe(),Od=0;return}catch(Be){_e=Be}if(ee.silent){Od+=1,Od>=3&&(ue=`refresh failing: ${_e.message}`,Pt());return}ue=`refresh failed: ${_e.message}`,Pt()}},Zn=async N=>{if(!I)return;let ee=I;S="busy",Ne();try{await Ju(e.target,ee.sessionId,N),S="normal",I=null,Ge=null,await nn(ee.sessionId)}catch(pe){S="normal",I=null,Ge=null,ue=`rename failed: ${pe.message}`,Ne()}},Hs=async N=>{try{await eE(e.target,N.sessionId),ue="title regen queued (press r to refresh)",Ne()}catch(ee){ue=`regen failed: ${ee.message}`,Ne()}},Ld=async N=>{let pe=(N.priority&&N.priority>0?N.priority:0)>0?null:1,Z=pe??0;for(let Be of o)Be.sessionId===N.sessionId&&(Be.priority=Z>0?Z:void 0);let _e=N.sessionId;o=Xg(o,s),Rn(),_e!==void 0&&Ps(_e),Pt(),ue=Z>0?"priority: high":"priority: normal",Ne();try{await Z0(e.target,N.sessionId,pe)}catch(Be){ue=`priority failed: ${Be.message}`,Ne()}},ss=async()=>{if(se)return;se=!0;let N=p>0?d[p-1]?.sessionId:void 0;ue="syncing agents\u2026",Ne();try{let{synced:ee,skipped:pe,agents:Z}=await V0(e.target);await nn(N),ue=`synced ${ee} new (${pe} known) from ${Z} agent${Z===1?"":"s"}`,Ne()}catch(ee){ue=`sync failed: ${ee.message}`,Ne()}finally{se=!1}},dr=!1,ep=async N=>{if(dr)return;dr=!0;let ee=N.title?.trim()||Qe(N.sessionId);ue=pg()?`showing ${ee} in ${dd()}\u2026`:`opening ${ee} in a new ${dd()} tab\u2026`,Ne();try{let pe=await ff({kind:"attach",sessionId:N.sessionId,title:N.title,cwd:rd(N)!==void 0?void 0:N.cwd});ue=pe.outcome==="revealed"?`jumped to ${ee} \u2014 already open in ${dd()}`:pe.outcome==="opened"?`opened ${ee} in a new ${dd()} tab`:`new tab failed: ${pe.error??"unknown error"}`}catch(pe){ue=`new tab failed: ${pe.message}`}finally{dr=!1,Ne()}},Nd=async()=>{if(dr)return;dr=!0;let N=Me.expandedText(),ee=[...Me.state().attachments],pe=ee.length;ue=`opening a new session in a new ${dd()} tab\u2026`,Ne();try{let Z=await fl({kind:"new",cwd:s,agentId:Zt,model:bn,prompt:N});Z.ok?(N.trim().length>0&&Me.setBuffer("",ee),ue=pe>0?`opened a new ${dd()} tab \u2014 ${pe} attachment${pe===1?"":"s"} stayed here`:`opened a new session in a new ${dd()} tab`):ue=`new tab failed: ${Z.error??"unknown error"}`}catch(Z){ue=`new tab failed: ${Z.message}`}finally{dr=!1,Pt()}},tp=async N=>{if(!I)return;let ee=I;S="busy",Ne();try{N==="kill"?await co(e.target,ee.sessionId):await nE(e.target,ee.sessionId),S="normal",I=null,ee.sessionId===e.currentSessionId&&(Tt=!0);let pe;if(N==="kill")pe=ee.sessionId;else{let Z=d.findIndex(_e=>_e.sessionId===ee.sessionId);Z>=0&&(pe=d[Z+1]?.sessionId??d[Z-1]?.sessionId)}await nn(pe)}catch(pe){S="normal",I=null,ue=`${N} failed: ${pe.message}`,Ne()}},sa=(N,ee)=>{N===0!=(ee===0)&&(Vt(),ee===0?(n.hideCursor(!1),cn()):n.hideCursor())},er=N=>{let ee=Math.min(f-1,Math.max(0,p+N));if(ee===p)return;let pe=p;p=ee,Qr(),mt(()=>{ts(),sa(pe,p)})},Ll=()=>ue===null?!1:(ue=null,Ne(),!0),Nl=()=>{Vf();let N=!1;ge({onKey:ee=>{if(ee==="CTRL_C"){Rr(),P({kind:"abort"});return}ut()},onMouse:ee=>{if(ee==="MOUSE_LEFT_BUTTON_PRESSED"){N=!0;return}ee!=="MOUSE_LEFT_BUTTON_RELEASED"||!N||(N=!1,ut())},onResize:()=>Vf()})},Kt=N=>{let ee=null,pe=null,Z=!0,_e=0,Be=null,Ue=0,at=()=>Z?["loading\u2026"]:pe!==null?[pe]:ee??[],vn=()=>{mt(()=>{n.hideCursor(),Ye.clearCache();let te=at(),ze=uo(n),qe=Cn(n),dt=Math.max(3,ze-6),Mt=Math.min(te.length,dt),_o=te.reduce((Ce,st)=>Math.max(Ce,st.length),0),lr=Math.min(Math.max(40,_o+2),Math.max(20,qe-6)),rn=zn(n,{contentHeight:Mt+2,contentWidth:lr,title:`Session info \u2014 ${Qe(N.sessionId)}`,overlay:!0});Be={x:rn.x,y:rn.y,w:rn.w,h:rn.h},Ue=Mt,_e=Math.max(0,Math.min(_e,Math.max(0,te.length-Mt)));for(let Ce=0;Ce<Mt;Ce++){let st=te[_e+Ce]??"";n.moveTo(rn.contentX,rn.contentY+Ce);let Tr=st.slice(0,rn.contentW-1);pe!==null?H(n,"modal-error",` ${Tr}`):H(n,"content",` ${Tr}`),n.styleReset()}let os=te.length-Mt-_e,is=te.length>Mt?`\u2191/\u2193/wheel scroll${os>0?` (${os} more)`:""} \xB7 Esc or click outside to return`:"Esc or click outside to return";n.moveTo(rn.contentX,rn.contentY+Mt+1),H(n,"modal-hint",` ${is}`),n.styleReset()})};vn();let ce=new AbortController,Te=()=>{ce.abort(),ut()},Pe=te=>{let ze=Math.max(0,at().length-Ue),qe=Math.max(0,Math.min(ze,_e+te));qe!==_e&&(_e=qe,vn())},Ve={onKey:te=>{if(te==="ESCAPE"||te==="CTRL_C"){Te();return}if(te==="UP"){Pe(-1);return}if(te==="DOWN"){Pe(1);return}if(te==="PAGE_UP"){Pe(-Math.max(1,Ue-1));return}if(te==="PAGE_DOWN"){Pe(Math.max(1,Ue-1));return}if(te==="HOME"){Pe(-Number.MAX_SAFE_INTEGER);return}if(te==="END"){Pe(Number.MAX_SAFE_INTEGER);return}},onMouse:(te,ze)=>{if(te==="MOUSE_WHEEL_UP"){Pe(-3);return}if(te==="MOUSE_WHEEL_DOWN"){Pe(3);return}if(te!=="MOUSE_LEFT_BUTTON_RELEASED"||Be===null)return;let qe=ze?.x??-1,dt=ze?.y??-1;qe>=Be.x&&qe<Be.x+Be.w&&dt>=Be.y&&dt<Be.y+Be.h||Te()},onResize:()=>vn()};ge(Ve),(async()=>{try{let te=await _n(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(N.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:ce.signal});if(!te.ok)throw new Error(`daemon returned HTTP ${te.status}`);let ze=await te.json(),qe=ys(ze),dt=Vk(qe,N.status);ee=Hm(dt,!1).replace(/\n$/,"").split(`
288
- `)}catch(te){if(ce.signal.aborted)return;pe=`failed to load info: ${te.message}`}finally{Z=!1,!Xt&&ae[ae.length-1]===Ve&&vn()}})()},Po=()=>{if(d.length===0){ue="no sessions to search",Ne();return}$=new Vo({history:[],collapsePastes:!1});let N=r.lastFind,ee=new Set(d.map(ce=>ce.sessionId)),pe=N?N.results.filter(ce=>ee.has(ce.sessionId)):[];N&&N.query.length>0&&$.setBuffer(N.query),E=pe,je(),M=N?.truncated??!1,F=Math.min(Math.max(0,N?.selectedIdx??0),Math.max(0,pe.length-1)),K=0,It=0,Y=null,z=!1,C=pe.length>0?"results":"input",x=!0,Io(),xo(),Ro();let Z=()=>{let ce=E[F];if(!ce)return;let Te=d.find(te=>te.sessionId===ce.sessionId),Pe=!!Te?.importedFromMachine&&!Te.remote&&!Te.upstreamSessionId,Ve=ce.snippets[K]?.recordedAt??ce.snippets[0]?.recordedAt;if(Pe){Qn(),Rr();let te={kind:"attach",sessionId:ce.sessionId};Te.agentId!==void 0&&(te.agentId=Te.agentId),Ve!==void 0&&(te.jumpToRecordedAt=Ve),P(te);return}(async()=>{let te=await B$(n,{sessionId:ce.sessionId,title:ce.title,cwd:ce.cwd},St);if(te==="cancel"){Qn(),Rr(),P({kind:"abort"});return}if(te==="back")return;Qn(),Rr();let ze={kind:"attach",sessionId:ce.sessionId,readonly:te==="view"};Te?.agentId!==void 0&&(ze.agentId=Te.agentId),Ve!==void 0&&(ze.jumpToRecordedAt=Ve),P(ze)})()},_e=ce=>{if(ce<0||ce>=E.length||ce===F)return;let Te=F,Pe=It;F=ce,K=0,xo(),It!==Pe?Ns():mt(()=>{Zi(Te,!1),Zi(F,!0)}),Ls()},Be=(ce,Te,Pe)=>{if(C==="input"){if(z)return;if(ce==="ESCAPE"||ce==="CTRL_C"){Ds();return}if(ce==="ENTER"||ce==="KP_ENTER"){if(ir().trim().length===0)return;Ao();return}if((ce==="DOWN"||ce==="TAB"||ce==="CTRL_N")&&E.length>0){C="results",F=0,K=0,mt(()=>{Xi(),Zi(0,!0),Ls(),n.hideCursor()});return}let Ve=$.state(),te=[...Ve.buffer],ze=Ve.row,qe=Ve.col,dt=null;if(ce==="")dt={type:"key",name:"ctrl-underscore"};else if(ce==="\x1B_"||ce==="\x1B")dt={type:"key",name:"alt-underscore"};else if(Pe?.isCharacter)dt={type:"char",ch:ce};else{let rn=qg(ce);rn!==null&&(dt={type:"key",name:rn})}if(dt===null){n.moveTo(si(),Co());return}$.feed(dt);let Mt=$.state();if(te.length===Mt.buffer.length&&te.every((rn,os)=>rn===Mt.buffer[os])&&ze===Mt.row&&qe===Mt.col){n.moveTo(si(),Co());return}let lr=wn;Io(),wn!==lr?Ro():xd();return}if(C==="results"){if(ce==="ESCAPE"||ce==="CTRL_C"){Ds();return}if(ce==="CTRL_F"){C="input",Ns(),Ls(),Xi();return}if(ce==="ENTER"||ce==="KP_ENTER"){Z();return}if(Pe?.isCharacter&&ce==="i"){let ze=E[F];if(!ze)return;let qe=d.find(dt=>dt.sessionId===ze.sessionId);if(!qe)return;Kt(qe);return}let Ve=ze=>{let qe=E[F];!qe||qe.snippets.length<=1||(K=(K+ze+qe.snippets.length)%qe.snippets.length,Zi(F,!0))};if(Pe?.isCharacter&&(ce==="n"||ce==="N")){Ve(1);return}if(Pe?.isCharacter&&(ce==="p"||ce==="P")){Ve(-1);return}if(ce==="LEFT"){Ve(-1);return}if(ce==="RIGHT"){Ve(1);return}let te=ze=>{if(ze<0&&F===0){C="input",mt(()=>{Zi(0,!1),Ls(),Xi()});return}_e(Math.min(E.length-1,Math.max(0,F+ze)))};switch(ce){case"UP":case"SHIFT_TAB":case"CTRL_P":te(-1);return;case"DOWN":case"TAB":case"CTRL_N":te(1);return;case"PAGE_UP":te(-Yn());return;case"PAGE_DOWN":te(Yn());return;case"HOME":te(-F);return;case"END":te(E.length);return}return}},Ue=ce=>{let Te=Nn(),Pe=Te+Yn()*2-1;if(ce<Te||ce>Pe)return null;let Ve=It+Math.floor((ce-Te)/2);return Ve>=0&&Ve<E.length?Ve:null},at=null;ge({onKey:Be,onMouse:(ce,Te)=>{if(z)return;if(ce==="MOUSE_WHEEL_UP"||ce==="MOUSE_WHEEL_DOWN"){if(E.length===0)return;let qe=ce==="MOUSE_WHEEL_UP"?-3:3,dt=Math.max(0,E.length-Yn()),Mt=Math.min(dt,Math.max(0,It+qe));if(Mt===It)return;It=Mt,F<It?(F=It,K=0):F>=It+Yn()&&(F=It+Yn()-1,K=0),Ns(),Ls();return}if(ce==="MOUSE_LEFT_BUTTON_PRESSED"){at={x:Te?.x??-1,y:Te?.y??-1};return}let Pe=Te?.y;if(typeof Pe!="number")return;if(ce==="MOUSE_MOTION"){if(C!=="results")return;let qe=Ue(Pe);qe!==null&&_e(qe);return}if(ce!=="MOUSE_LEFT_BUTTON_RELEASED")return;let Ve=at!==null&&Te?.x===at.x&&Pe===at.y;if(at=null,!Ve)return;if(Pe<=wn+2){C!=="input"&&(C="input",Ns(),Ls(),Xi(),n.moveTo(si(),Co()),n.hideCursor(!1));return}let te=Ue(Pe);if(te===null)return;if(C==="input"){C="results",F=te,K=0,xo(),mt(()=>{Xi(),Ns(),Ls(),n.hideCursor()});return}if(te!==F){_e(te);return}Z()},onResize:()=>Ro()})},Mo=(N,ee,pe)=>{if(S!=="busy"){if(N==="CTRL_O"){zt();return}if(N==="CTRL_L"){Jf();return}if(S==="rename"&&Ge){if(N==="ENTER"||N==="KP_ENTER"){let Z=Ge.text.trim();if(Z.length===0){S="normal",I=null,Ge=null,Ne();return}Zn(Z);return}if(N==="ESCAPE"||N==="CTRL_C"){S="normal",I=null,Ge=null,Ne();return}if(Ge.handleKey(N,pe?.isCharacter===!0)){Ne();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(pe?.isCharacter&&(N==="y"||N==="Y")){tp(S==="confirm-kill"?"kill":"delete");return}if(N==="ESCAPE"||N==="CTRL_C"||N==="ENTER"||N==="KP_ENTER"||pe?.isCharacter&&(N==="n"||N==="N")){S="normal",I=null,Ne();return}return}if(Ll(),Rt&&(Rt=!1,p=0,mt(()=>{Vt(),ts()})),N==="CTRL_F"&&p!==0){Po();return}if(p===0&&!b){if(N==="ESCAPE"){ra();return}if(N==="ENTER"||N==="KP_ENTER"){let te=Me.expandedText(),ze=en();te.trim().length>0&&(ze.prompt=te),ze.installStatus=Ar(),P(ze);return}if(N==="CTRL_T"){uf()&&Nd();return}if(N==="UP"&&y){let te=Date.now(),ze=te-k;if(k=te,ze<h){cn();return}y=!1}if(N==="DOWN"){let te=Me.state(),ze=te.historyIndex!==-1||te.queueIndex!==-1,qe=Gn.length===0||Gi===Gn.length-1;if(!ze&&qe&&d.length>0){er(1);return}}if(N==="PAGE_DOWN"&&(Gn.length===0||Gi===Gn.length-1)&&d.length>0){er(1);return}if(N==="CTRL_P"||N==="CTRL_N"){d.length>0&&er(1);return}if(y=!1,N==="TAB"){let te=Me.state(),ze=te.buffer[te.row]??"",qe=Gg(ze,te.col);if(qe!==null){let dt=Jg(qe.token,s);if(dt!==null){if(dt.replacement!==qe.token&&(Me.replaceRangeOnCurrentLine(qe.start,te.col,dt.replacement),To()),dt.candidates.length>1){let Mt=dt.candidates.join(" ");oe=`${dt.candidates.length} matches: ${Mt}`,Ir()}else Cr();cn();return}}}Cr();let Z=Me.state(),_e=[...Z.buffer],Be=Z.row,Ue=Z.col,at=null;if(N==="")at={type:"key",name:"ctrl-underscore"};else if(N==="\x1B_"||N==="\x1B")at={type:"key",name:"alt-underscore"};else if(pe?.isCharacter)at={type:"char",ch:N};else{let te=qg(N);if(te!==null){if(Xn(te)){cn();return}at={type:"key",name:te}}}if(at===null){cn();return}let vn=Me.feed(at),ce=Me.state(),Te=_e.length===ce.buffer.length&&_e.every((te,ze)=>te===ce.buffer[ze])&&Be===ce.row&&Ue===ce.col;if(vn.some(te=>te.type==="exit")){ra();return}for(let te of vn)te.type==="attachment-request"?Ad():te.type==="edit-in-editor"&&Qf();if(Te){cn();return}let Pe=Cs(ce.buffer,or);if(go(Pe,ce,Pf).rendered!==yn){Pt();return}To();return}if(!b&&pe?.isCharacter&&N==="?"){Nl();return}if(b){if(pe?.isCharacter){g+=N,Rn(),Pt();return}if(N==="BACKSPACE"){g.length>0?(g=g.slice(0,-1),Rn(),Pt()):(b=!1,Rn(),Pt());return}if(N==="ESCAPE"||N==="CTRL_C"){b=!1,g="",Rn(),Pt();return}}if(pe?.isCharacter){if(N==="/"){let Z=p>0?d[p-1]?.sessionId:null;b=!0,g="",Rn(),Ps(Z),Pt();return}if(N==="n"||N==="N"){er(1);return}if(N==="p"||N==="P"){er(-1);return}if(N==="c"||N==="C"){let Z=en();Z.installStatus=Ar(),P(Z);return}if(N==="q"||N==="Q"){ra();return}if(N==="o"||N==="O"){let Z=p>0?d[p-1]?.sessionId:null;r.filters.cwdOnly=!r.filters.cwdOnly,Rn(),Ps(Z),Pt();return}if(N==="h"||N==="H"){let Z=p>0?d[p-1]?.sessionId:null;r.filters.hostFilter=Y$(r.filters.hostFilter,o),r.pendingDefaultHost=void 0,Rn(),Ps(Z),Pt();return}if(N==="i"&&p>0){let Z=d[p-1];if(!Z)return;Kt(Z);return}if(N==="I"){let Z=p>0?d[p-1]?.sessionId:null;r.filters.includeNonInteractive=!r.filters.includeNonInteractive,Rn(),Ps(Z),Pt();return}if(N==="r"||N==="R"){let Z=p>0?d[p-1]?.sessionId:void 0;nn(Z);return}if(N==="s"||N==="S"){ss();return}if((N==="v"||N==="V")&&p>0){let Z=d[p-1];if(!Z)return;let _e={kind:"attach",sessionId:Z.sessionId,readonly:!0};Z.agentId!==void 0&&(_e.agentId=Z.agentId),_e.installStatus=Ar(),P(_e);return}if((N==="f"||N==="F")&&p>0){let Z=d[p-1];if(!Z)return;Rr();let _e={kind:"fork",sourceSessionId:Z.sessionId,sourceCwd:Z.cwd};Z.agentId!==void 0&&(_e.sourceAgentId=Z.agentId),Z.importedFromMachine!==void 0&&(_e.sourceImportedFromMachine=Z.importedFromMachine),Z.upstreamSessionId!==void 0&&(_e.sourceUpstreamSessionId=Z.upstreamSessionId),P(_e);return}if((N==="k"||N==="K")&&p>0){let Z=d[p-1];if(!Z)return;I={sessionId:Z.sessionId,cwd:Z.cwd,status:Z.status},S="confirm-kill",Ne();return}if(N==="t"&&p>0){let Z=d[p-1];if(!Z)return;I={sessionId:Z.sessionId,cwd:Z.cwd,status:Z.status},Ge=new Hi(Z.title??""),S="rename",Ne();return}if(N==="T"&&p>0){let Z=d[p-1];if(!Z)return;Hs({sessionId:Z.sessionId});return}if(N==="*"&&p>0){let Z=d[p-1];if(!Z)return;Ld(Z);return}if((N==="d"||N==="D")&&p>0){let Z=d[p-1];if(!Z)return;I={sessionId:Z.sessionId,cwd:Z.cwd,status:Z.status},S="confirm-delete",Ne();return}Rt=!1,p=0,Me.feed({type:"char",ch:N}),Pt();return}switch(N){case"CTRL_T":{if(!uf())return;if(Rt||p===0){Nd();return}let Z=d[p-1];if(!Z)return;ep(Z);return}case"UP":case"SHIFT_TAB":case"CTRL_P":N==="UP"&&(p===1&&(y=!0),k=Date.now()),er(-1);return;case"DOWN":case"TAB":case"CTRL_N":er(1);return;case"PAGE_UP":er(-it);return;case"PAGE_DOWN":er(it);return;case"HOME":er(1-p);return;case"END":er(f);return;case"RIGHT":if(Rt||p===0)break;case"ENTER":case"KP_ENTER":{if(Rt){let Be=Me.expandedText(),Ue=en();Be.trim().length>0&&(Ue.prompt=Be),Ue.installStatus=Ar(),P(Ue);return}if(p===0){let Be=en();Be.installStatus=Ar(),P(Be);return}let Z=d[p-1];if(!Z){Rr(),P({kind:"abort"});return}let _e={kind:"attach",sessionId:Z.sessionId};Z.agentId!==void 0&&(_e.agentId=Z.agentId),_e.installStatus=Ar(),P(_e);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":ra();return}}};ge({onKey:(N,ee,pe)=>Mo(N,ee,pe),onResize:()=>{Xt||Pt()}});let Bs=(N,ee)=>{if(Xt)return;if(ae.length!==1){ae[ae.length-1]?.onMouse?.(N,ee);return}if(S!=="normal")return;let pe=N==="MOUSE_MOTION",Z=N==="MOUSE_DRAG",_e=N==="MOUSE_LEFT_BUTTON_PRESSED",Be=N==="MOUSE_LEFT_BUTTON_RELEASED",Ue=N==="MOUSE_WHEEL_UP",at=N==="MOUSE_WHEEL_DOWN",vn=rt&&Date.now()-Ml<uy,ce=!rt||vn;if(_e){Dn={x:ee?.x??-1,y:ee?.y??-1},ai=ce;let Ce=ee?.x,st=ee?.y;!ce&&typeof Ce=="number"&&typeof st=="number"&&st>=On&&st<=Jn()&&ri({x:Ce,y:st});return}if(Z){if(Kn!==null){let Ce=ee?.x,st=ee?.y;typeof Ce=="number"&&typeof st=="number"&&es({x:Ce,y:st})}return}if(pe&&ce)return;let Te=Be&&Dn!==null&&ee?.x===Dn.x&&ee?.y===Dn.y,Pe=Te&&!ai,Ve=Te&&ai;if(Be&&Kn!==null){Dn=null,ai=!1;let Ce=ee?.x,st=ee?.y;dy(typeof Ce=="number"&&typeof st=="number"?{x:Ce,y:st}:null);return}if(Be&&(Dn=null,ai=!1,!Te))return;if(Ue||at){if(d.length===0)return;let Ce=Ue?-3:3,st=Math.max(0,d.length-it),Tr=Math.min(st,Math.max(0,m+Ce));if(Tr===m)return;if(m=Tr,p>0){let np=p-1;np<m?p=m+1:np>=m+it&&(p=m+it)}ts();return}if(!pe&&!Pe)return;let te=ee?.y;if(typeof te!="number")return;{let Ce=ee?.x,st=Eo!==null&&te===Xr()&&typeof Ce=="number"&&Ce>=Eo.start&&Ce<=Eo.end,Tr=rs!==null&&te===Xr()&&typeof Ce=="number"&&Ce>=rs.start&&Ce<=rs.end;(st!==di||Tr!==ea)&&(di=st,ea=Tr,Ne(),p===0?(cn(),n.hideCursor(!1)):n.hideCursor(!0))}if(Pe&&Eo!==null&&te===Xr()){let Ce=ee?.x;if(typeof Ce=="number"&&Ce>=Eo.start&&Ce<=Eo.end){ra();return}}if(Pe&&rs!==null&&te===Xr()){let Ce=ee?.x;if(typeof Ce=="number"&&Ce>=rs.start&&Ce<=rs.end){let st=p>0?d[p-1]?.sessionId:null;r.filters.hostFilter=Y$(r.filters.hostFilter,o),r.pendingDefaultHost=void 0,Rn(),Ps(st),Pt();return}}if(te>=On&&te<=Jn()){let Ce=null;if(te===On){let st=ee?.x;typeof st=="number"&&(_s!==null&&st>=_s.start&&st<=_s.end?Ce="host":Fn!==null&&st>=Fn.start&&st<=Fn.end?Ce="agent":Ms!==null&&st>=Ms.start&&st<=Ms.end&&(Ce="cwd"))}if(Ce!==kn&&(kn=Ce,Vt()),Pe&&te===On){if(kn==="agent"){ci("agent");return}if(kn==="host"){ci("host");return}if(kn==="cwd"){zt();return}}if((Pe||Ve)&&p!==0){Rt=!1;let st=p;p=0,mt(()=>{ts(),sa(st,p)});return}pe&&!Rt&&p!==0&&(Rt=!0,mt(()=>{Vt(),ts()}));return}kn!==null&&(kn=null,Vt()),Rt&&(Rt=!1,mt(()=>{Vt(),ts()}));let qe=Le()+1,dt=qe+it-1;if(te<qe||te>dt)return;let Mt=m+(te-qe);if(Mt<0||Mt>=d.length)return;let _o=d[Mt];if(!_o)return;let lr=Mt+1;if(pe&&p===0)return;let rn=p===0,os=p===lr;if(Ve&&p!==lr){let Ce=p;p=lr,Qr(),mt(()=>{ts(),sa(Ce,p)});return}if(Ve)return;if(p!==lr){let Ce=p;p=lr,Qr(),mt(()=>{ts(),sa(Ce,p)})}if(!Pe||rn||!os)return;let is={kind:"attach",sessionId:_o.sessionId};_o.agentId!==void 0&&(is.agentId=_o.agentId),is.installStatus=Ar(),P(is)},cr=()=>{n.grabInput({mouse:"motion"}),we({src:"grab",site:"picker.installGrab",on:!0});let N=n;N.stdin&&typeof N.onStdin=="function"&&(ar=N.onStdin,N.stdin.removeListener("data",N.onStdin),N.stdin.on("data",Md),be(Jm),be(Qm)),n.on("key",li),n.on("mouse",Bs),n.on("resize",Fl)},ui=()=>{be(Jo),be(sf);let N=n;N.stdin&&ar&&(N.stdin.removeListener("data",Md),N.stdin.on("data",ar),ar=null),ns=!1,ii="",n.off("key",li),n.off("mouse",Bs),n.off("resize",Fl),n.grabInput(!1),we({src:"grab",site:"picker.uninstallGrab",on:!1}),n.hideCursor(!1)};if(cr(),_l=()=>{$l=!0,J&&(J.abort(),J=null,W=!1),ui(),n.fullscreen(!1),be(`${rf}${Vm}`)},Pd=()=>{$l=!1,n.fullscreen(!0),t(),n.hideCursor(),cr(),Xt||Jf()},process.platform!=="win32"){let N=!1,ee=()=>{N&&(N=!1,Pd?.())};Ed=()=>{N||Xt||(N=!0,_l?.(),be(`
289
- `),process.once("SIGCONT",ee),process.kill(process.pid,"SIGTSTP"))}}_=setInterval($d,3e3)})}function xJ(n,e){let t="Create new session in ",r=Math.max(1,e-t.length);return t+Yu(V(n),r)}function Xg(n,e){let t=s=>s.priority&&s.priority>0?s.priority:0,r=s=>{let o=s.status==="warm",i=t(s)>0;return o&&s.busy&&s.awaitingInput?6:o&&s.busy?5:o&&s.awaitingInput?4:o&&i?3:o?2:i?1:0};return[...n].sort((s,o)=>{let i=r(o)-r(s);if(i!==0)return i;let a=t(o)-t(s);return a!==0?a:o.updatedAt.slice(0,16).localeCompare(s.updatedAt.slice(0,16))})}function IJ(n,e){return n?e.has(n):!0}function qS(n){return!!n.importedFromMachine&&!n.upstreamSessionId}function V$(n,e){if(e)return e;if(new Set(n.map(s=>s.host)).size<=1)return Hr;let r=Hr.indexOf("agent");return[...Hr.slice(0,r),"host",...Hr.slice(r)]}function CJ(n,e,t=Up()){if(e==="__all")return n;let r=o=>!o.remote&&(IJ(o.importedFromMachine,t)||!!o.upstreamSessionId);if(e==="__local")return n.filter(r);if(e==="__remotes")return n.filter(o=>o.remote?!qS(o):r(o));if(e.startsWith(ji)){let o=e.slice(ji.length);return n.filter(i=>i.remote===o&&!qS(i))}let s=e.startsWith(cd)?e.slice(cd.length):e;return n.filter(o=>o.importedFromMachine===s&&!t.has(s)&&!o.upstreamSessionId)}function Y$(n,e,t=Up()){let r=Q$(e,t),s=r.indexOf(n);return s===-1?"__local":r[(s+1)%r.length]??"__local"}function Q$(n,e){let t=new Set,r=new Set;for(let s of n){if(s.remote){qS(s)||t.add(s.remote);continue}s.importedFromMachine&&!s.upstreamSessionId&&!e.has(s.importedFromMachine)&&r.add(s.importedFromMachine)}return["__local",...t.size>0?["__remotes"]:[],...[...t].sort().map(s=>`${ji}${s}`),...[...r].sort().map(s=>`${cd}${s}`),"__all"]}function RJ(n,e,t=Up()){if(n==="all")return"__all";let r=Q$(e,t),s;return n===`${ji}all`?s=["__remotes"]:n.startsWith(ji)||n.startsWith(cd)?s=[n]:s=[`${ji}${n}`,`${cd}${n}`],s.find(o=>r.includes(o))??"__local"}function AJ(n){return n==="__local"?"host: local":n==="__remotes"?"host: local + remotes":n.startsWith(ji)?`remote: ${n.slice(ji.length)}`:n.startsWith(cd)?`host: ${n.slice(cd.length)}`:`host: ${n}`}function TJ(n,e){if(e.length===0)return!0;let t=e.toLowerCase(),r=[Qe(n.sessionId),n.upstreamSessionId??"",n.agentId??"",n.title??"",n.cwd,V(n.cwd)];for(let s of r)if(s.toLowerCase().includes(t))return!0;return!1}var Qg,Pf,kJ,G$,vJ,J$,ji,cd,X$=j(()=>{"use strict";Zc();xc();Gs();Se();mr();et();Ws();yg();td();pf();Vu();o_();Ph();vg();Sg();Kv();NS();HS();BS();mg();US();Li();of();WS();Gv();wS();Va();xn();Ea();Yk();ma();jS();Qg=2,Pf=4,kJ=4,G$=4,vJ=20,J$=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],["typing in list","jumps focus back to composer with that key"],["mouse-hover composer","Enter from anywhere creates a new session"],null,["\u2191 / \u2193, n / p, ^p / ^n","navigate sessions"],["PgUp / PgDn","page up / page down"],["Home / End","first / last"],["Enter","open selected session"],["v","view-only (open transcript without spawning the agent)"],null,["/","search sessions (metadata)"],["^f","find in session history (content + tool inputs)"],[" in results","n/p cycle snippets \xB7 i info \xB7 Enter open"],[" ","the query and results survive opening a hit"],["o","toggle cwd-only filter"],["h","cycle host filter (local / <peer> / all)"],["^o","change cwd (for the picker and any new sessions)"],["i","show info for the selected session"],["I","toggle include-cat filter"],["r","refresh from daemon"],["s","sync sessions from installed agents"],null,["k","kill the selected warm session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent"],["*","toggle high priority on the selected session (floats to top)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]];ji="remote:",cd="host:"});function _J(n,e){let t=n.findIndex(r=>r.id===e);return t===-1?0:t}async function GS(n,e,t,r){kr();let s=_J(e,t??EJ),o=0,i=null,a=null,d=()=>{let x=uo(n)-8;return Math.max(1,Math.min(PJ,e.length,x))},c=()=>{let x=d(),C=Math.max(0,e.length-x);o>C&&(o=C),o<0&&(o=0)},l=()=>{let x=d();s<o?o=s:s>=o+x&&(o=s-x+1),c()},u=null,f=0,p=(x,C)=>{if(x<o||x>=o+f)return;let $=e[x];if(!$)return;let E=C.contentW,M=C.contentY+2+(x-o);n.moveTo(C.contentX,M);let F=x===s?"\u276F":" ",K=$.description??$.name,Y=` ${F} ${$.id}`;if(x===s){let z=`${Y} ${K}`;H(n,"list-selected",ks(At(z,E),E))}else{let z=E-Y.length-2,re=z>1?` ${At(K,z)}`:"";H(n,"content",Y),re.length>0&&H(n,"list-description",re);let Q=Y.length+re.length;Q<E&&n.noFormat(" ".repeat(E-Q))}},m=(x,C)=>{let $=x.contentY+2+f+1;n.moveTo(x.contentX,$);let M=` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${e.length>C?` (${s+1}/${e.length})`:""}`,F=ks(At(M,x.contentW),x.contentW);H(n,"modal-hint",F)},b=()=>{c();let x=d(),C=x+4,$=Math.min(MJ,Math.max(40,Cn(n)-8)),E=zn(n,{contentHeight:C,contentWidth:$,title:r?.title??"Select agent",overlay:r?.overlay===!0});a=E,u=E,f=Math.min(x,e.length-o),i=E.contentY+2,n.moveTo(E.contentX,E.contentY),H(n,"content",` ${r?.intro??"Which agent should this session use?"}`);let M=Math.min(e.length,o+x);for(let F=o;F<M;F++)p(F,E);return m(E,x),E},g=()=>b(),h=x=>{let C=u;if(C===null){b();return}let $=d(),E=o;if(l(),o!==E){b();return}f=Math.min($,e.length-o),x!==s&&(p(x,C),p(s,C)),m(C,$)},y=()=>{if(s<e.length-1){let x=s;s++,h(x)}},k=()=>{if(s>0){let x=s;s--,h(x)}},S=()=>{let x=u;if(x===null){b();return}let C=d();c(),f=Math.min(C,e.length-o);let $=Math.min(e.length,o+C);for(let E=o;E<$;E++)p(E,x);for(let E=f;E<C;E++){let M=x.contentY+2+E;n.moveTo(x.contentX,M),n.noFormat(" ".repeat(x.contentW))}m(x,C)},I=x=>{let C=d(),$=Math.max(0,e.length-C);if($===0)return;let E=Math.max(0,Math.min($,o+x));E!==o&&(o=E,S())};return qr({term:n,render:g,overlay:r?.overlay===!0,onKey:(x,C,$,E)=>{if(x==="CTRL_C"||x==="CTRL_D"){E({kind:"cancel"});return}if(x==="ESCAPE"){E({kind:"back"});return}if(x==="ENTER"||x==="KP_ENTER"){let M=e[s];M&&E({kind:"select",agentId:M.id,persist:!1});return}if(x==="UP"||x==="SHIFT_TAB"){k();return}if(x==="DOWN"||x==="TAB"){y();return}if($?.isCharacter){let M=x.toLowerCase();if(M==="s"){let F=e[s];F&&E({kind:"select",agentId:F.id,persist:!0});return}if(M==="j"){y();return}if(M==="k"){k();return}}},onMouse:(x,C,$)=>{if(x==="MOUSE_WHEEL_UP"){I(-1);return}if(x==="MOUSE_WHEEL_DOWN"){I(1);return}if(x==="MOUSE_MOTION"){let z=C?.y;if(typeof z!="number"||i===null)return;let re=z-i;if(re<0||re>=f)return;let Q=o+re;if(Q<0||Q>=e.length)return;if(Q!==s){let ke=s;s=Q,h(ke)}return}if(x!=="MOUSE_LEFT_BUTTON_PRESSED")return;let E=C?.x,M=C?.y;if(a!==null&&typeof E=="number"&&typeof M=="number"&&(E<a.x||E>=a.x+a.w||M<a.y||M>=a.y+a.h)){$({kind:"back"});return}if(typeof M!="number"||i===null)return;let F=M-i;if(F<0||F>=f)return;let K=o+F;if(K<0||K>=e.length)return;let Y=e[K];Y&&$({kind:"select",agentId:Y.id,persist:!1})}})}var EJ,PJ,MJ,Z$=j(()=>{"use strict";Li();xn();EJ="opencode",PJ=20,MJ=88});function $J(n){let e=n.explicitAgentId??n.directoryDefaultAgent??n.prefs.lastChosenAgent??n.fallbackAgentId??n.configDefaultAgent;if(e===void 0||e.length===0)return{};let t=n.availableAgents.find(i=>i.id===e)?.extendsChain,r={id:e,...t?{extendsChain:t}:{}},s=e===n.prefs.lastChosenAgent?n.prefs.lastChosenModel:void 0,o=Or(n.directoryDefaultModels,r)?.value??s??Or(n.configDefaultModels,r)?.value;return{agentId:e,...o!==void 0?{model:o}:{}}}function eO(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n))typeof r.model=="string"&&(e[t]=r.model);return Object.keys(e).length>0?e:void 0}async function Mf(n){let e={},t;try{let i=await Kl(n.cwd);e=i.merged,t=i.homeRequest}catch{}let r=fp(e,"defaultAgent"),s=eO(pp(e,"sessionDefaults")),o=$J({...n.explicitAgentId!==void 0?{explicitAgentId:n.explicitAgentId}:{},...r!==void 0?{directoryDefaultAgent:r}:{},...s!==void 0?{directoryDefaultModels:s}:{},prefs:n.prefs,...n.fallbackAgentId!==void 0?{fallbackAgentId:n.fallbackAgentId}:{},configDefaultAgent:n.config.defaultAgent,configDefaultModels:eO(n.config.sessionDefaults),availableAgents:n.availableAgents});return t!==void 0&&t!==Oe()?{...o,notice:`that directory sets home: ${t} \u2014 run hydra there for a separate daemon`}:o}var tO=j(()=>{"use strict";Se();qd();Gs()});import OJ from"wrap-ansi";async function nO(n,e,t,r){kr();let s=r?.canGoBack!==!1,o=e?`Couldn't start ${e}`:"Couldn't start session",i=t.split(`
287
+ ${N}`},fy=(N,ee)=>{o=Xg(J0(o,N,ee),s),i=N.cursor},Od=0,Fd=async()=>{if(!e.target.isLocal)return!1;try{let N=await an(await He());return N.baseUrl===e.target.baseUrl&&N.wsUrl===e.target.wsUrl&&N.token===e.target.token?!1:(e.target.baseUrl=N.baseUrl,e.target.wsUrl=N.wsUrl,e.target.display=N.display,e.target.token=N.token,!0)}catch{return!1}},nn=async(N,ee={})=>{let pe=async()=>{let Z=ee.silent?Zf():"",_e=f,Be=i!==void 0,Ue=await Rk(e.target,{includeNonInteractive:!0,since:i,signal:ee.signal}),at=N??(p>0?d[p-1]?.sessionId:void 0);if(fy(Ue,Be),Rn(),at!==void 0){let vn=d.findIndex(ce=>ce.sessionId===at);vn>=0?p=vn+1:p=0}p>f-1&&(p=Math.max(0,f-1)),m+it>d.length&&(m=Math.max(0,d.length-it)),Qr(),!(ee.silent&&Zf()===Z)&&(f===_e?Td():Pt())};try{await pe(),Od=0}catch(Z){let _e=Z;if(await Fd())try{await pe(),Od=0;return}catch(Be){_e=Be}if(ee.silent){Od+=1,Od>=3&&(ue=`refresh failing: ${_e.message}`,Pt());return}ue=`refresh failed: ${_e.message}`,Pt()}},Zn=async N=>{if(!I)return;let ee=I;S="busy",Ne();try{await Ju(e.target,ee.sessionId,N),S="normal",I=null,Ge=null,await nn(ee.sessionId)}catch(pe){S="normal",I=null,Ge=null,ue=`rename failed: ${pe.message}`,Ne()}},Hs=async N=>{try{await eE(e.target,N.sessionId),ue="title regen queued (press r to refresh)",Ne()}catch(ee){ue=`regen failed: ${ee.message}`,Ne()}},Ld=async N=>{let pe=(N.priority&&N.priority>0?N.priority:0)>0?null:1,Z=pe??0;for(let Be of o)Be.sessionId===N.sessionId&&(Be.priority=Z>0?Z:void 0);let _e=N.sessionId;o=Xg(o,s),Rn(),_e!==void 0&&Ps(_e),Pt(),ue=Z>0?"priority: high":"priority: normal",Ne();try{await Z0(e.target,N.sessionId,pe)}catch(Be){ue=`priority failed: ${Be.message}`,Ne()}},ss=async()=>{if(se)return;se=!0;let N=p>0?d[p-1]?.sessionId:void 0;ue="syncing agents\u2026",Ne();try{let{synced:ee,skipped:pe,agents:Z}=await V0(e.target);await nn(N),ue=`synced ${ee} new (${pe} known) from ${Z} agent${Z===1?"":"s"}`,Ne()}catch(ee){ue=`sync failed: ${ee.message}`,Ne()}finally{se=!1}},dr=!1,ep=async N=>{if(dr)return;dr=!0;let ee=N.title?.trim()||Qe(N.sessionId);ue=pg()?`showing ${ee} in ${dd()}\u2026`:`opening ${ee} in a new ${dd()} tab\u2026`,Ne();try{let pe=await ff({kind:"attach",sessionId:N.sessionId,title:N.title,cwd:rd(N)!==void 0?void 0:N.cwd});ue=pe.outcome==="revealed"?`jumped to ${ee} \u2014 already open in ${dd()}`:pe.outcome==="opened"?`opened ${ee} in a new ${dd()} tab`:`new tab failed: ${pe.error??"unknown error"}`}catch(pe){ue=`new tab failed: ${pe.message}`}finally{dr=!1,Ne()}},Nd=async()=>{if(dr)return;dr=!0;let N=Me.expandedText(),ee=[...Me.state().attachments],pe=ee.length;ue=`opening a new session in a new ${dd()} tab\u2026`,Ne();try{let Z=await fl({kind:"new",cwd:s,agentId:Zt,model:bn,prompt:N});Z.ok?(N.trim().length>0&&Me.setBuffer("",ee),ue=pe>0?`opened a new ${dd()} tab \u2014 ${pe} attachment${pe===1?"":"s"} stayed here`:`opened a new session in a new ${dd()} tab`):ue=`new tab failed: ${Z.error??"unknown error"}`}catch(Z){ue=`new tab failed: ${Z.message}`}finally{dr=!1,Pt()}},tp=async N=>{if(!I)return;let ee=I;S="busy",Ne();try{N==="kill"?await co(e.target,ee.sessionId):await nE(e.target,ee.sessionId),S="normal",I=null,ee.sessionId===e.currentSessionId&&(Tt=!0);let pe;if(N==="kill")pe=ee.sessionId;else{let Z=d.findIndex(_e=>_e.sessionId===ee.sessionId);Z>=0&&(pe=d[Z+1]?.sessionId??d[Z-1]?.sessionId)}await nn(pe)}catch(pe){S="normal",I=null,ue=`${N} failed: ${pe.message}`,Ne()}},sa=(N,ee)=>{N===0!=(ee===0)&&(Vt(),ee===0?(n.hideCursor(!1),cn()):n.hideCursor())},er=N=>{let ee=Math.min(f-1,Math.max(0,p+N));if(ee===p)return;let pe=p;p=ee,Qr(),mt(()=>{ts(),sa(pe,p)})},Ll=()=>ue===null?!1:(ue=null,Ne(),!0),Nl=()=>{Vf();let N=!1;ge({onKey:ee=>{if(ee==="CTRL_C"){Rr(),E({kind:"abort"});return}ut()},onMouse:ee=>{if(ee==="MOUSE_LEFT_BUTTON_PRESSED"){N=!0;return}ee!=="MOUSE_LEFT_BUTTON_RELEASED"||!N||(N=!1,ut())},onResize:()=>Vf()})},Kt=N=>{let ee=null,pe=null,Z=!0,_e=0,Be=null,Ue=0,at=()=>Z?["loading\u2026"]:pe!==null?[pe]:ee??[],vn=()=>{mt(()=>{n.hideCursor(),Ye.clearCache();let te=at(),ze=uo(n),qe=Cn(n),dt=Math.max(3,ze-6),Mt=Math.min(te.length,dt),_o=te.reduce((Ce,st)=>Math.max(Ce,st.length),0),lr=Math.min(Math.max(40,_o+2),Math.max(20,qe-6)),rn=zn(n,{contentHeight:Mt+2,contentWidth:lr,title:`Session info \u2014 ${Qe(N.sessionId)}`,overlay:!0});Be={x:rn.x,y:rn.y,w:rn.w,h:rn.h},Ue=Mt,_e=Math.max(0,Math.min(_e,Math.max(0,te.length-Mt)));for(let Ce=0;Ce<Mt;Ce++){let st=te[_e+Ce]??"";n.moveTo(rn.contentX,rn.contentY+Ce);let Tr=st.slice(0,rn.contentW-1);pe!==null?H(n,"modal-error",` ${Tr}`):H(n,"content",` ${Tr}`),n.styleReset()}let os=te.length-Mt-_e,is=te.length>Mt?`\u2191/\u2193/wheel scroll${os>0?` (${os} more)`:""} \xB7 Esc or click outside to return`:"Esc or click outside to return";n.moveTo(rn.contentX,rn.contentY+Mt+1),H(n,"modal-hint",` ${is}`),n.styleReset()})};vn();let ce=new AbortController,Te=()=>{ce.abort(),ut()},Pe=te=>{let ze=Math.max(0,at().length-Ue),qe=Math.max(0,Math.min(ze,_e+te));qe!==_e&&(_e=qe,vn())},Ve={onKey:te=>{if(te==="ESCAPE"||te==="CTRL_C"){Te();return}if(te==="UP"){Pe(-1);return}if(te==="DOWN"){Pe(1);return}if(te==="PAGE_UP"){Pe(-Math.max(1,Ue-1));return}if(te==="PAGE_DOWN"){Pe(Math.max(1,Ue-1));return}if(te==="HOME"){Pe(-Number.MAX_SAFE_INTEGER);return}if(te==="END"){Pe(Number.MAX_SAFE_INTEGER);return}},onMouse:(te,ze)=>{if(te==="MOUSE_WHEEL_UP"){Pe(-3);return}if(te==="MOUSE_WHEEL_DOWN"){Pe(3);return}if(te!=="MOUSE_LEFT_BUTTON_RELEASED"||Be===null)return;let qe=ze?.x??-1,dt=ze?.y??-1;qe>=Be.x&&qe<Be.x+Be.w&&dt>=Be.y&&dt<Be.y+Be.h||Te()},onResize:()=>vn()};ge(Ve),(async()=>{try{let te=await _n(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(N.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:ce.signal});if(!te.ok)throw new Error(`daemon returned HTTP ${te.status}`);let ze=await te.json(),qe=ys(ze),dt=Vk(qe,N.status);ee=Hm(dt,!1).replace(/\n$/,"").split(`
288
+ `)}catch(te){if(ce.signal.aborted)return;pe=`failed to load info: ${te.message}`}finally{Z=!1,!Xt&&ae[ae.length-1]===Ve&&vn()}})()},Po=()=>{if(d.length===0){ue="no sessions to search",Ne();return}$=new Vo({history:[],collapsePastes:!1});let N=r.lastFind,ee=new Set(d.map(ce=>ce.sessionId)),pe=N?N.results.filter(ce=>ee.has(ce.sessionId)):[];N&&N.query.length>0&&$.setBuffer(N.query),P=pe,je(),M=N?.truncated??!1,F=Math.min(Math.max(0,N?.selectedIdx??0),Math.max(0,pe.length-1)),K=0,It=0,Y=null,z=!1,C=pe.length>0?"results":"input",x=!0,Io(),xo(),Ro();let Z=()=>{let ce=P[F];if(!ce)return;let Te=d.find(te=>te.sessionId===ce.sessionId),Pe=!!Te?.importedFromMachine&&!Te.remote&&!Te.upstreamSessionId,Ve=ce.snippets[K]?.recordedAt??ce.snippets[0]?.recordedAt;if(Pe){Qn(),Rr();let te={kind:"attach",sessionId:ce.sessionId};Te.agentId!==void 0&&(te.agentId=Te.agentId),Ve!==void 0&&(te.jumpToRecordedAt=Ve),E(te);return}(async()=>{let te=await B$(n,{sessionId:ce.sessionId,title:ce.title,cwd:ce.cwd},St);if(te==="cancel"){Qn(),Rr(),E({kind:"abort"});return}if(te==="back")return;Qn(),Rr();let ze={kind:"attach",sessionId:ce.sessionId,readonly:te==="view"};Te?.agentId!==void 0&&(ze.agentId=Te.agentId),Ve!==void 0&&(ze.jumpToRecordedAt=Ve),E(ze)})()},_e=ce=>{if(ce<0||ce>=P.length||ce===F)return;let Te=F,Pe=It;F=ce,K=0,xo(),It!==Pe?Ns():mt(()=>{Zi(Te,!1),Zi(F,!0)}),Ls()},Be=(ce,Te,Pe)=>{if(C==="input"){if(z)return;if(ce==="ESCAPE"||ce==="CTRL_C"){Ds();return}if(ce==="ENTER"||ce==="KP_ENTER"){if(ir().trim().length===0)return;Ao();return}if((ce==="DOWN"||ce==="TAB"||ce==="CTRL_N")&&P.length>0){C="results",F=0,K=0,mt(()=>{Xi(),Zi(0,!0),Ls(),n.hideCursor()});return}let Ve=$.state(),te=[...Ve.buffer],ze=Ve.row,qe=Ve.col,dt=null;if(ce==="")dt={type:"key",name:"ctrl-underscore"};else if(ce==="\x1B_"||ce==="\x1B")dt={type:"key",name:"alt-underscore"};else if(Pe?.isCharacter)dt={type:"char",ch:ce};else{let rn=qg(ce);rn!==null&&(dt={type:"key",name:rn})}if(dt===null){n.moveTo(si(),Co());return}$.feed(dt);let Mt=$.state();if(te.length===Mt.buffer.length&&te.every((rn,os)=>rn===Mt.buffer[os])&&ze===Mt.row&&qe===Mt.col){n.moveTo(si(),Co());return}let lr=wn;Io(),wn!==lr?Ro():xd();return}if(C==="results"){if(ce==="ESCAPE"||ce==="CTRL_C"){Ds();return}if(ce==="CTRL_F"){C="input",Ns(),Ls(),Xi();return}if(ce==="ENTER"||ce==="KP_ENTER"){Z();return}if(Pe?.isCharacter&&ce==="i"){let ze=P[F];if(!ze)return;let qe=d.find(dt=>dt.sessionId===ze.sessionId);if(!qe)return;Kt(qe);return}let Ve=ze=>{let qe=P[F];!qe||qe.snippets.length<=1||(K=(K+ze+qe.snippets.length)%qe.snippets.length,Zi(F,!0))};if(Pe?.isCharacter&&(ce==="n"||ce==="N")){Ve(1);return}if(Pe?.isCharacter&&(ce==="p"||ce==="P")){Ve(-1);return}if(ce==="LEFT"){Ve(-1);return}if(ce==="RIGHT"){Ve(1);return}let te=ze=>{if(ze<0&&F===0){C="input",mt(()=>{Zi(0,!1),Ls(),Xi()});return}_e(Math.min(P.length-1,Math.max(0,F+ze)))};switch(ce){case"UP":case"SHIFT_TAB":case"CTRL_P":te(-1);return;case"DOWN":case"TAB":case"CTRL_N":te(1);return;case"PAGE_UP":te(-Yn());return;case"PAGE_DOWN":te(Yn());return;case"HOME":te(-F);return;case"END":te(P.length);return}return}},Ue=ce=>{let Te=Nn(),Pe=Te+Yn()*2-1;if(ce<Te||ce>Pe)return null;let Ve=It+Math.floor((ce-Te)/2);return Ve>=0&&Ve<P.length?Ve:null},at=null;ge({onKey:Be,onMouse:(ce,Te)=>{if(z)return;if(ce==="MOUSE_WHEEL_UP"||ce==="MOUSE_WHEEL_DOWN"){if(P.length===0)return;let qe=ce==="MOUSE_WHEEL_UP"?-3:3,dt=Math.max(0,P.length-Yn()),Mt=Math.min(dt,Math.max(0,It+qe));if(Mt===It)return;It=Mt,F<It?(F=It,K=0):F>=It+Yn()&&(F=It+Yn()-1,K=0),Ns(),Ls();return}if(ce==="MOUSE_LEFT_BUTTON_PRESSED"){at={x:Te?.x??-1,y:Te?.y??-1};return}let Pe=Te?.y;if(typeof Pe!="number")return;if(ce==="MOUSE_MOTION"){if(C!=="results")return;let qe=Ue(Pe);qe!==null&&_e(qe);return}if(ce!=="MOUSE_LEFT_BUTTON_RELEASED")return;let Ve=at!==null&&Te?.x===at.x&&Pe===at.y;if(at=null,!Ve)return;if(Pe<=wn+2){C!=="input"&&(C="input",Ns(),Ls(),Xi(),n.moveTo(si(),Co()),n.hideCursor(!1));return}let te=Ue(Pe);if(te===null)return;if(C==="input"){C="results",F=te,K=0,xo(),mt(()=>{Xi(),Ns(),Ls(),n.hideCursor()});return}if(te!==F){_e(te);return}Z()},onResize:()=>Ro()})},Mo=(N,ee,pe)=>{if(S!=="busy"){if(N==="CTRL_O"){zt();return}if(N==="CTRL_L"){Jf();return}if(S==="rename"&&Ge){if(N==="ENTER"||N==="KP_ENTER"){let Z=Ge.text.trim();if(Z.length===0){S="normal",I=null,Ge=null,Ne();return}Zn(Z);return}if(N==="ESCAPE"||N==="CTRL_C"){S="normal",I=null,Ge=null,Ne();return}if(Ge.handleKey(N,pe?.isCharacter===!0)){Ne();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(pe?.isCharacter&&(N==="y"||N==="Y")){tp(S==="confirm-kill"?"kill":"delete");return}if(N==="ESCAPE"||N==="CTRL_C"||N==="ENTER"||N==="KP_ENTER"||pe?.isCharacter&&(N==="n"||N==="N")){S="normal",I=null,Ne();return}return}if(Ll(),Rt&&(Rt=!1,p=0,mt(()=>{Vt(),ts()})),N==="CTRL_F"&&p!==0){Po();return}if(p===0&&!b){if(N==="ESCAPE"){ra();return}if(N==="ENTER"||N==="KP_ENTER"){let te=Me.expandedText(),ze=en();te.trim().length>0&&(ze.prompt=te),ze.installStatus=Ar(),E(ze);return}if(N==="CTRL_T"){uf()&&Nd();return}if(N==="UP"&&y){let te=Date.now(),ze=te-k;if(k=te,ze<h){cn();return}y=!1}if(N==="DOWN"){let te=Me.state(),ze=te.historyIndex!==-1||te.queueIndex!==-1,qe=Gn.length===0||Gi===Gn.length-1;if(!ze&&qe&&d.length>0){er(1);return}}if(N==="PAGE_DOWN"&&(Gn.length===0||Gi===Gn.length-1)&&d.length>0){er(1);return}if(N==="CTRL_P"||N==="CTRL_N"){d.length>0&&er(1);return}if(y=!1,N==="TAB"){let te=Me.state(),ze=te.buffer[te.row]??"",qe=Gg(ze,te.col);if(qe!==null){let dt=Jg(qe.token,s);if(dt!==null){if(dt.replacement!==qe.token&&(Me.replaceRangeOnCurrentLine(qe.start,te.col,dt.replacement),To()),dt.candidates.length>1){let Mt=dt.candidates.join(" ");oe=`${dt.candidates.length} matches: ${Mt}`,Ir()}else Cr();cn();return}}}Cr();let Z=Me.state(),_e=[...Z.buffer],Be=Z.row,Ue=Z.col,at=null;if(N==="")at={type:"key",name:"ctrl-underscore"};else if(N==="\x1B_"||N==="\x1B")at={type:"key",name:"alt-underscore"};else if(pe?.isCharacter)at={type:"char",ch:N};else{let te=qg(N);if(te!==null){if(Xn(te)){cn();return}at={type:"key",name:te}}}if(at===null){cn();return}let vn=Me.feed(at),ce=Me.state(),Te=_e.length===ce.buffer.length&&_e.every((te,ze)=>te===ce.buffer[ze])&&Be===ce.row&&Ue===ce.col;if(vn.some(te=>te.type==="exit")){ra();return}for(let te of vn)te.type==="attachment-request"?Ad():te.type==="edit-in-editor"&&Qf();if(Te){cn();return}let Pe=Cs(ce.buffer,or);if(go(Pe,ce,Pf).rendered!==yn){Pt();return}To();return}if(!b&&pe?.isCharacter&&N==="?"){Nl();return}if(b){if(pe?.isCharacter){g+=N,Rn(),Pt();return}if(N==="BACKSPACE"){g.length>0?(g=g.slice(0,-1),Rn(),Pt()):(b=!1,Rn(),Pt());return}if(N==="ESCAPE"||N==="CTRL_C"){b=!1,g="",Rn(),Pt();return}}if(pe?.isCharacter){if(N==="/"){let Z=p>0?d[p-1]?.sessionId:null;b=!0,g="",Rn(),Ps(Z),Pt();return}if(N==="n"||N==="N"){er(1);return}if(N==="p"||N==="P"){er(-1);return}if(N==="c"||N==="C"){let Z=en();Z.installStatus=Ar(),E(Z);return}if(N==="q"||N==="Q"){ra();return}if(N==="o"||N==="O"){let Z=p>0?d[p-1]?.sessionId:null;r.filters.cwdOnly=!r.filters.cwdOnly,Rn(),Ps(Z),Pt();return}if(N==="h"||N==="H"){let Z=p>0?d[p-1]?.sessionId:null;r.filters.hostFilter=Y$(r.filters.hostFilter,o),r.pendingDefaultHost=void 0,Rn(),Ps(Z),Pt();return}if(N==="i"&&p>0){let Z=d[p-1];if(!Z)return;Kt(Z);return}if(N==="I"){let Z=p>0?d[p-1]?.sessionId:null;r.filters.includeNonInteractive=!r.filters.includeNonInteractive,Rn(),Ps(Z),Pt();return}if(N==="r"||N==="R"){let Z=p>0?d[p-1]?.sessionId:void 0;nn(Z);return}if(N==="s"||N==="S"){ss();return}if((N==="v"||N==="V")&&p>0){let Z=d[p-1];if(!Z)return;let _e={kind:"attach",sessionId:Z.sessionId,readonly:!0};Z.agentId!==void 0&&(_e.agentId=Z.agentId),_e.installStatus=Ar(),E(_e);return}if((N==="f"||N==="F")&&p>0){let Z=d[p-1];if(!Z)return;Rr();let _e={kind:"fork",sourceSessionId:Z.sessionId,sourceCwd:Z.cwd};Z.agentId!==void 0&&(_e.sourceAgentId=Z.agentId),Z.importedFromMachine!==void 0&&(_e.sourceImportedFromMachine=Z.importedFromMachine),Z.upstreamSessionId!==void 0&&(_e.sourceUpstreamSessionId=Z.upstreamSessionId),E(_e);return}if((N==="k"||N==="K")&&p>0){let Z=d[p-1];if(!Z)return;I={sessionId:Z.sessionId,cwd:Z.cwd,status:Z.status},S="confirm-kill",Ne();return}if(N==="t"&&p>0){let Z=d[p-1];if(!Z)return;I={sessionId:Z.sessionId,cwd:Z.cwd,status:Z.status},Ge=new Hi(Z.title??""),S="rename",Ne();return}if(N==="T"&&p>0){let Z=d[p-1];if(!Z)return;Hs({sessionId:Z.sessionId});return}if(N==="*"&&p>0){let Z=d[p-1];if(!Z)return;Ld(Z);return}if((N==="d"||N==="D")&&p>0){let Z=d[p-1];if(!Z)return;I={sessionId:Z.sessionId,cwd:Z.cwd,status:Z.status},S="confirm-delete",Ne();return}Rt=!1,p=0,Me.feed({type:"char",ch:N}),Pt();return}switch(N){case"CTRL_T":{if(!uf())return;if(Rt||p===0){Nd();return}let Z=d[p-1];if(!Z)return;ep(Z);return}case"UP":case"SHIFT_TAB":case"CTRL_P":N==="UP"&&(p===1&&(y=!0),k=Date.now()),er(-1);return;case"DOWN":case"TAB":case"CTRL_N":er(1);return;case"PAGE_UP":er(-it);return;case"PAGE_DOWN":er(it);return;case"HOME":er(1-p);return;case"END":er(f);return;case"RIGHT":if(Rt||p===0)break;case"ENTER":case"KP_ENTER":{if(Rt){let Be=Me.expandedText(),Ue=en();Be.trim().length>0&&(Ue.prompt=Be),Ue.installStatus=Ar(),E(Ue);return}if(p===0){let Be=en();Be.installStatus=Ar(),E(Be);return}let Z=d[p-1];if(!Z){Rr(),E({kind:"abort"});return}let _e={kind:"attach",sessionId:Z.sessionId};Z.agentId!==void 0&&(_e.agentId=Z.agentId),_e.installStatus=Ar(),E(_e);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":ra();return}}};ge({onKey:(N,ee,pe)=>Mo(N,ee,pe),onResize:()=>{Xt||Pt()}});let Bs=(N,ee)=>{if(Xt)return;if(ae.length!==1){ae[ae.length-1]?.onMouse?.(N,ee);return}if(S!=="normal")return;let pe=N==="MOUSE_MOTION",Z=N==="MOUSE_DRAG",_e=N==="MOUSE_LEFT_BUTTON_PRESSED",Be=N==="MOUSE_LEFT_BUTTON_RELEASED",Ue=N==="MOUSE_WHEEL_UP",at=N==="MOUSE_WHEEL_DOWN",vn=rt&&Date.now()-Ml<uy,ce=!rt||vn;if(_e){Dn={x:ee?.x??-1,y:ee?.y??-1},ai=ce;let Ce=ee?.x,st=ee?.y;!ce&&typeof Ce=="number"&&typeof st=="number"&&st>=On&&st<=Jn()&&ri({x:Ce,y:st});return}if(Z){if(Kn!==null){let Ce=ee?.x,st=ee?.y;typeof Ce=="number"&&typeof st=="number"&&es({x:Ce,y:st})}return}if(pe&&ce)return;let Te=Be&&Dn!==null&&ee?.x===Dn.x&&ee?.y===Dn.y,Pe=Te&&!ai,Ve=Te&&ai;if(Be&&Kn!==null){Dn=null,ai=!1;let Ce=ee?.x,st=ee?.y;dy(typeof Ce=="number"&&typeof st=="number"?{x:Ce,y:st}:null);return}if(Be&&(Dn=null,ai=!1,!Te))return;if(Ue||at){if(d.length===0)return;let Ce=Ue?-3:3,st=Math.max(0,d.length-it),Tr=Math.min(st,Math.max(0,m+Ce));if(Tr===m)return;if(m=Tr,p>0){let np=p-1;np<m?p=m+1:np>=m+it&&(p=m+it)}ts();return}if(!pe&&!Pe)return;let te=ee?.y;if(typeof te!="number")return;{let Ce=ee?.x,st=Eo!==null&&te===Xr()&&typeof Ce=="number"&&Ce>=Eo.start&&Ce<=Eo.end,Tr=rs!==null&&te===Xr()&&typeof Ce=="number"&&Ce>=rs.start&&Ce<=rs.end;(st!==di||Tr!==ea)&&(di=st,ea=Tr,Ne(),p===0?(cn(),n.hideCursor(!1)):n.hideCursor(!0))}if(Pe&&Eo!==null&&te===Xr()){let Ce=ee?.x;if(typeof Ce=="number"&&Ce>=Eo.start&&Ce<=Eo.end){ra();return}}if(Pe&&rs!==null&&te===Xr()){let Ce=ee?.x;if(typeof Ce=="number"&&Ce>=rs.start&&Ce<=rs.end){let st=p>0?d[p-1]?.sessionId:null;r.filters.hostFilter=Y$(r.filters.hostFilter,o),r.pendingDefaultHost=void 0,Rn(),Ps(st),Pt();return}}if(te>=On&&te<=Jn()){let Ce=null;if(te===On){let st=ee?.x;typeof st=="number"&&(_s!==null&&st>=_s.start&&st<=_s.end?Ce="host":Fn!==null&&st>=Fn.start&&st<=Fn.end?Ce="agent":Ms!==null&&st>=Ms.start&&st<=Ms.end&&(Ce="cwd"))}if(Ce!==kn&&(kn=Ce,Vt()),Pe&&te===On){if(kn==="agent"){ci("agent");return}if(kn==="host"){ci("host");return}if(kn==="cwd"){zt();return}}if((Pe||Ve)&&p!==0){Rt=!1;let st=p;p=0,mt(()=>{ts(),sa(st,p)});return}pe&&!Rt&&p!==0&&(Rt=!0,mt(()=>{Vt(),ts()}));return}kn!==null&&(kn=null,Vt()),Rt&&(Rt=!1,mt(()=>{Vt(),ts()}));let qe=Le()+1,dt=qe+it-1;if(te<qe||te>dt)return;let Mt=m+(te-qe);if(Mt<0||Mt>=d.length)return;let _o=d[Mt];if(!_o)return;let lr=Mt+1;if(pe&&p===0)return;let rn=p===0,os=p===lr;if(Ve&&p!==lr){let Ce=p;p=lr,Qr(),mt(()=>{ts(),sa(Ce,p)});return}if(Ve)return;if(p!==lr){let Ce=p;p=lr,Qr(),mt(()=>{ts(),sa(Ce,p)})}if(!Pe||rn||!os)return;let is={kind:"attach",sessionId:_o.sessionId};_o.agentId!==void 0&&(is.agentId=_o.agentId),is.installStatus=Ar(),E(is)},cr=()=>{n.grabInput({mouse:"motion"}),we({src:"grab",site:"picker.installGrab",on:!0});let N=n;N.stdin&&typeof N.onStdin=="function"&&(ar=N.onStdin,N.stdin.removeListener("data",N.onStdin),N.stdin.on("data",Md),be(Jm),be(Qm)),n.on("key",li),n.on("mouse",Bs),n.on("resize",Fl)},ui=()=>{be(Jo),be(sf);let N=n;N.stdin&&ar&&(N.stdin.removeListener("data",Md),N.stdin.on("data",ar),ar=null),ns=!1,ii="",n.off("key",li),n.off("mouse",Bs),n.off("resize",Fl),n.grabInput(!1),we({src:"grab",site:"picker.uninstallGrab",on:!1}),n.hideCursor(!1)};if(cr(),_l=()=>{$l=!0,J&&(J.abort(),J=null,W=!1),ui(),n.fullscreen(!1),be(`${rf}${Vm}`)},Pd=()=>{$l=!1,n.fullscreen(!0),t(),n.hideCursor(),cr(),Xt||Jf()},process.platform!=="win32"){let N=!1,ee=()=>{N&&(N=!1,Pd?.())};Ed=()=>{N||Xt||(N=!0,_l?.(),be(`
289
+ `),process.once("SIGCONT",ee),process.kill(process.pid,"SIGTSTP"))}}_=setInterval($d,3e3)})}function xJ(n,e){let t="Create new session in ",r=Math.max(1,e-t.length);return t+Yu(V(n),r)}function Xg(n,e){let t=s=>s.priority&&s.priority>0?s.priority:0,r=s=>{let o=s.status==="warm",i=t(s)>0;return o&&s.busy&&s.awaitingInput?6:o&&s.busy?5:o&&s.awaitingInput?4:o&&i?3:o?2:i?1:0};return[...n].sort((s,o)=>{let i=r(o)-r(s);if(i!==0)return i;let a=t(o)-t(s);return a!==0?a:o.updatedAt.slice(0,16).localeCompare(s.updatedAt.slice(0,16))})}function IJ(n,e){return n?e.has(n):!0}function qS(n){return!!n.importedFromMachine&&!n.upstreamSessionId}function V$(n,e){if(e)return e;if(new Set(n.map(s=>s.host)).size<=1)return Hr;let r=Hr.indexOf("agent");return[...Hr.slice(0,r),"host",...Hr.slice(r)]}function CJ(n,e,t=Up()){if(e==="__all")return n;let r=o=>!o.remote&&(IJ(o.importedFromMachine,t)||!!o.upstreamSessionId);if(e==="__local")return n.filter(r);if(e==="__remotes")return n.filter(o=>o.remote?!qS(o):r(o));if(e.startsWith(ji)){let o=e.slice(ji.length);return n.filter(i=>i.remote===o&&!qS(i))}let s=e.startsWith(cd)?e.slice(cd.length):e;return n.filter(o=>o.importedFromMachine===s&&!t.has(s)&&!o.upstreamSessionId)}function Y$(n,e,t=Up()){let r=Q$(e,t),s=r.indexOf(n);return s===-1?"__local":r[(s+1)%r.length]??"__local"}function Q$(n,e){let t=new Set,r=new Set;for(let s of n){if(s.remote){qS(s)||t.add(s.remote);continue}s.importedFromMachine&&!s.upstreamSessionId&&!e.has(s.importedFromMachine)&&r.add(s.importedFromMachine)}return["__local",...t.size>0?["__remotes"]:[],...[...t].sort().map(s=>`${ji}${s}`),...[...r].sort().map(s=>`${cd}${s}`),"__all"]}function RJ(n,e,t=Up()){if(n==="all")return"__all";let r=Q$(e,t),s;return n===`${ji}all`?s=["__remotes"]:n.startsWith(ji)||n.startsWith(cd)?s=[n]:s=[`${ji}${n}`,`${cd}${n}`],s.find(o=>r.includes(o))??"__local"}function AJ(n){return n==="__local"?"host: local":n==="__remotes"?"host: local + remotes":n.startsWith(ji)?`remote: ${n.slice(ji.length)}`:n.startsWith(cd)?`host: ${n.slice(cd.length)}`:`host: ${n}`}function TJ(n,e){if(e.length===0)return!0;let t=e.toLowerCase(),r=[Qe(n.sessionId),n.upstreamSessionId??"",n.agentId??"",n.title??"",n.cwd,V(n.cwd)];for(let s of r)if(s.toLowerCase().includes(t))return!0;return!1}var Qg,Pf,kJ,G$,vJ,J$,ji,cd,X$=j(()=>{"use strict";Zc();xc();Gs();Se();mr();et();Ws();yg();td();pf();Vu();o_();Ph();vg();Sg();Kv();NS();HS();BS();mg();US();Li();of();WS();Gv();wS();Va();xn();Ea();Yk();ma();jS();Qg=2,Pf=4,kJ=4,G$=4,vJ=20,J$=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],["typing in list","jumps focus back to composer with that key"],["mouse-hover composer","Enter from anywhere creates a new session"],null,["\u2191 / \u2193, n / p, ^p / ^n","navigate sessions"],["PgUp / PgDn","page up / page down"],["Home / End","first / last"],["Enter","open selected session"],["v","view-only (open transcript without spawning the agent)"],null,["/","search sessions (metadata)"],["^f","find in session history (content + tool inputs)"],[" in results","n/p cycle snippets \xB7 i info \xB7 Enter open"],[" ","the query and results survive opening a hit"],["o","toggle cwd-only filter"],["h","cycle host filter (local / <peer> / all)"],["^o","change cwd (for the picker and any new sessions)"],["i","show info for the selected session"],["I","toggle include-cat filter"],["r","refresh from daemon"],["s","sync sessions from installed agents"],null,["k","kill the selected warm session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent"],["*","toggle high priority on the selected session (floats to top)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]];ji="remote:",cd="host:"});function _J(n,e){let t=n.findIndex(r=>r.id===e);return t===-1?0:t}async function GS(n,e,t,r){kr();let s=_J(e,t??EJ),o=0,i=null,a=null,d=()=>{let x=uo(n)-8;return Math.max(1,Math.min(PJ,e.length,x))},c=()=>{let x=d(),C=Math.max(0,e.length-x);o>C&&(o=C),o<0&&(o=0)},l=()=>{let x=d();s<o?o=s:s>=o+x&&(o=s-x+1),c()},u=null,f=0,p=(x,C)=>{if(x<o||x>=o+f)return;let $=e[x];if(!$)return;let P=C.contentW,M=C.contentY+2+(x-o);n.moveTo(C.contentX,M);let F=x===s?"\u276F":" ",K=$.description??$.name,Y=` ${F} ${$.id}`;if(x===s){let z=`${Y} ${K}`;H(n,"list-selected",ks(At(z,P),P))}else{let z=P-Y.length-2,re=z>1?` ${At(K,z)}`:"";H(n,"content",Y),re.length>0&&H(n,"list-description",re);let Q=Y.length+re.length;Q<P&&n.noFormat(" ".repeat(P-Q))}},m=(x,C)=>{let $=x.contentY+2+f+1;n.moveTo(x.contentX,$);let M=` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${e.length>C?` (${s+1}/${e.length})`:""}`,F=ks(At(M,x.contentW),x.contentW);H(n,"modal-hint",F)},b=()=>{c();let x=d(),C=x+4,$=Math.min(MJ,Math.max(40,Cn(n)-8)),P=zn(n,{contentHeight:C,contentWidth:$,title:r?.title??"Select agent",overlay:r?.overlay===!0});a=P,u=P,f=Math.min(x,e.length-o),i=P.contentY+2,n.moveTo(P.contentX,P.contentY),H(n,"content",` ${r?.intro??"Which agent should this session use?"}`);let M=Math.min(e.length,o+x);for(let F=o;F<M;F++)p(F,P);return m(P,x),P},g=()=>b(),h=x=>{let C=u;if(C===null){b();return}let $=d(),P=o;if(l(),o!==P){b();return}f=Math.min($,e.length-o),x!==s&&(p(x,C),p(s,C)),m(C,$)},y=()=>{if(s<e.length-1){let x=s;s++,h(x)}},k=()=>{if(s>0){let x=s;s--,h(x)}},S=()=>{let x=u;if(x===null){b();return}let C=d();c(),f=Math.min(C,e.length-o);let $=Math.min(e.length,o+C);for(let P=o;P<$;P++)p(P,x);for(let P=f;P<C;P++){let M=x.contentY+2+P;n.moveTo(x.contentX,M),n.noFormat(" ".repeat(x.contentW))}m(x,C)},I=x=>{let C=d(),$=Math.max(0,e.length-C);if($===0)return;let P=Math.max(0,Math.min($,o+x));P!==o&&(o=P,S())};return qr({term:n,render:g,overlay:r?.overlay===!0,onKey:(x,C,$,P)=>{if(x==="CTRL_C"||x==="CTRL_D"){P({kind:"cancel"});return}if(x==="ESCAPE"){P({kind:"back"});return}if(x==="ENTER"||x==="KP_ENTER"){let M=e[s];M&&P({kind:"select",agentId:M.id,persist:!1});return}if(x==="UP"||x==="SHIFT_TAB"){k();return}if(x==="DOWN"||x==="TAB"){y();return}if($?.isCharacter){let M=x.toLowerCase();if(M==="s"){let F=e[s];F&&P({kind:"select",agentId:F.id,persist:!0});return}if(M==="j"){y();return}if(M==="k"){k();return}}},onMouse:(x,C,$)=>{if(x==="MOUSE_WHEEL_UP"){I(-1);return}if(x==="MOUSE_WHEEL_DOWN"){I(1);return}if(x==="MOUSE_MOTION"){let z=C?.y;if(typeof z!="number"||i===null)return;let re=z-i;if(re<0||re>=f)return;let Q=o+re;if(Q<0||Q>=e.length)return;if(Q!==s){let ke=s;s=Q,h(ke)}return}if(x!=="MOUSE_LEFT_BUTTON_PRESSED")return;let P=C?.x,M=C?.y;if(a!==null&&typeof P=="number"&&typeof M=="number"&&(P<a.x||P>=a.x+a.w||M<a.y||M>=a.y+a.h)){$({kind:"back"});return}if(typeof M!="number"||i===null)return;let F=M-i;if(F<0||F>=f)return;let K=o+F;if(K<0||K>=e.length)return;let Y=e[K];Y&&$({kind:"select",agentId:Y.id,persist:!1})}})}var EJ,PJ,MJ,Z$=j(()=>{"use strict";Li();xn();EJ="opencode",PJ=20,MJ=88});function $J(n){let e=n.explicitAgentId??n.directoryDefaultAgent??n.prefs.lastChosenAgent??n.fallbackAgentId??n.configDefaultAgent;if(e===void 0||e.length===0)return{};let t=n.availableAgents.find(i=>i.id===e)?.extendsChain,r={id:e,...t?{extendsChain:t}:{}},s=e===n.prefs.lastChosenAgent?n.prefs.lastChosenModel:void 0,o=Or(n.directoryDefaultModels,r)?.value??s??Or(n.configDefaultModels,r)?.value;return{agentId:e,...o!==void 0?{model:o}:{}}}function eO(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n))typeof r.model=="string"&&(e[t]=r.model);return Object.keys(e).length>0?e:void 0}async function Mf(n){let e={},t;try{let i=await Kl(n.cwd);e=i.merged,t=i.homeRequest}catch{}let r=fp(e,"defaultAgent"),s=eO(pp(e,"sessionDefaults")),o=$J({...n.explicitAgentId!==void 0?{explicitAgentId:n.explicitAgentId}:{},...r!==void 0?{directoryDefaultAgent:r}:{},...s!==void 0?{directoryDefaultModels:s}:{},prefs:n.prefs,...n.fallbackAgentId!==void 0?{fallbackAgentId:n.fallbackAgentId}:{},configDefaultAgent:n.config.defaultAgent,configDefaultModels:eO(n.config.sessionDefaults),availableAgents:n.availableAgents});return t!==void 0&&t!==Oe()?{...o,notice:`that directory sets home: ${t} \u2014 run hydra there for a separate daemon`}:o}var tO=j(()=>{"use strict";Se();qd();Gs()});import OJ from"wrap-ansi";async function nO(n,e,t,r){kr();let s=r?.canGoBack!==!1,o=e?`Couldn't start ${e}`:"Couldn't start session",i=t.split(`
290
290
  `).map(c=>c.trimEnd()).filter(c=>c.length>0),a=s?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",d=()=>{let c=Cn(n),l=uo(n),u=Math.min(FJ,Math.max(20,c-4)),f=Math.max(1,u-1),p=i.flatMap(I=>OJ(I,f,{hard:!0,trim:!1}).split(`
291
291
  `)),m=Math.max(1,l-4-4),b=p.length>m,g=b?p.slice(0,m-1):p,h=g.length+(b?1:0)+4,y=zn(n,{contentHeight:h,contentWidth:u,title:"Agent failed to start"}),k=y.contentW,S=0;n.moveTo(y.contentX,y.contentY+S),H(n,"modal-title",At(` ${o}`,k)),S+=2;for(let I of g)n.moveTo(y.contentX,y.contentY+S),H(n,"modal-error",At(` ${I}`,k)),S++;return b&&(n.moveTo(y.contentX,y.contentY+S),H(n,"modal-hint",At(" \u2026 (full details in ~/.hydra-acp/tui.log)",k)),S++),S++,n.moveTo(y.contentX,y.contentY+S),H(n,"modal-hint",At(` ${a}`,k)),y};return qr({term:n,render:()=>{d()},onKey:(c,l,u,f)=>{if(c==="r"||c==="R"||c==="ENTER"||c==="KP_ENTER"){f("retry");return}if(c==="ESCAPE"){f(s?"back":"cancel");return}c==="CTRL_C"&&f("cancel")}})}var FJ,rO=j(()=>{"use strict";Li();xn();FJ=100});import{exec as LJ}from"child_process";function Zg(n){let e=n.exec??NJ,t=new Set,r=new Map,s=o=>{t.add(o);let i=n.envFor?.(o);e(o,{cwd:n.cwd()??void 0,timeout:DJ,maxBuffer:HJ,env:i?{...process.env,...i}:void 0},(a,d)=>{t.delete(o),n.onOutput(o,a?null:n.sanitize(d))})};return{poll(o,i){for(let[a,d]of o){if(t.has(a))continue;let c=r.get(a);c!==void 0&&i-c<d||(r.set(a,i),s(a))}}}}var NJ,DJ,HJ,JS=j(()=>{"use strict";NJ=(n,e,t)=>{LJ(n,e,(r,s)=>t(r,s))},DJ=3e3,HJ=64*1024});function VS(n,e){let t=new Map,r=s=>{for(let o of s){if(typeof o=="string"||o.script===void 0)continue;let i=o.refreshMs??e,a=t.get(o.script);t.set(o.script,a===void 0?i:Math.min(a,i))}};return r(n.composer.top.left),r(n.composer.top.right),r(n.composer.bottom.left),r(n.composer.bottom.right),r(n.sessionbar.left),r(n.sessionbar.right),t}function BJ(n){let e=n.trim().replace(/\s+/g," ");return e.length===0?null:e}function sO(n){return Zg({cwd:n.cwd,envFor:n.envFor,sanitize:BJ,onOutput:n.onOutput,exec:n.exec})}var oO=j(()=>{"use strict";JS()});async function UJ(n,e){try{let t=await fetch(`${n.baseUrl}/v1/process-tokens`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({sessionLabel:e}),signal:AbortSignal.timeout(3e3)});if(!t.ok)return;let r=await t.json();return typeof r.token=="string"?r.token:void 0}catch{return}}async function iO(n,e,t){let r=new Map;return await Promise.all([...t.keys()].map(async s=>{let o=await UJ(n,e);o&&r.set(s,o)})),r}async function aO(n,e){try{await fetch(`${n.baseUrl}/v1/process-tokens/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`},signal:AbortSignal.timeout(3e3)})}catch{}}var dO=j(()=>{"use strict"});function _f(n){if(typeof n!="string")return null;let e=n.trim();return e.length>0?e:null}function cO(n){if(!n||typeof n!="object")return{origin:"client",label:null};let e=n,t=_f(e.fromSession);return t?{origin:"peer",label:_f(e.fromSessionTitle)??_f(e.fromLabel)??t}:{origin:"client",label:_f(e.fromLabel)??_f(e.name)}}var lO=j(()=>{"use strict"});function uO(n){let e={};if(!n||typeof n!="object")return e;let t=n;typeof t.historyPolicy=="string"&&(e.appliedPolicy=t.historyPolicy),typeof t.clientId=="string"&&t.clientId.length>0&&(e.clientId=t.clientId);let r=t._meta;if(r&&typeof r=="object"){let s=r["hydra-acp"];if(s&&typeof s=="object"){let o=s,i=o.turnStartedAt;typeof i=="number"&&(e.turnStartedAt=i),typeof o.armedSince=="number"&&o.armedSince>0&&(e.armedSince=o.armedSince),typeof o.armedTasks=="number"&&o.armedTasks>=0&&(e.armedTasks=o.armedTasks),Array.isArray(o.armedTaskList)&&(e.armedTaskList=o.armedTaskList)}}return e}function fO(n){return!n.replayDraining&&!n.amended&&n.pendingTurns>0&&n.queueSize===0&&!n.ownTurnInFlight&&!n.hasInFlightHead}function pO(n){return!n.blockOpen&&n.isStart}function hO(n){return n.daemonTurnStartedAt!==void 0?{pendingTurnsDelta:n.pendingTurns===0?1:0,banner:"busy",busySince:n.daemonTurnStartedAt}:{pendingTurnsDelta:n.pendingTurns>0?-n.pendingTurns:0,banner:"ready"}}var mO=j(()=>{"use strict"});function ey(n){let e=gi(n);if(e===null)throw new Error(`built-in theme has a malformed colour: ${n}`);return e}function $n(n,e){let t={};for(let[r,s]of Object.entries(n))t[r]=ey(s);return t.bg=ey(e.bg),t.fg=ey(e.fg),t}function Jr(n){return{fg:ey(n)}}function vr(n){return{fg:yt(n)}}function YS(n){return gO.find(e=>e.name===n)}function QS(){return gO.map(n=>n.name)}function yO(n){return n===void 0?"terminal":sc(n)?oV:iV}function wO(n,e,t){if(n.length===0)return;let r=n.indexOf(e);return r===-1?t===1?n[0]:n[n.length-1]:n[(r+t+n.length)%n.length]}var WJ,jJ,qJ,zJ,KJ,GJ,JJ,VJ,YJ,QJ,XJ,ZJ,eV,Dt,tV,nV,rV,sV,gO,oV,iV,XS=j(()=>{"use strict";ic();xn();WJ=$n({black:"#21222c",red:"#ff5555",green:"#50fa7b",yellow:"#f1fa8c",blue:"#bd93f9",magenta:"#ff79c6",cyan:"#8be9fd",white:"#f8f8f2",brightBlack:"#6272a4",brightRed:"#ff5555",brightGreen:"#50fa7b",brightYellow:"#f1fa8c",brightBlue:"#bd93f9",brightMagenta:"#ff79c6",brightCyan:"#8be9fd",brightWhite:"#ffffff"},{bg:"#282a36",fg:"#f8f8f2"}),jJ=$n({black:"#3b4252",red:"#bf616a",green:"#a3be8c",yellow:"#ebcb8b",blue:"#81a1c1",magenta:"#b48ead",cyan:"#88c0d0",white:"#e5e9f0",brightBlack:"#4c566a",brightRed:"#bf616a",brightGreen:"#a3be8c",brightYellow:"#ebcb8b",brightBlue:"#81a1c1",brightMagenta:"#b48ead",brightCyan:"#8fbcbb",brightWhite:"#eceff4"},{bg:"#2e3440",fg:"#d8dee9"}),qJ=$n({black:"#282828",red:"#cc241d",green:"#98971a",yellow:"#d79921",blue:"#458588",magenta:"#b16286",cyan:"#689d6a",white:"#a89984",brightBlack:"#928374",brightRed:"#fb4934",brightGreen:"#b8bb26",brightYellow:"#fabd2f",brightBlue:"#83a598",brightMagenta:"#d3869b",brightCyan:"#8ec07c",brightWhite:"#ebdbb2"},{bg:"#282828",fg:"#ebdbb2"}),zJ=$n({black:"#073642",red:"#dc322f",green:"#859900",yellow:"#b58900",blue:"#268bd2",magenta:"#d33682",cyan:"#2aa198",white:"#657b83",brightBlack:"#93a1a1",brightRed:"#cb4b16",brightGreen:"#859900",brightYellow:"#b58900",brightBlue:"#268bd2",brightMagenta:"#6c71c4",brightCyan:"#2aa198",brightWhite:"#073642"},{bg:"#fdf6e3",fg:"#657b83"}),KJ=(()=>{let n={};for(let e of Object.keys(ba))n[e]=yt(7);return n})(),GJ=$n({black:"#073642",red:"#dc322f",green:"#859900",yellow:"#b58900",blue:"#268bd2",magenta:"#d33682",cyan:"#2aa198",white:"#93a1a1",brightBlack:"#586e75",brightRed:"#cb4b16",brightGreen:"#859900",brightYellow:"#b58900",brightBlue:"#268bd2",brightMagenta:"#6c71c4",brightCyan:"#2aa198",brightWhite:"#fdf6e3"},{bg:"#002b36",fg:"#839496"}),JJ=$n({black:"#45475a",red:"#f38ba8",green:"#a6e3a1",yellow:"#f9e2af",blue:"#89b4fa",magenta:"#f5c2e7",cyan:"#94e2d5",white:"#bac2de",brightBlack:"#6c7086",brightRed:"#eba0ac",brightGreen:"#a6e3a1",brightYellow:"#fab387",brightBlue:"#b4befe",brightMagenta:"#cba6f7",brightCyan:"#89dceb",brightWhite:"#cdd6f4"},{bg:"#1e1e2e",fg:"#cdd6f4"}),VJ=$n({black:"#51576d",red:"#e78284",green:"#a6d189",yellow:"#e5c890",blue:"#8caaee",magenta:"#f4b8e4",cyan:"#81c8be",white:"#b5bfe2",brightBlack:"#737994",brightRed:"#ea999c",brightGreen:"#a6d189",brightYellow:"#ef9f76",brightBlue:"#babbf1",brightMagenta:"#ca9ee6",brightCyan:"#99d1db",brightWhite:"#c6d0f5"},{bg:"#303446",fg:"#c6d0f5"}),YJ=$n({black:"#494d64",red:"#ed8796",green:"#a6da95",yellow:"#eed49f",blue:"#8aadf4",magenta:"#f5bde6",cyan:"#8bd5ca",white:"#b8c0e0",brightBlack:"#6e738d",brightRed:"#ee99a0",brightGreen:"#a6da95",brightYellow:"#f5a97f",brightBlue:"#b7bdf8",brightMagenta:"#c6a0f6",brightCyan:"#91d7e3",brightWhite:"#cad3f5"},{bg:"#24273a",fg:"#cad3f5"}),QJ=$n({black:"#ccd0da",red:"#d20f39",green:"#40a02b",yellow:"#df8e1d",blue:"#1e66f5",magenta:"#ea76cb",cyan:"#179299",white:"#5c5f77",brightBlack:"#8c8fa1",brightRed:"#e64553",brightGreen:"#40a02b",brightYellow:"#fe640b",brightBlue:"#7287fd",brightMagenta:"#8839ef",brightCyan:"#04a5e5",brightWhite:"#4c4f69"},{bg:"#eff1f5",fg:"#4c4f69"}),XJ=$n({black:"#ebdbb2",red:"#9d0006",green:"#79740e",yellow:"#b57614",blue:"#076678",magenta:"#8f3f71",cyan:"#427b58",white:"#504945",brightBlack:"#7c6f64",brightRed:"#cc241d",brightGreen:"#98971a",brightYellow:"#af3a03",brightBlue:"#458588",brightMagenta:"#b16286",brightCyan:"#689d6a",brightWhite:"#3c3836"},{bg:"#fbf1c7",fg:"#3c3836"}),ZJ=$n({black:"#414868",red:"#f7768e",green:"#9ece6a",yellow:"#e0af68",blue:"#7aa2f7",magenta:"#bb9af7",cyan:"#7dcfff",white:"#a9b1d6",brightBlack:"#565f89",brightRed:"#ff757f",brightGreen:"#73daca",brightYellow:"#ff9e64",brightBlue:"#7aa2f7",brightMagenta:"#bb9af7",brightCyan:"#2ac3de",brightWhite:"#c0caf5"},{bg:"#1a1b26",fg:"#c0caf5"}),eV=$n({black:"#3f4451",red:"#e05561",green:"#8cc265",yellow:"#d18f52",blue:"#4aa5f0",magenta:"#c162de",cyan:"#42b3c2",white:"#abb2bf",brightBlack:"#5c6370",brightRed:"#ff616e",brightGreen:"#a5e075",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#e6e6e6"},{bg:"#282c34",fg:"#abb2bf"}),Dt={orange:"#e69f00",skyBlue:"#56b4e9",bluishGreen:"#009e73",yellow:"#f0e442",blue:"#0072b2",vermillion:"#d55e00",reddishPurple:"#cc79a7"},tV=$n({black:"#3a3a3a",red:Dt.reddishPurple,green:Dt.bluishGreen,yellow:Dt.orange,blue:Dt.blue,magenta:Dt.reddishPurple,cyan:Dt.skyBlue,white:"#d0d0d0",brightBlack:"#8a8a8a",brightRed:Dt.vermillion,brightGreen:Dt.bluishGreen,brightYellow:Dt.yellow,brightBlue:Dt.skyBlue,brightMagenta:Dt.reddishPurple,brightCyan:Dt.skyBlue,brightWhite:"#f0f0f0"},{bg:"#1c1c1c",fg:"#d0d0d0"});nV=$n({black:"#090618",red:"#c34043",green:"#76946a",yellow:"#c0a36e",blue:"#7e9cd8",magenta:"#957fb8",cyan:"#6a9589",white:"#c8c093",brightBlack:"#727169",brightRed:"#e82424",brightGreen:"#98bb6c",brightYellow:"#e6c384",brightBlue:"#7fb4ca",brightMagenta:"#938aa9",brightCyan:"#7aa89f",brightWhite:"#dcd7ba"},{bg:"#1f1f28",fg:"#dcd7ba"}),rV=$n({black:"#343f44",red:"#e67e80",green:"#a7c080",yellow:"#e69875",blue:"#7fbbb3",magenta:"#d699b6",cyan:"#83c092",white:"#d3c6aa",brightBlack:"#859289",brightRed:"#e67e80",brightGreen:"#a7c080",brightYellow:"#dbbc7f",brightBlue:"#7fbbb3",brightMagenta:"#d699b6",brightCyan:"#83c092",brightWhite:"#d3c6aa"},{bg:"#2d353b",fg:"#d3c6aa"}),sV=$n({black:"#141c12",red:"#ff4b4b",green:"#1cc24b",yellow:"#e6ff57",blue:"#30b3ff",magenta:"#c770ff",cyan:"#24f6d9",white:"#2eff6a",brightBlack:"#8ca391",brightRed:"#ff4b4b",brightGreen:"#2eff6a",brightYellow:"#ffa83d",brightBlue:"#30b3ff",brightMagenta:"#c770ff",brightCyan:"#00efff",brightWhite:"#62ff94"},{bg:"#0a0e0a",fg:"#62ff94"}),gO=[{name:"terminal",description:"your terminal's own 16 colours (default)",palette:ba},{name:"dracula",description:"dark, high contrast, purple-leaning",palette:WJ},{name:"nord",description:"dark, cool, low contrast",palette:jJ},{name:"gruvbox-dark",description:"dark, warm, retro",counterpart:"gruvbox-light",palette:qJ},{name:"catppuccin-mocha",description:"dark, soft pastel (the default on a dark terminal)",counterpart:"catppuccin-latte",palette:JJ},{name:"catppuccin-macchiato",description:"dark, soft pastel, one step lighter than mocha",counterpart:"catppuccin-latte",palette:YJ},{name:"catppuccin-frappe",description:"dark, soft pastel, the lightest of the dark flavours",counterpart:"catppuccin-latte",palette:VJ},{name:"catppuccin-latte",description:"light, soft pastel (the default on a light terminal)",counterpart:"catppuccin-mocha",palette:QJ},{name:"tokyo-night",description:"dark, deep blue",palette:ZJ},{name:"one-dark",description:"dark, the Atom default",palette:eV},{name:"kanagawa",description:"dark, muted ink tones",palette:nV},{name:"everforest",description:"dark, warm green, gentle contrast",palette:rV},{name:"matrix",description:"dark, green on black",palette:sV},{name:"gruvbox-light",description:"light, warm, retro",counterpart:"gruvbox-dark",palette:XJ},{name:"colorblind",description:"dark, no meaning carried on the red/green axis",palette:tV,roles:{ok:Jr(Dt.skyBlue),error:Jr(Dt.vermillion),errorSoft:Jr(Dt.vermillion),warn:Jr(Dt.orange),active:Jr(Dt.yellow),cold:Jr(Dt.reddishPurple),diffAdded:Jr(Dt.skyBlue),diffRemoved:Jr(Dt.vermillion),gitStaged:Jr(Dt.blue),gitDirty:Jr(Dt.orange),syntaxRegexp:Jr(Dt.reddishPurple),syntaxNumber:Jr(Dt.skyBlue)}},{name:"solarized-dark",description:"dark, low contrast",counterpart:"solarized-light",palette:GJ},{name:"solarized-light",description:"light",counterpart:"solarized-dark",palette:zJ},{name:"mono",description:"no colour; weight and glyphs only",palette:KJ,roles:{subtle:vr(8),muted:vr(8),fg:vr(7),fgStrong:vr(15),active:vr(15),error:vr(15),warn:vr(15),ok:vr(7),cold:vr(7),accent:vr(15),info:vr(7),reference:vr(15),focus:vr(15),selection:{bg:yt(8),fg:yt(15)},selectionBand:{bg:yt(8)},cursor:{bg:yt(15),fg:yt(0)},promptCursor:{bg:yt(15),fg:yt(0)},match:{bg:yt(15),fg:yt(0)},matchActive:{bg:yt(7),fg:yt(0)}}}];oV="catppuccin-mocha",iV="catppuccin-latte"});import{readdir as aV,readFile as dV}from"fs/promises";import{join as xO}from"path";function cV(n,e,t,r){let s=(c,l)=>{if(c===void 0)return;if(typeof c!="string")return r.push(`${e}${l}: must be a colour string, got ${ty(c)}`),null;let u=gi(c);return u===null?(r.push(`${e}${l}: is not a colour ("${c}") \u2014 expected #rgb, #rrggbb, or rgb(r,g,b)`),null):u};if(typeof n=="string"){let c=s(n,"");return c==null?null:t?{fg:c}:{bg:c}}if(typeof n!="object"||n===null||Array.isArray(n))return r.push(`${e}: must be a colour string or { fg, bg }, got ${ty(n)}`),null;let o=n;for(let c of Object.keys(o))c!=="fg"&&c!=="bg"&&r.push(`${e}: unknown key "${c}" \u2014 expected fg or bg`);let i=s(o.fg,".fg"),a=s(o.bg,".bg");if(i===null||a===null)return null;if(i===void 0&&a===void 0)return r.push(`${e}: needs at least one of fg or bg`),null;let d={};return i!==void 0&&(d.fg=i),a!==void 0&&(d.bg=a),d}function vO(n,e,t,r,s,o){let i={};if(n===void 0)return i;if(typeof n!="object"||n===null||Array.isArray(n))return o.push(`${t}: ${e} must be an object`),i;let a=new Set(r);for(let[d,c]of Object.entries(n)){if(!a.has(d)){let u=r.filter(f=>f.includes(d)||d.includes(f));o.push(`${t}: unknown ${e==="roles"?"role":"element"} "${d}"`+(u.length>0?` \u2014 did you mean ${u.slice(0,4).join(", ")}?`:"")+` (${r.length} available)`);continue}let l=cV(c,`${t}: ${e}.${d}`,s(d),o);l!==null&&(i[d]=l)}return i}async function ZS(n,e){let t=[],r=()=>({palette:ba,overrides:{roles:{},elements:{}},name:"terminal",problems:t});return n==null?r():typeof n=="string"?await IO(n,e,t,new Set)??r():typeof n!="object"||Array.isArray(n)?(t.push(`tui.theme must be a theme name or an object, got ${ty(n)}`),r()):{...await CO(n,"tui.theme",e,t,new Set),name:"custom",problems:t}}function ty(n){return Array.isArray(n)?"an array":typeof n}async function IO(n,e,t,r){if(r.has(n))return t.push(`theme "${n}": extends forms a cycle`),null;r.add(n);let s=await lV(n,e,t);if(s!==null)return{...await CO(s,`theme "${n}"`,e,t,r),name:n,problems:t};let o=YS(n);return o!==void 0?{palette:o.palette,overrides:{roles:{...o.roles??{}},elements:{}},name:n,problems:t}:(t.push(`unknown theme "${n}" \u2014 expected one of ${QS().join(", ")}, or a file at ${xO(e,`${n}.json`)}`),null)}async function lV(n,e,t){if(!/^[A-Za-z0-9._-]+$/.test(n)||n.startsWith("."))return null;let r=xO(e,`${n}.json`),s;try{s=await dV(r,"utf8")}catch{return null}try{let o=JSON.parse(s);return typeof o!="object"||o===null||Array.isArray(o)?(t.push(`theme file ${r}: expected a JSON object`),null):o}catch(o){return t.push(`theme file ${r}: ${o.message.split(`
292
292
  `)[0]}`),null}}async function CO(n,e,t,r,s){let o=ba,i={roles:{},elements:{}};if(n.extends!==void 0)if(typeof n.extends!="string")r.push(`${e}: extends must be a theme name`);else{let d=await IO(n.extends,t,r,s);d!==null&&(o=d.palette,Object.assign(i.roles,d.overrides.roles),Object.assign(i.elements,d.overrides.elements))}let a={...o};if(n.palette!==void 0)if(typeof n.palette!="object"||n.palette===null||Array.isArray(n.palette))r.push(`${e}: palette must be an object`);else{let d=new Set([...bO,...kO]);for(let[c,l]of Object.entries(n.palette)){if(!d.has(c)){r.push(`${e}: unknown palette slot "${c}" \u2014 expected one of ${[...bO,...kO].join(", ")}`);continue}if(typeof l!="string"){r.push(`${e}: palette.${c} must be a colour string, got ${ty(l)}`);continue}let u=gi(l);if(u===null){r.push(`${e}: palette.${c} is not a colour ("${l}") \u2014 expected #rgb, #rrggbb, or rgb(r,g,b)`);continue}a[c]=u}}return Object.assign(i.roles,vO(n.roles,"roles",e,qI(),KI,r)),Object.assign(i.elements,vO(n.elements,"elements",e,zI(),GI,r)),{palette:a,overrides:i}}async function RO(n){let e=[...QS()];try{for(let r of await aV(n)){if(!r.endsWith(".json"))continue;let s=r.slice(0,-5);e.includes(s)||e.push(s)}}catch{}let t=[];for(let r of e){let s=await ZS(r,n);t.push({name:r,palette:s.palette,overrides:s.overrides})}return t}function AO(n,e,t=process.env,r){if(n!=null)if(typeof n!="string")e.push(`tui.themeBackground must be "dark", "light", or a colour, got ${typeof n}`);else{let o=SO(n.trim().toLowerCase());if(o!==void 0)return o;let i=gi(n);if(i!==null)return i;e.push(`tui.themeBackground is not "dark", "light", or a colour ("${n}")`)}if(r!==void 0)return r;let s=TI(t);return s===void 0?void 0:SO(s)}function ex(n,e,t){if(t===void 0||n.bg===void 0)return;let r=sc(t),s=sc(n.bg);if(r===s)return;let o=YS(e)?.counterpart,i=o===void 0?"":` \u2014 try "${o}" instead`;return r?`"${e}" is a light theme and this terminal is dark${i}`:`"${e}" is a dark theme and this terminal is light${i}`}function SO(n){if(n==="dark")return Un(0,0,0);if(n==="light")return Un(255,255,255)}var bO,kO,TO=j(()=>{"use strict";ya();XS();ic();xn();bO=["black","red","green","yellow","blue","magenta","cyan","white","brightBlack","brightRed","brightGreen","brightYellow","brightBlue","brightMagenta","brightCyan","brightWhite"],kO=["bg","fg"]});import{resolve as uV}from"path";function pV(n,e){let t=0;for(let r=0;r<e;r++){let s=n.indexOf(" ",t);if(s===-1)return"";t=s+1}return n.slice(t)}function hV(){return{branch:null,staged:0,unstaged:0,untracked:0,ahead:0,behind:0,files:[]}}function EO(n,e){let t=hV(),r=(s,o)=>{e===null||s===""||t.files.push({path:uV(e,s),state:o})};for(let s of n.split(`
@@ -299,19 +299,19 @@ unhandled rejection: ${n(e)}
299
299
  [heap] ${t} rss=${r.rss} heapUsed=${r.heapUsed}
300
300
  `)}catch(e){we({src:"heap-snapshot-failed",err:e instanceof Error?e.message:String(e)})}})}async function ix(n,e,t){if(n.kind==="new"){let i=n.attachments?.length??0,a=await fl({kind:"new",cwd:n.cwd??t,agentId:n.agentId,model:n.model,prompt:n.prompt});return a.ok?i>0?`new session opened in a new tab \u2014 ${i} attachment${i===1?"":"s"} could not come along`:"new session opened in a new tab":`could not open a tab: ${a.error??"unknown error"}`}let r=e.find(i=>i.sessionId===n.sessionId),s=r?.title?.trim()||n.sessionId,o=await ff({kind:"attach",sessionId:n.sessionId,title:r?.title,cwd:rd(r)!==void 0?void 0:r?.cwd??t,jumpToRecordedAt:n.jumpToRecordedAt});switch(o.outcome){case"revealed":return n.jumpToRecordedAt!==void 0?`jumped to ${s} (already open \u2014 couldn't jump to the match there)`:`jumped to ${s}`;case"opened":return`opened ${s} in a new tab`;default:return`could not show ${s}: ${o.error??"unknown error"}`}}async function rF(n){JV(),Ev(n.terminalHostLauncher===!0,n.terminalHostLauncherOptOut===!0),$V.setResourceTimingBufferSize(0);let e=await He();xv(process.env,n.terminalHostOverride??e.tui.terminalHost);let t=n.target??await an(e);mI(e.tui.logMaxBytes);let r=await h$();kI(r.palette),XO=r.foreground;let s=r.background,o=[];Vr=AO(e.tui.themeBackground,o,process.env,s);let i=e.tui.theme===void 0?yO(Vr):void 0,a=await ZS(i??e.tui.theme,D.themesDir());if(a.problems.unshift(...o),e.tui.ambiguousWidth==="auto"){let x=await f$();YO=x?.wide,we({src:"width-probe",answered:x!==void 0,wide:x?.wide,widths:x?.widths})}Aw(a.palette,{...a.overrides,background:Vr,foreground:r.foreground}),ry=await RO(D.themesDir()),ld=a.name,ny=a.problems,$f=[];let d=ex(a.palette,a.name,Vr);if(d!==void 0&&$f.push(d),t.isLocal&&!n.target&&await Mi(e,t),n.agentId)try{let x=await Ua(t),C=tf(n.agentId,x.map($=>$.id));C!==void 0&&C!==n.agentId&&(n.explicitAgentId===n.agentId&&(n.explicitAgentId=C),n.agentId=C)}catch{}let c=FV.terminal;w$(c,{onBackground:x=>ZO?.(x),onScheme:x=>QO?.(x)}),e.tui.themeBackground===void 0&&be(m$),BI(ac(c)),L$(c);let l={},u={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:Gl(e),defaultEnterAction:e.tui.defaultEnterAction,sidebarVisible:e.tui.sidebar.enabled,sidebarCollapsed:[]},f=zS(e.tui.defaultHost),p=!1,m=()=>{p||(c.fullscreen(!0),p=!0)},b=()=>{p&&(Wi(),c.fullscreen(!1),p=!1,process.stdout.write(`
301
301
  `))};m();let g=()=>{p&&(c.fullscreen(!1),p=!1)};process.once("exit",g);let h=`script:${ax()}`,y=VS(vf({composer:e.tui.composer,sessionbar:e.tui.sessionbar}),e.tui.scriptRefreshMs);for(let[x,C]of sS(lS(e.tui.sidebar.gadgets),e.tui.scriptRefreshMs)){let $=y.get(x);y.set(x,$===void 0?C:Math.min($,C))}let k=y.size>0?await iO(t,h,y):new Map,S=n;try{for(;S!==null;)S=await QV(c,e,t,S,l,u,f,k)}finally{n$(),await Q_(),t$(),b(),process.off("exit",g),k.size>0&&await aO(t,h)}let I=await df();if(I&&process.stderr.write(`\u2728 ${cf(I)}
302
- `),process.stdout.isTTY){let x=await Ha(e);if(x?.version!==void 0){let C=x.version!==Fe,$=Ri(e),E=x.configDigest!==void 0&&x.configDigest!==$;if(C||E){let M=C?`daemon ${x.version} \u2260 cli ${Fe}`:"config changed since daemon started";process.stderr.write(ka("cli-warn",`! ${M} \u2014 run \`${Hn()} daemon restart\` to apply.`,eu(process.stderr))+`
302
+ `),process.stdout.isTTY){let x=await Ha(e);if(x?.version!==void 0){let C=x.version!==Fe,$=Ri(e),P=x.configDigest!==void 0&&x.configDigest!==$;if(C||P){let M=C?`daemon ${x.version} \u2260 cli ${Fe}`:"config changed since daemon started";process.stderr.write(ka("cli-warn",`! ${M} \u2014 run \`${Hn()} daemon restart\` to apply.`,eu(process.stderr))+`
303
303
  `)}}}if(l.sessionId&&process.stdout.isTTY){let x=Qe(l.sessionId),C=l.readonly?" --readonly":"";process.stdout.write(`Continue: ${Hn()} --session ${x}${C}
304
- `)}}function YV(n){let{order:e,states:t,startedAt:r,endedAt:s,stopReason:o,perToolExpanded:i,collapsedLimit:a=20}=n,d=e.filter(F=>!Fc(F,t.get(F)?.latestTitle)),c=d.length,l=a>0,u;if(!l||n.expanded)u=d;else{let F=Math.max(0,c-a),K=d.slice(F),Y=[];for(let z=0;z<F;z++){let re=d[z];if(re===void 0)continue;let Q=t.get(re);Q&&!qk(Q.status)&&Y.push(re)}u=[...Y,...K]}let f=c-u.length,p=s===null,m=s??Date.now(),b=m-r,g=!p&&o!==null&&o!=="end_turn"?o:null,h=g==="amended",y=h?`amended \xB7 ${jr(b)}`:`stopped (${g}) \xB7 ${jr(b)}`,k=p?"":` \xB7 ${Dm(m)}`,S;if(c===0)g!==null?S=y+k:S=p?`thinking \xB7 ${jr(b)}`:`thought \xB7 ${jr(b)}${k}`;else{let F=c===1?"tool":"tools",K=g!==null?y:p?jr(b):`took ${jr(b)}`,Y=[`${c} ${F}`,K];p&&Y.push(`started ${Dm(r)}`),p&&l&&f>0&&Y.push(`${f} hidden`),S=Y.join(" \xB7 ")+k}let I=c===0&&p;if(I)return{lines:[{body:""}],rowOwners:[null]};let x=h?"tool-status-cancelled":"tool-status-fail",E=[{prefix:"\u2699 ",prefixStyle:I?"tool-status-running":g!==null?x:"tool",body:S,bodyStyle:I?"tool-status-running":g!==null?x:"status-idle"}],M=[null];for(let F of u){let K=t.get(F);if(K){let Y=ef(K,m),z=i?.has(F)??!1;for(let re of Y)re.hoverSubKey=F,z||(re.maxWrapRows=VV);if(E.push(...Y),M.push(...Y.map(()=>F)),z){let re=WE(K);for(let Q of re)Q.hoverSubKey=F;E.push(...re),M.push(...re.map(()=>F))}}}return{lines:E,rowOwners:M}}async function QV(n,e,t,r,s,o,i,a){if(r.terminalHostLauncher&&r.sessionId===void 0&&r.forceNew!==!0&&r.resume!==!0)for(;;){let w=await GO(n,e,t,r,i,o);if(!w)return n.grabInput(!1),null;w.installStatus?.finalize();let v=await ix(w.sessionId==="__new__"?{kind:"new",...r.cwd!==void 0?{cwd:r.cwd}:{},...w.agentId?{agentId:w.agentId}:{},...r.model!==void 0?{model:r.model}:{},...r.initialPrompt!==void 0?{prompt:r.initialPrompt}:{}}:{kind:"attach",sessionId:w.sessionId},[],w.cwd);H(n,"content",`${v}
305
- `),w.sessionId!=="__new__"&&(r.pickerSelect=w.sessionId),delete r.initialPrompt,delete r.initialAttachments}let d=await GO(n,e,t,r,i,o);if(!d)return n.grabInput(!1),we({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let c=d.resolved?.status==="warm"&&t.isLocal,l=d.sessionId==="__new__"?"Starting new session\u2026":d.isFreshFork?"Forking session\u2026":d.resolved?.status==="warm"?"Attaching to session\u2026":"Resuming session\u2026",u=r.installStatus;r.installStatus&&delete r.installStatus;let f=d.installStatus??u??Yg(c?"":l,K$(n));c||f.write(l);let p=t.isLocal?async()=>(await an(await He())).wsUrl:t.wsUrl,m=t.isLocal?async()=>["acp.v1",`hydra-acp-token.${(await an(await He())).token}`]:["acp.v1",`hydra-acp-token.${t.token}`],b=null,g=null,h=new cl({url:p,subprotocols:m,onConnect:async w=>{w||b&&await b()},onDisconnect:w=>{g&&g(w)},log:w=>we({src:"resilient-ws",line:w})}),y=new pn(h);await h.start(),y.onNotification(Np,w=>{let v=UC.safeParse(w);v.success&&f.applyProgress(v.data)});let k=[],S=null,I=!1,x=!1,C=(w,v,R)=>{w&&(S?S(w,v,R):k.push({event:w,rawUpdate:v,recordedAt:R}))},$,E=w=>{w!==$&&($=w,w!==void 0&&A.appendLines([{prefix:" ",body:`\u2500\u2500 T${w} \u2500\u2500`,bodyStyle:"muted"}]))},M=null,F=null,K=!1,Y=0,z=0,re=!1,Q=!1,ke,xe=null,je=null,Ge=!1,ue=!1,oe=null,$e=!1,lt=null,Tt=null,Me=null,Jt=null,Ye=null,As=null,Ki=!1,Kn=()=>setInterval(()=>{if(X===null)return;if(xe===null){lt!==null&&X.setBanner({});return}let w=As===null?0:Date.now()-As;w<zO&&(Ki=!1);let R=lt===null&&!Sr()&&w>=zO;X.setBanner({elapsedMs:Date.now()-xe,stalled:R}),R&&!Ki&&(Ki=!0,X.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`no output for ${Math.round(w/6e4)}m and nothing running. ^C to cancel`,bodyStyle:"tool-status-fail"}])),ur()},1e3),Ts=!1,Ht=(w,v,R)=>{let O=z;z=Math.max(0,z+w),we({src:"pending-turns",delta:w,before:O,after:z,origin:v??null,label:R??null}),w>0&&V_({origin:v??null,label:R});let T=typeof X<"u"&&X!==null;O===0&&z>0?(Q=!1,xe=Date.now(),As=Date.now(),X?.setSidebarSnapshot({busySince:xe}),Et?.setTurnRunning(!0),T&&X.setBanner({status:"busy",elapsedMs:0,stalled:!1}),oe===null&&T&&(oe=Kn())):O>0&&z===0?(Q=!1,or!==null&&(clearTimeout(or),or=null),it=!1,xe=null,Ge?je=Date.now():ue=!0,X?.setSidebarSnapshot({busySince:null,lastTurnEndedAt:je}),As=null,Et?.setTurnRunning(!1),oe!==null&&lt===null&&(clearInterval(oe),oe=null),T&&X.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):z>0&&Q&&(Q=!1,T&&X.setBanner({status:"busy",stalled:!1}))},X=null,Et=null,Sr=()=>!1,gn,Yr,Xo=null,ay=new Set(["session_info_update","_hydra_current_model_update","current_mode_update","available_commands_update","_hydra_available_modes_update","usage_update","config_option_update","_hydra_compaction","_hydra_workspace","clarifier_question_asked","clarifier_question_answered","clarifier_question_dismissed"]),vl=w=>{let{update:v}=w??{},R=$C(w),O=Xs(v,{cwd:rt});ZV(v,O),As=Date.now();let T=v?.sessionUpdate;if(typeof T=="string"&&!ay.has(T)){let L=v??{};typeof L.messageId=="string"&&(gn=L.messageId);let B=Fp(w);B!==void 0&&(Yr=B)}if(T==="prompt_received"){let L=cO(v?.sentBy);Ht(1,L.origin,L.label)}else O?.kind==="turn-complete"&&(Ht(-1),K=!0);if(T==="permission_resolved"){Hf(v);return}if(T==="_hydra_compaction"){yo(v);return}if(T==="_hydra_workspace"){Gi(v);return}if(T==="clarifier_question_asked"){let L=v,B=typeof L.question?.question=="string"?L.question.question:"",ne=B.length>50?B.slice(0,49)+"\u2026":B;A.notify(ne?`new question: ${ne} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}T==="clarifier_question_answered"||T==="clarifier_question_dismissed"||(C(O,v,R),Ji(v))};y.onNotification("session/update",w=>{if(!I){if(Xo!==null){Xo.push(w);return}vl(w)}}),y.onNotification("hydra-acp/session/closed",()=>{if(I)return;z>0&&Ht(-z),typeof X<"u"&&X!==null&&X.setBanner({status:"cold",elapsedMs:void 0}),On()});let Es=new Map,Zo=200,Wt=0,it=!1,ud=4e3,or=null;y.onNotification("hydra-acp/prompt_queue/added",w=>{if(I)return;let v=w??{};if(typeof v.messageId!="string")return;if(typeof v._meta?.["hydra-acp"]?.amending=="string"){let O=v.messageId,T=v.prompt,L=setTimeout(()=>{I||(Es.delete(O),nn.set(O,Fd(O,T)),X&&Et&&dr())},Zo);Es.set(O,L)}else nn.set(v.messageId,Fd(v.messageId,v.prompt)),X&&Et&&dr();if(Ms!==void 0&&v.originator?.clientId===Ms){let O=Zn.shift();O&&(O.messageId=v.messageId,Hs.set(v.messageId,O))}});let Gn=(w,v)=>{let R=nn.get(w);R!==void 0&&(v?R.held=!0:delete R.held,X&&Et&&dr())},yn=(w,v)=>{v!==void 0&&X?.setSidebarSnapshot({armedTasks:v}),lt!==w&&(lt=w,X?.setBanner({armedSince:w??void 0}),X?.setSidebarSnapshot({armedSince:w}),w!==null&&oe===null&&X!==null&&(oe=Kn()),w===null&&xe===null&&oe!==null&&(clearInterval(oe),oe=null))};y.onNotification("hydra-acp/session/armed_tasks_updated",w=>{if(I)return;let v=w??{},R=typeof v.count=="number"?v.count:0;yn(R>0&&typeof v.since=="number"?v.since:null,Array.isArray(v.tasks)?sx(v.tasks):void 0)}),y.onNotification("hydra-acp/prompt_queue/held",w=>{if(I)return;let v=w??{};typeof v.messageId=="string"&&Gn(v.messageId,!0)}),y.onNotification("hydra-acp/prompt_queue/released",w=>{if(I)return;let v=w??{};typeof v.messageId=="string"&&Gn(v.messageId,!1)}),y.onNotification("hydra-acp/prompt_queue/updated",w=>{if(I)return;let v=w??{};if(typeof v.messageId!="string")return;let R=nn.get(v.messageId);if(R===void 0)return;let O=Fd(v.messageId,v.prompt);R.held&&(O.held=!0),nn.set(v.messageId,O);let T=Hs.get(v.messageId);if(T){let L=Array.isArray(v.prompt)?v.prompt:[],B="",ne=[];for(let le of L){if(!le||typeof le!="object")continue;let de=le;de.type==="text"&&typeof de.text=="string"?B+=de.text:de.type==="image"&&typeof de.data=="string"&&typeof de.mimeType=="string"&&ne.push({data:de.data,mimeType:de.mimeType,sizeBytes:Math.floor(de.data.length*3/4)})}T.text=B,T.attachments=ne}X&&Et&&dr()}),y.onNotification("hydra-acp/prompt_queue/removed",w=>{if(I)return;let v=w??{};if(typeof v.messageId!="string")return;v.reason==="started"&&(ke=v.messageId);let R=Es.get(v.messageId);R!==void 0&&(clearTimeout(R),Es.delete(v.messageId)),nn.delete(v.messageId)&&X&&Et&&dr();let T=Hs.get(v.messageId);T&&(Hs.delete(v.messageId),v.reason==="started"&&(T.flushed=!0,C({kind:"user-text",text:T.displayText,attachments:T.attachments}),ss=T))}),y.onNotification("hydra-acp/cancel_failed",w=>{if(I)return;let v=w??{};if(!(typeof X<"u"&&X!==null))return;Wt=Date.now();let O=typeof v.message=="string"&&v.message.length>0?`: ${v.message}`:"";if(v.reason==="unresponsive"){X.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`agent kept resuming after repeated cancels${O} \u2014 hydra restarted it automatically.`,bodyStyle:"tool-status-fail"}]);return}it=!0;let T=typeof v.code=="number"?` (${v.code})`:"";X.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${T}${O} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),y.onNotification("hydra-acp/prompt/amended",w=>{if(I)return;let v=w??{};if(typeof v.cancelledMessageId!="string")return;let R=v.cancelledMessageId;Ld.add(R),ss!==null&&ss.messageId!==void 0&&ss.messageId===R&&(C({kind:"turn-complete",stopReason:"cancelled",amended:!0}),ss=null,Ld.delete(R))}),y.onNotification("hydra-acp/context_self_compacted",()=>{I||A.notify("agent compacted its own context \u2014 recall armed",4e3)});let yo=w=>{let v=w??{},R=typeof v.phase=="string"?v.phase:void 0;if(R==="started")A.setCompactionIndicator("compacting...");else if(R==="iteration")A.setCompactionIndicator("compacting...");else if(R==="deferred")A.setCompactionIndicator("compaction queued (waiting for idle)");else if(R==="swapped")A.setCompactionIndicator(null),A.notify("compacted",2e3);else if(R==="rolled_back")A.setCompactionIndicator(null),A.notify("rolled back",2e3);else if(R==="failed"){A.setCompactionIndicator(null);let O=typeof v.error=="string"?v.error:"unknown error",T=O.length>40?O.slice(0,40)+"...":O;A.notify(`compaction failed: ${T}`,5e3)}},Gi=w=>{let v=w??{},R=typeof v.phase=="string"?v.phase:void 0;if(R==="drift"){let L=typeof v.behind=="number"?v.behind:0;A.notify(L>0?`source moved on, ${L} commit(s) ahead \u2014 /hydra workspace sync`:"source moved on \u2014 /hydra workspace sync",6e3);return}if(R==="provisioning"){A.setWorkspaceIndicator("creating workspace...");return}if(R==="setup"){A.setWorkspaceIndicator("running workspace setup...");return}if(R==="swapping"){A.setWorkspaceIndicator("moving session into workspace...");return}if(R==="landing"){A.setWorkspaceIndicator("merging workspace back...");return}if(R==="applying"){A.setWorkspaceIndicator("staging workspace changes...");return}if(R==="returning"){A.setWorkspaceIndicator("returning to source tree...");return}if(R==="failed"){A.setWorkspaceIndicator(null);let L=typeof v.error=="string"?v.error:"unknown error";A.notify(`workspace failed: ${L.length>40?L.slice(0,40)+"...":L}`,5e3);return}if(R!=="entered"&&R!=="left"||(A.setWorkspaceIndicator(null),typeof v.cwd!="string"||v.cwd.length===0))return;rt=v.cwd,dp=null;let O=typeof v.sourceCwd=="string"?v.sourceCwd:v.cwd,T=typeof v.label=="string"?v.label:void 0;A.setSessionbar({cwd:v.cwd,...R==="entered"&&T!==void 0?{workspace:{label:T,path:v.cwd,sourceCwd:O}}:{workspace:void 0}}),Dl(),A.setSidebarSnapshot({workspace:R==="entered"&&T!==void 0?{label:T,path:v.cwd}:null}),A.notify(R==="entered"?`isolated in ${T??"a workspace"}`:"returned to source tree",2e3)},Sl=()=>{Tt===null&&(Tt=setInterval(async()=>{try{let w=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!w.ok)return;let v=await w.json();v.forkSynthesisState===void 0?(A.setSynthesisIndicator(null),A.notify("synthesis complete",2e3),Tt!==null&&(clearInterval(Tt),Tt=null)):v.forkSynthesisState==="failed"&&(A.setSynthesisIndicator("\u26A0 synthesis failed"),A.notify("synthesis failed \u2014 fork still usable via recall",8e3),Tt!==null&&(clearInterval(Tt),Tt=null))}catch{}},5e3))},fd=()=>{Tt!==null&&(clearInterval(Tt),Tt=null)},wo=()=>{Me!==null&&(clearInterval(Me),Me=null)},On=()=>{if(Me!==null)return;let w=!1;Me=setInterval(async()=>{if(!(w||I)){w=!0;try{let v=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!v.ok){v.status===404&&wo();return}if((await v.json()).status!=="warm")return;wo(),we({src:"cold-watch",step:"warm-detected",sessionId:me}),b&&await b({skipInitialize:!0,beforeReplay:()=>{X?.appendLines([{prefix:" ",body:"-- session resumed by another client, catching up --",bodyStyle:"muted"}])}})}catch{}finally{w=!1}}},WV)},Hf=w=>{let v=w??{},R=typeof v.toolCallId=="string"?v.toolCallId:void 0,O;v.outcome&&typeof v.outcome=="object"?O=v.outcome:typeof v.chosenOptionId=="string"&&(O={kind:"selected",optionId:v.chosenOptionId}),wn(R,O?{outcome:O}:void 0)},Xe=null,wn=(w,v)=>{if(!Xe||Xe.toolCallId&&w&&Xe.toolCallId!==w)return;let R=Xe.resolve;Xe=null,A.setPermissionPrompt(null),R(v??{outcome:{outcome:"cancelled"}})},Ji=w=>{if(!Xe?.toolCallId)return;let v=w??{};v.sessionUpdate!=="tool_call"&&v.sessionUpdate!=="tool_call_update"||v.toolCallId===Xe.toolCallId&&(!v.status||v.status==="pending"||wn(v.toolCallId,void 0))},Vi=()=>{if(!Xe){A.setPermissionPrompt(null);return}A.setPermissionPrompt({title:Xe.title,detail:Xe.detail,options:Xe.options.map(w=>({label:w.name})),selectedIndex:Xe.selectedIndex})},bo=w=>{if(!Xe)return;let{options:v,resolve:R}=Xe;if(Xe=null,A.setPermissionPrompt(null),w===null){R({outcome:{outcome:"cancelled"}});return}R({outcome:{outcome:"selected",optionId:w}})};y.onRequest("session/request_permission",async w=>{if(I)return{outcome:{outcome:"cancelled"}};if(r.dangerouslySkipPermissions)return Qa(w);let v=w??{},O=(Array.isArray(v.options)?v.options:[]).map(le=>({optionId:le.optionId,name:ot(le.name??""),...le.kind!==void 0?{kind:le.kind}:{}})),T=v.toolCall?.title??v.toolCall?.name??"tool",L=ot(T),B=ot(JP(GP(w))),ne=v.toolCall?.toolCallId;return O.length===0?(A.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${L} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(le=>{Xe={title:L,detail:B,options:O,selectedIndex:0,resolve:le,toolCallId:ne},Vi()})}),y.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let Yi,pd,Rn=!0,Ps=!1,Qr=!1;try{let w=await y.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:Fe}});pd=w?.agentInfo?.name,w?.agentCapabilities?.promptCapabilities?.image===!1&&(Rn=!1),Ps=Pn(w?._meta??void 0).prompt?.amending===!0,Qr=w?._meta?.steering?.supported===!0}catch{}let me=d.sessionId,Rt=d.agentId,rt=d.cwd,Xt;t.isLocal||(d.remote=t.display);let Bf=d.remote,Zt=pl(d),bn=null,ko=()=>(bn===null&&(bn=EV(qi.join(_V(),"hydra-remote-exec-"))),bn),ei=()=>Zt?ko():rt,xl=d.jumpToRecordedAt,Ms,Fn,_s,kn,hd,md,gd,ti,yd,xr,ni,Qi,Il=!1;if(d.sessionId==="__new__"){let w={};r.agentId&&(w.agentId=r.agentId),r.name&&(w.title=r.name),r.model&&(w.model=r.model),r.workspace===!0&&(w.workspace={});let v={cwd:d.cwd,...Object.keys(w).length>0?{_meta:{[pt]:w}}:{}},R;try{R=await FP({request:()=>y.request("session/new",v),showBanner:(L,B,ne)=>LP(n,L,B,ne,{authenticate:le=>y.request("authenticate",{methodId:le,_meta:{[pt]:{agentId:L}}})}),resolveOnboarding:async L=>{if(L)try{return(await Ua(t)).find(le=>le.id===L)?.onboarding}catch{return}},fallbackAgentId:r.agentId})}catch(L){n.grabInput(!1),we({src:"grab",site:"runSession.session-new-failed",on:!1}),h.close().catch(()=>{});let B=L instanceof Error?L.message:String(L);we({src:"session-new-failed",agentId:r.agentId??null,message:B});let ne=await nO(n,r.agentId,B,{canGoBack:!r.forceNew});if(ne==="cancel")return null;let le={...r};return delete le.sessionId,delete le.resume,ne==="retry"?le.forceNew=!0:(delete le.forceNew,delete le.agentId),le}if(R.kind==="cancel")return n.grabInput(!1),we({src:"grab",site:"runSession.auth-cancel",on:!1}),h.close().catch(()=>{}),null;if(R.kind==="back"){n.grabInput(!1),we({src:"grab",site:"runSession.auth-back",on:!1}),h.close().catch(()=>{});let L={...r};return delete L.sessionId,delete L.forceNew,delete L.resume,delete L.agentId,L}let O=R.result;f.write(l),me=O.sessionId,gS(me),s.sessionId=me,s.readonly=!1;let T=Pn(O._meta??void 0);T.clientId&&(Ms=T.clientId),Yi=T.upstreamSessionId,T.agentId&&(Rt=T.agentId),T.cwd&&(rt=T.cwd),Fn=T.workspaceInfo,T.title&&(Xt=T.title),_s=T.currentModel,kn=T.currentMode,yd=T.currentUsage,xr=T.turnStartedAt,ni=T.armedSince,Qi=T.armedTaskList,T.availableCommands&&(hd=Jp(T.availableCommands)),T.availableModes&&(md=T.availableModes),gd=qO(O.configOptions),ti=T.queue}else{let w={};r.readonly===!0&&(w.readonly=!0),e.tui.toolContent==="references"&&(w.toolContent="references"),r.drip===!0&&(w.replayMode="drip",r.dripSpeed!==void 0&&(w.dripSpeed=r.dripSpeed)),d.resumeHint!==void 0&&(w.resume={upstreamSessionId:d.resumeHint.upstreamSessionId,agentId:d.resumeHint.agentId,cwd:d.resumeHint.cwd});let v=await y.request("session/attach",{sessionId:d.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:Fe},...Object.keys(w).length>0?{_meta:{[pt]:w}}:{}});me=v.sessionId,gS(me),v.clientId&&(Ms=v.clientId),s.sessionId=me,s.readonly=r.readonly===!0;let R=Pn(v._meta??void 0);Il=R.resurrected===!0,Yi=R.upstreamSessionId,R.agentId&&(Rt=R.agentId),R.cwd&&(rt=R.cwd),Fn=R.workspaceInfo,R.title&&(Xt=R.title),_s=R.currentModel,kn=R.currentMode,yd=R.currentUsage,xr=R.turnStartedAt,ni=R.armedSince,Qi=R.armedTaskList,R.availableCommands&&(hd=Jp(R.availableCommands)),R.availableModes&&(md=R.availableModes),gd=qO(v.configOptions),ti=R.queue}let $s=D.tuiHistoryFile(me),Uf=D.globalTuiHistoryFile(),Ne=await Pu($s).catch(()=>[]),Ln=await Pu(Uf).catch(()=>[]);Ln.length>e.tui.promptHistoryMaxEntries&&(Ln=Ln.slice(Ln.length-e.tui.promptHistoryMaxEntries));let Jn=[...Ne],Le=new Vo({history:Eh(Ln,Jn)});Et=Le;let Wf=!1,Xr=()=>{X?.setBanner({hintsExhausted:jA(Ne.length,e.tui.composer.hintTurns)})},cn=(w,v)=>{let R=w.replace(/\n+$/,"");if(R.length===0)return;let O=(v??w).replace(/\n+$/,""),T=Mu(Ne,R),L=T!==Ne;Ne=T,Jn=Mu(Jn,O);let B=Mu(Ln,R,e.tui.promptHistoryMaxEntries),ne=B!==Ln;Ln=B,Le.setHistory(Eh(Ln,Jn)),L&&Ta($s,Ne).catch(()=>{}),ne&&qA(Uf,R).catch(()=>{}),Xr(),X?.clearHintReveal()};z>0&&Le.setTurnRunning(!0);let Zr=[],vo=null;$$(O$(e.tui.ambiguousWidth,process.env,YO)),qE(e.tui.diffContextLines);let Os=!1,A,jf=()=>{Os&&(Os=!1,A.start())},Cl=()=>{Os||(Os=!0,A.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",jf);let qf=jV(e.tui.openFileCommand);A=new jg({term:n,dispatcher:Le,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:o.mouseEnabled,inAppSelection:o.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,openFileCommand:qf?.argv,openFileSource:qf?.source,openFileInTerminal:e.tui.openFileInTerminal,progressIndicator:e.tui.progressIndicator,readonly:r.readonly===!0,onSidebarCollapseChange:(w,v)=>{o.sidebarCollapsed=X?.sidebarCollapsedIds()??[],!v&&(w==="git"?Dl():w==="sessions"?vy():w==="resources"&&Mx(),Bl())},onSuspend:process.platform!=="win32"?Cl:void 0,onLayoutChange:()=>{Rx()},onBlockClick:(w,v,R)=>{DF(w,v,R)},onHydraLinkClick:w=>(Xf(w),!0),onBlockVisible:w=>{RF(w)},onHoverRun:w=>{if(!w.startsWith("thought:"))return null;let v=ce.get(w);if(v!==void 0&&v.length>0)return new Set(v);let R=A.contiguousRun(w,new Set(at.keys()));return R.length>0?new Set(R):null},onBarAction:(w,v)=>{if(w==="toggle-mode"){er(!0);return}if(w==="rename-session"){Pd(v);return}if(w==="choose-model"){se("model");return}if(w==="choose-agent"){se("agent");return}if(w==="choose-mode"){se("mode");return}if(w==="choose-config"){se(v);return}let R=w==="switch-session"?{type:"switch-session"}:w==="detach"?{type:"exit"}:w==="toggle-options"?{type:"toggle-options"}:{type:"show-help"};r.readonly===!0&&ox(R)||Ar(R)},onFormClick:w=>ta(w),onPermissionClick:w=>Pt(w),onCompactionClick:w=>Rd(w),onHelpClick:()=>A.setHelpPrompt(null),onMouse:w=>{if(w.kind!=="press"||w.button!=="middle")return;let v={type:"attachment-request",source:"primary"};r.readonly===!0&&ox(v)||Ar(v)},onKey:w=>{for(let v of w){if(re&&Ro(v)){v.type==="key"&&we({src:"key-swallowed",site:"compactionPrompt",name:v.name});continue}if(Xe&&Jf(v)){v.type==="key"&&we({src:"key-swallowed",site:"permission",name:v.name});continue}if(Zi(v)){v.type==="key"&&we({src:"key-swallowed",site:"help",name:v.name});continue}if(ci(v)){v.type==="key"&&we({src:"key-swallowed",site:`form:${Vt??"none"}`,name:v.name});continue}if(kd(v)){v.type==="key"&&we({src:"key-swallowed",site:"scrollbackSearch",name:v.name});continue}if(Kf(v)){v.type==="key"&&we({src:"key-swallowed",site:"completion",name:v.name});continue}if(Gf(v)){v.type==="key"&&we({src:"key-swallowed",site:"btwClose",name:v.name});continue}if(v.type==="key"&&v.name==="escape"&&A.isScrolledBack()){A.scrollToBottom();continue}if(v.type==="attachment-paths"){Zf(v.paths);continue}if(v.type==="key"&&Vf(v.name)){we({src:"key-swallowed",site:"userHotkey",name:v.name});continue}let R=Le.feed(v);for(let O of R)r.readonly===!0&&ox(O)||Ar(O)}Rl(),A.setBannerSearchIndicator(Le.state().historySearchQuery),A.setAttachments(Le.state().attachments),A.refreshPrompt()}}),X=A,A.setStickyBottomKey("plan");let zf=[{name:"/help",description:"Show TUI built-in commands"},{name:"/quit",description:"Exit the TUI"},{name:"/clear",description:"Clear scrollback"},{name:"/sessions",description:"List sessions"},{name:"/resume",description:"Switch sessions (open the picker)"},{name:"/session",description:"Switch session: /session <id|next|prev> (no arg opens picker)"},{name:"/rename",description:"Rename this session (alias for /hydra title): /rename [title]"},{name:"/title",description:"Rename this session: /title [title] (no arg opens the field)"},{name:"/model",description:"Switch model: /model [model-id] (no arg opens the picker)"},{name:"/mode",description:"Switch mode: /mode [mode-id] (no arg opens the picker)"},{name:"/agent",description:"Switch agent: /agent [agent-id] (no arg opens the picker)"},{name:"/btw",description:"Run an ancillary forked session: /btw <prompt> (no args toggles the last overlay)"},{name:"/export",description:"Export this session as a markdown transcript: /export [path]"}],wd=hd??[],ri=md??[],es=gd??[],dy=()=>{let w=new Set,v=[];for(let R of[...zf,...wd])w.has(R.name)||(w.add(R.name),v.push(R));return v},bd=()=>{let w=Le.state().buffer,v=w[0]??"";if(!v.startsWith("/"))return[];if(w.length>1)return[];let R=v.indexOf(" "),O=R===-1?v:v.slice(0,R);if(O.lastIndexOf("/")>0)return[];let T=dy().filter(L=>L.name.startsWith(O));return T.length===1&&T[0]?.name===O?[]:T},So=[],Rl=()=>{let w=bd();if(w.length>0){So=[],A.setCompletions(w);return}A.setCompletions(So)},Kf=w=>{if(w.type!=="key"||w.name!=="tab")return So.length>0&&(So=[]),!1;let v=bd();if(A.isOverlayOpen()&&v.length===0)return A.toggleFocusedPane(),!0;if(v.length>0){So=[];let R=Le.state().buffer[0]??"",O=U$({matches:v.map(T=>T.name),firstLine:R});return O===null||Le.replaceFirstLine(O),!0}return Al()},Al=()=>{if(Zt)return!1;let w=Le.state(),v=w.buffer[w.row]??"",R=Gg(v,w.col);if(R===null)return!1;let O=Jg(R.token,rt);return O===null?!1:(O.replacement!==R.token&&Le.replaceRangeOnCurrentLine(R.start,w.col,O.replacement),So=O.candidates.length>1?O.candidates.map(T=>({name:T})):[],!0)},Gf=w=>!A.isOverlayOpen()||w.type!=="key"||w.name!=="escape"&&w.name!=="ctrl-c"?!1:(M&&(M.cancel(),M=null,F=null),A.closeBtwOverlay(),!0),kd=w=>{if(!A.isScrollbackSearchActive())return w.type==="key"&&w.name==="ctrl-r"&&A.isScrolledBack()?(A.enterScrollbackSearch(),A.updateScrollbackSearchTerm(""),!0):!1;if(w.type==="char"){let v=A.scrollbackSearchTerm()+w.ch;return A.updateScrollbackSearchTerm(v),!0}if(w.type==="paste"){let v=A.scrollbackSearchTerm()+w.text.replace(/\n/g," ");return A.updateScrollbackSearchTerm(v),!0}if(w.type==="key")switch(w.name){case"ctrl-r":return A.advanceScrollbackSearch(),!0;case"ctrl-s":return A.retreatScrollbackSearch(),!0;case"backspace":{let v=A.scrollbackSearchTerm();return v.length===0?A.cancelScrollbackSearch():A.updateScrollbackSearchTerm(v.slice(0,-1)),!0}case"enter":return A.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return A.cancelScrollbackSearch(),!0;default:return!0}return!0},Pt=w=>{if(!Xe)return;let v=Xe.options;if(w.kind==="hint"){if(w.action==="cancel"){bo(null);return}bo(v[Xe.selectedIndex]?.optionId??null);return}let R=v[w.index];if(R){if(w.select===!0){Xe.selectedIndex=w.index,Vi();return}bo(R.optionId)}},Jf=w=>{if(!Xe)return!1;let v=Xe.options;if(w.type==="key")switch(w.name){case"up":return Xe.selectedIndex=Math.max(0,Xe.selectedIndex-1),Vi(),!0;case"down":return Xe.selectedIndex=Math.min(v.length-1,Xe.selectedIndex+1),Vi(),!0;case"enter":{let R=v[Xe.selectedIndex];return R&&bo(R.optionId),!0}case"escape":case"ctrl-c":return bo(null),!0;default:return!0}if(w.type==="char"&&/^[1-9]$/.test(w.ch)){let R=parseInt(w.ch,10)-1,O=v[R];return O&&bo(O.optionId),!0}return!0},Vf=w=>{let v=e.tui.hotkeys[w];return v?(Vg(v,{sessionId:me,cwd:ei(),agentId:Rt||pd||"",baseUrl:t.baseUrl,tokenFile:D.authToken()},{notify:R=>A.notify(R),cwd:ei(),emitLines:R=>{A.appendLines(R.map(O=>{let T;switch(O.style){case"meta":T="muted";break;case"stderr":case"error":T="tool-status-fail";break;default:T="notice"}return{prefix:" ",body:O.text,bodyStyle:T}}))}}),!0):!1},vd=()=>Rt||pd||"?",Nn=vd(),Vn={...yd??{}};f.finalize(),A.start({skipFullscreen:!0}),A.setHideThoughts(!o.showThoughts),A.setBarConfig({composer:e.tui.composer,sessionbar:e.tui.sessionbar});let It=VS(vf({composer:e.tui.composer,sessionbar:e.tui.sessionbar}),e.tui.scriptRefreshMs),Yn=w=>{let v=a.get(w);if(v===void 0)return;let R={HYDRA_ACP_TOKEN:v,HYDRA_ACP_DAEMON_URL:t.baseUrl};return me!==null&&(R.HYDRA_ACP_SESSION_ID=me),R};if(It.size>0){let w=sO({cwd:ei,envFor:Yn,onOutput:(v,R)=>A.setScriptOutput(v,R)});Jt=setInterval(()=>{w.poll(It,Date.now())},1e3),Jt.unref?.(),w.poll(It,Date.now())}let xo=lS(e.tui.sidebar.gadgets);A.setSidebarProcessGadgets(_g(xo)),A.setSidebarGadgets(xo.map(Mg));let Tl=sS(xo,e.tui.scriptRefreshMs),Io=new Map;for(let w of _g(xo)){let v=Io.get(w.script)??[];v.push(w.id),Io.set(w.script,v)}let Sd=()=>{let w=new Map;for(let[v,R]of Tl)(Io.get(v)??[]).some(T=>A.isSidebarGadgetActive(T))&&w.set(v,R);return w};if(Tl.size>0){let w=Zg({cwd:ei,envFor:Yn,sanitize:N_,onOutput:(v,R)=>A.setProcessOutput(v,R)});Ye=setInterval(()=>{w.poll(Sd(),Date.now())},1e3),Ye.unref?.(),w.poll(Sd(),Date.now())}Xr(),A.setSidebarWidth(e.tui.sidebar.width??null),A.setSidebarBorder(e.tui.sidebar.border),A.setSidebarSnapshot({usage:{...Vn},model:_s??null,mode:kn??null,configOptions:jO(es),sessionId:me===null?null:Qe(me),host:me===null?null:eo(me)?.name??null,agent:Nn,workspace:Fn===void 0?null:{label:Fn.label,path:Fn.path}}),A.setSessionbar({agent:Nn,cwd:rt,remote:Bf,...Fn===void 0?{}:{workspace:{label:Fn.label,path:Fn.path,sourceCwd:Fn.sourceCwd}},sessionId:me,title:Xt,model:_s,usage:{...Vn}}),kn&&A.setBanner({currentMode:kn}),df().then(w=>{w&&A.notify(`\u2728 ${cf(w)}`,3e4)}).catch(()=>{});let ln=null,si=new Promise(w=>{ln=w}),Co=()=>{if(y.notify("session/cancel",{sessionId:me}).catch(()=>{}),or===null){let w=Date.now();or=setTimeout(()=>{or=null,z!==0&&(Wt>=w||it||(it=!0,X?.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"cancel not acknowledged by agent; the turn is still running. Cancel again to force-stop (restarts the agent).",bodyStyle:"tool-status-fail"}])))},ud)}},Xi=()=>{it=!1,X!==null&&X.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"force-stopping agent \u2014 turn aborted; resumes on your next message\u2026",bodyStyle:"tool-status-fail"}]),y.request("hydra-acp/session/force_cancel",{sessionId:me}).catch(()=>{})},xd=()=>{X!==null&&z===1&&(Q=!0,X.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},El=()=>{let w=Zr[0];if(w){w.cancel(),xd();return}if(z>0){it?Xi():Co(),xd();return}Pl()},Pl=()=>{_d(0)},cy=()=>{let w="enqueue prompt (sends now, or queues during a turn)",v="amend the in-flight turn (cancel + replace)";return[...o.defaultEnterAction==="amend"?[["Enter",v],["Ctrl+Enter / Shift+Enter / ^S",w]]:[["Enter",w],["Ctrl+Enter / Shift+Enter / ^S",v]],...qV]},Yf=()=>{if(A.isHelpPromptActive()){A.setHelpPrompt(null);return}A.setHelpPrompt({title:`Hotkeys \xB7 hydra-acp v${Fe}`,entries:cy(),hint:"any key dismisses \xB7 /help lists commands"})},Id=()=>{re=!1,A.setCompactionPrompt(null),A.setCompactionIndicator("compaction queued...");let w=me;fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(w)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}}).catch(()=>{})},Fs=()=>{re=!1,A.setCompactionPrompt(null)},Cd=w=>{let v=A.compactionPromptSpec();if(!v)return;let R=v.options.length;if(R===0)return;let O=((v.selectedIndex+w)%R+R)%R;O!==v.selectedIndex&&A.setCompactionPrompt({...v,selectedIndex:O})},Rd=w=>{if(!re)return;let v=A.compactionPromptSpec();if(!v)return;if(w.kind==="hint"){if(w.action==="cancel"){Fs();return}v.options[v.selectedIndex]?.key==="y"?Id():Fs();return}let R=v.options[w.index];if(R){if(w.select===!0){w.index!==v.selectedIndex&&A.setCompactionPrompt({...v,selectedIndex:w.index});return}R.key==="y"?Id():Fs()}},Ro=w=>{if(!re)return!1;if(w.type==="key"){if(w.name==="escape")return Fs(),!0;if(w.name==="up")return Cd(-1),!0;if(w.name==="down")return Cd(1),!0;if(w.name==="enter"){let v=A.compactionPromptSpec();return v?.options[v.selectedIndex]?.key==="y"?Id():Fs(),!0}}if(w.type==="char"){let v=w.ch.toLowerCase();if(v==="y"||v==="1")return Id(),!0;if(v==="n"||v==="2")return Fs(),!0}return!0},Zi=w=>A.isHelpPromptActive()?(w.type==="key"&&w.name==="ctrl-g",A.setHelpPrompt(null),!0):!1,Ls=["tools","plan","thoughts","diffs","mouse","enter","sidebar","theme"],Ns=0,ir=null,oi=[],Ao=[],Qn=[],Ds=0,Vt=null,Ir=null,Cr=(w,v)=>{w!=="chooser"&&(P=null),Vt=w,Ir=v,A.setFormPrompt(KM(v))},Xn=w=>{Vt===w&&(Vt=null,Ir=null,P=null,_=new Map,A.setFormPrompt(null))},To=w=>{switch(w){case"tools":return o.toolsExpanded?"expanded":"collapsed";case"plan":return o.planExpanded?"expanded":"collapsed";case"thoughts":return o.showThoughts?"shown":"hidden";case"diffs":return o.showFileUpdates;case"mouse":return o.mouseEnabled?"on":"off";case"enter":return o.defaultEnterAction;case"sidebar":return A.isSidebarVisible()?"shown":"hidden";case"theme":return ld}},Ad=w=>{switch(w){case"tools":return"Tools";case"plan":return"Plan";case"thoughts":return"Thoughts";case"diffs":return"File updates";case"mouse":return"Mouse capture";case"enter":return"Enter key";case"sidebar":return"Sidebar";case"theme":return"Theme"}},Qf=()=>({title:"Session options",rows:Ls.map(w=>({id:w,kind:"select",label:Ad(w),value:To(w)})),cursor:Ns,hints:[{label:"\u2191/\u2193 row"},{label:"\u2190/\u2192 cycle"},{label:"\u23CE next",action:"commit"},{label:"s save default",action:"save"},{label:"Esc close",action:"close"}]}),ly=()=>{Vt==="options"&&Cr("options",Qf())},ts=()=>{if(Vt==="options"){Xn("options");return}Ns=0,Cr("options",Qf())},Td=()=>{ir!==null&&Cr("questions",eF(ir,oi,Qn,Ds))},ns=()=>{ir=null,oi=[],Ao=[],Qn=[],Ds=0,Xn("questions")},ii=async()=>{if(ir!==null){ns();return}try{let v=await y.request(HM,{sessionId:me}),R=LV(v.questions??[]);if(R.length===0){A.notify("no open questions");return}let O=DV(R);ir=O,Ds=0,oi=O.map(T=>NV(T.representative)),Ao=O.map(()=>!1),Qn=O.map(()=>!1),Td()}catch(w){A.notify("clarifier unavailable"),we({src:"questions",step:"list_failed",error:w.message})}},Ml=()=>{let w=ry.find(R=>R.name===ld);if(w===void 0)return;Aw(w.palette,{...w.overrides,background:Vr,foreground:XO}),Cx(),hy(),wy(),os(),A.fullRedraw();let v=ex(w.palette,ld,Vr);v!==void 0&&A.notify(v)},uy=(w=1)=>{if(ry.length===0){A.notify("no themes available");return}let v=wO(ry.map(R=>R.name),ld,w);v!==void 0&&(ld=v,Ml())},Dn=null,ai=w=>{Dn!==null&&(clearTimeout(Dn),Dn=null),e.tui.themeBackground===void 0&&(Vr!==void 0&&Vr.kind==="rgb"&&w.kind==="rgb"&&Vr.r===w.r&&Vr.g===w.g&&Vr.b===w.b||(Vr=w,Ml()))};QO=w=>{e.tui.themeBackground===void 0&&(Dn!==null&&clearTimeout(Dn),Dn=setTimeout(()=>{Dn=null,ai(y$(w))},200),Dn.unref?.(),be("\x1B]11;?\x07"))},ZO=ai;let di=(w,v=1)=>{switch(w){case"tools":o.toolsExpanded=!o.toolsExpanded,_e.clear(),Be.clear(),hy();break;case"plan":o.planExpanded=!o.planExpanded,dt=null,os();break;case"thoughts":o.showThoughts=!o.showThoughts,A.setHideThoughts(!o.showThoughts);break;case"diffs":o.showFileUpdates=o.showFileUpdates==="diff"?"edit":"diff",Mo.clear(),wy();break;case"mouse":{let R=!A.isMouseEnabled();A.setMouseEnabled(R),o.mouseEnabled=R;break}case"enter":o.defaultEnterAction=o.defaultEnterAction==="amend"?"enqueue":"amend";break;case"sidebar":Ay(!A.isSidebarVisible());break;case"theme":uy(v);break}ly()},rs=w=>{(async()=>{try{switch(w){case"tools":case"plan":A.notify(`${Ad(w)} is session-only \u2014 not saved`);return;case"thoughts":await ua("showThoughts",o.showThoughts);break;case"diffs":await ua("showFileUpdates",o.showFileUpdates);break;case"mouse":await ua("mouse",o.mouseEnabled);break;case"enter":await ua("defaultEnterAction",o.defaultEnterAction);break;case"sidebar":await jy(A.isSidebarVisible());break;case"theme":await ua("theme",ld);break}A.notify(`saved default: ${Ad(w)} ${To(w)}`)}catch(v){A.notify(`save failed: ${v instanceof Error?v.message:String(v)}`)}})()},ea=w=>{let v=R=>Ls[R];switch(w.type){case"row":{Ns=w.row;let R=w.viaDigit===!0?v(w.row):void 0;R?di(R):ly();return}case"cycle":{let R=v(w.row);R&&(Ns=w.row,di(R,w.delta));return}case"advance":{let R=v(w.row);R&&di(R);return}case"save":{let R=v(w.row);R&&rs(R);return}case"close":case"cancel":Xn("options");return;default:return}},ar=(w,v)=>{if(w.type==="key"){if(w.name==="ctrl-o")return Xn("options"),!0;if(w.name==="ctrl-d")return Xn("options"),!1}return ea(gf(v,w)),!0},Ed="title",_l=(w,v)=>{let R=w.rows.find(O=>O.id===v);return R?.kind==="text"?R.editor.text:""},Pd=w=>{if(Vt!=="title"){if(r.readonly===!0){A.notify("view-only: rename disabled");return}if(me==="__new__"){A.notify("no active session to rename");return}Cr("title",JM({title:"Rename session",id:Ed,label:"title:",initial:w,hints:[{label:"\u23CE save",action:"commit"},{label:"Esc cancel",action:"close"}]}))}},$l=w=>{let v=_l(w,Ed).trim(),R=me;Xn("title"),v.length!==0&&Ju(t,R,v).catch(O=>{A.notify(`rename failed: ${O.message}`)})},Ol=(w,v)=>{switch(v.type){case"commit":$l(w);return;case"close":case"cancel":Xn("title");return;case"edited":Cr("title",w);return;default:return}},Md=(w,v)=>(Ol(v,gf(v,w)),!0),P=null,_=new Map,W=(w,v)=>{let R=w.options.find(L=>L.value===v);if(R)return R.value;let O=v.toLowerCase(),T=w.options.filter(L=>L.value.toLowerCase().startsWith(O));return T.length===1?T[0].value:null},J=w=>{if(r.readonly===!0)return A.notify(`view-only: ${w} switching disabled`),null;if(me==="__new__")return A.notify("no active session yet"),null;let v=es.find(R=>R.id===w);return!v||v.options.length===0?(A.notify(`no ${w} option advertised for this session`),null):v},se=w=>{if(Vt==="chooser"&&P?.kind==="values"&&P.configId===w)return;let v=J(w);v&&(P={kind:"values",configId:w},Cr("chooser",jM(v)))},ae=()=>{if(es.length===0){A.notify("no config options advertised for this session");return}P={kind:"index"},_=new Map,Cr("chooser",Ov(es,_))},ge=w=>{Cr("chooser",{...Ov(es,_),cursor:w})},ut=()=>{let w=new Map(es.map(v=>[v.id,v.currentValue]));for(let[v,R]of _)w.get(v)!==R&&St(v,R);_=new Map},St=(w,v)=>{A.notify(`switching ${w} to ${v}\u2026`),y.request("session/set_config_option",{sessionId:me,configId:w,value:v}).catch(R=>{A.notify(`${w} switch failed: ${R instanceof Error?R.message:String(R)}`)})},en=(w,v)=>{(async()=>{try{if(w==="agent")await hi(v);else{let R=Rt||pd||"";if(!R){A.notify(`can't save a ${w} default without an agent`);return}await Jl(R,w,v)}A.notify(`saved default: ${w} ${v}`)}catch(R){A.notify(`save failed: ${R instanceof Error?R.message:String(R)}`)}})()},tn=(w,v)=>{let R=P;if(R===null)return;let O=B=>w.rows[B]?.id,T=B=>{let ne=O(B);return ne===void 0?void 0:es.find(le=>le.id===ne)},L=B=>_.get(B.id)??B.currentValue;switch(v.type){case"row":Cr("chooser",{...w,cursor:v.row});return;case"cycle":{let B=T(v.row);if(!B)return;_.set(B.id,qM(B,L(B),v.delta)),ge(v.row);return}case"advance":ut(),Xn("chooser");return;case"commit":{let B=O(v.row);if(R.kind!=="values"||B===void 0)return;Xn("chooser"),St(R.configId,B);return}case"save":{if(R.kind==="values"){let ne=O(v.row);ne!==void 0&&(en(R.configId,ne),Xn("chooser"),St(R.configId,ne));return}let B=T(v.row);if(B){let ne=L(B);en(B.id,ne),ne!==B.currentValue&&St(B.id,ne)}return}case"close":_=new Map,Xn("chooser");return;case"cancel":_=new Map,Xn("chooser");return;default:return}},zt=(w,v)=>P===null?!1:(tn(v,gf(v,w)),!0),ci=w=>{let v=Ir;if(Vt===null||v===null)return!1;switch(Vt){case"questions":return Fl(w);case"options":return ar(w,v);case"title":return Md(w,v);case"chooser":return zt(w,v)}},ta=w=>{let v=Ir;if(!(Vt===null||v===null))for(let R of GM(v,w))switch(Vt){case"options":ea(R);break;case"title":Ol(v,R);break;case"chooser":tn(v,R);break;case"questions":li(ir===null?{type:"noop"}:nF(R,ir,oi,Ao,Qn,me));break}},li=w=>{switch(w.type){case"noop":return;case"row":Ds=w.selectedRow,Td();return;case"cycle":Ds=w.selectedRow,oi[w.selectedRow]=w.newValueIndex,Ao[w.selectedRow]=!0,Qn[w.selectedRow]=!1,Td();return;case"dismiss-toggle":{let v=w.selectedRow;Qn[v]?(Qn[v]=!1,Ao[v]=!1):(Qn[v]=!0,Ao[v]=!0),Td();return}case"discard":ns();return;case"save":{let v=w.dispatches;if(ns(),v.length===0)return;(async()=>{let R=0,O=0,T=0;for(let B of v)try{await y.request(B.method,B.params),B.type==="dismiss"?O++:R++}catch(ne){T++,we({src:"questions",step:"dispatch_failed",method:B.method,error:ne.message})}let L=[];R>0&&L.push(`${R} answered`),O>0&&L.push(`${O} dismissed`),T>0&&L.push(`${T} failed`),L.length>0&&A.notify(`clarifier: ${L.join(", ")}`)})();return}}},Fl=w=>ir===null?!1:(li(UV(w,!0,ir,oi,Ao,Qn,Ds,me)),!0),na=()=>{if(!I){I=!0,M?(M.cancel(),M=null,F=null):F!==null&&(co(t,F).catch(()=>{}),F=null),process.off("SIGINT",El),process.platform!=="win32"&&process.off("SIGCONT",jf),oe!==null&&(clearInterval(oe),oe=null),Tt!==null&&(clearInterval(Tt),Tt=null),wo();for(let w of Es.values())clearTimeout(w);Es.clear(),$x(),_x(),Jt!==null&&(clearInterval(Jt),Jt=null),Ye!==null&&(clearInterval(Ye),Ye=null),bn!==null&&(MV(bn,{recursive:!0,force:!0}),bn=null),A.clearWindowTitle(),A.stop({keepFullscreen:!0}),Ta($s,Ne).catch(()=>{}),h.close().catch(()=>{})}},_d=(w=0)=>{na(),ln&&(ln(null),ln=null),w!==0&&process.exit(w)},Rr=async()=>{if(we({src:"switch-session",step:"entered",finishSessionNull:ln===null}),!ln)return;M?(M.cancel(),M=null,F=null):F!==null&&(co(t,F).catch(()=>{}),F=null),fd(),wo(),A.setSynthesisIndicator(null);let w=Le.state().buffer.join(`
304
+ `)}}function YV(n){let{order:e,states:t,startedAt:r,endedAt:s,stopReason:o,perToolExpanded:i,collapsedLimit:a=20}=n,d=e.filter(F=>!Fc(F,t.get(F)?.latestTitle)),c=d.length,l=a>0,u;if(!l||n.expanded)u=d;else{let F=Math.max(0,c-a),K=d.slice(F),Y=[];for(let z=0;z<F;z++){let re=d[z];if(re===void 0)continue;let Q=t.get(re);Q&&!qk(Q.status)&&Y.push(re)}u=[...Y,...K]}let f=c-u.length,p=s===null,m=s??Date.now(),b=m-r,g=!p&&o!==null&&o!=="end_turn"?o:null,h=g==="amended",y=h?`amended \xB7 ${jr(b)}`:`stopped (${g}) \xB7 ${jr(b)}`,k=p?"":` \xB7 ${Dm(m)}`,S;if(c===0)g!==null?S=y+k:S=p?`thinking \xB7 ${jr(b)}`:`thought \xB7 ${jr(b)}${k}`;else{let F=c===1?"tool":"tools",K=g!==null?y:p?jr(b):`took ${jr(b)}`,Y=[`${c} ${F}`,K];p&&Y.push(`started ${Dm(r)}`),p&&l&&f>0&&Y.push(`${f} hidden`),S=Y.join(" \xB7 ")+k}let I=c===0&&p;if(I)return{lines:[{body:""}],rowOwners:[null]};let x=h?"tool-status-cancelled":"tool-status-fail",P=[{prefix:"\u2699 ",prefixStyle:I?"tool-status-running":g!==null?x:"tool",body:S,bodyStyle:I?"tool-status-running":g!==null?x:"status-idle"}],M=[null];for(let F of u){let K=t.get(F);if(K){let Y=ef(K,m),z=i?.has(F)??!1;for(let re of Y)re.hoverSubKey=F,z||(re.maxWrapRows=VV);if(P.push(...Y),M.push(...Y.map(()=>F)),z){let re=WE(K);for(let Q of re)Q.hoverSubKey=F;P.push(...re),M.push(...re.map(()=>F))}}}return{lines:P,rowOwners:M}}async function QV(n,e,t,r,s,o,i,a){if(r.terminalHostLauncher&&r.sessionId===void 0&&r.forceNew!==!0&&r.resume!==!0)for(;;){let w=await GO(n,e,t,r,i,o);if(!w)return n.grabInput(!1),null;w.installStatus?.finalize();let v=await ix(w.sessionId==="__new__"?{kind:"new",...r.cwd!==void 0?{cwd:r.cwd}:{},...w.agentId?{agentId:w.agentId}:{},...r.model!==void 0?{model:r.model}:{},...r.initialPrompt!==void 0?{prompt:r.initialPrompt}:{}}:{kind:"attach",sessionId:w.sessionId},[],w.cwd);H(n,"content",`${v}
305
+ `),w.sessionId!=="__new__"&&(r.pickerSelect=w.sessionId),delete r.initialPrompt,delete r.initialAttachments}let d=await GO(n,e,t,r,i,o);if(!d)return n.grabInput(!1),we({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let c=d.resolved?.status==="warm"&&t.isLocal,l=d.sessionId==="__new__"?"Starting new session\u2026":d.isFreshFork?"Forking session\u2026":d.resolved?.status==="warm"?"Attaching to session\u2026":"Resuming session\u2026",u=r.installStatus;r.installStatus&&delete r.installStatus;let f=d.installStatus??u??Yg(c?"":l,K$(n));c||f.write(l);let p=t.isLocal?async()=>(await an(await He())).wsUrl:t.wsUrl,m=t.isLocal?async()=>["acp.v1",`hydra-acp-token.${(await an(await He())).token}`]:["acp.v1",`hydra-acp-token.${t.token}`],b=null,g=null,h=new cl({url:p,subprotocols:m,onConnect:async w=>{w||b&&await b()},onDisconnect:w=>{g&&g(w)},log:w=>we({src:"resilient-ws",line:w})}),y=new pn(h);await h.start(),y.onNotification(Np,w=>{let v=UC.safeParse(w);v.success&&f.applyProgress(v.data)});let k=[],S=null,I=!1,x=!1,C=(w,v,R)=>{w&&(S?S(w,v,R):k.push({event:w,rawUpdate:v,recordedAt:R}))},$,P=w=>{w!==$&&($=w,w!==void 0&&A.appendLines([{prefix:" ",body:`\u2500\u2500 T${w} \u2500\u2500`,bodyStyle:"muted"}]))},M=null,F=null,K=!1,Y=0,z=0,re=!1,Q=!1,ke,xe=null,je=null,Ge=!1,ue=!1,oe=null,$e=!1,lt=null,Tt=null,Me=null,Jt=null,Ye=null,As=null,Ki=!1,Kn=()=>setInterval(()=>{if(X===null)return;if(xe===null){lt!==null&&X.setBanner({});return}let w=As===null?0:Date.now()-As;w<zO&&(Ki=!1);let R=lt===null&&!Sr()&&w>=zO;X.setBanner({elapsedMs:Date.now()-xe,stalled:R}),R&&!Ki&&(Ki=!0,X.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`no output for ${Math.round(w/6e4)}m and nothing running. ^C to cancel`,bodyStyle:"tool-status-fail"}])),ur()},1e3),Ts=!1,Ht=(w,v,R)=>{let O=z;z=Math.max(0,z+w),we({src:"pending-turns",delta:w,before:O,after:z,origin:v??null,label:R??null}),w>0&&V_({origin:v??null,label:R});let T=typeof X<"u"&&X!==null;O===0&&z>0?(Q=!1,xe=Date.now(),As=Date.now(),X?.setSidebarSnapshot({busySince:xe}),Et?.setTurnRunning(!0),T&&X.setBanner({status:"busy",elapsedMs:0,stalled:!1}),oe===null&&T&&(oe=Kn())):O>0&&z===0?(Q=!1,or!==null&&(clearTimeout(or),or=null),it=!1,xe=null,Ge?je=Date.now():ue=!0,X?.setSidebarSnapshot({busySince:null,lastTurnEndedAt:je}),As=null,Et?.setTurnRunning(!1),oe!==null&&lt===null&&(clearInterval(oe),oe=null),T&&X.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):z>0&&Q&&(Q=!1,T&&X.setBanner({status:"busy",stalled:!1}))},X=null,Et=null,Sr=()=>!1,gn,Yr,Xo=null,ay=new Set(["session_info_update","_hydra_current_model_update","current_mode_update","available_commands_update","_hydra_available_modes_update","usage_update","config_option_update","_hydra_compaction","_hydra_workspace","clarifier_question_asked","clarifier_question_answered","clarifier_question_dismissed"]),vl=w=>{let{update:v}=w??{},R=$C(w),O=Xs(v,{cwd:rt});ZV(v,O),As=Date.now();let T=v?.sessionUpdate;if(typeof T=="string"&&!ay.has(T)){let L=v??{};typeof L.messageId=="string"&&(gn=L.messageId);let B=Fp(w);B!==void 0&&(Yr=B)}if(T==="prompt_received"){let L=cO(v?.sentBy);Ht(1,L.origin,L.label)}else O?.kind==="turn-complete"&&(Ht(-1),K=!0);if(T==="permission_resolved"){Hf(v);return}if(T==="_hydra_compaction"){yo(v);return}if(T==="_hydra_workspace"){Gi(v);return}if(T==="clarifier_question_asked"){let L=v,B=typeof L.question?.question=="string"?L.question.question:"",ne=B.length>50?B.slice(0,49)+"\u2026":B;A.notify(ne?`new question: ${ne} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}T==="clarifier_question_answered"||T==="clarifier_question_dismissed"||(C(O,v,R),Ji(v))};y.onNotification("session/update",w=>{if(!I){if(Xo!==null){Xo.push(w);return}vl(w)}}),y.onNotification("hydra-acp/session/closed",()=>{if(I)return;z>0&&Ht(-z),typeof X<"u"&&X!==null&&X.setBanner({status:"cold",elapsedMs:void 0}),On()});let Es=new Map,Zo=200,Wt=0,it=!1,ud=4e3,or=null;y.onNotification("hydra-acp/prompt_queue/added",w=>{if(I)return;let v=w??{};if(typeof v.messageId!="string")return;if(typeof v._meta?.["hydra-acp"]?.amending=="string"){let O=v.messageId,T=v.prompt,L=setTimeout(()=>{I||(Es.delete(O),nn.set(O,Fd(O,T)),X&&Et&&dr())},Zo);Es.set(O,L)}else nn.set(v.messageId,Fd(v.messageId,v.prompt)),X&&Et&&dr();if(Ms!==void 0&&v.originator?.clientId===Ms){let O=Zn.shift();O&&(O.messageId=v.messageId,Hs.set(v.messageId,O))}});let Gn=(w,v)=>{let R=nn.get(w);R!==void 0&&(v?R.held=!0:delete R.held,X&&Et&&dr())},yn=(w,v)=>{v!==void 0&&X?.setSidebarSnapshot({armedTasks:v}),lt!==w&&(lt=w,X?.setBanner({armedSince:w??void 0}),X?.setSidebarSnapshot({armedSince:w}),w!==null&&oe===null&&X!==null&&(oe=Kn()),w===null&&xe===null&&oe!==null&&(clearInterval(oe),oe=null))};y.onNotification("hydra-acp/session/armed_tasks_updated",w=>{if(I)return;let v=w??{},R=typeof v.count=="number"?v.count:0;yn(R>0&&typeof v.since=="number"?v.since:null,Array.isArray(v.tasks)?sx(v.tasks):void 0)}),y.onNotification("hydra-acp/prompt_queue/held",w=>{if(I)return;let v=w??{};typeof v.messageId=="string"&&Gn(v.messageId,!0)}),y.onNotification("hydra-acp/prompt_queue/released",w=>{if(I)return;let v=w??{};typeof v.messageId=="string"&&Gn(v.messageId,!1)}),y.onNotification("hydra-acp/prompt_queue/updated",w=>{if(I)return;let v=w??{};if(typeof v.messageId!="string")return;let R=nn.get(v.messageId);if(R===void 0)return;let O=Fd(v.messageId,v.prompt);R.held&&(O.held=!0),nn.set(v.messageId,O);let T=Hs.get(v.messageId);if(T){let L=Array.isArray(v.prompt)?v.prompt:[],B="",ne=[];for(let le of L){if(!le||typeof le!="object")continue;let de=le;de.type==="text"&&typeof de.text=="string"?B+=de.text:de.type==="image"&&typeof de.data=="string"&&typeof de.mimeType=="string"&&ne.push({data:de.data,mimeType:de.mimeType,sizeBytes:Math.floor(de.data.length*3/4)})}T.text=B,T.attachments=ne}X&&Et&&dr()}),y.onNotification("hydra-acp/prompt_queue/removed",w=>{if(I)return;let v=w??{};if(typeof v.messageId!="string")return;v.reason==="started"&&(ke=v.messageId);let R=Es.get(v.messageId);R!==void 0&&(clearTimeout(R),Es.delete(v.messageId)),nn.delete(v.messageId)&&X&&Et&&dr();let T=Hs.get(v.messageId);T&&(Hs.delete(v.messageId),v.reason==="started"&&(T.flushed=!0,C({kind:"user-text",text:T.displayText,attachments:T.attachments}),ss=T))}),y.onNotification("hydra-acp/cancel_failed",w=>{if(I)return;let v=w??{};if(!(typeof X<"u"&&X!==null))return;Wt=Date.now();let O=typeof v.message=="string"&&v.message.length>0?`: ${v.message}`:"";if(v.reason==="unresponsive"){X.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`agent kept resuming after repeated cancels${O} \u2014 hydra restarted it automatically.`,bodyStyle:"tool-status-fail"}]);return}it=!0;let T=typeof v.code=="number"?` (${v.code})`:"";X.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${T}${O} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),y.onNotification("hydra-acp/prompt/amended",w=>{if(I)return;let v=w??{};if(typeof v.cancelledMessageId!="string")return;let R=v.cancelledMessageId;Ld.add(R),ss!==null&&ss.messageId!==void 0&&ss.messageId===R&&(C({kind:"turn-complete",stopReason:"cancelled",amended:!0}),ss=null,Ld.delete(R))}),y.onNotification("hydra-acp/context_self_compacted",()=>{I||A.notify("agent compacted its own context \u2014 recall armed",4e3)});let yo=w=>{let v=w??{},R=typeof v.phase=="string"?v.phase:void 0;if(R==="started")A.setCompactionIndicator("compacting...");else if(R==="iteration")A.setCompactionIndicator("compacting...");else if(R==="deferred")A.setCompactionIndicator("compaction queued (waiting for idle)");else if(R==="swapped")A.setCompactionIndicator(null),A.notify("compacted",2e3);else if(R==="rolled_back")A.setCompactionIndicator(null),A.notify("rolled back",2e3);else if(R==="failed"){A.setCompactionIndicator(null);let O=typeof v.error=="string"?v.error:"unknown error",T=O.length>40?O.slice(0,40)+"...":O;A.notify(`compaction failed: ${T}`,5e3)}},Gi=w=>{let v=w??{},R=typeof v.phase=="string"?v.phase:void 0;if(R==="drift"){let L=typeof v.behind=="number"?v.behind:0;A.notify(L>0?`source moved on, ${L} commit(s) ahead \u2014 /hydra workspace sync`:"source moved on \u2014 /hydra workspace sync",6e3);return}if(R==="provisioning"){A.setWorkspaceIndicator("creating workspace...");return}if(R==="setup"){A.setWorkspaceIndicator("running workspace setup...");return}if(R==="swapping"){A.setWorkspaceIndicator("moving session into workspace...");return}if(R==="landing"){A.setWorkspaceIndicator("merging workspace back...");return}if(R==="applying"){A.setWorkspaceIndicator("staging workspace changes...");return}if(R==="returning"){A.setWorkspaceIndicator("returning to source tree...");return}if(R==="failed"){A.setWorkspaceIndicator(null);let L=typeof v.error=="string"?v.error:"unknown error";A.notify(`workspace failed: ${L.length>40?L.slice(0,40)+"...":L}`,5e3);return}if(R!=="entered"&&R!=="left"||(A.setWorkspaceIndicator(null),typeof v.cwd!="string"||v.cwd.length===0))return;rt=v.cwd,dp=null;let O=typeof v.sourceCwd=="string"?v.sourceCwd:v.cwd,T=typeof v.label=="string"?v.label:void 0;A.setSessionbar({cwd:v.cwd,...R==="entered"&&T!==void 0?{workspace:{label:T,path:v.cwd,sourceCwd:O}}:{workspace:void 0}}),Dl(),A.setSidebarSnapshot({workspace:R==="entered"&&T!==void 0?{label:T,path:v.cwd}:null}),A.notify(R==="entered"?`isolated in ${T??"a workspace"}`:"returned to source tree",2e3)},Sl=()=>{Tt===null&&(Tt=setInterval(async()=>{try{let w=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!w.ok)return;let v=await w.json();v.forkSynthesisState===void 0?(A.setSynthesisIndicator(null),A.notify("synthesis complete",2e3),Tt!==null&&(clearInterval(Tt),Tt=null)):v.forkSynthesisState==="failed"&&(A.setSynthesisIndicator("\u26A0 synthesis failed"),A.notify("synthesis failed \u2014 fork still usable via recall",8e3),Tt!==null&&(clearInterval(Tt),Tt=null))}catch{}},5e3))},fd=()=>{Tt!==null&&(clearInterval(Tt),Tt=null)},wo=()=>{Me!==null&&(clearInterval(Me),Me=null)},On=()=>{if(Me!==null)return;let w=!1;Me=setInterval(async()=>{if(!(w||I)){w=!0;try{let v=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!v.ok){v.status===404&&wo();return}if((await v.json()).status!=="warm")return;wo(),we({src:"cold-watch",step:"warm-detected",sessionId:me}),b&&await b({skipInitialize:!0,beforeReplay:()=>{X?.appendLines([{prefix:" ",body:"-- session resumed by another client, catching up --",bodyStyle:"muted"}])}})}catch{}finally{w=!1}}},WV)},Hf=w=>{let v=w??{},R=typeof v.toolCallId=="string"?v.toolCallId:void 0,O;v.outcome&&typeof v.outcome=="object"?O=v.outcome:typeof v.chosenOptionId=="string"&&(O={kind:"selected",optionId:v.chosenOptionId}),wn(R,O?{outcome:O}:void 0)},Xe=null,wn=(w,v)=>{if(!Xe||Xe.toolCallId&&w&&Xe.toolCallId!==w)return;let R=Xe.resolve;Xe=null,A.setPermissionPrompt(null),R(v??{outcome:{outcome:"cancelled"}})},Ji=w=>{if(!Xe?.toolCallId)return;let v=w??{};v.sessionUpdate!=="tool_call"&&v.sessionUpdate!=="tool_call_update"||v.toolCallId===Xe.toolCallId&&(!v.status||v.status==="pending"||wn(v.toolCallId,void 0))},Vi=()=>{if(!Xe){A.setPermissionPrompt(null);return}A.setPermissionPrompt({title:Xe.title,detail:Xe.detail,options:Xe.options.map(w=>({label:w.name})),selectedIndex:Xe.selectedIndex})},bo=w=>{if(!Xe)return;let{options:v,resolve:R}=Xe;if(Xe=null,A.setPermissionPrompt(null),w===null){R({outcome:{outcome:"cancelled"}});return}R({outcome:{outcome:"selected",optionId:w}})};y.onRequest("session/request_permission",async w=>{if(I)return{outcome:{outcome:"cancelled"}};if(r.dangerouslySkipPermissions)return Qa(w);let v=w??{},O=(Array.isArray(v.options)?v.options:[]).map(le=>({optionId:le.optionId,name:ot(le.name??""),...le.kind!==void 0?{kind:le.kind}:{}})),T=v.toolCall?.title??v.toolCall?.name??"tool",L=ot(T),B=ot(JP(GP(w))),ne=v.toolCall?.toolCallId;return O.length===0?(A.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${L} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(le=>{Xe={title:L,detail:B,options:O,selectedIndex:0,resolve:le,toolCallId:ne},Vi()})}),y.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let Yi,pd,Rn=!0,Ps=!1,Qr=!1;try{let w=await y.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:Fe}});pd=w?.agentInfo?.name,w?.agentCapabilities?.promptCapabilities?.image===!1&&(Rn=!1),Ps=Pn(w?._meta??void 0).prompt?.amending===!0,Qr=w?._meta?.steering?.supported===!0}catch{}let me=d.sessionId,Rt=d.agentId,rt=d.cwd,Xt;t.isLocal||(d.remote=t.display);let Bf=d.remote,Zt=pl(d),bn=null,ko=()=>(bn===null&&(bn=EV(qi.join(_V(),"hydra-remote-exec-"))),bn),ei=()=>Zt?ko():rt,xl=d.jumpToRecordedAt,Ms,Fn,_s,kn,hd,md,gd,ti,yd,xr,ni,Qi,Il=!1;if(d.sessionId==="__new__"){let w={};r.agentId&&(w.agentId=r.agentId),r.name&&(w.title=r.name),r.model&&(w.model=r.model),r.workspace===!0&&(w.workspace={});let v={cwd:d.cwd,...Object.keys(w).length>0?{_meta:{[pt]:w}}:{}},R;try{R=await FP({request:()=>y.request("session/new",v),showBanner:(L,B,ne)=>LP(n,L,B,ne,{authenticate:le=>y.request("authenticate",{methodId:le,_meta:{[pt]:{agentId:L}}})}),resolveOnboarding:async L=>{if(L)try{return(await Ua(t)).find(le=>le.id===L)?.onboarding}catch{return}},fallbackAgentId:r.agentId})}catch(L){n.grabInput(!1),we({src:"grab",site:"runSession.session-new-failed",on:!1}),h.close().catch(()=>{});let B=L instanceof Error?L.message:String(L);we({src:"session-new-failed",agentId:r.agentId??null,message:B});let ne=await nO(n,r.agentId,B,{canGoBack:!r.forceNew});if(ne==="cancel")return null;let le={...r};return delete le.sessionId,delete le.resume,ne==="retry"?le.forceNew=!0:(delete le.forceNew,delete le.agentId),le}if(R.kind==="cancel")return n.grabInput(!1),we({src:"grab",site:"runSession.auth-cancel",on:!1}),h.close().catch(()=>{}),null;if(R.kind==="back"){n.grabInput(!1),we({src:"grab",site:"runSession.auth-back",on:!1}),h.close().catch(()=>{});let L={...r};return delete L.sessionId,delete L.forceNew,delete L.resume,delete L.agentId,L}let O=R.result;f.write(l),me=O.sessionId,gS(me),s.sessionId=me,s.readonly=!1;let T=Pn(O._meta??void 0);T.clientId&&(Ms=T.clientId),Yi=T.upstreamSessionId,T.agentId&&(Rt=T.agentId),T.cwd&&(rt=T.cwd),Fn=T.workspaceInfo,T.title&&(Xt=T.title),_s=T.currentModel,kn=T.currentMode,yd=T.currentUsage,xr=T.turnStartedAt,ni=T.armedSince,Qi=T.armedTaskList,T.availableCommands&&(hd=Jp(T.availableCommands)),T.availableModes&&(md=T.availableModes),gd=qO(O.configOptions),ti=T.queue}else{let w={};r.readonly===!0&&(w.readonly=!0),e.tui.toolContent==="references"&&(w.toolContent="references"),r.drip===!0&&(w.replayMode="drip",r.dripSpeed!==void 0&&(w.dripSpeed=r.dripSpeed)),d.resumeHint!==void 0&&(w.resume={upstreamSessionId:d.resumeHint.upstreamSessionId,agentId:d.resumeHint.agentId,cwd:d.resumeHint.cwd});let v=await y.request("session/attach",{sessionId:d.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:Fe},...Object.keys(w).length>0?{_meta:{[pt]:w}}:{}});me=v.sessionId,gS(me),v.clientId&&(Ms=v.clientId),s.sessionId=me,s.readonly=r.readonly===!0;let R=Pn(v._meta??void 0);Il=R.resurrected===!0,Yi=R.upstreamSessionId,R.agentId&&(Rt=R.agentId),R.cwd&&(rt=R.cwd),Fn=R.workspaceInfo,R.title&&(Xt=R.title),_s=R.currentModel,kn=R.currentMode,yd=R.currentUsage,xr=R.turnStartedAt,ni=R.armedSince,Qi=R.armedTaskList,R.availableCommands&&(hd=Jp(R.availableCommands)),R.availableModes&&(md=R.availableModes),gd=qO(v.configOptions),ti=R.queue}let $s=D.tuiHistoryFile(me),Uf=D.globalTuiHistoryFile(),Ne=await Pu($s).catch(()=>[]),Ln=await Pu(Uf).catch(()=>[]);Ln.length>e.tui.promptHistoryMaxEntries&&(Ln=Ln.slice(Ln.length-e.tui.promptHistoryMaxEntries));let Jn=[...Ne],Le=new Vo({history:Eh(Ln,Jn)});Et=Le;let Wf=!1,Xr=()=>{X?.setBanner({hintsExhausted:jA(Ne.length,e.tui.composer.hintTurns)})},cn=(w,v)=>{let R=w.replace(/\n+$/,"");if(R.length===0)return;let O=(v??w).replace(/\n+$/,""),T=Mu(Ne,R),L=T!==Ne;Ne=T,Jn=Mu(Jn,O);let B=Mu(Ln,R,e.tui.promptHistoryMaxEntries),ne=B!==Ln;Ln=B,Le.setHistory(Eh(Ln,Jn)),L&&Ta($s,Ne).catch(()=>{}),ne&&qA(Uf,R).catch(()=>{}),Xr(),X?.clearHintReveal()};z>0&&Le.setTurnRunning(!0);let Zr=[],vo=null;$$(O$(e.tui.ambiguousWidth,process.env,YO)),qE(e.tui.diffContextLines);let Os=!1,A,jf=()=>{Os&&(Os=!1,A.start())},Cl=()=>{Os||(Os=!0,A.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",jf);let qf=jV(e.tui.openFileCommand);A=new jg({term:n,dispatcher:Le,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:o.mouseEnabled,inAppSelection:o.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,openFileCommand:qf?.argv,openFileSource:qf?.source,openFileInTerminal:e.tui.openFileInTerminal,progressIndicator:e.tui.progressIndicator,readonly:r.readonly===!0,onSidebarCollapseChange:(w,v)=>{o.sidebarCollapsed=X?.sidebarCollapsedIds()??[],!v&&(w==="git"?Dl():w==="sessions"?vy():w==="resources"&&Mx(),Bl())},onSuspend:process.platform!=="win32"?Cl:void 0,onLayoutChange:()=>{Rx()},onBlockClick:(w,v,R)=>{DF(w,v,R)},onHydraLinkClick:w=>(Xf(w),!0),onBlockVisible:w=>{RF(w)},onHoverRun:w=>{if(!w.startsWith("thought:"))return null;let v=ce.get(w);if(v!==void 0&&v.length>0)return new Set(v);let R=A.contiguousRun(w,new Set(at.keys()));return R.length>0?new Set(R):null},onBarAction:(w,v)=>{if(w==="toggle-mode"){er(!0);return}if(w==="rename-session"){Pd(v);return}if(w==="choose-model"){se("model");return}if(w==="choose-agent"){se("agent");return}if(w==="choose-mode"){se("mode");return}if(w==="choose-config"){se(v);return}let R=w==="switch-session"?{type:"switch-session"}:w==="detach"?{type:"exit"}:w==="toggle-options"?{type:"toggle-options"}:{type:"show-help"};r.readonly===!0&&ox(R)||Ar(R)},onFormClick:w=>ta(w),onPermissionClick:w=>Pt(w),onCompactionClick:w=>Rd(w),onHelpClick:()=>A.setHelpPrompt(null),onMouse:w=>{if(w.kind!=="press"||w.button!=="middle")return;let v={type:"attachment-request",source:"primary"};r.readonly===!0&&ox(v)||Ar(v)},onKey:w=>{for(let v of w){if(re&&Ro(v)){v.type==="key"&&we({src:"key-swallowed",site:"compactionPrompt",name:v.name});continue}if(Xe&&Jf(v)){v.type==="key"&&we({src:"key-swallowed",site:"permission",name:v.name});continue}if(Zi(v)){v.type==="key"&&we({src:"key-swallowed",site:"help",name:v.name});continue}if(ci(v)){v.type==="key"&&we({src:"key-swallowed",site:`form:${Vt??"none"}`,name:v.name});continue}if(kd(v)){v.type==="key"&&we({src:"key-swallowed",site:"scrollbackSearch",name:v.name});continue}if(Kf(v)){v.type==="key"&&we({src:"key-swallowed",site:"completion",name:v.name});continue}if(Gf(v)){v.type==="key"&&we({src:"key-swallowed",site:"btwClose",name:v.name});continue}if(v.type==="key"&&v.name==="escape"&&A.isScrolledBack()){A.scrollToBottom();continue}if(v.type==="attachment-paths"){Zf(v.paths);continue}if(v.type==="key"&&Vf(v.name)){we({src:"key-swallowed",site:"userHotkey",name:v.name});continue}let R=Le.feed(v);for(let O of R)r.readonly===!0&&ox(O)||Ar(O)}Rl(),A.setBannerSearchIndicator(Le.state().historySearchQuery),A.setAttachments(Le.state().attachments),A.refreshPrompt()}}),X=A,A.setStickyBottomKey("plan");let zf=[{name:"/help",description:"Show TUI built-in commands"},{name:"/quit",description:"Exit the TUI"},{name:"/clear",description:"Clear scrollback"},{name:"/sessions",description:"List sessions"},{name:"/resume",description:"Switch sessions (open the picker)"},{name:"/session",description:"Switch session: /session <id|next|prev> (no arg opens picker)"},{name:"/rename",description:"Rename this session (alias for /hydra title): /rename [title]"},{name:"/title",description:"Rename this session: /title [title] (no arg opens the field)"},{name:"/model",description:"Switch model: /model [model-id] (no arg opens the picker)"},{name:"/mode",description:"Switch mode: /mode [mode-id] (no arg opens the picker)"},{name:"/agent",description:"Switch agent: /agent [agent-id] (no arg opens the picker)"},{name:"/btw",description:"Run an ancillary forked session: /btw <prompt> (no args toggles the last overlay)"},{name:"/export",description:"Export this session as a markdown transcript: /export [path]"}],wd=hd??[],ri=md??[],es=gd??[],dy=()=>{let w=new Set,v=[];for(let R of[...zf,...wd])w.has(R.name)||(w.add(R.name),v.push(R));return v},bd=()=>{let w=Le.state().buffer,v=w[0]??"";if(!v.startsWith("/"))return[];if(w.length>1)return[];let R=v.indexOf(" "),O=R===-1?v:v.slice(0,R);if(O.lastIndexOf("/")>0)return[];let T=dy().filter(L=>L.name.startsWith(O));return T.length===1&&T[0]?.name===O?[]:T},So=[],Rl=()=>{let w=bd();if(w.length>0){So=[],A.setCompletions(w);return}A.setCompletions(So)},Kf=w=>{if(w.type!=="key"||w.name!=="tab")return So.length>0&&(So=[]),!1;let v=bd();if(A.isOverlayOpen()&&v.length===0)return A.toggleFocusedPane(),!0;if(v.length>0){So=[];let R=Le.state().buffer[0]??"",O=U$({matches:v.map(T=>T.name),firstLine:R});return O===null||Le.replaceFirstLine(O),!0}return Al()},Al=()=>{if(Zt)return!1;let w=Le.state(),v=w.buffer[w.row]??"",R=Gg(v,w.col);if(R===null)return!1;let O=Jg(R.token,rt);return O===null?!1:(O.replacement!==R.token&&Le.replaceRangeOnCurrentLine(R.start,w.col,O.replacement),So=O.candidates.length>1?O.candidates.map(T=>({name:T})):[],!0)},Gf=w=>!A.isOverlayOpen()||w.type!=="key"||w.name!=="escape"&&w.name!=="ctrl-c"?!1:(M&&(M.cancel(),M=null,F=null),A.closeBtwOverlay(),!0),kd=w=>{if(!A.isScrollbackSearchActive())return w.type==="key"&&w.name==="ctrl-r"&&A.isScrolledBack()?(A.enterScrollbackSearch(),A.updateScrollbackSearchTerm(""),!0):!1;if(w.type==="char"){let v=A.scrollbackSearchTerm()+w.ch;return A.updateScrollbackSearchTerm(v),!0}if(w.type==="paste"){let v=A.scrollbackSearchTerm()+w.text.replace(/\n/g," ");return A.updateScrollbackSearchTerm(v),!0}if(w.type==="key")switch(w.name){case"ctrl-r":return A.advanceScrollbackSearch(),!0;case"ctrl-s":return A.retreatScrollbackSearch(),!0;case"backspace":{let v=A.scrollbackSearchTerm();return v.length===0?A.cancelScrollbackSearch():A.updateScrollbackSearchTerm(v.slice(0,-1)),!0}case"enter":return A.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return A.cancelScrollbackSearch(),!0;default:return!0}return!0},Pt=w=>{if(!Xe)return;let v=Xe.options;if(w.kind==="hint"){if(w.action==="cancel"){bo(null);return}bo(v[Xe.selectedIndex]?.optionId??null);return}let R=v[w.index];if(R){if(w.select===!0){Xe.selectedIndex=w.index,Vi();return}bo(R.optionId)}},Jf=w=>{if(!Xe)return!1;let v=Xe.options;if(w.type==="key")switch(w.name){case"up":return Xe.selectedIndex=Math.max(0,Xe.selectedIndex-1),Vi(),!0;case"down":return Xe.selectedIndex=Math.min(v.length-1,Xe.selectedIndex+1),Vi(),!0;case"enter":{let R=v[Xe.selectedIndex];return R&&bo(R.optionId),!0}case"escape":case"ctrl-c":return bo(null),!0;default:return!0}if(w.type==="char"&&/^[1-9]$/.test(w.ch)){let R=parseInt(w.ch,10)-1,O=v[R];return O&&bo(O.optionId),!0}return!0},Vf=w=>{let v=e.tui.hotkeys[w];return v?(Vg(v,{sessionId:me,cwd:ei(),agentId:Rt||pd||"",baseUrl:t.baseUrl,tokenFile:D.authToken()},{notify:R=>A.notify(R),cwd:ei(),emitLines:R=>{A.appendLines(R.map(O=>{let T;switch(O.style){case"meta":T="muted";break;case"stderr":case"error":T="tool-status-fail";break;default:T="notice"}return{prefix:" ",body:O.text,bodyStyle:T}}))}}),!0):!1},vd=()=>Rt||pd||"?",Nn=vd(),Vn={...yd??{}};f.finalize(),A.start({skipFullscreen:!0}),A.setHideThoughts(!o.showThoughts),A.setBarConfig({composer:e.tui.composer,sessionbar:e.tui.sessionbar});let It=VS(vf({composer:e.tui.composer,sessionbar:e.tui.sessionbar}),e.tui.scriptRefreshMs),Yn=w=>{let v=a.get(w);if(v===void 0)return;let R={HYDRA_ACP_TOKEN:v,HYDRA_ACP_DAEMON_URL:t.baseUrl};return me!==null&&(R.HYDRA_ACP_SESSION_ID=me),R};if(It.size>0){let w=sO({cwd:ei,envFor:Yn,onOutput:(v,R)=>A.setScriptOutput(v,R)});Jt=setInterval(()=>{w.poll(It,Date.now())},1e3),Jt.unref?.(),w.poll(It,Date.now())}let xo=lS(e.tui.sidebar.gadgets);A.setSidebarProcessGadgets(_g(xo)),A.setSidebarGadgets(xo.map(Mg));let Tl=sS(xo,e.tui.scriptRefreshMs),Io=new Map;for(let w of _g(xo)){let v=Io.get(w.script)??[];v.push(w.id),Io.set(w.script,v)}let Sd=()=>{let w=new Map;for(let[v,R]of Tl)(Io.get(v)??[]).some(T=>A.isSidebarGadgetActive(T))&&w.set(v,R);return w};if(Tl.size>0){let w=Zg({cwd:ei,envFor:Yn,sanitize:N_,onOutput:(v,R)=>A.setProcessOutput(v,R)});Ye=setInterval(()=>{w.poll(Sd(),Date.now())},1e3),Ye.unref?.(),w.poll(Sd(),Date.now())}Xr(),A.setSidebarWidth(e.tui.sidebar.width??null),A.setSidebarBorder(e.tui.sidebar.border),A.setSidebarSnapshot({usage:{...Vn},model:_s??null,mode:kn??null,configOptions:jO(es),sessionId:me===null?null:Qe(me),host:me===null?null:eo(me)?.name??null,agent:Nn,workspace:Fn===void 0?null:{label:Fn.label,path:Fn.path}}),A.setSessionbar({agent:Nn,cwd:rt,remote:Bf,...Fn===void 0?{}:{workspace:{label:Fn.label,path:Fn.path,sourceCwd:Fn.sourceCwd}},sessionId:me,title:Xt,model:_s,usage:{...Vn}}),kn&&A.setBanner({currentMode:kn}),df().then(w=>{w&&A.notify(`\u2728 ${cf(w)}`,3e4)}).catch(()=>{});let ln=null,si=new Promise(w=>{ln=w}),Co=()=>{if(y.notify("session/cancel",{sessionId:me}).catch(()=>{}),or===null){let w=Date.now();or=setTimeout(()=>{or=null,z!==0&&(Wt>=w||it||(it=!0,X?.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"cancel not acknowledged by agent; the turn is still running. Cancel again to force-stop (restarts the agent).",bodyStyle:"tool-status-fail"}])))},ud)}},Xi=()=>{it=!1,X!==null&&X.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"force-stopping agent \u2014 turn aborted; resumes on your next message\u2026",bodyStyle:"tool-status-fail"}]),y.request("hydra-acp/session/force_cancel",{sessionId:me}).catch(()=>{})},xd=()=>{X!==null&&z===1&&(Q=!0,X.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},El=()=>{let w=Zr[0];if(w){w.cancel(),xd();return}if(z>0){it?Xi():Co(),xd();return}Pl()},Pl=()=>{_d(0)},cy=()=>{let w="enqueue prompt (sends now, or queues during a turn)",v="amend the in-flight turn (cancel + replace)";return[...o.defaultEnterAction==="amend"?[["Enter",v],["Ctrl+Enter / Shift+Enter / ^S",w]]:[["Enter",w],["Ctrl+Enter / Shift+Enter / ^S",v]],...qV]},Yf=()=>{if(A.isHelpPromptActive()){A.setHelpPrompt(null);return}A.setHelpPrompt({title:`Hotkeys \xB7 hydra-acp v${Fe}`,entries:cy(),hint:"any key dismisses \xB7 /help lists commands"})},Id=()=>{re=!1,A.setCompactionPrompt(null),A.setCompactionIndicator("compaction queued...");let w=me;fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(w)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}}).catch(()=>{})},Fs=()=>{re=!1,A.setCompactionPrompt(null)},Cd=w=>{let v=A.compactionPromptSpec();if(!v)return;let R=v.options.length;if(R===0)return;let O=((v.selectedIndex+w)%R+R)%R;O!==v.selectedIndex&&A.setCompactionPrompt({...v,selectedIndex:O})},Rd=w=>{if(!re)return;let v=A.compactionPromptSpec();if(!v)return;if(w.kind==="hint"){if(w.action==="cancel"){Fs();return}v.options[v.selectedIndex]?.key==="y"?Id():Fs();return}let R=v.options[w.index];if(R){if(w.select===!0){w.index!==v.selectedIndex&&A.setCompactionPrompt({...v,selectedIndex:w.index});return}R.key==="y"?Id():Fs()}},Ro=w=>{if(!re)return!1;if(w.type==="key"){if(w.name==="escape")return Fs(),!0;if(w.name==="up")return Cd(-1),!0;if(w.name==="down")return Cd(1),!0;if(w.name==="enter"){let v=A.compactionPromptSpec();return v?.options[v.selectedIndex]?.key==="y"?Id():Fs(),!0}}if(w.type==="char"){let v=w.ch.toLowerCase();if(v==="y"||v==="1")return Id(),!0;if(v==="n"||v==="2")return Fs(),!0}return!0},Zi=w=>A.isHelpPromptActive()?(w.type==="key"&&w.name==="ctrl-g",A.setHelpPrompt(null),!0):!1,Ls=["tools","plan","thoughts","diffs","mouse","enter","sidebar","theme"],Ns=0,ir=null,oi=[],Ao=[],Qn=[],Ds=0,Vt=null,Ir=null,Cr=(w,v)=>{w!=="chooser"&&(E=null),Vt=w,Ir=v,A.setFormPrompt(KM(v))},Xn=w=>{Vt===w&&(Vt=null,Ir=null,E=null,_=new Map,A.setFormPrompt(null))},To=w=>{switch(w){case"tools":return o.toolsExpanded?"expanded":"collapsed";case"plan":return o.planExpanded?"expanded":"collapsed";case"thoughts":return o.showThoughts?"shown":"hidden";case"diffs":return o.showFileUpdates;case"mouse":return o.mouseEnabled?"on":"off";case"enter":return o.defaultEnterAction;case"sidebar":return A.isSidebarVisible()?"shown":"hidden";case"theme":return ld}},Ad=w=>{switch(w){case"tools":return"Tools";case"plan":return"Plan";case"thoughts":return"Thoughts";case"diffs":return"File updates";case"mouse":return"Mouse capture";case"enter":return"Enter key";case"sidebar":return"Sidebar";case"theme":return"Theme"}},Qf=()=>({title:"Session options",rows:Ls.map(w=>({id:w,kind:"select",label:Ad(w),value:To(w)})),cursor:Ns,hints:[{label:"\u2191/\u2193 row"},{label:"\u2190/\u2192 cycle"},{label:"\u23CE next",action:"commit"},{label:"s save default",action:"save"},{label:"Esc close",action:"close"}]}),ly=()=>{Vt==="options"&&Cr("options",Qf())},ts=()=>{if(Vt==="options"){Xn("options");return}Ns=0,Cr("options",Qf())},Td=()=>{ir!==null&&Cr("questions",eF(ir,oi,Qn,Ds))},ns=()=>{ir=null,oi=[],Ao=[],Qn=[],Ds=0,Xn("questions")},ii=async()=>{if(ir!==null){ns();return}try{let v=await y.request(HM,{sessionId:me}),R=LV(v.questions??[]);if(R.length===0){A.notify("no open questions");return}let O=DV(R);ir=O,Ds=0,oi=O.map(T=>NV(T.representative)),Ao=O.map(()=>!1),Qn=O.map(()=>!1),Td()}catch(w){A.notify("clarifier unavailable"),we({src:"questions",step:"list_failed",error:w.message})}},Ml=()=>{let w=ry.find(R=>R.name===ld);if(w===void 0)return;Aw(w.palette,{...w.overrides,background:Vr,foreground:XO}),Cx(),hy(),wy(),os(),A.fullRedraw();let v=ex(w.palette,ld,Vr);v!==void 0&&A.notify(v)},uy=(w=1)=>{if(ry.length===0){A.notify("no themes available");return}let v=wO(ry.map(R=>R.name),ld,w);v!==void 0&&(ld=v,Ml())},Dn=null,ai=w=>{Dn!==null&&(clearTimeout(Dn),Dn=null),e.tui.themeBackground===void 0&&(Vr!==void 0&&Vr.kind==="rgb"&&w.kind==="rgb"&&Vr.r===w.r&&Vr.g===w.g&&Vr.b===w.b||(Vr=w,Ml()))};QO=w=>{e.tui.themeBackground===void 0&&(Dn!==null&&clearTimeout(Dn),Dn=setTimeout(()=>{Dn=null,ai(y$(w))},200),Dn.unref?.(),be("\x1B]11;?\x07"))},ZO=ai;let di=(w,v=1)=>{switch(w){case"tools":o.toolsExpanded=!o.toolsExpanded,_e.clear(),Be.clear(),hy();break;case"plan":o.planExpanded=!o.planExpanded,dt=null,os();break;case"thoughts":o.showThoughts=!o.showThoughts,A.setHideThoughts(!o.showThoughts);break;case"diffs":o.showFileUpdates=o.showFileUpdates==="diff"?"edit":"diff",Mo.clear(),wy();break;case"mouse":{let R=!A.isMouseEnabled();A.setMouseEnabled(R),o.mouseEnabled=R;break}case"enter":o.defaultEnterAction=o.defaultEnterAction==="amend"?"enqueue":"amend";break;case"sidebar":Ay(!A.isSidebarVisible());break;case"theme":uy(v);break}ly()},rs=w=>{(async()=>{try{switch(w){case"tools":case"plan":A.notify(`${Ad(w)} is session-only \u2014 not saved`);return;case"thoughts":await ua("showThoughts",o.showThoughts);break;case"diffs":await ua("showFileUpdates",o.showFileUpdates);break;case"mouse":await ua("mouse",o.mouseEnabled);break;case"enter":await ua("defaultEnterAction",o.defaultEnterAction);break;case"sidebar":await jy(A.isSidebarVisible());break;case"theme":await ua("theme",ld);break}A.notify(`saved default: ${Ad(w)} ${To(w)}`)}catch(v){A.notify(`save failed: ${v instanceof Error?v.message:String(v)}`)}})()},ea=w=>{let v=R=>Ls[R];switch(w.type){case"row":{Ns=w.row;let R=w.viaDigit===!0?v(w.row):void 0;R?di(R):ly();return}case"cycle":{let R=v(w.row);R&&(Ns=w.row,di(R,w.delta));return}case"advance":{let R=v(w.row);R&&di(R);return}case"save":{let R=v(w.row);R&&rs(R);return}case"close":case"cancel":Xn("options");return;default:return}},ar=(w,v)=>{if(w.type==="key"){if(w.name==="ctrl-o")return Xn("options"),!0;if(w.name==="ctrl-d")return Xn("options"),!1}return ea(gf(v,w)),!0},Ed="title",_l=(w,v)=>{let R=w.rows.find(O=>O.id===v);return R?.kind==="text"?R.editor.text:""},Pd=w=>{if(Vt!=="title"){if(r.readonly===!0){A.notify("view-only: rename disabled");return}if(me==="__new__"){A.notify("no active session to rename");return}Cr("title",JM({title:"Rename session",id:Ed,label:"title:",initial:w,hints:[{label:"\u23CE save",action:"commit"},{label:"Esc cancel",action:"close"}]}))}},$l=w=>{let v=_l(w,Ed).trim(),R=me;Xn("title"),v.length!==0&&Ju(t,R,v).catch(O=>{A.notify(`rename failed: ${O.message}`)})},Ol=(w,v)=>{switch(v.type){case"commit":$l(w);return;case"close":case"cancel":Xn("title");return;case"edited":Cr("title",w);return;default:return}},Md=(w,v)=>(Ol(v,gf(v,w)),!0),E=null,_=new Map,W=(w,v)=>{let R=w.options.find(L=>L.value===v);if(R)return R.value;let O=v.toLowerCase(),T=w.options.filter(L=>L.value.toLowerCase().startsWith(O));return T.length===1?T[0].value:null},J=w=>{if(r.readonly===!0)return A.notify(`view-only: ${w} switching disabled`),null;if(me==="__new__")return A.notify("no active session yet"),null;let v=es.find(R=>R.id===w);return!v||v.options.length===0?(A.notify(`no ${w} option advertised for this session`),null):v},se=w=>{if(Vt==="chooser"&&E?.kind==="values"&&E.configId===w)return;let v=J(w);v&&(E={kind:"values",configId:w},Cr("chooser",jM(v)))},ae=()=>{if(es.length===0){A.notify("no config options advertised for this session");return}E={kind:"index"},_=new Map,Cr("chooser",Ov(es,_))},ge=w=>{Cr("chooser",{...Ov(es,_),cursor:w})},ut=()=>{let w=new Map(es.map(v=>[v.id,v.currentValue]));for(let[v,R]of _)w.get(v)!==R&&St(v,R);_=new Map},St=(w,v)=>{A.notify(`switching ${w} to ${v}\u2026`),y.request("session/set_config_option",{sessionId:me,configId:w,value:v}).catch(R=>{A.notify(`${w} switch failed: ${R instanceof Error?R.message:String(R)}`)})},en=(w,v)=>{(async()=>{try{if(w==="agent")await hi(v);else{let R=Rt||pd||"";if(!R){A.notify(`can't save a ${w} default without an agent`);return}await Jl(R,w,v)}A.notify(`saved default: ${w} ${v}`)}catch(R){A.notify(`save failed: ${R instanceof Error?R.message:String(R)}`)}})()},tn=(w,v)=>{let R=E;if(R===null)return;let O=B=>w.rows[B]?.id,T=B=>{let ne=O(B);return ne===void 0?void 0:es.find(le=>le.id===ne)},L=B=>_.get(B.id)??B.currentValue;switch(v.type){case"row":Cr("chooser",{...w,cursor:v.row});return;case"cycle":{let B=T(v.row);if(!B)return;_.set(B.id,qM(B,L(B),v.delta)),ge(v.row);return}case"advance":ut(),Xn("chooser");return;case"commit":{let B=O(v.row);if(R.kind!=="values"||B===void 0)return;Xn("chooser"),St(R.configId,B);return}case"save":{if(R.kind==="values"){let ne=O(v.row);ne!==void 0&&(en(R.configId,ne),Xn("chooser"),St(R.configId,ne));return}let B=T(v.row);if(B){let ne=L(B);en(B.id,ne),ne!==B.currentValue&&St(B.id,ne)}return}case"close":_=new Map,Xn("chooser");return;case"cancel":_=new Map,Xn("chooser");return;default:return}},zt=(w,v)=>E===null?!1:(tn(v,gf(v,w)),!0),ci=w=>{let v=Ir;if(Vt===null||v===null)return!1;switch(Vt){case"questions":return Fl(w);case"options":return ar(w,v);case"title":return Md(w,v);case"chooser":return zt(w,v)}},ta=w=>{let v=Ir;if(!(Vt===null||v===null))for(let R of GM(v,w))switch(Vt){case"options":ea(R);break;case"title":Ol(v,R);break;case"chooser":tn(v,R);break;case"questions":li(ir===null?{type:"noop"}:nF(R,ir,oi,Ao,Qn,me));break}},li=w=>{switch(w.type){case"noop":return;case"row":Ds=w.selectedRow,Td();return;case"cycle":Ds=w.selectedRow,oi[w.selectedRow]=w.newValueIndex,Ao[w.selectedRow]=!0,Qn[w.selectedRow]=!1,Td();return;case"dismiss-toggle":{let v=w.selectedRow;Qn[v]?(Qn[v]=!1,Ao[v]=!1):(Qn[v]=!0,Ao[v]=!0),Td();return}case"discard":ns();return;case"save":{let v=w.dispatches;if(ns(),v.length===0)return;(async()=>{let R=0,O=0,T=0;for(let B of v)try{await y.request(B.method,B.params),B.type==="dismiss"?O++:R++}catch(ne){T++,we({src:"questions",step:"dispatch_failed",method:B.method,error:ne.message})}let L=[];R>0&&L.push(`${R} answered`),O>0&&L.push(`${O} dismissed`),T>0&&L.push(`${T} failed`),L.length>0&&A.notify(`clarifier: ${L.join(", ")}`)})();return}}},Fl=w=>ir===null?!1:(li(UV(w,!0,ir,oi,Ao,Qn,Ds,me)),!0),na=()=>{if(!I){I=!0,M?(M.cancel(),M=null,F=null):F!==null&&(co(t,F).catch(()=>{}),F=null),process.off("SIGINT",El),process.platform!=="win32"&&process.off("SIGCONT",jf),oe!==null&&(clearInterval(oe),oe=null),Tt!==null&&(clearInterval(Tt),Tt=null),wo();for(let w of Es.values())clearTimeout(w);Es.clear(),$x(),_x(),Jt!==null&&(clearInterval(Jt),Jt=null),Ye!==null&&(clearInterval(Ye),Ye=null),bn!==null&&(MV(bn,{recursive:!0,force:!0}),bn=null),A.clearWindowTitle(),A.stop({keepFullscreen:!0}),Ta($s,Ne).catch(()=>{}),h.close().catch(()=>{})}},_d=(w=0)=>{na(),ln&&(ln(null),ln=null),w!==0&&process.exit(w)},Rr=async()=>{if(we({src:"switch-session",step:"entered",finishSessionNull:ln===null}),!ln)return;M?(M.cancel(),M=null,F=null):F!==null&&(co(t,F).catch(()=>{}),F=null),fd(),wo(),A.setSynthesisIndicator(null);let w=Le.state().buffer.join(`
306
306
  `);w.replace(/\s+$/,"").length>0&&cn(w),A.pauseRepaint(),A.stop({keepFullscreen:!0}),Ta($s,Ne).catch(()=>{});let v=!1,R=null;try{let O=null,T=null,L=await Pr();for(;O===null;){let de=await ao(t,{includeNonInteractive:!0}),Ft=[];try{Ft=await Ua(t)}catch{}let ft=await Ak(t),De=await aF(t,ft),xt=Sn=>Mf({cwd:Sn,config:L,prefs:o,...r.explicitAgentId!==void 0?{explicitAgentId:r.explicitAgentId}:{},...r.agentId!==void 0?{fallbackAgentId:r.agentId}:{},availableAgents:Ft}),sn=Sn=>Mf({cwd:Sn,config:L,prefs:o,...r.explicitAgentId!==void 0?{explicitAgentId:r.explicitAgentId}:{},availableAgents:Ft}),{agentId:gt,model:$o}=await xt(rt),_t=await KS(n,{cwd:rt,sessions:de,config:e,target:t,currentSessionId:me,prefs:i,...gt?{composerAgentId:gt}:{},...$o?{composerModel:$o}:{},...Ft.length>0?{availableAgents:Ft}:{},...ft.length>0?{availableHosts:ft}:{},...ft.length>0?{hostInfo:De}:{},...r.newHost!==void 0?{composerHost:r.newHost}:{},onComposerAgentChange:(Sn,oa)=>{Of(o,Sn,oa)},onCwdChange:sn});if(_t.kind==="abort")return;if(_t.kind==="exit"){v=!0,_d(0);return}if(_t.kind==="new"){O={choice:_t,sessions:de};break}if(_t.kind==="fork"){let Sn=await iF(n,t,_t,de);if(Sn.kind==="cancel")return;if(Sn.kind==="back")continue;O={choice:{kind:"attach",sessionId:Sn.ctx.sessionId,...Sn.ctx.agentId?{agentId:Sn.ctx.agentId}:{}},sessions:de},T={readonly:!1,cwd:Sn.ctx.cwd},Sn.ctx.resumeHint!==void 0&&(T.resumeHint=Sn.ctx.resumeHint);break}let An=de.find(Sn=>Sn.sessionId===_t.sessionId);if(!(An!==void 0&&!!An.importedFromMachine&&!An.remote&&!An.upstreamSessionId&&_t.readonly!==!0)){if(t.isLocal&&An&&!An.importedFromMachine&&!An.remote&&_t.readonly!==!0&&!(await mf(An.cwd)).ok){_t.installStatus?.finalize(),delete _t.installStatus;let oa=await ad(n,An,{defaultCwd:Ze(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(oa.kind==="cancel")return;if(oa.kind==="back")continue;O={choice:_t,sessions:de},T={readonly:!1,cwd:oa.path,resumeHint:{agentId:_t.agentId??An.agentId??"",cwd:oa.path,upstreamSessionId:""}};break}O={choice:_t,sessions:de};break}let Lx={...r,readonly:!1};_t.installStatus?.finalize(),delete _t.installStatus;let Ul=await sF(n,t,An,_t,Lx);if(Ul.kind==="cancel")return;Ul.kind!=="back"&&(O={choice:_t,sessions:de},T={readonly:Lx.readonly===!0,cwd:Ul.ctx.cwd},Ul.ctx.resumeHint!==void 0&&(T.resumeHint=Ul.ctx.resumeHint))}let{choice:B}=O;if(r.terminalHostLauncher&&(B.kind==="attach"||B.kind==="new")){B.installStatus?.finalize(),delete B.installStatus,R=await ix(B,O.sessions,T?.cwd??rt);return}let ne=ln;if(ln=null,na(),v=!0,B.kind==="new"){let{sessionId:de,agentId:Ft,...ft}=r,De={...ft,cwd:B.cwd??rt,forceNew:!0,readonly:!1};B.prompt!==void 0&&(De.initialPrompt=B.prompt),B.attachments&&B.attachments.length>0&&(De.initialAttachments=B.attachments),B.agentId!==void 0&&(De.agentId=B.agentId,B.agentExplicit&&Of(o,B.agentId,B.model)),B.model!==void 0&&(De.model=B.model),B.host!==void 0?De.newHost=B.host:delete De.newHost,B.installStatus!==void 0&&(De.installStatus=B.installStatus),ne(De);return}if(B.kind!=="attach")return;let le={...r,sessionId:B.sessionId,cwd:T?.cwd??rt,readonly:T?.readonly??B.readonly===!0};B.agentId!==void 0&&(le.agentId=B.agentId),T?.resumeHint!==void 0?le.resumeHint=T.resumeHint:delete le.resumeHint,B.jumpToRecordedAt!==void 0?le.jumpToRecordedAt=B.jumpToRecordedAt:delete le.jumpToRecordedAt,B.installStatus!==void 0?le.installStatus=B.installStatus:delete le.installStatus,ne(le)}finally{!v&&ln&&(A.start({skipFullscreen:!0}),A.resumeRepaint(),R&&A.notify(R))}},$d=async(w="next")=>{if(!ln)return;let v=await ao(t,{status:"warm"});if(v.length<=1)return;let R=v.findIndex(de=>de.sessionId===me),L=((R===-1?0:R)+(w==="prev"?-1:1)+v.length)%v.length,B=v[L],ne=ln;ln=null,na();let le={...r,sessionId:B.sessionId,cwd:rt,readonly:!1,resolved:B};B.agentId!==void 0&&(le.agentId=B.agentId),ne(le)},Xf=async w=>{if(!ln)return;let v=await ao(t,{includeNonInteractive:!0}),R=w.trim();if(!R){A.notify("usage: /session <id|next|prev>");return}let O=R.startsWith(Yt)?[R]:[R,Yt+R],T=v.find(ne=>O.includes(ne.sessionId));if(!T){let ne=v.filter(le=>O.some(de=>le.sessionId.startsWith(de)));if(ne.length===1)T=ne[0];else if(ne.length>1){A.notify(`ambiguous session id: ${R} (${ne.length} matches)`);return}}if(!T){A.notify(`no session matches: ${R}`);return}if(T.sessionId===me){A.notify("already on that session");return}if(r.terminalHostLauncher){let ne=await ix({kind:"attach",sessionId:T.sessionId},v,T.cwd??rt);A.notify(ne);return}let L=ln;ln=null,na();let B={...r,sessionId:T.sessionId,cwd:T.cwd??rt,readonly:!1,resolved:T};T.agentId!==void 0&&(B.agentId=T.agentId),delete B.resumeHint,L(B)},Ar=w=>{switch(w.type){case"send":o.defaultEnterAction==="amend"?sa(w.text,w.attachments,w.displayText):Nd(w.text,w.attachments,w.displayText);return;case"amend":o.defaultEnterAction==="amend"?Nd(w.text,w.attachments,w.displayText):sa(w.text,w.attachments,w.displayText);return;case"queue-edit":{let v=ep(w.index);if(!v)return;let R=[];w.text.length>0&&R.push({type:"text",text:w.text});for(let O of w.attachments)R.push({type:"image",data:O.data,mimeType:O.mimeType});y.request("hydra-acp/prompt/update",{sessionId:me,messageId:v,prompt:R}).then(O=>{let T=O;if(T.updated||T.reason==="ok"){let L=Hs.get(v);L&&(L.text=w.text,L.displayText=w.displayText??w.text,L.attachments=w.attachments)}else A.notify(`queue edit skipped (${T.reason})`)}).catch(O=>{A.notify(`queue edit failed: ${O.message}`)});return}case"queue-remove":{let v=ep(w.index);if(!v)return;y.request("hydra-acp/prompt/cancel",{sessionId:me,messageId:v}).then(R=>{let O=R;!O.cancelled&&O.reason!=="ok"&&A.notify(`queue cancel skipped (${O.reason})`)}).catch(R=>{A.notify(`queue cancel failed: ${R.message}`)});return}case"cancel":{if(A.isOverlayOpen()){M&&(M.cancel(),M=null,F=null),A.closeBtwOverlay();return}let v=Zr[0];if(w.prefill&&v){let R=nn.size===0,O=Le.state().buffer.every(T=>T==="");R&&O&&(vo={text:v.text,attachments:v.attachments})}v?v.cancel():z>0&&Co(),xd();return}case"exit":Pl();return;case"plan-toggle":er(w.on);return;case"redraw-banner":A.setBanner({});return;case"redraw":A.fullRedraw();return;case"scroll-to-top":A.scrollToTop();return;case"scroll-to-bottom":A.scrollToBottom();return;case"switch-session":Rr().catch(v=>{we({src:"switch-session-failed",stack:v instanceof Error?v.stack??v.message:String(v)})});return;case"next-live-session":$d("next").catch(()=>{});return;case"prev-live-session":$d("prev").catch(()=>{});return;case"toggle-options":ts();return;case"toggle-sidebar":Ay(!A.isSidebarVisible());return;case"toggle-questions":ii();return;case"toggle-thoughts":o.showThoughts=!o.showThoughts,A.setHideThoughts(!o.showThoughts),A.notify(o.showThoughts?"thoughts shown":"thoughts hidden");return;case"show-help":Yf();return;case"escalate-search":A.enterScrollbackSearch(),A.updateScrollbackSearchTerm(w.query);return;case"attachment-request":fy(w.source);return;case"edit-in-editor":ra();return}},ra=async()=>{let w=await Ig(Le.expandedText(),{suspend:()=>A.stop(),resume:()=>A.start(),notify:v=>A.notify(v)});w!==null&&(Le.setBuffer(w,Le.state().attachments),A.setAttachments(Le.state().attachments),A.refreshPrompt())},Zf=async w=>{if(!Rn){A.notify("agent does not accept image attachments");return}let v=0;for(let R of w){if(R.startsWith("data:")){let T=Bv(R);if(!T){A.notify("unsupported data: URI");continue}if(T.sizeBytes>po){A.notify(`image too large (${zr(T.sizeBytes)}, max ${zr(po)})`);continue}Le.addAttachment({mimeType:T.mimeType,data:T.data,name:"pasted image",sizeBytes:T.sizeBytes}),v++;continue}let O=yf(R);if(!O){A.notify(`unsupported image type: ${qi.basename(R)}`);continue}try{let T=await rx.readFile(R);if(T.length>po){A.notify(`image too large (${zr(T.length)}, max ${zr(po)})`);continue}Le.addAttachment({mimeType:O,data:T.toString("base64"),name:qi.basename(R),sizeBytes:T.length}),v++}catch(T){A.notify(`cannot read ${qi.basename(R)}: ${T.message}`)}}v>0&&(A.setAttachments(Le.state().attachments),A.refreshPrompt())},fy=async(w="clipboard")=>{let v=w==="primary"?await l_():await kg();if(!v.ok){A.notify(v.reason);return}if(v.kind==="image"){if(!Rn){A.notify("agent does not accept image attachments");return}Le.addAttachment(v.attachment),A.setAttachments(Le.state().attachments),A.refreshPrompt();return}let R=Le.feed({type:"paste",text:v.text});for(let O of R)Ar(O);A.refreshPrompt()},Od=w=>{let v=w.attachmentCount>0?`${w.text} \xB7 \u{1F4CE}\xD7${w.attachmentCount}`:w.text;return w.held?`\u23F8 ${v}`:v},Fd=(w,v)=>{let R=Array.isArray(v)?v:[],O="",T=0;for(let L of R){if(!L||typeof L!="object")continue;let B=L;B.type==="text"&&typeof B.text=="string"?O+=B.text:B.type==="image"&&(T+=1)}return{messageId:w,text:ot(O),attachmentCount:T}},nn=new Map,Zn=[],Hs=new Map,Ld=new Set,ss=null,dr=()=>{let w=[...nn.values()],v=w.map(Od);A.setQueuedPrompts(v),A.setBanner({queued:w.length}),A.setSidebarSnapshot({queued:w.length}),Le.setQueue(w.map(R=>R.text))},ep=w=>[...nn.values()][w]?.messageId;if(ti&&ti.length>0){for(let w of ti){if(w.position===0){ke=w.messageId;continue}nn.set(w.messageId,Fd(w.messageId,w.prompt))}nn.size>0&&dr()}let Nd=(w,v,R)=>{A.scrollToBottom(),!Ll(w)&&(cn(w,R),Nl(w,v,R))},tp=(w,v,R)=>{if(A.scrollToBottom(),Ll(w))return;if(cn(w,R),!Ps||ke===void 0){Nl(w,v,R);return}let O=ke,T=[];w.length>0&&T.push({type:"text",text:w});for(let ne of v)T.push({type:"image",data:ne.data,mimeType:ne.mimeType});let L={text:w,displayText:R??w,attachments:v,flushed:!1};Zn.push(L);let B=()=>{let ne=Zn.indexOf(L);ne>=0&&Zn.splice(ne,1),L.messageId!==void 0&&Hs.delete(L.messageId)};y.request("hydra-acp/prompt/amend",{sessionId:me,targetMessageId:O,prompt:T}).then(ne=>{let le=ne;if(le.amended&&le.reason==="ok"){Ht(1,"self");return}if(B(),le.reason==="target_completed"){A.notify("previous response finished \u2014 press Enter to send as a new turn"),Le.setBuffer(w,v),A.refreshPrompt();return}if(le.reason==="target_cancelled"){A.notify("amend skipped \u2014 previous turn was cancelled"),Le.setBuffer(w,v),A.refreshPrompt();return}if(le.reason==="target_not_found"){A.notify("amend skipped \u2014 no matching prompt"),Le.setBuffer(w,v),A.refreshPrompt();return}}).catch(ne=>{B(),A.notify(`amend failed: ${ne.message}`),Le.setBuffer(w,v),A.refreshPrompt()})},sa=(w,v,R)=>{if(A.scrollToBottom(),Ll(w))return;if(cn(w,R),!Qr){tp(w,v,R);return}let O=[];w.length>0&&O.push({type:"text",text:w});for(let B of v)O.push({type:"image",data:B.data,mimeType:B.mimeType});let T={text:w,displayText:R??w,attachments:v,flushed:!1};Zn.push(T);let L=()=>{let B=Zn.indexOf(T);B>=0&&Zn.splice(B,1),T.messageId!==void 0&&Hs.delete(T.messageId)};y.request("_session/steering",{sessionId:me,prompt:O}).then(B=>{let ne=B;if(ne.outcome==="injected"){let le=Zn.indexOf(T);le>=0&&Zn.splice(le,1),T.flushed=!0,C({kind:"user-text",text:T.displayText,attachments:T.attachments}),ss=T;return}if(ne.outcome==="startedNewTurn"){ne.detached!==!0&&Ht(1,"self");return}L(),A.notify("steering failed"),Le.setBuffer(w,v),A.refreshPrompt()}).catch(B=>{if(B.code===-32601){L(),tp(w,v,R);return}L(),A.notify(`steering failed: ${B.message}`),Le.setBuffer(w,v),A.refreshPrompt()})},er=async w=>{if(ri.length===0){A.notify("no modes advertised by agent");return}let v=A.currentModeId(),R=ri.findIndex(L=>L.id===v),O=R===-1?0:(R+1)%ri.length,T=ri[O]?.id;if(T){A.setBanner({currentMode:T});try{await y.request("session/set_mode",{sessionId:me,modeId:T})}catch(L){A.notify(`set_mode failed: ${L.message}`)}}},Ll=w=>{let v=w.replace(/\s+$/,"");if(!v.startsWith("/")||v.includes(`
307
307
  `))return!1;let R=v.indexOf(" "),O=R===-1?v:v.slice(0,R);switch(O){case"/quit":case"/exit":return Pl(),!0;case"/clear":return Kt.clear(),Bs.clear(),cr.length=0,ui.clear(),Te=null,Pe=null,Ve=null,Po.clear(),Mo.clear(),Z.clear(),_e.clear(),at.clear(),vn.clear(),ce.clear(),A.clearScrollback(),!0;case"/help":{let T=[{prefix:" ",body:"Built-in commands:",bodyStyle:"local-heading"}];for(let L of zf)T.push({prefix:" ",body:` ${L.name.padEnd(12)} ${L.description??""}`,bodyStyle:"local-item"});if(wd.length>0){T.push({prefix:" ",body:"Agent commands:",bodyStyle:"local-heading"});for(let L of wd)T.push({prefix:" ",body:` ${L.name.padEnd(12)} ${L.description??""}`,bodyStyle:"local-item"})}return A.appendLines(T),!0}case"/agent":case"/model":case"/mode":{let T=O.slice(1),L=R===-1?"":v.slice(R+1).trim();if(!L)return se(T),!0;let B=J(T);if(!B)return!0;let ne=W(B,L);return ne===null?(A.notify(`unknown ${T}: ${L}`),!0):ne===B.currentValue?(A.notify(`already on ${T} ${ne}`),!0):(St(T,ne),!0)}case"/hydra":{let T=R===-1?"":v.slice(R+1).trim(),L=T.length>0?T.split(/\s+/):[];return L[0]!=="config"||L.length>2?!1:L.length===1?(ae(),!0):es.some(B=>B.id===L[1])?(se(L[1]),!0):!1}case"/title":{let T=R===-1?"":v.slice(R+1).trim();return T?r.readonly===!0?(A.notify("view-only: rename disabled"),!0):(Ju(t,me,T).catch(L=>{A.notify(`rename failed: ${L.message}`)}),!0):(Pd(A.sessionTitle()??""),!0)}case"/sessions":return A.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"notice"}]),!0;case"/resume":return Rr().catch(T=>{we({src:"switch-session-failed",stack:T instanceof Error?T.stack??T.message:String(T)})}),!0;case"/session":{let T=R===-1?"":v.slice(R+1).trim();return T?T==="next"||T==="prev"?($d(T).catch(L=>{A.notify(`session ${T} failed: ${L.message}`)}),!0):(Xf(T).catch(L=>{A.notify(`session switch failed: ${L.message}`)}),!0):(Rr().catch(L=>{we({src:"switch-session-failed",stack:L instanceof Error?L.stack??L.message:String(L)})}),!0)}case"/rename":{let T=R===-1?"":v.slice(R+1).trim(),L=T.length>0?`/hydra title ${T}`:"/hydra title";return cn(v,v),Nl(L,[],v),!0}case"/btw":{let T=R===-1?"":v.slice(R+1).trim();if(!T)return A.isOverlayOpen()?(M&&(M.cancel(),M=null,F=null),A.closeBtwOverlay(),!0):(A.reopenBtwOverlay()||A.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"notice-error"}]),!0);if(me==="__new__")return A.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"notice-error"}]),!0;Y+=1;let L=Y;M&&(M.cancel(),M=null);let B=null;F!==null&&!K?B=F:F!==null&&(co(t,F).catch(()=>{}),F=null),K=!1,A.openBtwOverlay(),A.setBtwOverlayStatus({label:"busy",style:"busy"});let ne=new gg({getMaxWidth:()=>{let ft=A.width();return ft>0?ft:void 0}});ne.on("changed",()=>{A.setBtwOverlayContent(ne.getLines())});let le={};ne.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:T}]});let de=ft=>{ne.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ft}})},Ft={};return B!==null&&(Ft.reuseSessionId=B),YM(t,me,T,Ft).then(ft=>{if(L!==Y){ft.cancel();return}M=ft,F=ft.sessionId,A.setBtwOverlayMeta({sessionId:ft.sessionId}),ft.on("event",De=>{if(L===Y)if(De.kind==="update"){ne.append(De.update);let xt=Xs(De.update);if(xt&&xt.kind==="usage-update"){let sn=!1;xt.used!==void 0&&le.used!==xt.used&&(le.used=xt.used,sn=!0),xt.size!==void 0&&le.size!==xt.size&&(le.size=xt.size,sn=!0),xt.costAmount!==void 0&&le.costAmount!==xt.costAmount&&(le.costAmount=xt.costAmount,sn=!0),xt.costCurrency!==void 0&&le.costCurrency!==xt.costCurrency&&(le.costCurrency=xt.costCurrency,sn=!0),sn&&A.setBtwOverlayMeta({usage:{...le}})}}else De.kind==="completed"?(A.setBtwOverlayStatus({label:"done",style:"done"}),M=null):De.kind==="cancelled"?(A.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),M=null,F=null):De.kind==="errored"&&(A.setBtwOverlayStatus({label:"errored",style:"errored"}),de(`btw errored: ${De.error.message}`),F!==null&&co(t,F).catch(()=>{}),M=null,F=null)})}).catch(ft=>{if(L!==Y)return;let De=ft instanceof Error?ft.message:String(ft);A.setBtwOverlayStatus({label:"errored",style:"errored"}),de(`btw startup failed: ${De}`),A.appendLines([{prefix:" ",body:`btw startup failed: ${De}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(me==="__new__")return A.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"notice-error"}]),!0;let T=R===-1?"":v.slice(R+1).trim(),L=me;return(async()=>{try{let B=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(L)}/transcript`,{headers:{Authorization:`Bearer ${t.token}`}});if(!B.ok){let De=await B.text().catch(()=>"");A.appendLines([{prefix:" ",body:`/export failed: HTTP ${B.status} ${De}`.trim(),bodyStyle:"notice-error"}]);return}let ne=await B.text(),le=new Date().toISOString().replace(/[:.]/g,"-"),de=`hydra-${Qe(L)}-${le}.md`,Ft=T.length>0?Ze(T):de,ft=qi.resolve(Ft);await rx.mkdir(qi.dirname(ft),{recursive:!0}),await rx.writeFile(ft,ne,{encoding:"utf8",mode:384}),A.appendLines([{prefix:" ",body:`Wrote ${ft}`,bodyStyle:"notice-ok"}])}catch(B){A.appendLines([{prefix:" ",body:`/export failed: ${B.message}`,bodyStyle:"notice-error"}])}})(),!0}default:return!1}},Nl=async(w,v,R)=>{let O=[];w.length>0&&O.push({type:"text",text:w});for(let De of v)O.push({type:"image",data:De.data,mimeType:De.mimeType});Ht(1,"self");let T={text:w,displayText:R??w,attachments:v,flushed:!1};Zn.push(T),z===1&&(it=!1);let L=!1,B=!1,ne=null,le=De=>{typeof X<"u"&&X!==null&&X.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:De,bodyStyle:"tool-status-fail"}])},de=!1,Ft={text:w,attachments:v,cancel:()=>{if(it){it=!1,de=!0,le("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),y.request("hydra-acp/session/force_cancel",{sessionId:me}).catch(xt=>{le(`force-stop failed: ${xt.message}`)});return}if(L)return;L=!0,y.notify("session/cancel",{sessionId:me}).catch(()=>{});let De=Date.now();ne=setTimeout(()=>{B||Wt>=De||(it=!0,le("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent)."))},ud)}};Zr.push(Ft);let ft;try{let De=await y.request("session/prompt",{sessionId:me,prompt:O});De&&typeof De.stopReason=="string"&&(ft=De.stopReason)}catch(De){let xt=Zn.indexOf(T);xt>=0&&Zn.splice(xt,1),T.messageId!==void 0&&Hs.delete(T.messageId),de?A.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):A.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:De.message,bodyStyle:"tool-status-fail"}])}finally{B=!0;let De=Zr.indexOf(Ft);if(De>=0&&Zr.splice(De,1),De===0&&Zr.length>0&&(it=!1),ne!==null&&(clearTimeout(ne),ne=null),Ht(-1),T.flushed&&ss===T){let xt=T.messageId!==void 0&&Ld.has(T.messageId);xt&&T.messageId!==void 0&&Ld.delete(T.messageId);let sn={kind:"turn-complete"};ft!==void 0&&(sn.stopReason=ft),xt&&(sn.amended=!0),C(sn),ss=null}if(vo!==null){let{text:xt,attachments:sn}=vo;vo=null,Le.state().buffer.every($o=>$o==="")&&(Le.setBuffer(xt,sn),A.refreshPrompt())}}},Kt=new Map;Sr=()=>{for(let w of Kt.values())if(tS(w.status))return!0;return!1};let Po=new Map,Mo=new Map,Bs=new Map,cr=[],ui=new Map,N=[],ee=0,pe=`tools:${ee}`,Z=new Map,_e=new Map,Be=new Set,Ue=new Map,at=new Map,vn=new Map,ce=new Map,Te=null,Pe=null,Ve=null,te=null,ze=null,qe=!1,dt=null,Mt=e.tui.maxToolItems,_o=e.tui.maxPlanItems,lr=()=>({maxPlanItems:dt??o.planExpanded?1/0:_o}),rn=w=>{let v=KV(w.entries);qe&&(qe=!1,GV({stale:!0,hasKey:A.hasKey("plan"),prevFingerprint:ze,fingerprint:v})==="fresh"&&A.clearKey("plan")),ze=v;let R=qo(w,lr());R.length>0&&A.upsertLines("plan",[{body:""},...R]);let O=w.entries.length>0&&w.entries.every(T=>(T.status??"pending")==="completed");A.setStickyBottomKey(O?null:"plan")},os=()=>{if(te===null)return;let w=qo(te,lr());w.length>0&&A.upsertLines("plan",[{body:""},...w])},is="",Ce=null,st=0,Tr,np=()=>{if(Ce===null)return;let w=A.width(),v=zo(is,w>0?{maxWidth:w}:void 0);v.length!==0&&A.upsertLines(Ce,v)},bF=(w,v)=>{w.length!==0&&(Ce===null&&(A.ensureSeparator(),Ce=`agent:${st}`,st+=1,is="",Tr=v),is+=w,vn.set(Ce,is),np())},as=()=>{Ce=null,is="",Tr=void 0},Dd="",fi=null,hx=0,py,kF=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),vF=()=>{if(fi===null||Dd.length===0)return;let w=nl(Dd);w.length!==0&&A.upsertLines(fi,w)},mx=w=>{let v=at.get(w);if(v===void 0)return[];let R=nl(v.text);return v.workerTaskId&&R.unshift({prefix:" ",body:`[T${v.workerTaskId}] `,bodyStyle:"muted"}),R},SF=(w,v)=>{w.length!==0&&(fi===null&&(A.ensureSeparator("thought"),fi=`thought:${hx}`,hx+=1,Dd="",py=v),Dd+=w,at.set(fi,{text:Dd,workerTaskId:v}),vF())},ds=()=>{py=void 0,fi=null,Dd=""},gx=w=>YV({...w,collapsedLimit:Mt}),yx=w=>_e.get(w)??o.toolsExpanded,ur=()=>{if(Te===null)return;let{lines:w,rowOwners:v}=gx({order:cr,states:Kt,startedAt:Te,endedAt:Pe,stopReason:Ve,expanded:yx(pe),perToolExpanded:Be});A.upsertLines(pe,w),Ue.set(pe,v)},rp=w=>{let v=Z.get(w);if(!v)return;let{lines:R,rowOwners:O}=gx({order:v.order,states:v.states,startedAt:v.startedAt,endedAt:v.endedAt,stopReason:v.stopReason,expanded:yx(w),perToolExpanded:Be});A.upsertLines(w,R),Ue.set(w,O)},hy=()=>{Te!==null&&!Z.has(pe)&&ur();for(let w of Z.keys())rp(w)},my=()=>{Te!==null&&Z.set(pe,{order:[...cr],states:new Map(Kt),startedAt:Te,endedAt:Pe??Date.now(),stopReason:Ve,rowOwners:Ue.get(pe)??[]})},wx=w=>{ee+=1,pe=`tools:${ee}`,Te=w??Date.now(),Pe=null,Ve=null,ur()};function xF(w){if(!w||typeof w!="object")return null;let v=w,R=Array.isArray(v.content)?v.content:void 0,O=[],T=L=>{if(typeof L=="string"){O.push({text:Gt(L)});return}if(L&&typeof L=="object"){let B=L;typeof B.__hydraBlob=="string"&&O.push({hash:B.__hydraBlob})}};for(let L of R??[]){if(!L||typeof L!="object")continue;let B=L;if(B.type==="content"&&B.content&&typeof B.content=="object"){let ne=B.content;if(ne.text!==void 0){T(ne.text);continue}}if(B.type==="text"&&B.text!==void 0){T(B.text);continue}B.text!==void 0&&T(B.text)}if(O.length===0)for(let L of hR(v))T(L);return O.length>0?O:null}let bx=(w,v)=>{let R=v.map(L=>"text"in L?L.text:"").join(`
308
308
  `);if(R.length===0)return;let{text:O,truncated:T}=UE(R);w.resultText=O,w.resultTruncated=T},sp=new Set,IF=(w,v)=>{!v.some(O=>"hash"in O)||sp.has(w)||(sp.add(w),(async()=>{let O=await Promise.all(v.map(async L=>"text"in L?L:{text:await op(L.hash)??""}));sp.delete(w);let T=Kt.get(w);if(!T)for(let L of Z.values()){let B=L.states.get(w);if(B){T=B;break}}if(T){bx(T,O),Kt.has(w)&&ur();for(let[L,B]of Z)B.states.has(w)&&rp(L);A.repaintNow()}})().catch(()=>{sp.delete(w)}))},gy=(w,v)=>{let R=v??Kt.get(w);if(R===void 0)return;let O=_O(R,Po.get(w)??R.editDiff,rt);if(O.length===0){ui.delete(w);return}ui.set(w,O)},kx=(w,v,R,O,T,L,B,ne,le,de,Ft,ft,De=!1)=>{let xt=!Kt.has(w),sn=Kt.get(w),gt=sn??{initialTitle:v??"tool",latestTitle:v??"tool",status:R??"pending",startedAt:ft??Date.now()};if(!sn&&le!==void 0&&(gt.workerTaskId=le),Ft!==void 0&&gt.rawKind===void 0&&(gt.rawKind=Ft),sn&&v!==void 0&&(gt.latestTitle=v),L!==void 0&&gt.detail===void 0&&(gt.detail=L),B!==void 0&&gt.detailFull===void 0&&(gt.detailFull=B),ne!==void 0&&ne.length>0&&(gt.locations=ne),sn&&R!==void 0&&(gt.status=R),sn||(gt.status=R??"pending"),gt.endedAt===void 0&&qk(gt.status)&&(gt.endedAt=ft??Date.now(),gt.startedAt!==void 0&&gt.endedAt<gt.startedAt&&(gt.endedAt=gt.startedAt),Ry()),O!==void 0&&(gt.errorText=O),T!==void 0&&(gt.editDiff=T),de!==void 0){let _t=qp(de);_t.length>0&&(gt.patchedFiles=_t);let An=gR(de);An!==void 0&&(gt.editStats=An);let Ty=eb(de);Ty!==void 0&&(gt.resultSummary=Ty)}if(de!==void 0){let _t=xF(de);_t!==null&&(bx(gt,_t),_t.some(An=>"hash"in An)&&IF(w,_t))}Kt.set(w,gt),gy(w,gt);let $o=FO(de);$o!==null&&(N=$o,Ry(),$o.length>0&&rn({kind:"plan",entries:$o})),xt&&(pO({blockOpen:Te!==null,isStart:De})&&(ee+=1,pe=`tools:${ee}`,Te=Date.now(),Pe=null,Ve=null),Te!==null&&cr.push(w),A.isSidebarVisible()&&Bl())},op=async w=>{try{let v=await y.request("hydra-acp/session/tool_content",{sessionId:me,hash:w});return typeof v?.content=="string"?v.content:null}catch{return null}},ip=new Set,yy=w=>w.oldRef!==void 0||w.newRef!==void 0||w.patchRef!==void 0,CF=(w,v)=>{ip.has(w)||yy(v)&&(ip.add(w),(async()=>{let[R,O]=await Promise.all([v.oldRef?op(v.oldRef.hash):Promise.resolve(v.oldText),v.newRef?op(v.newRef.hash):Promise.resolve(v.newText)]),T=!1;if(v.patchRef){let Ft=await op(v.patchRef.hash);Ft===null?T=!0:{oldText:R,newText:O}=Cc(Ft)}if(T||v.oldRef!==void 0&&R===null||v.newRef!==void 0&&O===null){ip.delete(w);let Ft=Sx(w,v,Uk(v,"diff",{deferredStatus:"error"}));Ft.length>0&&(A.upsertLines(`editdiff:${w}`,Ft),A.repaintNow());return}let B={...v.path!==void 0?{path:v.path}:{},oldText:R??"",newText:O??""};Po.set(w,B);let ne=Kt.get(w);ne?.editDiff&&(ne.editDiff=B),gy(w),ip.delete(w);let le=Mo.get(w),de=le===void 0?o.showFileUpdates:le?"diff":"edit";de!=="none"&&(ap(w,B,de==="diff"?"diff":"edit"),A.repaintNow())})())},vx=new Map,Sx=(w,v,R)=>{let O=vx.get(w);return O===void 0&&(O=Kt.get(w)?.locations?.[0]?.line??NF(v),vx.set(w,O)),O===null?R:R.map(T=>T.links===void 0?T:{...T,links:T.links.map(L=>({...L,url:`${L.url}#L${O}`}))})},ap=(w,v,R)=>{let O=`editdiff:${w}`,T=Sx(w,v,Uk(v,R));if(T.length===0){A.removeKey(O);return}A.upsertLines(O,T),R==="diff"&&yy(v)&&A.notifyWhenVisible(O)},RF=w=>{if(!w.startsWith("editdiff:"))return;let v=w.slice(9),R=Po.get(v);R&&yy(R)&&CF(v,R)},xx=w=>{let v=Kt.get(w);Ix(w,v?.editDiff,v?.status),v?.patchedFiles!==void 0&&aR(v.patchedFiles).forEach((R,O)=>{Ix(`${w}#${O}`,R,v.status)})},Ix=(w,v,R)=>{let O=`editdiff:${w}`,T=o.showFileUpdates,L;if(T==="none"||!v||R!=="completed")L=null;else{let ne=Mo.get(w);L=ne!==void 0?ne?"diff":"edit":T==="diff"?"diff":"edit"}if(L===null){A.removeKey(O);return}let B=v;Po.set(w,B),gy(w),ap(w,B,L)},wy=()=>{let w=o.showFileUpdates;for(let[v,R]of Po){let O=`editdiff:${v}`,T=Mo.get(v),L=T===void 0?w:T?"diff":"edit";if(L==="none"){A.removeKey(O);continue}ap(v,R,L==="diff"?"diff":"edit")}},Cx=()=>{let w=A.width(),v=w>0?{maxWidth:w}:void 0;for(let[O,T]of vn){let L=zo(T,v);L.length>0&&A.upsertLines(O,L)}let R=new Set;for(let O of ce.values())for(let T of O)R.add(T);for(let O of at.keys()){if(R.has(O))continue;let T=mx(O);T.length>0&&A.upsertLines(O,T)}},Rx=()=>{A.isSidebarOverlay()||(hy(),wy(),os(),Cx())},by=!1,dp=null,Ax=w=>{WO("git",["status","--porcelain=v2","--branch"],{cwd:w,timeout:3e3,maxBuffer:4*1024*1024},(v,R)=>{by=!1,A.setSidebarSnapshot({git:v?null:EO(R,dp)})})},Dl=()=>{if(by||rt===null)return;if(Zt){A.setSidebarSnapshot({git:null});return}let w=rt;if(by=!0,dp!==null){Ax(w);return}WO("git",["rev-parse","--show-toplevel"],{cwd:w,timeout:3e3},(v,R)=>{v||(dp=R.trim()||null),Ax(w)})},ky=!1,vy=()=>{ky||(ky=!0,(async()=>{try{let w=await ao(t,{status:"warm"}),v=[];for(let R of w)R.sessionId!==me&&v.push({sessionId:R.sessionId,label:R.title!==void 0&&R.title.length>0?R.title:Qe(R.sessionId),busy:R.busy===!0,armed:(R.armedTasks??0)>0,blocked:R.awaitingInput===!0});A.setSidebarSnapshot({liveSessions:v})}catch{}finally{ky=!1}})())},AF="hydra",TF="agent",cp=null,Sy=!1,lp=null,Hl=null,xy=null,Iy=!1,Tx=(()=>{try{let w=new URL(t.baseUrl).hostname;return w==="127.0.0.1"||w==="localhost"||w==="::1"||w==="[::1]"}catch{return!1}})(),Ex=()=>{Iy||me===null||(Iy=!0,(async()=>{try{let w=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(w.ok){let v=await w.json();xy=typeof v.agentPid=="number"?v.agentPid:null}}catch{}finally{Iy=!1}})())},Px=()=>{Sy||(Sy=!0,(async()=>{try{let w=[],v=process.cpuUsage(),R=Date.now();w.push({label:AF,rssBytes:process.memoryUsage.rss(),cpuFraction:DO(v,lp,Hl===null?0:R-Hl),processes:1}),lp=v,Hl=R;let O=xy;if(O!==null){let T=await BO([O]),L=HO(T,cp,O);L!==null&&w.push({label:TF,...L}),cp=T}A.setSidebarSnapshot({resources:w})}finally{Sy=!1}})())},Mx=()=>{A.isSidebarGadgetActive("resources")&&(cp=null,lp=null,Hl=null,Tx&&Ex(),Px())},EF=()=>{cp=null,lp=null,Hl=null,xy=null,A.setSidebarSnapshot({resources:[]})},PF=()=>{A.isSidebarGadgetActive("sessions")&&vy()},MF=()=>{A.setSidebarSnapshot({liveSessions:[]})},_F=()=>{A.isSidebarGadgetActive("git")&&Dl()},_x=()=>{A.setSidebarSnapshot({git:null})},$F=5,Hd=null,Cy=0,OF=()=>{Hd===null&&(Cy=0,Hd=setInterval(()=>{Cy++;let w=Cy%$F===0;(xe!==null||w)&&Bl(),w&&A.isSidebarGadgetActive("git")&&Dl(),w&&A.isSidebarGadgetActive("sessions")&&vy(),w&&A.isSidebarGadgetActive("resources")&&(Tx&&Ex(),Px())},1e3),Hd.unref?.())},$x=()=>{Hd!==null&&(clearInterval(Hd),Hd=null)},Ry=()=>{A.isSidebarVisible()&&(Bl(),A.isSidebarGadgetActive("git")&&Dl())},Ay=w=>{o.sidebarVisible=w,A.setSidebarVisible(w),Rx(),Bl(),A.isSidebarSuppressed()?A.notify("sidebar needs a wider terminal (80+ columns)"):w&&A.isSidebarOverlay()&&A.notify("sidebar overlaying transcript (too wide to reflow)"),A.fullRedraw(),w?(_F(),PF(),Mx(),OF()):(_x(),MF(),EF(),$x())},Bl=()=>{A.setSidebarSnapshot({busySince:xe,lastTurnEndedAt:je,queued:nn.size,plan:FF(),editedFiles:LF(),running:R_(cr,Kt,rt),sessionId:me===null?null:Qe(me),agent:vd()})},FF=()=>te!==null&&te.entries.length>0?te.entries:N,LF=()=>$O([...ui.values()].flat()),NF=w=>{if(!w.path||Zt)return null;let v=Gt(w.oldText).split(`
309
309
  `),R=Gt(w.newText).split(`
310
310
  `),O=0,T=Math.min(v.length,R.length);for(;O<T&&v[O]===R[O];)O++;let L=R[O];if(!L)return null;let B=qi.isAbsolute(w.path)?w.path:qi.resolve(rt,w.path),ne;try{ne=PV(B,"utf8")}catch{return null}let le=ne.split(`
311
- `);for(let de=0;de<le.length;de++)if(le[de]===L)return de+1;return null},DF=(w,v,R=null)=>{if(w.startsWith("editdiff:")){let O=w.slice(9),T=Po.get(O);if(!T)return;let L=Mo.get(O)??o.showFileUpdates==="diff";Mo.set(O,!L),ap(O,T,L?"edit":"diff"),A.repaintNow();return}if(w==="plan"){if(te===null)return;dt=!(dt??o.planExpanded),os(),A.repaintNow();return}if(w.startsWith("tools:")){if(R===null&&v===0){let L=_e.get(w)??o.toolsExpanded;_e.set(w,!L),w===pe&&Te!==null?ur():rp(w),A.repaintNow();return}let T=R??Ue.get(w)?.[v];if(!T)return;zV(T,Be),w===pe&&Te!==null?ur():rp(w),A.repaintNow();return}if(w.startsWith("thought:")){if(!at.has(w))return;let O=ce.get(w);if(O!==void 0){ce.delete(w),A.setRunCollapsed(O,!1,mx(w)),A.repaintNow();return}let T=A.contiguousRun(w,new Set(at.keys()));if(T.length===0)return;let L=T[0];ce.set(L,T),A.setRunCollapsed(T,!0,[kF()]),A.repaintNow();return}};S=(w,v,R)=>{if(w.kind==="available-commands"){wd=w.commands,Rl();return}if(w.kind==="available-modes"){ri=w.modes;return}if(w.kind==="config-options"){es=w.options,A.setSidebarSnapshot({configOptions:jO(w.options)});let T=w.options.find(B=>B.id==="agent");T&&T.currentValue&&T.currentValue!==Rt&&(Rt=T.currentValue,A.setSessionbar({agent:T.currentValue}),A.setSidebarSnapshot({agent:vd()}));let L=w.options.find(B=>B.id==="mode");L&&(ri=L.options.map(B=>({id:B.value,name:B.name??B.value,...B.description!==void 0?{description:B.description}:{}})));return}if(w.kind==="mode-changed"){A.setBanner({currentMode:w.mode||void 0}),A.setSidebarSnapshot({mode:w.mode||null});return}if(w.kind==="session-info"){w.title!==void 0&&A.setSessionbar({title:w.title}),w.agentId!==void 0&&w.agentId!==Rt&&(Rt=w.agentId,A.setSessionbar({agent:w.agentId}),A.setSidebarSnapshot({agent:vd()})),w.pendingAgentSwap!==void 0&&(typeof w.pendingAgentSwap=="string"?A.setCompactionIndicator(`switching to ${w.pendingAgentSwap}...`):(A.setCompactionIndicator(null),w.agentId!==void 0&&A.notify(`switched to ${w.agentId}`,2e3)));return}if(w.kind==="usage-update"){let T=!1;w.used!==void 0&&Vn.used!==w.used&&(Vn.used=w.used,T=!0),w.size!==void 0&&Vn.size!==w.size&&(Vn.size=w.size,T=!0),w.costAmount!==void 0&&Vn.costAmount!==w.costAmount&&(Vn.costAmount=w.costAmount,T=!0),w.costCurrency!==void 0&&Vn.costCurrency!==w.costCurrency&&(Vn.costCurrency=w.costCurrency,T=!0),T&&(A.setSessionbar({usage:{...Vn}}),A.setSidebarSnapshot({usage:{...Vn}}));return}if(w.kind==="user-text"){Wf&&cn(w.text),as(),ds(),Te!==null&&(Pe=R??Date.now(),ur()),ss=null,A.ensureSeparator();let T=qo(w);T.length>0&&(R!==void 0&&(T[0].recordedAt=R),A.appendLines(T)),my(),qe=!0,A.setStickyBottomKey(null),te=null,dt=null,Kt.clear(),Bs.clear(),cr.length=0,Pe=null,wx(R),A.redraw();return}if(w.kind==="agent-text"){ds(),Ce!==null&&Tr!==w.workerTaskId&&as(),Ce===null&&E(w.workerTaskId),bF(w.text,w.workerTaskId);return}if(w.kind==="agent-thought"){as(),fi!==null&&py!==w.workerTaskId&&ds(),fi===null&&E(w.workerTaskId),SF(w.text,w.workerTaskId);return}if(w.kind==="exit-plan-mode"){as(),ds();let T=Bs.get(w.toolCallId),L={plan:w.plan??T?.plan??"",status:w.status??T?.status};if(Bs.set(w.toolCallId,L),L.plan.length===0)return;let B=zE(L);B.length>0&&A.upsertLines(w.toolCallId,B);return}if(w.kind==="tool-call"){w.parentToolUseId===void 0&&(as(),ds()),Kt.has(w.toolCallId)||E(w.workerTaskId),kx(w.toolCallId,w.title,w.status,void 0,w.editDiff,w.detail,w.detailFull,w.locations,w.workerTaskId,v,w.rawKind,R,!0),ur(),xx(w.toolCallId);return}if(w.kind==="plan"){as(),ds(),te=w,Ry(),rn(w);return}if(w.kind==="turn-started"){if(!w.unsolicited)return;as(),ds(),A.ensureSeparator(),A.appendLines(qo(w)),$e||($e=!0,Ht(1,"agent",w.cause??null));return}if(w.kind==="turn-ended"){if(!w.unsolicited)return;as(),ds(),Te!==null&&Pe===null&&(Pe=R??Date.now(),ur()),$e&&($e=!1,Ht(-1));return}if(w.kind==="tool-call-update"){w.parentToolUseId===void 0&&(as(),ds()),kx(w.toolCallId,w.title,w.status,w.errorText,w.editDiff,w.detail,w.detailFull,w.locations,w.workerTaskId,v,void 0,R),w.upstreamInterrupted&&(Ts=!0),ur(),xx(w.toolCallId);return}w.kind==="model-changed"&&(A.setSessionbar({model:w.model}),A.setSidebarSnapshot({model:w.model}));let O=qo(w);if(O.length>0&&A.appendLines(O),w.kind==="turn-complete"){ke=void 0,as(),ds();let T=w.amended?"amended":w.stopReason;if(!w.amended&&Ts&&(T===void 0||T==="end_turn")&&(T="error"),te!==null&&T!==void 0&&T!=="end_turn"){let L=qo({...te,stopped:!0,amended:w.amended===!0},lr());L.length>0&&A.upsertLines("plan",[{body:""},...L])}te=null,dt=null,qe=!0,A.setStickyBottomKey(null),Te!==null?(Pe=R??Date.now(),Ve=T??null,ur(),my()):T!==void 0&&T!=="end_turn"&&T!=="amended"&&A.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${T}`,bodyStyle:"tool-status-fail"}]),Kt.clear(),Bs.clear(),cr.length=0,Te=null,Pe=null,Ve=null,Ts=!1,A.ensureSeparator(),fO({pendingTurns:z,queueSize:nn.size,ownTurnInFlight:Zr.length>0,hasInFlightHead:ke!==void 0,replayDraining:x,amended:w.amended===!0})&&Ht(-z)}};let Ox=k;k=[];let up=[];for(let{event:w}of Ox)w.kind==="user-text"&&typeof w.text=="string"&&up.push(w.text);A.pauseRepaint(),x=!0;try{for(let{event:w,rawUpdate:v,recordedAt:R}of Ox)S(w,v,R);xl!==void 0&&A.scrollToTurnAt(xl)}finally{x=!1,A.resumeRepaint()}if(up.length>0){let w=Vb(Ne,up);w!==Ne&&(Ne=w,Jn=Vb(Jn,up),Le.setHistory(Eh(Ln,Jn)),Ta($s,Ne).catch(()=>{}),Xr())}Wf=!0,A.setSidebarCollapsed(o.sidebarCollapsed),o.sidebarVisible&&Ay(!0),(async()=>{try{let w=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}/compact/status`,{headers:{Authorization:`Bearer ${t.token}`}});if(!w.ok)return;let v=await w.json();if(typeof v.pendingAgentSwap=="string")A.setCompactionIndicator(`switching to ${v.pendingAgentSwap}...`);else{let L=v.compactionState?.status;L==="requested"||L==="running"?A.setCompactionIndicator("compacting..."):(L==="swap_pending"||L==="swap_deferred")&&A.setCompactionIndicator("compaction queued (waiting for idle)")}if(!Il||v.shouldCompact!==!0)return;let R=v.currentUsage?.used,O=v.currentUsage?.size,T=typeof R=="number"&&typeof O=="number"&&O>0?`This session is using ${ho(R)} of its ${ho(O)} token context window.`:`This session has ~${wT(v.approxTokens??0)} tokens of history above the compaction watermark.`;re=!0,A.setCompactionPrompt({message:T,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),(async()=>{try{let w=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!w.ok)return;let v=await w.json();if(ue&&je===null&&xe===null&&typeof v.updatedAt=="string"){let R=Date.parse(v.updatedAt);Number.isFinite(R)&&(je=R,A.setSidebarSnapshot({lastTurnEndedAt:je}))}v.forkSynthesisState==="running"?(A.setSynthesisIndicator("synthesizing context\u2026"),Sl()):v.forkSynthesisState==="failed"&&(A.setSynthesisIndicator("\u26A0 synthesis failed"),A.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),xr!==void 0&&z>0?(xe=xr,A.setBanner({status:"busy",elapsedMs:Date.now()-xr}),oe===null&&(oe=Kn()),Te===null&&wx(xr),Te=xr,ur()):xr===void 0&&z>0&&Ht(-z),yn(ni??null,Qi===void 0?void 0:sx(Qi)),Ge=!0;let HF=()=>{if(Xe){let w=Xe.resolve;Xe=null,A.setPermissionPrompt(null),w({outcome:{outcome:"cancelled"}})}as(),ds()},Fx=()=>{Te!==null&&(Pe=Date.now(),Ve="reconnect-recovery-failed",ur(),my(),Kt.clear(),Bs.clear(),cr.length=0,Te=null,Pe=null,Ve=null)};return g=w=>{we({src:"reconnect",step:"disconnect",message:w?.message}),A.setBanner({status:"disconnected",elapsedMs:void 0})},b=async w=>{let v=w?.skipInitialize===!0;if(we({src:"reconnect",step:"begin",sessionId:me,skipInitialize:v}),t.isLocal)try{let de=await an(await He());(de.baseUrl!==t.baseUrl||de.wsUrl!==t.wsUrl||de.token!==t.token)&&(we({src:"reconnect",step:"target-refresh",oldBase:t.baseUrl,newBase:de.baseUrl}),t.baseUrl=de.baseUrl,t.wsUrl=de.wsUrl,t.display=de.display,t.token=de.token)}catch(de){we({src:"reconnect",step:"target-refresh-failed",message:de instanceof Error?de.message:String(de)})}HF();let R={jsonrpc:"2.0",id:`tui-reinit-${ax()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:Fe}}};if(!v){we({src:"reconnect",step:"initialize-send"});try{await h.request(R),we({src:"reconnect",step:"initialize-ok"})}catch(de){we({src:"reconnect",step:"initialize-fail",message:de.message})}}let O=gn!==void 0||Yr!==void 0,T={jsonrpc:"2.0",id:`tui-reattach-${ax()}`,method:"session/attach",params:{sessionId:me,historyPolicy:O?"after_message":"none",...O&&gn!==void 0?{afterMessageId:gn}:{},...O&&Yr!==void 0?{afterSeq:Yr}:{},clientInfo:{name:"hydra-acp-tui",version:Fe},...(()=>{let de={};return Yi!==void 0&&(de.resume={upstreamSessionId:Yi,agentId:Rt,cwd:rt}),e.tui.toolContent==="references"&&(de.toolContent="references"),Object.keys(de).length>0?{_meta:{[pt]:de}}:{}})()}};Xo=[];let L,B,ne;we({src:"reconnect",step:"attach-send",useAfterMessage:O,lastSeenMessageId:gn,lastSeenSeq:Yr});try{let de=await h.request(T);if(we({src:"reconnect",step:"attach-resp",hasError:!!de.error}),de.error)throw new Error(de.error.message);ne=uO(de.result),L=ne.appliedPolicy,ne.clientId!==void 0&&(Ms=ne.clientId)}catch(de){B=de,we({src:"reconnect",step:"attach-fail",message:B.message})}let le=Xo??[];if(Xo=null,B)Fx(),A.appendLines([{prefix:" ",body:`reattach failed: ${B.message}`,bodyStyle:"tool-status-fail"}]);else if(O&&L!=="after_message")Fx(),A.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"reconnect couldn't replay events since last seen \u2014 scrollback may be incomplete",bodyStyle:"tool-status-fail"}]);else{le.length>0&&w?.beforeReplay?.(),x=!0;try{for(let de of le)vl(de)}finally{x=!1}}if(B||wo(),ne){let de=hO({daemonTurnStartedAt:ne.turnStartedAt,pendingTurns:z});de.pendingTurnsDelta!==0&&Ht(de.pendingTurnsDelta),de.banner==="busy"&&de.busySince!==void 0?(xe=de.busySince,A.setBanner({status:"busy",elapsedMs:Date.now()-de.busySince}),oe===null&&(oe=Kn())):A.setBanner({status:"ready",elapsedMs:void 0}),ne.armedTasks!==void 0&&yn(ne.armedTasks>0?ne.armedSince??null:null,ne.armedTaskList===void 0?void 0:sx(ne.armedTaskList))}else A.setBanner({status:z>0?"busy":"ready",elapsedMs:z>0?0:void 0});we({src:"reconnect",step:"end"})},y.onClose(w=>{w&&H(n,"notice-error",`
311
+ `);for(let de=0;de<le.length;de++)if(le[de]===L)return de+1;return null},DF=(w,v,R=null)=>{if(w.startsWith("editdiff:")){let O=w.slice(9),T=Po.get(O);if(!T)return;let L=Mo.get(O)??o.showFileUpdates==="diff";Mo.set(O,!L),ap(O,T,L?"edit":"diff"),A.repaintNow();return}if(w==="plan"){if(te===null)return;dt=!(dt??o.planExpanded),os(),A.repaintNow();return}if(w.startsWith("tools:")){if(R===null&&v===0){let L=_e.get(w)??o.toolsExpanded;_e.set(w,!L),w===pe&&Te!==null?ur():rp(w),A.repaintNow();return}let T=R??Ue.get(w)?.[v];if(!T)return;zV(T,Be),w===pe&&Te!==null?ur():rp(w),A.repaintNow();return}if(w.startsWith("thought:")){if(!at.has(w))return;let O=ce.get(w);if(O!==void 0){ce.delete(w),A.setRunCollapsed(O,!1,mx(w)),A.repaintNow();return}let T=A.contiguousRun(w,new Set(at.keys()));if(T.length===0)return;let L=T[0];ce.set(L,T),A.setRunCollapsed(T,!0,[kF()]),A.repaintNow();return}};S=(w,v,R)=>{if(w.kind==="available-commands"){wd=w.commands,Rl();return}if(w.kind==="available-modes"){ri=w.modes;return}if(w.kind==="config-options"){es=w.options,A.setSidebarSnapshot({configOptions:jO(w.options)});let T=w.options.find(B=>B.id==="agent");T&&T.currentValue&&T.currentValue!==Rt&&(Rt=T.currentValue,A.setSessionbar({agent:T.currentValue}),A.setSidebarSnapshot({agent:vd()}));let L=w.options.find(B=>B.id==="mode");L&&(ri=L.options.map(B=>({id:B.value,name:B.name??B.value,...B.description!==void 0?{description:B.description}:{}})));return}if(w.kind==="mode-changed"){A.setBanner({currentMode:w.mode||void 0}),A.setSidebarSnapshot({mode:w.mode||null});return}if(w.kind==="session-info"){w.title!==void 0&&A.setSessionbar({title:w.title}),w.agentId!==void 0&&w.agentId!==Rt&&(Rt=w.agentId,A.setSessionbar({agent:w.agentId}),A.setSidebarSnapshot({agent:vd()})),w.pendingAgentSwap!==void 0&&(typeof w.pendingAgentSwap=="string"?A.setCompactionIndicator(`switching to ${w.pendingAgentSwap}...`):(A.setCompactionIndicator(null),w.agentId!==void 0&&A.notify(`switched to ${w.agentId}`,2e3)));return}if(w.kind==="usage-update"){let T=!1;w.used!==void 0&&Vn.used!==w.used&&(Vn.used=w.used,T=!0),w.size!==void 0&&Vn.size!==w.size&&(Vn.size=w.size,T=!0),w.costAmount!==void 0&&Vn.costAmount!==w.costAmount&&(Vn.costAmount=w.costAmount,T=!0),w.costCurrency!==void 0&&Vn.costCurrency!==w.costCurrency&&(Vn.costCurrency=w.costCurrency,T=!0),T&&(A.setSessionbar({usage:{...Vn}}),A.setSidebarSnapshot({usage:{...Vn}}));return}if(w.kind==="user-text"){Wf&&cn(w.text),as(),ds(),Te!==null&&(Pe=R??Date.now(),ur()),ss=null,A.ensureSeparator();let T=qo(w);T.length>0&&(R!==void 0&&(T[0].recordedAt=R),A.appendLines(T)),my(),qe=!0,A.setStickyBottomKey(null),te=null,dt=null,Kt.clear(),Bs.clear(),cr.length=0,Pe=null,wx(R),A.redraw();return}if(w.kind==="agent-text"){ds(),Ce!==null&&Tr!==w.workerTaskId&&as(),Ce===null&&P(w.workerTaskId),bF(w.text,w.workerTaskId);return}if(w.kind==="agent-thought"){as(),fi!==null&&py!==w.workerTaskId&&ds(),fi===null&&P(w.workerTaskId),SF(w.text,w.workerTaskId);return}if(w.kind==="exit-plan-mode"){as(),ds();let T=Bs.get(w.toolCallId),L={plan:w.plan??T?.plan??"",status:w.status??T?.status};if(Bs.set(w.toolCallId,L),L.plan.length===0)return;let B=zE(L);B.length>0&&A.upsertLines(w.toolCallId,B);return}if(w.kind==="tool-call"){w.parentToolUseId===void 0&&(as(),ds()),Kt.has(w.toolCallId)||P(w.workerTaskId),kx(w.toolCallId,w.title,w.status,void 0,w.editDiff,w.detail,w.detailFull,w.locations,w.workerTaskId,v,w.rawKind,R,!0),ur(),xx(w.toolCallId);return}if(w.kind==="plan"){as(),ds(),te=w,Ry(),rn(w);return}if(w.kind==="turn-started"){if(!w.unsolicited)return;as(),ds(),A.ensureSeparator(),A.appendLines(qo(w)),$e||($e=!0,Ht(1,"agent",w.cause??null));return}if(w.kind==="turn-ended"){if(!w.unsolicited)return;as(),ds(),Te!==null&&Pe===null&&(Pe=R??Date.now(),ur()),$e&&($e=!1,Ht(-1));return}if(w.kind==="tool-call-update"){w.parentToolUseId===void 0&&(as(),ds()),kx(w.toolCallId,w.title,w.status,w.errorText,w.editDiff,w.detail,w.detailFull,w.locations,w.workerTaskId,v,void 0,R),w.upstreamInterrupted&&(Ts=!0),ur(),xx(w.toolCallId);return}w.kind==="model-changed"&&(A.setSessionbar({model:w.model}),A.setSidebarSnapshot({model:w.model}));let O=qo(w);if(O.length>0&&A.appendLines(O),w.kind==="turn-complete"){ke=void 0,as(),ds();let T=w.amended?"amended":w.stopReason;if(!w.amended&&Ts&&(T===void 0||T==="end_turn")&&(T="error"),te!==null&&T!==void 0&&T!=="end_turn"){let L=qo({...te,stopped:!0,amended:w.amended===!0},lr());L.length>0&&A.upsertLines("plan",[{body:""},...L])}te=null,dt=null,qe=!0,A.setStickyBottomKey(null),Te!==null?(Pe=R??Date.now(),Ve=T??null,ur(),my()):T!==void 0&&T!=="end_turn"&&T!=="amended"&&A.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${T}`,bodyStyle:"tool-status-fail"}]),Kt.clear(),Bs.clear(),cr.length=0,Te=null,Pe=null,Ve=null,Ts=!1,A.ensureSeparator(),fO({pendingTurns:z,queueSize:nn.size,ownTurnInFlight:Zr.length>0,hasInFlightHead:ke!==void 0,replayDraining:x,amended:w.amended===!0})&&Ht(-z)}};let Ox=k;k=[];let up=[];for(let{event:w}of Ox)w.kind==="user-text"&&typeof w.text=="string"&&up.push(w.text);A.pauseRepaint(),x=!0;try{for(let{event:w,rawUpdate:v,recordedAt:R}of Ox)S(w,v,R);xl!==void 0&&A.scrollToTurnAt(xl)}finally{x=!1,A.resumeRepaint()}if(up.length>0){let w=Vb(Ne,up);w!==Ne&&(Ne=w,Jn=Vb(Jn,up),Le.setHistory(Eh(Ln,Jn)),Ta($s,Ne).catch(()=>{}),Xr())}Wf=!0,A.setSidebarCollapsed(o.sidebarCollapsed),o.sidebarVisible&&Ay(!0),(async()=>{try{let w=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}/compact/status`,{headers:{Authorization:`Bearer ${t.token}`}});if(!w.ok)return;let v=await w.json();if(typeof v.pendingAgentSwap=="string")A.setCompactionIndicator(`switching to ${v.pendingAgentSwap}...`);else{let L=v.compactionState?.status;L==="requested"||L==="running"?A.setCompactionIndicator("compacting..."):(L==="swap_pending"||L==="swap_deferred")&&A.setCompactionIndicator("compaction queued (waiting for idle)")}if(!Il||v.shouldCompact!==!0)return;let R=v.currentUsage?.used,O=v.currentUsage?.size,T=typeof R=="number"&&typeof O=="number"&&O>0?`This session is using ${ho(R)} of its ${ho(O)} token context window.`:`This session has ~${wT(v.approxTokens??0)} tokens of history above the compaction watermark.`;re=!0,A.setCompactionPrompt({message:T,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),(async()=>{try{let w=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(me)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!w.ok)return;let v=await w.json();if(ue&&je===null&&xe===null&&typeof v.updatedAt=="string"){let R=Date.parse(v.updatedAt);Number.isFinite(R)&&(je=R,A.setSidebarSnapshot({lastTurnEndedAt:je}))}v.forkSynthesisState==="running"?(A.setSynthesisIndicator("synthesizing context\u2026"),Sl()):v.forkSynthesisState==="failed"&&(A.setSynthesisIndicator("\u26A0 synthesis failed"),A.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),xr!==void 0&&z>0?(xe=xr,A.setBanner({status:"busy",elapsedMs:Date.now()-xr}),oe===null&&(oe=Kn()),Te===null&&wx(xr),Te=xr,ur()):xr===void 0&&z>0&&Ht(-z),yn(ni??null,Qi===void 0?void 0:sx(Qi)),Ge=!0;let HF=()=>{if(Xe){let w=Xe.resolve;Xe=null,A.setPermissionPrompt(null),w({outcome:{outcome:"cancelled"}})}as(),ds()},Fx=()=>{Te!==null&&(Pe=Date.now(),Ve="reconnect-recovery-failed",ur(),my(),Kt.clear(),Bs.clear(),cr.length=0,Te=null,Pe=null,Ve=null)};return g=w=>{we({src:"reconnect",step:"disconnect",message:w?.message}),A.setBanner({status:"disconnected",elapsedMs:void 0})},b=async w=>{let v=w?.skipInitialize===!0;if(we({src:"reconnect",step:"begin",sessionId:me,skipInitialize:v}),t.isLocal)try{let de=await an(await He());(de.baseUrl!==t.baseUrl||de.wsUrl!==t.wsUrl||de.token!==t.token)&&(we({src:"reconnect",step:"target-refresh",oldBase:t.baseUrl,newBase:de.baseUrl}),t.baseUrl=de.baseUrl,t.wsUrl=de.wsUrl,t.display=de.display,t.token=de.token)}catch(de){we({src:"reconnect",step:"target-refresh-failed",message:de instanceof Error?de.message:String(de)})}HF();let R={jsonrpc:"2.0",id:`tui-reinit-${ax()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:Fe}}};if(!v){we({src:"reconnect",step:"initialize-send"});try{await h.request(R),we({src:"reconnect",step:"initialize-ok"})}catch(de){we({src:"reconnect",step:"initialize-fail",message:de.message})}}let O=gn!==void 0||Yr!==void 0,T={jsonrpc:"2.0",id:`tui-reattach-${ax()}`,method:"session/attach",params:{sessionId:me,historyPolicy:O?"after_message":"none",...O&&gn!==void 0?{afterMessageId:gn}:{},...O&&Yr!==void 0?{afterSeq:Yr}:{},clientInfo:{name:"hydra-acp-tui",version:Fe},...(()=>{let de={};return Yi!==void 0&&(de.resume={upstreamSessionId:Yi,agentId:Rt,cwd:rt}),e.tui.toolContent==="references"&&(de.toolContent="references"),Object.keys(de).length>0?{_meta:{[pt]:de}}:{}})()}};Xo=[];let L,B,ne;we({src:"reconnect",step:"attach-send",useAfterMessage:O,lastSeenMessageId:gn,lastSeenSeq:Yr});try{let de=await h.request(T);if(we({src:"reconnect",step:"attach-resp",hasError:!!de.error}),de.error)throw new Error(de.error.message);ne=uO(de.result),L=ne.appliedPolicy,ne.clientId!==void 0&&(Ms=ne.clientId)}catch(de){B=de,we({src:"reconnect",step:"attach-fail",message:B.message})}let le=Xo??[];if(Xo=null,B)Fx(),A.appendLines([{prefix:" ",body:`reattach failed: ${B.message}`,bodyStyle:"tool-status-fail"}]);else if(O&&L!=="after_message")Fx(),A.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"reconnect couldn't replay events since last seen \u2014 scrollback may be incomplete",bodyStyle:"tool-status-fail"}]);else{le.length>0&&w?.beforeReplay?.(),x=!0;try{for(let de of le)vl(de)}finally{x=!1}}if(B||wo(),ne){let de=hO({daemonTurnStartedAt:ne.turnStartedAt,pendingTurns:z});de.pendingTurnsDelta!==0&&Ht(de.pendingTurnsDelta),de.banner==="busy"&&de.busySince!==void 0?(xe=de.busySince,A.setBanner({status:"busy",elapsedMs:Date.now()-de.busySince}),oe===null&&(oe=Kn())):A.setBanner({status:"ready",elapsedMs:void 0}),ne.armedTasks!==void 0&&yn(ne.armedTasks>0?ne.armedSince??null:null,ne.armedTaskList===void 0?void 0:sx(ne.armedTaskList))}else A.setBanner({status:z>0?"busy":"ready",elapsedMs:z>0?0:void 0});we({src:"reconnect",step:"end"})},y.onClose(w=>{w&&H(n,"notice-error",`
312
312
  connection lost: ${w.message}
313
313
  `),_d(w?1:0)}),process.on("SIGINT",El),ny.length>0&&(A.appendLines(ny.map(w=>({prefix:" ",body:`theme: ${w}`,bodyStyle:"notice-error"}))),ny=[]),$f.length>0&&(A.notify($f.join(" \xB7 "),1e4),$f=[]),(d.sessionId==="__new__"||d.freshOnRemote===!0)&&(r.initialPrompt||r.initialAttachments&&r.initialAttachments.length>0)&&Nd(r.initialPrompt??"",r.initialAttachments??[]),await si}async function GO(n,e,t,r,s,o){let i=r.cwd??process.cwd();if(r.sessionId){let d={sessionId:r.sessionId,agentId:r.agentId??"",cwd:i};r.resumeHint!==void 0&&(d.resumeHint=r.resumeHint),r.resolved!==void 0&&(d.resolved=r.resolved);let c=rd(r.resolved);return c!==void 0&&(d.remote=c),r.jumpToRecordedAt!==void 0&&(d.jumpToRecordedAt=r.jumpToRecordedAt),d}if(r.forceNew)return await VO(n,t,r,o)!=="ok"?null:await JO(t,r,i,e);if(r.resume){let d=r$();if(d){let f=(await ao(t,{all:!0,includeNonInteractive:!0})).find(p=>p.sessionId===d);if(f)return{sessionId:f.sessionId,agentId:f.agentId??"",cwd:f.cwd??i,resolved:f}}let c=await ao(t,{cwd:i,all:!0}),l=Rm(c,i);return l?{sessionId:l.sessionId,agentId:l.agentId??"",cwd:i,resolved:l}:(H(n,"cli-warn",`No sessions found for ${i}.
314
- `),null)}let a=await Pr();for(;;){let d=await ao(t,{includeNonInteractive:!0}),c=[];try{c=await Ua(t)}catch{}let l=await Ak(t),u=await aF(t,l),f=C=>Mf({cwd:C,config:a,prefs:o,...r.explicitAgentId!==void 0?{explicitAgentId:r.explicitAgentId}:{},...r.agentId!==void 0?{fallbackAgentId:r.agentId}:{},availableAgents:c}),p=C=>Mf({cwd:C,config:a,prefs:o,...r.explicitAgentId!==void 0?{explicitAgentId:r.explicitAgentId}:{},availableAgents:c}),{agentId:m,model:b}=await f(i),g=await KS(n,{cwd:i,sessions:d,config:e,target:t,prefs:s,...r.pickerSelect!==void 0?{currentSessionId:r.pickerSelect}:{},...m?{composerAgentId:m}:{},...b?{composerModel:b}:{},...c.length>0?{availableAgents:c}:{},...l.length>0?{availableHosts:l}:{},...l.length>0?{hostInfo:u}:{},...r.newHost!==void 0?{composerHost:r.newHost}:{},onComposerAgentChange:(C,$)=>{Of(o,C,$)},onCwdChange:p,...r.initialPrompt!==void 0?{initialPrompt:r.initialPrompt}:{},...r.initialAttachments&&r.initialAttachments.length>0?{initialAttachments:r.initialAttachments}:{}});if(g.kind==="abort"||g.kind==="exit")return null;if(g.kind==="new"){g.agentId!==void 0&&(r.agentId=g.agentId,g.agentExplicit&&Of(o,g.agentId,g.model)),g.model!==void 0&&(r.model=g.model),g.host!==void 0?r.newHost=g.host:delete r.newHost,g.prompt!==void 0&&(r.initialPrompt=g.prompt),g.attachments&&g.attachments.length>0&&(r.initialAttachments=g.attachments),g.cwd!==void 0&&(i=g.cwd,r.cwd=g.cwd);let C=g.installStatus,$=await VO(n,t,r,o,()=>{C&&(C.finalize(),C=void 0)});if($==="cancel")return C&&C.finalize(),null;if($==="back"){C&&C.finalize();continue}let E=await JO(t,r,i,e);return C&&(E.installStatus=C),E}if(g.kind==="fork"){let C=await iF(n,t,g,d);if(C.kind==="cancel")return null;if(C.kind==="back")continue;return C.ctx}r.readonly=g.readonly===!0;let h=g.installStatus,y=()=>{h&&(h.finalize(),h=void 0)},k=d.find(C=>C.sessionId===g.sessionId);if(k!==void 0&&!!k.importedFromMachine&&!k.remote&&!k.upstreamSessionId&&!r.readonly){y();let C=await sF(n,t,k,g,r);if(C.kind==="cancel")return null;if(C.kind==="back")continue;return C.ctx}if(t.isLocal&&k&&!k.importedFromMachine&&!k.remote&&!r.readonly&&!(await mf(k.cwd)).ok){y();let $=await ad(n,k,{defaultCwd:Ze(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if($.kind==="cancel")return null;if($.kind==="back")continue;let E=g.agentId??k.agentId??"",M={sessionId:g.sessionId,agentId:E,cwd:$.path,resumeHint:{agentId:E,cwd:$.path,upstreamSessionId:""}};return g.jumpToRecordedAt!==void 0&&(M.jumpToRecordedAt=g.jumpToRecordedAt),M}let I={sessionId:g.sessionId,agentId:g.agentId??"",cwd:i};h&&(I.installStatus=h),k!==void 0&&(I.resolved=k);let x=rd(k);return x!==void 0&&(I.remote=x),g.jumpToRecordedAt!==void 0&&(I.jumpToRecordedAt=g.jumpToRecordedAt),I}}async function sF(n,e,t,r,s){for(;;){let o=await N$(n,t);if(o==="cancel")return{kind:"cancel"};if(o==="back")return{kind:"back"};if(o==="view"){s.readonly=!0;let c=r.agentId??t.agentId??"",l={sessionId:r.sessionId,agentId:c,cwd:t.cwd},u=rd(t);return u!==void 0&&(l.remote=u),r.jumpToRecordedAt!==void 0&&(l.jumpToRecordedAt=r.jumpToRecordedAt),{kind:"ctx",ctx:l}}let i=await oF(n,e,r.agentId??t.agentId??"");if(i.kind==="cancel")return{kind:"cancel"};if(i.kind==="back")continue;let a=await ad(n,t);if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")continue;let d=i.agentId;return{kind:"ctx",ctx:{sessionId:r.sessionId,agentId:d,cwd:a.path,resumeHint:{agentId:d,cwd:a.path,upstreamSessionId:""}}}}}async function oF(n,e,t){if(!t)return{kind:"ok",agentId:t,changed:!1};let r;try{r=await Ua(e)}catch{return{kind:"ok",agentId:t,changed:!1}}if(r.length===0||r.some(o=>o.id===t))return{kind:"ok",agentId:t,changed:!1};let s=await GS(n,r,t,{title:"Agent not available here",intro:`Source agent "${t}" isn't installed on this machine \u2014 pick a local agent to fork to:`});return s.kind==="cancel"?{kind:"cancel"}:s.kind==="back"?{kind:"back"}:{kind:"ok",agentId:s.agentId,changed:!0}}async function iF(n,e,t,r){let s=r.find(u=>u.sessionId===t.sourceSessionId),o=!!t.sourceImportedFromMachine&&!t.sourceUpstreamSessionId,i=t.sourceCwd,a=await oF(n,e,t.sourceAgentId??s?.agentId??"");if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")return{kind:"back"};let d=a.changed?a.agentId:void 0;if(o){if(!s)return{kind:"back"};let u=await ad(n,s);if(u.kind==="cancel")return{kind:"cancel"};if(u.kind==="back")return{kind:"back"};i=u.path}let c=d??t.sourceAgentId??"",l;try{l=await Y0(e,t.sourceSessionId,{...o?{cwd:i}:{},...d?{agentId:d}:{}})}catch(u){return H(n,"notice-error",`
314
+ `),null)}let a=await Pr();for(;;){let d=await ao(t,{includeNonInteractive:!0}),c=[];try{c=await Ua(t)}catch{}let l=await Ak(t),u=await aF(t,l),f=C=>Mf({cwd:C,config:a,prefs:o,...r.explicitAgentId!==void 0?{explicitAgentId:r.explicitAgentId}:{},...r.agentId!==void 0?{fallbackAgentId:r.agentId}:{},availableAgents:c}),p=C=>Mf({cwd:C,config:a,prefs:o,...r.explicitAgentId!==void 0?{explicitAgentId:r.explicitAgentId}:{},availableAgents:c}),{agentId:m,model:b}=await f(i),g=await KS(n,{cwd:i,sessions:d,config:e,target:t,prefs:s,...r.pickerSelect!==void 0?{currentSessionId:r.pickerSelect}:{},...m?{composerAgentId:m}:{},...b?{composerModel:b}:{},...c.length>0?{availableAgents:c}:{},...l.length>0?{availableHosts:l}:{},...l.length>0?{hostInfo:u}:{},...r.newHost!==void 0?{composerHost:r.newHost}:{},onComposerAgentChange:(C,$)=>{Of(o,C,$)},onCwdChange:p,...r.initialPrompt!==void 0?{initialPrompt:r.initialPrompt}:{},...r.initialAttachments&&r.initialAttachments.length>0?{initialAttachments:r.initialAttachments}:{}});if(g.kind==="abort"||g.kind==="exit")return null;if(g.kind==="new"){g.agentId!==void 0&&(r.agentId=g.agentId,g.agentExplicit&&Of(o,g.agentId,g.model)),g.model!==void 0&&(r.model=g.model),g.host!==void 0?r.newHost=g.host:delete r.newHost,g.prompt!==void 0&&(r.initialPrompt=g.prompt),g.attachments&&g.attachments.length>0&&(r.initialAttachments=g.attachments),g.cwd!==void 0&&(i=g.cwd,r.cwd=g.cwd);let C=g.installStatus,$=await VO(n,t,r,o,()=>{C&&(C.finalize(),C=void 0)});if($==="cancel")return C&&C.finalize(),null;if($==="back"){C&&C.finalize();continue}let P=await JO(t,r,i,e);return C&&(P.installStatus=C),P}if(g.kind==="fork"){let C=await iF(n,t,g,d);if(C.kind==="cancel")return null;if(C.kind==="back")continue;return C.ctx}r.readonly=g.readonly===!0;let h=g.installStatus,y=()=>{h&&(h.finalize(),h=void 0)},k=d.find(C=>C.sessionId===g.sessionId);if(k!==void 0&&!!k.importedFromMachine&&!k.remote&&!k.upstreamSessionId&&!r.readonly){y();let C=await sF(n,t,k,g,r);if(C.kind==="cancel")return null;if(C.kind==="back")continue;return C.ctx}if(t.isLocal&&k&&!k.importedFromMachine&&!k.remote&&!r.readonly&&!(await mf(k.cwd)).ok){y();let $=await ad(n,k,{defaultCwd:Ze(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if($.kind==="cancel")return null;if($.kind==="back")continue;let P=g.agentId??k.agentId??"",M={sessionId:g.sessionId,agentId:P,cwd:$.path,resumeHint:{agentId:P,cwd:$.path,upstreamSessionId:""}};return g.jumpToRecordedAt!==void 0&&(M.jumpToRecordedAt=g.jumpToRecordedAt),M}let I={sessionId:g.sessionId,agentId:g.agentId??"",cwd:i};h&&(I.installStatus=h),k!==void 0&&(I.resolved=k);let x=rd(k);return x!==void 0&&(I.remote=x),g.jumpToRecordedAt!==void 0&&(I.jumpToRecordedAt=g.jumpToRecordedAt),I}}async function sF(n,e,t,r,s){for(;;){let o=await N$(n,t);if(o==="cancel")return{kind:"cancel"};if(o==="back")return{kind:"back"};if(o==="view"){s.readonly=!0;let c=r.agentId??t.agentId??"",l={sessionId:r.sessionId,agentId:c,cwd:t.cwd},u=rd(t);return u!==void 0&&(l.remote=u),r.jumpToRecordedAt!==void 0&&(l.jumpToRecordedAt=r.jumpToRecordedAt),{kind:"ctx",ctx:l}}let i=await oF(n,e,r.agentId??t.agentId??"");if(i.kind==="cancel")return{kind:"cancel"};if(i.kind==="back")continue;let a=await ad(n,t);if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")continue;let d=i.agentId;return{kind:"ctx",ctx:{sessionId:r.sessionId,agentId:d,cwd:a.path,resumeHint:{agentId:d,cwd:a.path,upstreamSessionId:""}}}}}async function oF(n,e,t){if(!t)return{kind:"ok",agentId:t,changed:!1};let r;try{r=await Ua(e)}catch{return{kind:"ok",agentId:t,changed:!1}}if(r.length===0||r.some(o=>o.id===t))return{kind:"ok",agentId:t,changed:!1};let s=await GS(n,r,t,{title:"Agent not available here",intro:`Source agent "${t}" isn't installed on this machine \u2014 pick a local agent to fork to:`});return s.kind==="cancel"?{kind:"cancel"}:s.kind==="back"?{kind:"back"}:{kind:"ok",agentId:s.agentId,changed:!0}}async function iF(n,e,t,r){let s=r.find(u=>u.sessionId===t.sourceSessionId),o=!!t.sourceImportedFromMachine&&!t.sourceUpstreamSessionId,i=t.sourceCwd,a=await oF(n,e,t.sourceAgentId??s?.agentId??"");if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")return{kind:"back"};let d=a.changed?a.agentId:void 0;if(o){if(!s)return{kind:"back"};let u=await ad(n,s);if(u.kind==="cancel")return{kind:"cancel"};if(u.kind==="back")return{kind:"back"};i=u.path}let c=d??t.sourceAgentId??"",l;try{l=await Y0(e,t.sourceSessionId,{...o?{cwd:i}:{},...d?{agentId:d}:{}})}catch(u){return H(n,"notice-error",`
315
315
  fork failed: ${u.message}
316
316
  `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:c,cwd:i,isFreshFork:!0,...o?{resumeHint:{agentId:c,cwd:i,upstreamSessionId:""}}:{}}}}async function aF(n,e){let t=await Promise.all(e.map(s=>sE(n,s))),r={};return e.forEach((s,o)=>{let i=t[o];i&&(r[s]=i)}),r}async function JO(n,e,t,r){let s=XV(e,t,r);if(e.newHost===void 0)return s;let o=await rE(n,{remote:e.newHost,...e.agentId!==void 0?{agentId:e.agentId}:{}});return{...s,sessionId:o.sessionId,agentId:o.agentId??s.agentId,remote:e.newHost,freshOnRemote:!0}}function XV(n,e,t){return{sessionId:"__new__",agentId:n.agentId??t.defaultAgent??"",cwd:e}}function Of(n,e,t){if(n.lastChosenAgent=e,t===void 0){delete n.lastChosenModel;return}n.lastChosenModel=t}async function VO(n,e,t,r,s){if(t.agentId||await Ky())return"ok";let o;try{o=await Ua(e)}catch{return"ok"}if(o.length===0)return"ok";s&&s();let i=await He(),a=r.lastChosenAgent??i.defaultAgent,d=await GS(n,o,a);if(d.kind==="cancel")return"cancel";if(d.kind==="back")return"back";t.agentId=d.agentId;let c=o.find(l=>l.id===d.agentId);if(Of(r,d.agentId,Or(i.sessionDefaults,{id:d.agentId,extendsChain:c?.extendsChain})?.value.model),d.persist)try{await hi(d.agentId)}catch{}return"ok"}function ZV(n,e){we({src:"session/update",update:n,event:e===null?null:{kind:e.kind}})}var ny,$f,ry,ld,Vr,YO,QO,XO,ZO,dx,zO,WV,qV,KO,VV,dF=j(()=>{"use strict";ob();Do();fn();pv();et();$v();Ws();Ba();Bc();Xd();WM();mr();mu();Se();vi();Gs();xh();ma();rr();ng();yv();Ph();Vu();zM();VM();QM();XM();X$();jS();Gm();BS();HS();Z$();tO();fv();rO();NS();ak();Eg();oO();Zv();yg();dO();JS();$g();uS();Sg();Kv();wg();vg();WS();yS();td();pf();pS();lO();zg();US();mO();Ho();Ko();xn();ic();TO();XS();ya();Va();SS();kS();PO();OO();nS();LO();UO();ny=[],$f=[],ry=[],ld="terminal",QO=null,ZO=null;dx="dismiss";zO=12e4,WV=12e3;qV=[["Alt+Enter","newline in prompt"],["Shift+Tab","cycle agent modes (plan / accept-edits / etc.)"],["Tab","indent \xB7 slash-command / file-path completion"],null,["\u2191 / \u2193","prompt history \xB7 queue navigation"],["\u2190/\u2192 Home/End","cursor movement"],["Alt+B / Alt+F","word back / forward"],["^A / ^E","line start / end"],["^W / ^U / ^K","kill word / line / to end"],["^Y","yank last kill"],null,["^P","switch session (picker)"],["Alt+N / Alt+Tab","next warm session"],["Alt+P","previous warm session"],["^T","show / hide thoughts"],["^S","show / hide sidebar (with an empty draft; amends otherwise)"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter \xB7 sidebar)"],null,["^R","history reverse search (^S walks forward once engaged)"],["PgUp / PgDn","scroll scrollback"],["Alt+PgUp / Alt+PgDn","jump to previous / next prompt"],["Mouse wheel","scroll scrollback (when mouse capture is on)"],["Middle-click","paste PRIMARY selection (terminal-style)"],["Double-click","open file under cursor / sidebar file row (tui.openFileCommand, else $HYDRA_EDITOR/$VISUAL/$EDITOR \u2014 a $EDITOR takes over the terminal until you quit it)"],["Double-click bar","cwd opens \xB7 title renames \xB7 agent/model/mode pick \xB7 else copy"],["Click in a modal","row picks / cycles it \xB7 hint words act \xB7 wheel walks the list"],["Right-click","extend selection to click (drag past top/bottom to autoscroll)"],["^X ^E","edit prompt in $HYDRA_EDITOR/$VISUAL/$EDITOR"],null,["^C","cancel turn (twice to exit)"],["Esc","cancel turn and prefill draft"],["^D","exit (or delete-forward in prompt)"],["^L","force full redraw"],["^G","toggle this help"]];KO=!1;VV=2});var cF={};ia(cF,{runTui:()=>rF});var lF=j(()=>{"use strict";dF()});import{readFileSync as e6}from"fs";import{fileURLToPath as t6}from"url";import{dirname as n6,resolve as r6}from"path";var Nx=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","files","fold","follow","force","foreground","help","include-cat","info","inactive","json","new","no-color","no-dangerously-skip-permissions","no-from-note","no-pager","no-restart","no-terminal-host-launcher","no-wait","tools","raw","reattach","readonly","remove","replace","rotate-token","terminal-host-launcher","verbose","version","workspace","yes"]),UF=new Set(["agent","args","columns","command","cwd","dir","drip-speed","env","extends","from","from-label","from-session","host","jump-to-recorded-at","last","message","into","model","name","out","prompt","public-host","session","since","stream-bytes","stream-threshold","tail","terminal-host","timeout","to"]);function Dx(n){for(let e of Object.keys(n))if(!Nx.has(e)&&!UF.has(e))return e}function Ey(n){let e=[],t={},r=0;for(;r<n.length;){let s=n[r];if(s===void 0)break;if(s.startsWith("--")){let o=s.indexOf("=");if(o!==-1){let d=s.slice(2,o);t[d]=s.slice(o+1),r+=1;continue}let i=s.slice(2);if(Nx.has(i)){t[i]=!0,r+=1;continue}let a=n[r+1];if(a!==void 0&&!a.startsWith("--")){t[i]=a,r+=2;continue}t[i]=!0,r+=1;continue}e.push(s),r+=1}return{positional:e,flags:t}}function WF(n,e){let t=n[e];if(typeof t=="string")return t}function Oo(n,e){return n[e]===!0||n[e]==="true"}var jF="HYDRA_ACP_";function qF(n){return jF+n.toUpperCase().replace(/-/g,"_")}function Ke(n,e){let t=WF(n,e);return t!==void 0?t:process.env[qF(e)]}et();Ws();async function pI(n,e){let t=typeof n=="string"&&n.trim().length>0?n.trim():void 0;if(t===void 0)return;if(t.startsWith("hydra://")){let o=Vl(t);return{target:await uI(o,{allowPrompt:e.allowPrompt}),sessionId:o.sessionId,fromUrl:!0}}let r=await He();return{target:await an(r),sessionId:t,fromUrl:!1}}function iw(n){let e=n.session;if(typeof e=="string"&&e.length>0)return e;let t=process.env.HYDRA_ACP_TARGET_SESSION;if(typeof t=="string"&&t.length>0)return t}ma();Se();et();Fo();import*as yI from"fs/promises";_r();async function wI(n){if(await yI.mkdir(D.home(),{recursive:!0}),await Qd(),!await Wd()){let t=Ud();await da(t),process.stdout.write(`Initialized ${D.authToken()}
317
317
  Service token: ${t}
@@ -352,7 +352,7 @@ ${e}
352
352
 
353
353
  ${Ab}`:`${t}
354
354
 
355
- ${Ab}`;return CA(n,r,cA)}function HH(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let r=t.content;return r&&typeof r.text=="string"?r.text:""}function BH(n){let e=new Set;IA(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&IA(e,t.availableModels),e}function IA(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let r=t.modelId??t.value??t.id;typeof r=="string"&&r.length>0&&n.add(r)}}}Gs();Ch();Se();var qH=jH("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",12),zH=2,Rh=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??zH}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]={kind:"title"},this.drain())}scheduleCompaction(e,t){if(this.stopped)return;let r=t?.targetAgentId;if(this.inflight.has(e))return;let s=this.queued[e];if(s&&s.kind==="title"){this.queued[e]={kind:"compaction",...r?{targetAgentId:r}:{}};return}this.queued[e]={kind:"compaction",...r?{targetAgentId:r}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let r=t-Date.now();if(r<=0)return;let s=[...this.inflight.values()];if(s.length===0){await new Promise(o=>{setTimeout(o,25).unref?.()});continue}await Promise.race([Promise.race(s),new Promise(o=>{setTimeout(o,r).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let t=Object.keys(this.queued)[0];if(!t)return;let r=this.queued[t];delete this.queued[t];let s=this.runOne(t,r).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,s)}}async runOne(e,t){let r=t.kind,s=t.targetAgentId;try{let o=await this.opts.store.read(e);if(!o){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let i=await this.opts.histories.load(e,{maxEntries:1/0}),a=o.summarizedThroughEntry;if(a!==void 0&&i.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${i.length})`);return}a!==void 0&&i.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${i.length}) for ${e} \u2014 re-baselining`);let d=r==="compaction"?s??this.opts.compactionAgent??o.agentId:this.opts.synopsisAgent??o.agentId,c=await this.opts.registry.getAgent(d);if(!c){this.opts.logger?.warn(`synopsis: agent ${d} not in registry for session ${e}; skipping`);return}let l=await Fr(c,[],{npmRegistry:this.opts.npmRegistry}),u=this.opts.compactionAgent===void 0&&s===void 0,f=r==="compaction"?this.opts.compactionModel??(u?o.currentModel:void 0):this.opts.synopsisModel,p=D.sessionDir(e);if(await FA.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${d} historyLen=${i.length} model=${JSON.stringify(f??"(default)")} cwd=${p}`),r==="compaction"){let m=this.opts.compactionMaxIterations??3,b=0,g=a??0,h,y=0,k,S=Date.now(),I=qH(),x={targetAgentId:s},C=E=>this.opts.onCompactionStateChange?.(e,{runId:I,...E},x)??Promise.resolve(),$=E=>{this.opts.broadcastHydraCompaction?.(e,E,x)};await C({status:"requested",requestedAt:S}),$({sessionUpdate:"_hydra_compaction",phase:"started",requestedAt:S});try{do{b++,this.opts.logger?.info(`synopsis: compaction iteration ${b} sessionId=${e} historyLen=${i.length} watermark=${g}`);let E=await this.opts.histories.load(e,{maxEntries:1/0});if(E.length===g)break;let M=await RA({agentId:d,cwd:p,plan:l,history:E,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(K,Y)=>{C({status:"running",requestedAt:S,iter:b,worker:{upstreamSessionId:K,pid:Y??0}})},onFailure:K=>{k=K}});if(M){let K=_A(M.synopsis,E);K&&$A(K)&&(await this.opts.persistSynopsis(e,K,E.length),h=K,y=E.length,k=void 0,await C({status:"running",requestedAt:S,iter:b}),$({sessionUpdate:"_hydra_compaction",phase:"iteration",iter:b,historyLen:E.length}),await this.opts.onSynthesisArtifact?.(e,K,y,s,I),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${b} fields=${OA(K)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${b} returned no result`);if(g=E.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===g)break}while(b<m);if(h)this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} runId=${I} watermark=${y} iterations=${b}`+(b>=m?` (hit maxIterations=${m})`:"")),$({sessionUpdate:"_hydra_compaction",phase:"converged",iter:b,summarizedThroughEntry:y});else{b>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${m} without producing artifact sessionId=${e}: ${k??"no reason captured"}`);let E=k??(b===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${b} iteration(s)`);await C({status:"failed",requestedAt:S,iter:b,lastError:E}),$({sessionUpdate:"_hydra_compaction",phase:"failed",error:E}),s&&await this.opts.onSynthesisUnavailable?.(e,s,E)}}catch(E){let M=E instanceof Error?E.message:String(E);if(this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${M}`),await C({status:"failed",requestedAt:S,iter:b,lastError:M}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"_hydra_compaction",phase:"failed",error:M},{targetAgentId:s}),s)try{await this.opts.onSynthesisUnavailable?.(e,s,M)}catch{}}}else{let m=await Sh({agentId:d,cwd:p,plan:l,history:i,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!m){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let b=_A(m.synopsis,i);b&&$A(b)?(await this.opts.persistSynopsis(e,b,i.length),m.title&&await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!m.title)} fields=${OA(b)}`)):m.title&&(await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(o){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${o.message}`)}}};function _A(n,e){let t=PA(e),r=EA(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:r.length>0?r:n.tools_used}:t.length===0&&r.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:r.length>0?r:void 0}}function $A(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function OA(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}Se();import*as vt from"fs/promises";import{createReadStream as XH}from"fs";import{createGunzip as ZH,gzip as eB,gunzip as tB}from"zlib";import{createInterface as nB}from"readline";import{promisify as UA}from"util";function LA(n){return n==="summary"?"summary":"inline"}var jb=256,KH=["totalMatches","totalFiles","referenceCount","truncated","exitCode"],GH=["content","stdout","stderr"];function NA(n,e){return e!=="summary"?n:n.map(JH)}function JH(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,r=t.update;if(!r||typeof r!="object"||Array.isArray(r))return n;let s=r;if(s.sessionUpdate!=="tool_call"&&s.sessionUpdate!=="tool_call_update")return n;let o={...s};Array.isArray(s.content)&&(o.content=s.content.map(DA));let i=s.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,d={};a.error!==void 0&&(d.error=Ah(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata);for(let c of KH)a[c]!==void 0&&(d[c]=a[c]);for(let c of GH)typeof a[c]=="string"&&(d[c]=Ah(a[c]));o.rawOutput=d}return{...n,params:{...t,update:o}}}function VH(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function DA(n){if(VH(n)){let r=n,s={type:"diff",oldText:"",newText:""};return typeof r.path=="string"&&(s.path=r.path),s}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=Ah(e.text)),typeof e.content=="string"?t.content=Ah(e.content):e.content&&typeof e.content=="object"&&(t.content=DA(e.content)),t}function Ah(n){if(typeof n=="string"&&n.length>jb){let e=n.length-jb;return`${n.slice(0,jb)}\u2026[+${e} chars omitted from summary export]`}return n}var YH=2048;function HA(n){let e=new Set,t=r=>{if(BA(r)){e.add(r.__hydraBlob);return}if(Array.isArray(r)){for(let s of r)t(s);return}if(r&&typeof r=="object")for(let s of Object.values(r))t(s)};for(let r of n)t(r.params);return e}function BA(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function QH(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let r=t.sessionUpdate;return r==="tool_call"||r==="tool_call_update"}async function Kb(n,e){if(!QH(n))return n;let t=n.params,r=t.update,s=await qb(r,e);return{...n,params:{...t,update:s}}}async function qb(n,e){if(typeof n=="string"){if(n.length<=YH)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let r of n)t.push(await qb(r,e));return t}if(n&&typeof n=="object"){let t={};for(let[r,s]of Object.entries(n))t[r]=await qb(s,e);return t}return n}async function Gb(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let r=await zb(t,e);return r===t?n:{...n,params:r}}async function zb(n,e){if(BA(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,r=[];for(let s of n){let o=await zb(s,e);o!==s&&(t=!0),r.push(o)}return t?r:n}if(n&&typeof n=="object"){let t=!1,r={};for(let[s,o]of Object.entries(n)){let i=await zb(o,e);i!==o&&(t=!0),r[s]=i}return t?r:n}return n}var rB=UA(eB),sB=UA(tB),oB=/^history\.jsonl\.(\d+)(\.gz)?$/,gs=/^[A-Za-z0-9_-]+$/,iB=1e3,aB=1e7,dB=10,Th=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;archiveLineCounts=new Map;constructor(e={}){this.maxEntries=e.maxEntries??iB,this.archiveMaxBytes=e.archiveMaxBytes??aB,this.archiveTiers=e.archiveTiers??dB}async append(e,t){if(gs.test(e))return this.enqueue(e,async()=>{await vt.mkdir(D.sessionDir(e),{recursive:!0});let r=await Kb(t,o=>Ew(e,o)),s=JSON.stringify(r)+`
355
+ ${Ab}`;return CA(n,r,cA)}function HH(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let r=t.content;return r&&typeof r.text=="string"?r.text:""}function BH(n){let e=new Set;IA(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&IA(e,t.availableModels),e}function IA(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let r=t.modelId??t.value??t.id;typeof r=="string"&&r.length>0&&n.add(r)}}}Gs();Ch();Se();var qH=jH("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",12),zH=2,Rh=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??zH}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]={kind:"title"},this.drain())}scheduleCompaction(e,t){if(this.stopped)return;let r=t?.targetAgentId;if(this.inflight.has(e))return;let s=this.queued[e];if(s&&s.kind==="title"){this.queued[e]={kind:"compaction",...r?{targetAgentId:r}:{}};return}this.queued[e]={kind:"compaction",...r?{targetAgentId:r}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let r=t-Date.now();if(r<=0)return;let s=[...this.inflight.values()];if(s.length===0){await new Promise(o=>{setTimeout(o,25).unref?.()});continue}await Promise.race([Promise.race(s),new Promise(o=>{setTimeout(o,r).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let t=Object.keys(this.queued)[0];if(!t)return;let r=this.queued[t];delete this.queued[t];let s=this.runOne(t,r).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,s)}}async runOne(e,t){let r=t.kind,s=t.targetAgentId;try{let o=await this.opts.store.read(e);if(!o){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let i=await this.opts.histories.load(e,{maxEntries:1/0}),a=o.summarizedThroughEntry;if(a!==void 0&&i.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${i.length})`);return}a!==void 0&&i.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${i.length}) for ${e} \u2014 re-baselining`);let d=r==="compaction"?s??this.opts.compactionAgent??o.agentId:this.opts.synopsisAgent??o.agentId,c=await this.opts.registry.getAgent(d);if(!c){this.opts.logger?.warn(`synopsis: agent ${d} not in registry for session ${e}; skipping`);return}let l=await Fr(c,[],{npmRegistry:this.opts.npmRegistry}),u=this.opts.compactionAgent===void 0&&s===void 0,f=r==="compaction"?this.opts.compactionModel??(u?o.currentModel:void 0):this.opts.synopsisModel,p=D.sessionDir(e);if(await FA.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${d} historyLen=${i.length} model=${JSON.stringify(f??"(default)")} cwd=${p}`),r==="compaction"){let m=this.opts.compactionMaxIterations??3,b=0,g=a??0,h,y=0,k,S=Date.now(),I=qH(),x={targetAgentId:s},C=P=>this.opts.onCompactionStateChange?.(e,{runId:I,...P},x)??Promise.resolve(),$=P=>{this.opts.broadcastHydraCompaction?.(e,P,x)};await C({status:"requested",requestedAt:S}),$({sessionUpdate:"_hydra_compaction",phase:"started",requestedAt:S});try{do{b++,this.opts.logger?.info(`synopsis: compaction iteration ${b} sessionId=${e} historyLen=${i.length} watermark=${g}`);let P=await this.opts.histories.load(e,{maxEntries:1/0});if(P.length===g)break;let M=await RA({agentId:d,cwd:p,plan:l,history:P,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(K,Y)=>{C({status:"running",requestedAt:S,iter:b,worker:{upstreamSessionId:K,pid:Y??0}})},onFailure:K=>{k=K}});if(M){let K=_A(M.synopsis,P);K&&$A(K)&&(await this.opts.persistSynopsis(e,K,P.length),h=K,y=P.length,k=void 0,await C({status:"running",requestedAt:S,iter:b}),$({sessionUpdate:"_hydra_compaction",phase:"iteration",iter:b,historyLen:P.length}),await this.opts.onSynthesisArtifact?.(e,K,y,s,I),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${b} fields=${OA(K)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${b} returned no result`);if(g=P.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===g)break}while(b<m);if(h)this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} runId=${I} watermark=${y} iterations=${b}`+(b>=m?` (hit maxIterations=${m})`:"")),$({sessionUpdate:"_hydra_compaction",phase:"converged",iter:b,summarizedThroughEntry:y});else{b>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${m} without producing artifact sessionId=${e}: ${k??"no reason captured"}`);let P=k??(b===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${b} iteration(s)`);await C({status:"failed",requestedAt:S,iter:b,lastError:P}),$({sessionUpdate:"_hydra_compaction",phase:"failed",error:P}),s&&await this.opts.onSynthesisUnavailable?.(e,s,P)}}catch(P){let M=P instanceof Error?P.message:String(P);if(this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${M}`),await C({status:"failed",requestedAt:S,iter:b,lastError:M}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"_hydra_compaction",phase:"failed",error:M},{targetAgentId:s}),s)try{await this.opts.onSynthesisUnavailable?.(e,s,M)}catch{}}}else{let m=await Sh({agentId:d,cwd:p,plan:l,history:i,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!m){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let b=_A(m.synopsis,i);b&&$A(b)?(await this.opts.persistSynopsis(e,b,i.length),m.title&&await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!m.title)} fields=${OA(b)}`)):m.title&&(await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(o){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${o.message}`)}}};function _A(n,e){let t=PA(e),r=EA(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:r.length>0?r:n.tools_used}:t.length===0&&r.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:r.length>0?r:void 0}}function $A(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function OA(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}Se();import*as vt from"fs/promises";import{createReadStream as XH}from"fs";import{createGunzip as ZH,gzip as eB,gunzip as tB}from"zlib";import{createInterface as nB}from"readline";import{promisify as UA}from"util";function LA(n){return n==="summary"?"summary":"inline"}var jb=256,KH=["totalMatches","totalFiles","referenceCount","truncated","exitCode"],GH=["content","stdout","stderr"];function NA(n,e){return e!=="summary"?n:n.map(JH)}function JH(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,r=t.update;if(!r||typeof r!="object"||Array.isArray(r))return n;let s=r;if(s.sessionUpdate!=="tool_call"&&s.sessionUpdate!=="tool_call_update")return n;let o={...s};Array.isArray(s.content)&&(o.content=s.content.map(DA));let i=s.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,d={};a.error!==void 0&&(d.error=Ah(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata);for(let c of KH)a[c]!==void 0&&(d[c]=a[c]);for(let c of GH)typeof a[c]=="string"&&(d[c]=Ah(a[c]));o.rawOutput=d}return{...n,params:{...t,update:o}}}function VH(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function DA(n){if(VH(n)){let r=n,s={type:"diff",oldText:"",newText:""};return typeof r.path=="string"&&(s.path=r.path),s}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=Ah(e.text)),typeof e.content=="string"?t.content=Ah(e.content):e.content&&typeof e.content=="object"&&(t.content=DA(e.content)),t}function Ah(n){if(typeof n=="string"&&n.length>jb){let e=n.length-jb;return`${n.slice(0,jb)}\u2026[+${e} chars omitted from summary export]`}return n}var YH=2048;function HA(n){let e=new Set,t=r=>{if(BA(r)){e.add(r.__hydraBlob);return}if(Array.isArray(r)){for(let s of r)t(s);return}if(r&&typeof r=="object")for(let s of Object.values(r))t(s)};for(let r of n)t(r.params);return e}function BA(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function QH(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let r=t.sessionUpdate;return r==="tool_call"||r==="tool_call_update"}async function Kb(n,e){if(!QH(n))return n;let t=n.params,r=t.update,s=await qb(r,e);return{...n,params:{...t,update:s}}}async function qb(n,e){if(typeof n=="string"){if(n.length<=YH)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let r of n)t.push(await qb(r,e));return t}if(n&&typeof n=="object"){let t={};for(let[r,s]of Object.entries(n))t[r]=await qb(s,e);return t}return n}async function Gb(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let r=await zb(t,e);return r===t?n:{...n,params:r}}async function zb(n,e){if(BA(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,r=[];for(let s of n){let o=await zb(s,e);o!==s&&(t=!0),r.push(o)}return t?r:n}if(n&&typeof n=="object"){let t=!1,r={};for(let[s,o]of Object.entries(n)){let i=await zb(o,e);i!==o&&(t=!0),r[s]=i}return t?r:n}return n}var rB=UA(eB),sB=UA(tB),oB=/^history\.jsonl\.(\d+)(\.gz)?$/,gs=/^[A-Za-z0-9_-]+$/,iB=1e3,aB=1e7,dB=10,Th=class{writeQueues=new Map;maxEntries;archiveMaxBytes;archiveTiers;nextArchiveIndex=new Map;archiveLineCounts=new Map;constructor(e={}){this.maxEntries=e.maxEntries??iB,this.archiveMaxBytes=e.archiveMaxBytes??aB,this.archiveTiers=e.archiveTiers??dB}async append(e,t){if(gs.test(e))return this.enqueue(e,async()=>{await vt.mkdir(D.sessionDir(e),{recursive:!0});let r=await Kb(t,o=>Ew(e,o)),s=JSON.stringify(r)+`
356
356
  `;await vt.appendFile(D.historyFile(e),s,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(gs.test(e))return this.enqueue(e,async()=>{await vt.mkdir(D.sessionDir(e),{recursive:!0});let r=[];for(let o of t)r.push(await Kb(o,i=>Ew(e,i)));let s=r.length===0?"":r.map(o=>JSON.stringify(o)).join(`
357
357
  `)+`
358
358
  `;await vt.writeFile(D.historyFile(e),s,{encoding:"utf8",mode:384})})}async compact(e,t){if(gs.test(e))return this.enqueue(e,async()=>{let r;try{r=await vt.readFile(D.historyFile(e),"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}let s=r.split(`
@@ -388,9 +388,9 @@ A sync was attempted first and could not complete: ${$.message}`}catch($){C=`
388
388
  A sync was attempted first but was refused: ${$ instanceof Error?$.message:String($)}`}if(!l){let $=await i.currentLineName(r)??"the source";throw new Error(`cannot fast-forward ${$} in ${V(r)} to ${s}. The source has moved on since this workspace was created. The source is untouched.${C}
389
389
  `+(C.length>0?`Or land it by hand with: git -C ${r} merge ${s}`:`Resolve it in the workspace with \`/hydra workspace sync\` (which leaves the conflict there to fix), or land it by hand with: git -C ${r} merge ${s}`))}}let f=i!==void 0&&i.capabilities().supports.nestedTrees?await i.captureNested(e.path,await i.listNested(e.path)).catch(()=>[]):[],p,m=await i.status(a).catch(()=>{});if(m!==void 0&&m.changedPaths.length>0&&(p=await i.captureWorkingState(e.path,`hydra: uncommitted work in ${e.label}`).catch(()=>{}),p===void 0))throw new Error(`could not capture the uncommitted work in ${V(e.path)}; nothing was changed`);if(!d.clean&&!(await i.resetTo(r,c)).ok)throw new Error(`could not clear ${V(r)} for the merge; your work is preserved at ${d.retainedRef}. Nothing was merged.`);let b=await i.integrate({into:r,from:s,fastForwardOnly:!0});if(!b.ok)throw new Error(`merge failed: ${b.reason??"unknown error"}`);let g=!0;if(p!==void 0){let x=await i.captureDelta(r,b.snapshot,p);x!==void 0&&(g=(await i.applyDelta(r,x)).ok)}let h=await Bo({source:r,capture:d,provider:i});h&&await xi({source:r,ws:a,capture:d,provider:i});let y={applied:[],failed:[]},k=i!==void 0&&i.capabilities().supports.nestedTrees?await i.integrateNested(r,e.path,f).catch(()=>y):y,S=await i.captureWorkingState(r,`hydra: source state after landing ${e.label}`).catch(()=>{});S!==void 0&&await i.retainSnapshot({...a,path:r},this.baselineRefFor(e.label),S).catch(()=>{});let I=[];g||I.push(` WARNING: the workspace's uncommitted changes could not be replayed; they remain reachable from ${s}.`),h||I.push(e.clean===!0?` WARNING: this workspace started clean, so your uncommitted work was never copied in. The whole of it is being replayed now and it overlaps what the agent changed. All of it is preserved at ${d.retainedRef}; recover with: git -C ${r} diff ${d.base} ${d.retainedRef}`:` WARNING: your own edits to ${V(r)} overlap the workspace's changes and could not be replayed on top. They are preserved at ${d.retainedRef}; recover with: git -C ${r} diff ${d.base} ${d.retainedRef}`);for(let x of k.failed)I.push(` WARNING: nested tree ${x.path} was NOT reconciled: ${x.reason}. ${V(r)} now records a different state for it, so it will report it as modified until you resolve that.`);return{merged:`Merged ${s} into ${V(r)}${u.join("")}`,warnings:I}}async applyWorkspaceToSource(e,t){let r=e.sourceCwd;if(!await this.dirExists(r))throw new Error(`source tree ${V(r)} no longer exists`);let s=We(e.provider);if(s===void 0)throw new Error(`no provider "${e.provider}" available to apply this workspace`);if(!s.capabilities().supports.captureWorkingState)throw new Error(`provider "${e.provider}" cannot snapshot a working tree, so there is no change set to apply. Use \`/hydra workspace stop\` to land this workspace instead.`);let o=this.asWorkspace(e);if((await s.status({...o,path:r}).catch(()=>{}))?.hasStagedWork===!0)throw new Error(`${V(r)} already has changes staged for its next commit, and \`apply\` delivers into that same index: the two sets would be indistinguishable, and unstaging one would unstage both. Commit or unstage them first, or use \`/hydra workspace merge\`, which lands the work as commits and does not touch the index.`);let a=await s.currentState(r);if(a===void 0)throw new Error(`could not read the state of ${V(r)}`);let d=e.line,c=d!==void 0&&await s.contains(r,{state:a,within:d}).catch(()=>!1),l=c?a:e.snapshot??"";if(l.length===0)throw new Error(`workspace ${e.label} has no recorded base to measure its changes against, so there is no way to tell its work apart from what the source already had`);let u=await Au({source:r,ws:o,startSnapshotRef:this.startRefFor(e.label),baselineRef:this.baselineRefFor(e.label),retainRef:Ru(t),provider:s}),f=s.capabilities().supports.nestedTrees?(await s.listNested(e.path).catch(()=>[])).filter(k=>k.changedPaths.length>0||k.recorded!==void 0&&k.recorded!==k.actual):[],p=await s.captureWorkingState(e.path,`hydra: apply from ${e.label}`).catch(()=>{});if(p===void 0)throw new Error(`could not snapshot the work in ${V(e.path)}; nothing was changed`);let m=await s.captureDelta(r,l,p);if(m===void 0)throw new Error(`could not work out what ${e.label} changed; ${V(r)} was not touched`);if(m.trim().length===0)return await xi({source:r,ws:o,capture:u,provider:s}),{applied:`Nothing to apply: ${e.label} holds no changes ${V(r)} does not already have.`,warnings:[]};if(!u.clean&&!(await s.resetTo(r,a)).ok)throw new Error(`could not clear ${V(r)} to apply onto; your work is preserved at ${u.retainedRef}. Nothing was applied.`);let b=await s.applyDelta(r,m,{stage:!0,tolerant:!c});if(!b.ok){await s.resetTo(r,a).catch(()=>{});let k=await Bo({source:r,capture:u,provider:s});throw k&&await xi({source:r,ws:o,capture:u,provider:s}),new Error(`could not apply ${e.label} into ${V(r)}: ${b.reason??"the change set did not apply"}.`+(c?"":" The source has moved on since this workspace was created; `/hydra workspace sync` brings those commits in here, which is what lets the change set apply against them.")+(k?` ${V(r)} is as you left it.`:` Your uncommitted work there is preserved at ${u.retainedRef}.`))}let g=await Bo({source:r,capture:u,provider:s});g&&await xi({source:r,ws:o,capture:u,provider:s});let h=await s.captureWorkingState(r,`hydra: source state after applying ${e.label}`).catch(()=>{});h!==void 0&&await s.retainSnapshot({...o,path:r},this.baselineRefFor(e.label),h).catch(()=>{});let y=[];b.alreadyPresent===!0&&y.push(` Nothing was staged: ${V(r)} already had every one of those changes.`),g||y.push(` WARNING: your own edits to ${V(r)} overlap the workspace's changes and could not be replayed on top. They are preserved at ${u.retainedRef}; recover with: git -C ${r} diff ${u.base} ${u.retainedRef}`);for(let k of f)y.push(` WARNING: nested tree ${k.relPath} was NOT included: a change set can only move the pointer to it, not what is inside. Land it with \`/hydra workspace stop\`, or copy that work across by hand.`);return{applied:`Applied ${e.label} into ${V(r)} as staged changes; still working in ${V(e.path)}.
390
390
  Nothing was committed: review it with \`git -C ${r} diff --cached\` and commit it however you like. The workspace and its history are untouched.`,warnings:y}}async leaveWorkspace(e,t,r){let s=r.exit!=="detached",o=We(t.provider),i={path:t.path,sourceCwd:t.sourceCwd,label:t.label,provider:t.provider,...t.snapshot!==void 0?{snapshot:t.snapshot}:{},...t.vcs!==void 0?{vcs:t.vcs}:{}},a=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:t.sourceCwd,workspace:void 0,historyLength:a.length,note:`Returned to the source tree at ${t.sourceCwd}`+(r.exit==="landed"?" after merging the workspace.":r.exit==="discarded"?" after discarding the workspace and its work.":" without merging."),...await this.recordSynopsisFor(e.sessionId),left:{path:t.path,removed:s}}),await this.mutateRecord(e.sessionId,{cwd:e.cwd},["workspace"]),this.invalidateListCache(),e.broadcastWorkspacePhase({phase:"left",cwd:e.cwd,sourceCwd:t.sourceCwd,integrated:r.exit==="landed"}),o!==void 0&&await this.enqueueKeyed(this.workspaceQueues,t.path,async()=>{let d=this.liveSessionsIn(t.path,e.sessionId);if(d.length>0){this.logger?.info?.(`session workspace: ${e.sessionId} left ${t.path}; ${d.length} live session(s) remain, so it stays`);return}await this.reclaimAfterLastLeaver(o,i,t,e.sessionId,r)})}async reclaimAfterLastLeaver(e,t,r,s,o){await e.unlock(t).catch(()=>{});for(let i of[this.startRefFor(r.label),this.baselineRefFor(r.label)])await e.dropSnapshotRef(t,i).catch(()=>{});o.exit!=="detached"&&(o.exit==="landed"&&await e.dropSnapshotRef(t,this.snapshotRefFor(r.label)).catch(()=>{}),await e.removeWorkspace(t,{force:!0,discardLine:!0}).catch(()=>{}))}async joinDivergence(e,t,r){let[s,o]=await Promise.all([e.captureWorkingState(t,"hydra: source state at join").catch(()=>{}),e.captureWorkingState(r.path,"hydra: workspace state at join").catch(()=>{})]);if(s===void 0||o===void 0)return`could not compare ${V(t)} with ${V(r.path)}, so refusing to join a workspace that may not match your tree`;let i=await Promise.all([s,o].map(a=>e.contentId(t,a).catch(()=>{})));if(!(i[0]!==void 0&&i[0]===i[1]))return`${V(t)} and ${V(r.path)} have diverged, and joining does not carry work across \u2014 whichever side you are not in would be left behind. Land or stash one of them first: \`git -C ${t} stash\` if the difference is yours, or \`/hydra workspace merge\` from the session already in there if it is theirs.`}liveSessionsWithLabel(e,t){let r=[];for(let s of this.sessions.values()){let o=s.workspace;o===void 0||o.sourceCwd!==e||(o.label===t||o.requestedLabel===t)&&r.push(s)}return r}async joinWorkspace(e,t,r,s){let o=We(r.provider);if(o===void 0)throw new Error(`no provider "${r.provider}" to join that workspace with`);if(o.capabilities().supports.captureWorkingState){let i=await this.joinDivergence(o,s,r);if(i!==void 0)throw new Error(i)}return await this.enqueueKeyed(this.workspaceQueues,r.path,async()=>{if(this.sessions.get(t.sessionId)?.workspace?.path!==r.path)throw new Error(`${V(r.path)} was released while joining it; run the command again`);e.broadcastWorkspacePhase({phase:"swapping"});let i=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:r.path,workspace:{path:r.path,sourceCwd:r.sourceCwd,label:r.label,...r.requestedLabel!==void 0?{requestedLabel:r.requestedLabel}:{},provider:r.provider,...r.snapshot!==void 0?{snapshot:r.snapshot}:{},...r.line!==void 0?{line:r.line}:{},...r.vcs!==void 0?{vcs:{...r.vcs}}:{}},historyLength:i.length,note:`Continuing in an isolated workspace at ${r.path}, derived from ${s}, shared with another session.`,...await this.recordSynopsisFor(e.sessionId)}),await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),this.invalidateListCache();let a=r.line;e.broadcastWorkspacePhase({phase:"entered",cwd:e.cwd,sourceCwd:r.sourceCwd,label:r.label,...a!==void 0?{branch:a}:{}});let d=this.liveSessionsIn(r.path,e.sessionId).map(l=>Qe(l.sessionId)),c=[`Joined workspace ${V(r.path)}`,` source: ${V(r.sourceCwd)}`];return a!==void 0&&c.push(` branch: ${a}`),c.push(` shared with: ${d.join(", ")}`),c.push(" your edits will interleave with that session's"),c.push("Use `/hydra workspace stop` to leave; the work lands when the last session leaves."),c.join(`
391
- `)})}async startWorkspace(e,t,r){if(e.workspace!==void 0)throw new Error(`already isolated in ${V(e.workspace.path)}. Use \`/hydra workspace stop\` to merge and return first, or \`detach\` to leave it behind.`);let s=e.cwd,o=We();if(o===void 0)throw new Error("no workspace provider available");let i=await e.quiesceBlocker();if(i!==void 0)throw new Error(i);let a=o.capabilities();if(t!==void 0){let x=this.liveSessionsWithLabel(s,t)[0];if(x!==void 0&&x.workspace!==void 0)return await this.joinWorkspace(e,x,x.workspace,s)}let d,c=[],l=!1,u=!1,f=[],p=[],m=r?.clean===!0;if(a.supports.captureWorkingState){let x=await o.status({path:s,sourceCwd:s,label:"source",provider:o.kind}).catch(()=>{});u=x!==void 0;let C=a.supports.nestedTrees&&x!==void 0&&x.changedPaths.length>0?await o.listNested(s).catch(()=>[]):[];if(x!==void 0&&x.changedPaths.length>0&&m)f=Fb(x.changedPaths,C);else if(x!==void 0&&x.changedPaths.length>0&&(c=Fb(x.changedPaths,C),p=await o.captureNested(s,C).catch(()=>[]),l=x.hasStagedWork===!0,d=await o.captureWorkingState(s,"hydra: work carried into workspace").catch(()=>{}),d===void 0))throw new Error("could not snapshot your uncommitted work, so refusing to move it. Commit or stash first.")}e.broadcastWorkspacePhase({phase:"provisioning"});let b=await o.createWorkspace({sourceCwd:s,label:t??`s-${e.sessionId.slice(-8)}`});if(!b.ok)throw e.broadcastWorkspacePhase({phase:"failed",error:b.reason}),new Error(b.reason);let g=b.workspace,h=this.startRefFor(g.label),y,k=!1,S=[];try{a.locking&&await o.lock(g,`session ${e.sessionId}`).catch(()=>{});let x=d??g.snapshot;if(x===void 0)throw new Error(`provider "${g.provider}" gave the workspace no base to anchor landing against`);await o.retainSnapshot(g,h,x),e.broadcastWorkspacePhase({phase:"setup"}),k=d!==void 0?await this.copyCarriedWork(g,d,s):!0;let C=await this.materializeNestedTrees(g);if(p.length>0){let E=await o.reproduceNested(g.path,s,p).catch(M=>({applied:[],failed:p.map(F=>({path:F.relPath,reason:M instanceof Error?M.message:String(M)}))}));E.failed.length>0&&(k=!1,S=E.failed)}y=await this.applyWorkspaceSetup(g,e.sessionId),C!==void 0&&(y=y===void 0?C:`${C}; ${y}`),e.broadcastWorkspacePhase({phase:"swapping"});let $=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:g.path,workspace:{path:g.path,sourceCwd:g.sourceCwd,label:g.label,...t!==void 0&&t!==g.label?{requestedLabel:t}:{},provider:g.provider,...g.snapshot!==void 0?{snapshot:g.snapshot}:{},...g.line!==void 0?{line:g.line}:{},...g.vcs!==void 0?{vcs:{...g.vcs}}:{},...d===void 0?{clean:!0}:{}},historyLength:$.length,note:`Continuing in an isolated workspace at ${g.path}, derived from ${s}.`,...await this.recordSynopsisFor(e.sessionId)})}catch(x){let C=await this.unwindStartWorkspace({provider:o,ws:g,startRef:h,carried:d}),$=x instanceof Error?x.message:String(x);throw e.broadcastWorkspacePhase({phase:"failed",error:$}),new Error(C===void 0?$:`${$}
391
+ `)})}async startWorkspace(e,t,r){if(e.workspace!==void 0)throw new Error(`already isolated in ${V(e.workspace.path)}. Use \`/hydra workspace stop\` to merge and return first, or \`detach\` to leave it behind.`);let s=e.cwd,o=We();if(o===void 0)throw new Error("no workspace provider available");let i=await e.quiesceBlocker();if(i!==void 0)throw new Error(i);let a=o.capabilities();if(t!==void 0){let x=this.liveSessionsWithLabel(s,t)[0];if(x!==void 0&&x.workspace!==void 0)return await this.joinWorkspace(e,x,x.workspace,s)}let d,c=[],l=!1,u=!1,f=[],p=[],m=r?.clean===!0;if(a.supports.captureWorkingState){let x=await o.status({path:s,sourceCwd:s,label:"source",provider:o.kind}).catch(()=>{});u=x!==void 0;let C=a.supports.nestedTrees&&x!==void 0&&x.changedPaths.length>0?await o.listNested(s).catch(()=>[]):[];if(x!==void 0&&x.changedPaths.length>0&&m)f=Fb(x.changedPaths,C);else if(x!==void 0&&x.changedPaths.length>0&&(c=Fb(x.changedPaths,C),p=await o.captureNested(s,C).catch(()=>[]),l=x.hasStagedWork===!0,d=await o.captureWorkingState(s,"hydra: work carried into workspace").catch(()=>{}),d===void 0))throw new Error("could not snapshot your uncommitted work, so refusing to move it. Commit or stash first.")}e.broadcastWorkspacePhase({phase:"provisioning"});let b=await o.createWorkspace({sourceCwd:s,label:t??`s-${e.sessionId.slice(-8)}`});if(!b.ok)throw e.broadcastWorkspacePhase({phase:"failed",error:b.reason}),new Error(b.reason);let g=b.workspace,h=this.startRefFor(g.label),y,k=!1,S=[];try{a.locking&&await o.lock(g,`session ${e.sessionId}`).catch(()=>{});let x=d??g.snapshot;if(x===void 0)throw new Error(`provider "${g.provider}" gave the workspace no base to anchor landing against`);await o.retainSnapshot(g,h,x),e.broadcastWorkspacePhase({phase:"setup"}),k=d!==void 0?await this.copyCarriedWork(g,d,s):!0;let C=await this.materializeNestedTrees(g);if(p.length>0){let P=await o.reproduceNested(g.path,s,p).catch(M=>({applied:[],failed:p.map(F=>({path:F.relPath,reason:M instanceof Error?M.message:String(M)}))}));P.failed.length>0&&(k=!1,S=P.failed)}y=await this.applyWorkspaceSetup(g,e.sessionId),C!==void 0&&(y=y===void 0?C:`${C}; ${y}`),e.broadcastWorkspacePhase({phase:"swapping"});let $=await this.histories.load(e.sessionId).catch(()=>[]);await e.swapIntoWorkspace({cwd:g.path,workspace:{path:g.path,sourceCwd:g.sourceCwd,label:g.label,...t!==void 0&&t!==g.label?{requestedLabel:t}:{},provider:g.provider,...g.snapshot!==void 0?{snapshot:g.snapshot}:{},...g.line!==void 0?{line:g.line}:{},...g.vcs!==void 0?{vcs:{...g.vcs}}:{},...d===void 0?{clean:!0}:{}},historyLength:$.length,note:`Continuing in an isolated workspace at ${g.path}, derived from ${s}.`,...await this.recordSynopsisFor(e.sessionId)})}catch(x){let C=await this.unwindStartWorkspace({provider:o,ws:g,startRef:h,carried:d}),$=x instanceof Error?x.message:String(x);throw e.broadcastWorkspacePhase({phase:"failed",error:$}),new Error(C===void 0?$:`${$}
392
392
  ${C}`)}await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),this.invalidateListCache(),e.broadcastWorkspacePhase({phase:"entered",cwd:e.cwd,sourceCwd:g.sourceCwd,label:g.label,...g.line!==void 0?{branch:g.line}:{}});let I=[`Moved into workspace ${V(g.path)}`,` source: ${V(s)}`];if(g.line!==void 0&&I.push(` branch: ${g.line}`),t!==void 0&&t!==g.label&&I.push(` note: "${t}" was already taken by a surviving branch, so this is "${g.label}"`),d!==void 0){I.push(k?` carried ${c.length} uncommitted file(s) in; the source tree is untouched:`:` WARNING: could not copy ${c.length} uncommitted file(s); the workspace starts from HEAD. They are untouched in the source tree:`);for(let x of Ra(c))I.push(` ${x}`);k&&l&&I.push(" staging did not come along; everything above is unstaged here");for(let x of S)I.push(` nested tree ${x.path}: ${x.reason}`)}else if(f.length>0){I.push(` started clean: ${f.length} uncommitted file(s) stayed in the source and did NOT come along:`);for(let x of Ra(f))I.push(` ${x}`)}else u&&I.push(" source tree was clean; nothing carried in");return y!==void 0&&I.push(` ${y}`),I.push("Use `/hydra workspace stop` to merge back and return."),I.join(`
393
- `)}async copyCarriedWork(e,t,r){let s=await this.patchFromSnapshot(r,t,e.provider);if(s===void 0)return!1;if(s.length===0)return!0;let o=We(e.provider);return o===void 0?!1:(await o.applyDelta(e.path,s)).ok}async patchFromSnapshot(e,t,r){let s=We(r);if(s===void 0)return;let o=await s.currentState(e);if(o!==void 0)return await s.captureDelta(e,o,t).catch(()=>{})}async unwindStartWorkspace(e){let{provider:t,ws:r,startRef:s,carried:o}=e;await t.unlock(r).catch(()=>{}),o!==void 0&&await t.dropSnapshotRef(r,s).catch(()=>{}),await t.removeWorkspace(r,{force:!0}).catch(()=>{})}async materializeNestedTrees(e,t){let r=We(e.provider);if(r?.capabilities().supports.nestedTrees!==!0)return;let s=await r.materializeNested({path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:r.kind},t).catch(o=>({ok:!1,count:0,reason:o instanceof Error?o.message:String(o)}));return s.ok?s.count>0?`populated ${s.count} nested tree(s)`:void 0:`nested trees FAILED: ${s.reason??"unknown"}`}async applyWorkspaceSetup(e,t){let r=await wh(e.sourceCwd).catch(()=>({})),s=[];if(r.carry!==void 0&&r.carry.length>0){let o=await Bb(e.sourceCwd,e.path,r.carry).catch(()=>{});o!==void 0&&o.copied.length>0&&s.push(`carried ${o.copied.length} config file(s)`)}if(r.postCreate!==void 0){let o=await bh(r.postCreate,{workspacePath:e.path,sourceCwd:e.sourceCwd,label:e.label,sessionId:t,...r.hookTimeoutSeconds!==void 0?{timeoutSeconds:r.hookTimeoutSeconds}:{}});s.push(o.ok?"ran postCreate":`postCreate FAILED: ${o.reason??"unknown"}`)}return s.length>0?s.join("; "):void 0}async deriveForkWorkspace(e,t){let r=We(e.provider);if(r===void 0)return;let s=r.capabilities(),o=s.sharedHistory?await r.currentState(e.path)??"":"",i=await r.createWorkspace({sourceCwd:e.sourceCwd,label:t,...o.length>0?{from:o}:{contentFrom:e.path}}).catch(d=>({ok:!1,reason:String(d)}));if(!i.ok){this.logger?.warn?.(`fork workspace: could not derive from ${e.path}: ${i.reason}`);return}let a=i.workspace;if(o.length>0&&s.supports.captureWorkingState){let d=await r.captureWorkingState(e.path,`hydra: fork carry from ${e.label}`).catch(()=>{});d!==void 0&&d!==o&&await this.copyUncommittedInto(e.path,a.path,o,d,a.provider).catch(()=>{})}return{path:a.path,sourceCwd:a.sourceCwd,label:a.label,provider:a.provider,...a.snapshot!==void 0?{snapshot:a.snapshot}:{},...a.line!==void 0?{line:a.line}:{},...a.vcs!==void 0?{vcs:{...a.vcs}}:{}}}async copyUncommittedInto(e,t,r,s,o){let i=We(o);if(i===void 0)return!1;let a=await i.captureDelta(e,r,s).catch(()=>{});return a===void 0||a.trim().length===0?!1:(await i.applyDelta(t,a,{stage:!0})).ok}async recoverWorkspace(e){let t=We(e.provider);if(t===void 0)return;let r={path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:e.provider,...e.snapshot!==void 0?{snapshot:e.snapshot}:{},...e.vcs!==void 0?{vcs:e.vcs}:{}};if(t.capabilities().supports.rematerialize){let o=await t.rematerialize(r).catch(i=>({ok:!1,reason:String(i)}));if(o.ok)return this.logger?.info?.(`session workspace: restored ${o.workspace.path} from retained state`),{...e,path:o.workspace.path};this.logger?.warn?.(`session workspace: could not restore: ${o.reason}`)}if(!await this.dirExists(e.sourceCwd))return;let s=await t.createWorkspace({sourceCwd:e.sourceCwd,label:`${e.label}-r`}).catch(o=>({ok:!1,reason:String(o)}));if(s.ok)return this.logger?.warn?.(`session workspace: ${e.path} is gone and could not be restored; resurrecting in a fresh workspace ${s.workspace.path} from ${e.sourceCwd}. Uncommitted work from the old workspace is not recoverable.`),{path:s.workspace.path,sourceCwd:s.workspace.sourceCwd,label:s.workspace.label,provider:s.workspace.provider,...s.workspace.snapshot!==void 0?{snapshot:s.workspace.snapshot}:{},...s.workspace.vcs!==void 0?{vcs:{...s.workspace.vcs}}:{}}}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let b=new Error(`agent ${e} not found in registry`);throw b.code=G.AgentNotInstalled,b}let r=await Fr(t,[],{npmRegistry:this.npmRegistry}),s=this.spawner({agentId:e,cwd:YA.homedir(),plan:r}),o;try{o=await s.connection.request("initialize",{protocolVersion:1,clientCapabilities:vc,clientInfo:{name:"hydra",version:Fe}})}catch(b){throw await s.kill().catch(()=>{}),Ci(b,s)}if(s.authMethods=Fu(o.authMethods),s.steeringSupported=Ou(o),(o.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await s.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(s)}catch(b){throw await s.kill().catch(()=>{}),b}await s.kill().catch(()=>{});let d=new Map,c=Hw(t);d.set(e,c);let l=new Set;for(let b of this.sessions.values()){let g=await this.agentStoreKey(b.agentId,d);l.add(`${g}::${b.upstreamSessionId}`)}let u=await this.store.list().catch(()=>[]);for(let b of u){l.add(`${await this.agentStoreKey(b.agentId,d)}::${b.upstreamSessionId}`);for(let g of b.upstreamGenerations??[])l.add(`${await this.agentStoreKey(g.agentId,d)}::${g.upstreamSessionId}`)}let f=D.sessionsDir(),p=[],m=0;for(let b of a){let g=`${c}::${b.sessionId}`;if(l.has(g)){m+=1;continue}if(yB(b.cwd,f)){m+=1;continue}let h=c,y=await this.tombstones.read(h,b.sessionId).catch(()=>{});if(!y&&c!==e&&(h=e,y=await this.tombstones.read(h,b.sessionId).catch(()=>{})),y){if(!xA(y,b.updatedAt)){m+=1;continue}await this.tombstones.remove(h,b.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${b.sessionId} (upstream updatedAt advanced past ${y.upstreamUpdatedAt??"<unset>"})`)}l.add(g);let k=`${Yt}${Ma()}`,S=new Date().toISOString(),I=b.updatedAt??S,x={sessionId:k,lineageId:xu(),upstreamSessionId:b.sessionId,agentId:e,cwd:b.cwd,pendingHistorySync:!0,interactive:!wB(b.title),createdAt:I,updatedAt:I};b.title!==void 0&&(x.title=b.title);let C=_b(x);await this.store.write(C),p.push({version:1,...C})}return{synced:p,skipped:m}}async listTombstones(e={}){let t=e.grep?.toLowerCase();return(await this.tombstones.list(e.agentId)).filter(s=>e.since===void 0||s.deletedAt>=e.since).filter(s=>t===void 0||[s.title,s.cwd,s.sessionId,s.upstreamSessionId].some(o=>o?.toLowerCase().includes(t))).sort((s,o)=>s.deletedAt<o.deletedAt?1:-1)}async undeleteSessions(e){let t=await this.tombstones.list(),r=[],s=[],o=[];for(let a of e){let d=t.filter(l=>l.upstreamSessionId===a),c=d.length>0?d:t.filter(l=>l.sessionId===a||l.sessionId===`${Yt}${a}`);if(c.length===0){s.push({id:a,reason:"no tombstone found"});continue}if(c.length>1){s.push({id:a,reason:"ambiguous: several tombstones match; pass an upstream id",candidates:c.map(l=>l.upstreamSessionId)});continue}o.push({id:a,tombstone:c[0]})}let i=new Map;for(let a of o){let d=i.get(a.tombstone.agentId)??[];d.push(a),i.set(a.tombstone.agentId,d)}for(let[a,d]of i){let c=u=>{let{version:f,...p}=u;return this.tombstones.add(p).catch(()=>{})};for(let u of d)await this.tombstones.remove(a,u.tombstone.upstreamSessionId);let l;try{l=(await this.syncFromAgent(a)).synced}catch(u){for(let f of d)await c(f.tombstone),s.push({id:f.id,reason:`agent sync failed: ${u.message}`});continue}for(let u of d){let f=l.find(p=>p.upstreamSessionId===u.tombstone.upstreamSessionId);if(!f){await c(u.tombstone),s.push({id:u.id,reason:`agent ${a} no longer lists this session`});continue}r.push({id:u.id,sessionId:f.sessionId,upstreamSessionId:u.tombstone.upstreamSessionId})}}return{restored:r,failed:s}}async collectAgentSessions(e){let t=[],r,s=new Set;for(let o=0;o<100;o+=1){let i={};r!==void 0&&(i.cursor=r);let a=await e.connection.request("session/list",i),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let l={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(l.title=c.title),typeof c.updatedAt=="string"&&(l.updatedAt=c.updatedAt),t.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||s.has(a.nextCursor))break;s.add(a.nextCursor),r=a.nextCursor}return t}async applySeedModel(e,t,r,s,o){try{let{verb:i,result:a}=await ki({request:(d,c)=>e.connection.request(d,c),sessionId:t,modelId:r,...o?{verb:o}:{},logger:this.logger});return this.logger?.info(`${s}: ${i} accepted`),{accepted:!0,result:a}}catch(i){return this.logger?.warn(`${s} rejected by agent (${i.message}); session will use the agent's own default`),{accepted:!1}}}async applySeedMode(e,t,r,s){try{let o=await e.connection.request("session/set_mode",{sessionId:t,modeId:r});return this.logger?.info(`${s}: session/set_mode accepted`),{accepted:!0,result:o}}catch(o){return this.logger?.warn(`${s} rejected by agent (${o.message}); session will use the agent's own default mode`),{accepted:!1}}}async restoreConfigOptionValues(e,t,r,s){if(!r||Object.keys(r).length===0)return s;let o=s;for(let[i,a]of Object.entries(r)){let d=`resurrect: persisted configOptionValues.${i}=${JSON.stringify(a)}`,c=o.find(f=>f.id===i);if(!c){this.logger?.warn(`${d}: agent does not currently advertise configId=${i}; skipping session/set_config_option`);continue}if(a===c.currentValue)continue;let l=Ec(a,c.options.map(f=>f.value));if(l.kind!=="exact"&&l.kind!=="resolved"){this.logger?.warn(`${d} ${l.kind}; skipping session/set_config_option`);continue}let u=l.kind==="resolved"?l.modelId:a;try{let f=await e.connection.request("session/set_config_option",{sessionId:t,configId:i,value:u});this.logger?.info(`${d}: session/set_config_option accepted`),o=_a(f)?$a(f):o.map(p=>p.id===i?{...p,currentValue:u}:p)}catch(f){this.logger?.warn(`${d}: session/set_config_option rejected by agent (${f.message})`)}}return o}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=G.AgentNotInstalled,i}let r=await Fr(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),s=Ap(e.selfSessionId,e.forwardedEnv),o=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...s?{extraEnv:s}:{}});try{let i=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:vc,clientInfo:{name:"hydra",version:Fe}}),a=i.agentCapabilities;o.authMethods=Fu(i.authMethods),o.steeringSupported=Ou(i);let d=Qb(t),c=await o.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[],...d&&{_meta:d}}),l=c.sessionId;if(typeof l!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let u=Xb(c),f=Zb(c),p=Ic(c),m=Or(this.sessionDefaults,t),b=m?.value,g=e.configDefaults,h=m?.from??e.agentId,y=e.model??g?.model??b?.model,k;if(y&&y!==u){let E=Tc(y,f),M=e.model!==void 0?`model=${JSON.stringify(y)}`:g?.model!==void 0?`configDefaults.model=${JSON.stringify(y)}`:`sessionDefaults[${h}].model=${JSON.stringify(y)}`;if(E.kind==="exact"||E.kind==="none"){let F=await this.applySeedModel(o,l,y,M,p);F.accepted&&(u=y,k=F.result)}else if(E.kind==="resolved")if(E.modelId===u)u=E.modelId;else{let F=await this.applySeedModel(o,l,E.modelId,`${M} resolved to ${JSON.stringify(E.modelId)}`,p);F.accepted&&(u=E.modelId,k=F.result)}else if(E.kind==="ambiguous")this.logger?.warn(`${M} is ambiguous (trailing-segment matches [${E.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(u)}`);else{let F=f.map(K=>K.modelId).join(", ");this.logger?.warn(`${M} not in agent's availableModels ([${F}]); skipping session/set_model, session will use ${JSON.stringify(u)}`)}}let S=ek(c),I=tk(c),x=g?.mode??b?.mode;if(x&&x!==I){let E=g?.mode!==void 0?`configDefaults.mode=${JSON.stringify(x)}`:`sessionDefaults[${h}].mode=${JSON.stringify(x)}`;if(S.length>0&&!S.some(M=>M.id===x)){let M=S.map(F=>F.id).join(", ");this.logger?.warn(`${E} not in agent's availableModes ([${M}]); skipping session/set_mode, session will use ${JSON.stringify(I)}`)}else{let M=await this.applySeedMode(o,l,x,E);M.accepted&&(I=x,_a(M.result)&&(k=M.result))}}let C={...b??{},...g??{}};if(delete C.model,delete C.mode,Object.keys(C).length>0){let E=$a(_a(k)?k:c);for(let[M,F]of Object.entries(C)){let K=`sessionDefaults[${h}].${M}=${JSON.stringify(F)}`,Y=E.find(Q=>Q.id===M);if(!Y){this.logger?.warn(`${K}: agent does not currently advertise configId=${M}; skipping session/set_config_option`);continue}let z=Ec(F,Y.options.map(Q=>Q.value));if(z.kind!=="exact"&&z.kind!=="resolved"){this.logger?.warn(`${K} ${z.kind}; skipping session/set_config_option`);continue}let re=z.kind==="resolved"?z.modelId:F;if(re!==Y.currentValue)try{let Q=await o.connection.request("session/set_config_option",{sessionId:l,configId:M,value:re});this.logger?.info(`${K}: session/set_config_option accepted`),_a(Q)&&(E=$a(Q),k=Q)}catch(Q){this.logger?.warn(`${K}: session/set_config_option rejected by agent (${Q.message})`)}}}let $=$a(_a(k)?k:c);return{agent:o,upstreamSessionId:l,agentMeta:c._meta,agentCapabilities:a,initialModel:u,initialModels:f.length>0?f:void 0,initialModes:S.length>0?S:void 0,initialMode:I,initialConfigOptions:$.length>0?$:void 0,modelVerb:p}}catch(i){throw await o.kill().catch(()=>{}),Ci(JA(i,o,e.agentId,{command:r.command,args:r.args,cwd:e.cwd}),o)}}async bootstrapAgentLoad(e,t){let r=await this.registry.getAgent(t.agentId);if(!r){let a=new Error(`agent ${t.agentId} not found in registry`);throw a.code=G.AgentNotInstalled,a}let s=await Fr(r,t.agentArgs??[],{npmRegistry:this.npmRegistry}),o=Ap(t.selfSessionId,t.forwardedEnv),i=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:s,...o?{extraEnv:o}:{}});try{let a=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:vc,clientInfo:{name:"hydra",version:Fe}}),d=a.agentCapabilities;i.authMethods=Fu(a.authMethods),i.steeringSupported=Ou(a);let c=Qb(r),l=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...c&&{_meta:c}}),u=Xb(l),f=Ii(Zb(l)),p=ek(l),m=tk(l),b=Ii($a(l));return{agent:i,upstreamSessionId:e,agentMeta:l._meta,agentCapabilities:d,initialModel:u,initialModels:f,initialModes:p.length>0?p:void 0,initialMode:m,initialConfigOptions:b,modelVerb:Ic(l)}}catch(a){throw await i.kill().catch(()=>{}),Ci(JA(a,i,t.agentId,{command:s.command,args:s.args,cwd:t.cwd}),i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)throw new Error("session is not live \u2014 cannot roll back a cold session");let r=await this.store.read(e);if(!r)throw new Error("session record not found");let s=r.rollbackBreadcrumb;if(!s)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let o=r.compactionState;if(o!=null)throw new Error(`compaction is in progress (status: ${o.status}) \u2014 wait for it to complete before rolling back`);if(!await t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:s.previousUpstreamSessionId,previousSummarizedThroughEntry:s.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:s.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let r=this.pendingAuthAgents.get(e);if(r&&r.isAlive())return r;let s=await this.registry.getAgent(e);if(!s){let d=new Error(`agent ${e} not found in registry`);throw d.code=G.AgentNotInstalled,d}let o=await Fr(s,[],{npmRegistry:this.npmRegistry}),i=t??Ze(this.defaultCwd),a=this.spawner({agentId:e,cwd:i,plan:o});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:vc,clientInfo:{name:"hydra",version:Fe}});a.authMethods=Fu(d.authMethods),a.steeringSupported=Ou(d)}catch(d){throw await a.kill().catch(()=>{}),Ci(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let r=new Error(`agent ${e} not found in registry`);throw r.code=G.AgentNotInstalled,r}return Fr(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.driftNoticed.delete(e.sessionId),this.invalidateListCache(),t||this.store.touch(e.sessionId).catch(()=>{}),t&&e.workspace!==void 0&&this.releaseWorkspace(e.workspace,e.sessionId).catch(()=>{}),t){if(e.upstreamSessionId){let s=Nc({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),o=this.tombstoneAllGenerations(e.sessionId,{agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,...e.title!==void 0?{title:e.title}:{},...s!==void 0?{interactive:s}:{}},"user").catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===o&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,o);return}let r=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===r&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,r);return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:r,...s})=>{this.persistAgentChange(e.sessionId,t,r,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:QA(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(r=>({name:r.name,...r.description!==void 0?{description:r.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(r=>({id:r.id,...r.name!==void 0?{name:r.name}:{},...r.description!==void 0?{description:r.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(r=>({modelId:r.modelId,...r.name!==void 0?{name:r.name}:{},...r.description!==void 0?{description:r.description}:{}}))}).catch(()=>{})}),e.onConfigOptionsChange(t=>{this.persistSnapshot(e.sessionId,{configOptionValues:Object.fromEntries(t.map(r=>[r.id,r.currentValue]))}).catch(()=>{})}),e.onAttentionFlagsChange(t=>{this.mutateRecord(e.sessionId,{attentionFlags:t}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),r=bB(e,t);await this.store.write(r)}).catch(t=>{this.logger?.warn(`failed to persist session record for ${e.sessionId}: ${t instanceof Error?t.message:String(t)}`)})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async pageHistory(e,t){let r=await this.store.read(e);if(!this.sessions.has(e)&&!r)return;let s=this.sessions.get(e)?.side??r?.side,o=await this.histories.pageBefore(e,{...t,skip:a=>bu(a.method,a.params)}),i=Sc(o.entries,s);return{entries:i,hasMore:o.hasMore&&i.length===o.entries.length}}async loadHistory(e,t={}){return this.histories.load(e,t)}async loadToolBlob(e,t){return au(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let r=t.title;return r||(r=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:r,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:kB(t.currentUsage),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,configOptionValues:t.configOptionValues,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,side:t.side,forkSynthesisState:t.forkSynthesisState,forwardedEnv:t.forwardedEnv,workspace:t.workspace,compactionState:t.compactionState,attentionFlags:t.attentionFlags?.filter(s=>!(s.source==="daemon"&&s.reason.startsWith("permission:")))}}async setForwardedEnv(e,t){if(t===void 0)return;let r=this.sessions.get(e);r&&(r.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);if(!s)return;let o={...s,forwardedEnv:t};await this.store.write(o)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let r={...t};delete r.pendingHistorySync,await this.store.write(r)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let r of t){let s=r.params;if(s?.update?.sessionUpdate!=="prompt_received")continue;let o=s.update.sentBy;if(typeof o?.fromSession=="string"||typeof o?.clientId=="string"&&o.clientId.startsWith("transformer:"))continue;let i=Ca(s.update.prompt),a=Cb(i,200);if(a&&!a.startsWith("/"))return a}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}setLiveConfig(e){e.sessionDefaults&&(this.sessionDefaults=e.sessionDefaults)}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let r=t.agent.installId,s=t.agent.version,o=e.get(r);o||(o=new Set,e.set(r,o)),o.add(s)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(Yt))return;let t=Yt+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let r=new Error(`session ${e} not found`);throw r.code=G.SessionNotFound,r}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,workspace:e.workspace,workspaceError:e.workspaceError,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,side:e.side,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,turnStartedAt:e.turnStartedAt,armedTasks:e.armedBackgroundTasks.length,...e.armedSince!==void 0?{armedSince:e.armedSince}:{},awaitingInput:e.awaitingInput,agentPid:e.agentPid}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await Lu(t.sessionId),d=Nc({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),c=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,side:t.side,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:d,priority:t.priority,createdAt:new Date(t.createdAt).toISOString(),updatedAt:c,attachedClients:t.attachedCount,status:"warm",agentPid:t.agentPid,busy:t.turnStartedAt!==void 0,turnStartedAt:t.turnStartedAt,armedTasks:t.armedBackgroundTasks.length,...t.armedSince!==void 0?{armedSince:t.armedSince}:{},awaitingInput:t.awaitingInput}}let r=await this.store.read(e).catch(()=>{});if(!r)return;let s=await Lu(r.sessionId),o=Nc(r,s.hasContent),i=s.mtime??r.updatedAt;return{sessionId:r.sessionId,upstreamSessionId:r.upstreamSessionId,cwd:r.cwd,title:r.title,agentId:r.agentId,currentModel:r.currentModel,currentUsage:Pa(r.currentUsage),importedFromMachine:r.importedFromMachine,importedFromUpstreamSessionId:r.importedFromUpstreamSessionId,parentSessionId:r.parentSessionId,forkedFromSessionId:r.forkedFromSessionId,forkedFromMessageId:r.forkedFromMessageId,side:r.side,forkSynthesisState:r.forkSynthesisState,originatingClient:r.originatingClient,interactive:o,priority:r.priority,createdAt:r.createdAt,updatedAt:i,attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1}}async list(e={}){return(await this.listing(e)).entries}async listing(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}|${e.status??""}`,r=Date.now(),s=this.listCache.get(t);if(s&&s.expiresAt>r)return s.promise;let o=this.listUncached(e);return this.listCache.set(t,{expiresAt:r+n.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(t);i&&i.promise===o&&this.listCache.delete(t)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=await this.store.cursor(),{entries:r,liveIds:s}=await this.warmRows(e);if(e.status==="warm")return{entries:r,cursor:t};let o=await this.store.list().catch(i=>{throw this.logger?.warn(`session list: store.list() failed: ${i?.message??String(i)}`),i});return r.push(...await this.coldRows(o,s,e)),r.sort((i,a)=>i.updatedAt<a.updatedAt?1:-1),{entries:r,cursor:t}}async listSince(e,t){let{entries:r,liveIds:s}=await this.warmRows(e);if(e.status==="warm")return{entries:r,removed:[],cursor:await this.store.cursor()};let o=await this.store.listChangedSince(t);return r.push(...await this.coldRows(o.records,s,e)),r.sort((i,a)=>i.updatedAt<a.updatedAt?1:-1),{entries:r,removed:o.removed,cursor:o.cursor}}async seedSessionIndex(){await this.store.ensureIndex();let e=await this.tombstones.list().catch(()=>[]);for(let t of e){if(t.sessionId===void 0)continue;let r=Date.parse(t.deletedAt);Number.isNaN(r)||await this.store.markDeleted(t.sessionId,r)}}static includeRow(e,t){return e.includeNonInteractive?!0:t===!0}async warmRows(e){let t=[],r=new Set,s=[...this.sessions.values()].filter(i=>KA(e.cwd,i));if(e.status==="cold"){for(let i of s)r.add(i.sessionId);return{entries:t,liveIds:r}}let o=await Promise.all(s.map(i=>Lu(i.sessionId)));for(let i=0;i<o.length;i+=1){let a=s[i],d=o[i];r.add(a.sessionId);let c=Nc({interactive:a.interactive,...a.originatingClient?{originatingClient:a.originatingClient}:{}},d.hasContent);if(!n.includeRow(e,c))continue;let l=d.mtime??new Date(a.updatedAt).toISOString();t.push({sessionId:a.sessionId,upstreamSessionId:a.upstreamSessionId,cwd:a.cwd,workspace:a.workspace,workspaceError:a.workspaceError,title:a.title,agentId:a.agentId,currentModel:a.currentModel,currentUsage:a.currentUsage,parentSessionId:a.parentSessionId,forkedFromSessionId:a.forkedFromSessionId,forkedFromMessageId:a.forkedFromMessageId,side:a.side,originatingClient:a.originatingClient,interactive:c,priority:a.priority,createdAt:new Date(a.createdAt).toISOString(),updatedAt:l,attachedClients:a.attachedCount,status:"warm",agentPid:a.agentPid,busy:a.turnStartedAt!==void 0,turnStartedAt:a.turnStartedAt,armedTasks:a.armedBackgroundTasks.length,...a.armedSince!==void 0?{armedSince:a.armedSince}:{},awaitingInput:a.awaitingInput,compactionState:a.compactionState,forkSynthesisState:a.forkSynthesisState})}return{entries:t,liveIds:r}}async coldRows(e,t,r){let s=[],o=e.filter(a=>!t.has(a.sessionId)&&KA(r.cwd,a)),i=await Promise.all(o.map(a=>Lu(a.sessionId)));for(let a=0;a<o.length;a+=1){let d=o[a],c=i[a],l=Nc(d,c.hasContent);if(!n.includeRow(r,l))continue;let u=c.mtime??d.updatedAt;s.push({sessionId:d.sessionId,upstreamSessionId:d.upstreamSessionId,cwd:d.cwd,workspace:d.workspace,title:d.title,agentId:d.agentId,currentModel:d.currentModel,currentUsage:Pa(d.currentUsage),importedFromMachine:d.importedFromMachine,importedFromUpstreamSessionId:d.importedFromUpstreamSessionId,parentSessionId:d.parentSessionId,forkedFromSessionId:d.forkedFromSessionId,forkedFromMessageId:d.forkedFromMessageId,side:d.side,originatingClient:d.originatingClient,interactive:l,priority:d.priority,createdAt:d.createdAt,updatedAt:u,attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1,compactionState:d.compactionState,forkSynthesisState:d.forkSynthesisState})}return s}async exportBundle(e,t={}){let r=await this.store.read(e);if(!r)return;let s;if(r.lineageId)s=r;else{let c=xu(),l={...r,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:c}))}).catch(()=>{}),s=l}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await VA(e);if(o!=="references")return{record:s,history:i,promptHistory:a};let d={};for(let c of HA(i)){let l=await iC(e,c);l&&(d[c]=l.toString("base64"))}return{record:s,history:i,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let r=await this.store.findByLineageId(e.session.lineageId);if(r){if(!t.replace){let i=new Error(`bundle already imported as ${r.sessionId}`);throw i.code=G.BundleAlreadyImported,i.existingSessionId=r.sessionId,i}let o=this.sessions.get(r.sessionId);return o&&await o.close({deleteRecord:!1,by:"bundle-import-overwrite"}).catch(()=>{}),await this.writeImportedRecord({sessionId:r.sessionId,bundle:e,preservedCreatedAt:r.createdAt,cwd:t.cwd}),{sessionId:r.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let s=`${Yt}${Ma()}`;return await this.writeImportedRecord({sessionId:s,bundle:e,cwd:t.cwd}),{sessionId:s,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let r=await this.store.read(e);if(!r){let x=new Error(`source session not found: ${e}`);throw x.code=G.SessionNotFound,x}let s=t.agentId??r.agentId,o=s!==r.agentId;if(o&&!await this.registry.getAgent(s)){let C=new Error(`agent ${s} not found in registry`);throw C.code=G.AgentNotInstalled,C}let i=await this.histories.load(e).catch(()=>[]),a=i,d,c=t.mode??(t.side?"verbatim":"synthesis"),l,u,f,p=12e4;if(c==="verbatim")if(t.forkAt!==void 0){let x=oh(i,t.forkAt);if(x<0){let C=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw C.code=G.InvalidParams,C}d=t.forkAt,a=i.slice(0,x+1)}else{let x=IB(i);x?(d=x.messageId,a=i.slice(0,x.index+1)):(d="",a=i.slice(0,0))}else{if(t.forkAt!==void 0&&t.forkAt!==""){let C=oh(i,t.forkAt);if(C<0){let $=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw $.code=G.InvalidParams,$}d=t.forkAt,a=i.slice(0,C+1)}else d="",a=i;let x=await this.registry.getAgent(s);if(!x){let C=new Error(`agent ${s} not found in registry`);throw C.code=G.AgentNotInstalled,C}f=x,u=r.currentModel,l="running"}let m=await VA(e),b=c==="synthesis",g={...r,lineageId:xu(),agentId:s,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...o?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},h=_u({record:g,history:a,promptHistory:m.length>0?m:void 0,hydraVersion:Fe,machine:Ys()}),y=`${Yt}${Ma()}`,k=t.cwd,S;if(t.cwd===void 0&&r.workspace!==void 0){let x=await this.deriveForkWorkspace(r.workspace,`${r.workspace.label}-fork-${y.slice(-6)}`);x!==void 0?(S=x,k=x.path):(k=r.workspace.sourceCwd,this.logger?.warn?.(`fork ${y}: could not derive an isolated workspace from ${r.workspace.path}; running unisolated in ${k}`))}await this.writeImportedRecord({sessionId:y,bundle:h,cwd:k,...S!==void 0?{workspace:S}:{},forkedFromSessionId:e,forkedFromMessageId:d,...t.side!==void 0?{side:{...t.side.selection!==void 0?{selection:t.side.selection}:{},...zC(a)}}:{},...l!==void 0?{forkSynthesisState:l}:{}});let I=b?(async()=>{try{let x=await Fr(f,[],{npmRegistry:this.npmRegistry}),C=await Sh({agentId:s,cwd:t.cwd??D.sessionDir(e),plan:x,history:a,modelId:u,sessionId:e,logger:this.logger,timeoutMs:p});C&&C.synopsis?await this.mutateRecord(y,{synopsis:C.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(y,{},["forkSynthesisState"]))}catch(x){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${x.message}`);try{await this.mutateRecord(y,{},["forkSynthesisState"])}catch(C){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${C.message}`)}}})():Promise.resolve();if(t.prompt!==void 0&&t.prompt.trim()!==""){let x=t.prompt;I.catch(()=>{}).then(()=>this.deliverHeadlessPrompt(y,x)).catch(C=>{this.logger?.warn(`forkSession(${e}): headless prompt delivery to ${y} failed: ${C.message}`)})}return{sessionId:y,forkedFromSessionId:e,forkedAt:d}}async deliverHeadlessPrompt(e,t){let r=await this.loadFromDisk(e);if(!r){this.logger?.warn(`deliverHeadlessPrompt: ${e} vanished before its prompt could be sent`);return}let s=this.sessions.get(e)??await this.resurrect(r),o=gB(),i={clientId:`fork-prompt-${Ma().slice(0,8)}`,connection:new pn(o),clientInfo:{name:"hydra-acp-fork",version:Fe}};await s.attach(i,"none");try{await s.prompt(i.clientId,{sessionId:e,prompt:[{type:"text",text:t}]})}finally{s.detach(i.clientId),o.close()}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await aC(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Oa.utimes(D.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Ta(D.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let r=new Date().toISOString(),s=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...s?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,...e.side!==void 0?{side:e.side}:{}}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,workspace:e.workspace,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??r,updatedAt:e.bundle.session.updatedAt})})}async agentStoreKey(e,t){let r=t.get(e);if(r!==void 0)return r;let s=e;try{let o=await this.registry.getAgent(e);o&&(s=Hw(o))}catch{}return t.set(e,s),s}async tombstoneAllGenerations(e,t,r){let s=await this.store.read(e).catch(()=>{}),o=new Map;for(let d of s?.upstreamGenerations??[])d.upstreamSessionId&&o.set(`${d.agentId}::${d.upstreamSessionId}`,{agentId:d.agentId,upstreamSessionId:d.upstreamSessionId});o.set(`${t.agentId}::${t.upstreamSessionId}`,{agentId:t.agentId,upstreamSessionId:t.upstreamSessionId});let i=new Date().toISOString(),a=new Map;for(let d of o.values())await this.tombstones.add({agentId:await this.agentStoreKey(d.agentId,a),upstreamSessionId:d.upstreamSessionId,sessionId:e,deletedAt:i,upstreamUpdatedAt:t.upstreamUpdatedAt,cwd:t.cwd,...t.title!==void 0?{title:t.title}:{},reason:r,...t.interactive!==void 0?{interactive:t.interactive}:{}}).catch(()=>{})}async deleteRecord(e,t="user"){let r=await this.store.read(e);if(!r)return!1;if(r.upstreamSessionId){let s=await Lu(e),o=Nc(r,s.hasContent);await this.tombstoneAllGenerations(e,{agentId:r.agentId,upstreamSessionId:r.upstreamSessionId,upstreamUpdatedAt:r.updatedAt,cwd:r.cwd,...r.title!==void 0?{title:r.title}:{},...o!==void 0?{interactive:o}:{}},t)}return r.workspace!==void 0&&await this.releaseWorkspace(r.workspace,e).catch(()=>{}),await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let t=this.pendingDeletions.get(e);t&&await t}async isTombstoned(e,t){let r=await this.agentStoreKey(e,new Map);return(await this.tombstones.read(r,t).catch(()=>{})??(r!==e?await this.tombstones.read(e,t).catch(()=>{}):void 0))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async isRetiredGeneration(e,t){let r=await this.store.read(e).catch(()=>{});return!r||r.upstreamSessionId===t?!1:(r.upstreamGenerations??[]).some(s=>s.upstreamSessionId===t)}async clearWorkspaceBinding(e){if(this.get(e)!==void 0)return"live";let t=await this.store.read(e).catch(()=>{});if(!t)return"missing";let r=t.workspace?.sourceCwd;return await this.mutateRecord(e,r!==void 0?{cwd:r}:{},["workspace"]),"cleared"}async setCwd(e,t){if(this.get(e)!==void 0)return"live";let r=await this.store.read(e).catch(()=>{});return r?r.workspace!==void 0?"bound":await this.dirExists(t)?(await this.mutateRecord(e,{cwd:t}),this.invalidateListCache(),"set"):"not-a-directory":"missing"}async setPriority(e,t){let r=this.get(e);if(r)return r.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let s=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,s),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let r=this.get(e);return r?(await r.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,r){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:r})}async persistAgentChange(e,t,r,s={}){await this.mutateRecord(e,{agentId:t,upstreamSessionId:r},void 0,o=>({upstreamGenerations:XA(o,t,r,void 0,s)}))}async persistSnapshot(e,t){let r={};t.currentModel!==void 0&&(r.currentModel=t.currentModel),t.currentMode!==void 0&&(r.currentMode=t.currentMode),t.currentUsage!==void 0&&(r.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(r.agentCommands=t.agentCommands),t.agentModes!==void 0&&(r.agentModes=t.agentModes),t.agentModels!==void 0&&(r.agentModels=t.agentModels),t.configOptionValues!==void 0&&(r.configOptionValues=t.configOptionValues),t.interactive!==void 0&&(r.interactive=t.interactive),t.cwd!==void 0&&(r.cwd=t.cwd),await this.mutateRecord(e,r)}async mutateRecord(e,t,r=[],s){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o,...t,...s?s(o):{},updatedAt:new Date().toISOString()};for(let a of r)delete i[a];await this.store.write(i)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,t){return(await this.store.read(e))?.extensionState?.[t]??{}}async getExtensionStateKey(e,t,r){return(await this.getExtensionState(e,t))[r]}async setExtensionStateKey(e,t,r,s){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o.extensionState??{}},a={...i[t]??{},[r]:s},d=Buffer.byteLength(JSON.stringify(a),"utf8");if(d>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${d} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);i[t]=a;let c={...o,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(c)})}async deleteExtensionStateKey(e,t,r){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);if(!s?.extensionState?.[t])return;let o={...s.extensionState},i={...o[t]};if(!(r in i))return;delete i[r],Object.keys(i).length===0?delete o[t]:o[t]=i;let a={...s,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){return this.enqueueKeyed(this.metaWriteQueues,e,t)}enqueueKeyed(e,t,r){let o=(e.get(t)??Promise.resolve()).catch(()=>{}).then(r),i=o.catch(()=>{});return e.set(t,i),i.finally(()=>{e.get(t)===i&&e.delete(t)}),o}liveSessionsIn(e,t){let r=[];for(let s of this.sessions.values())s.sessionId!==t&&s.workspace?.path===e&&r.push(s);return r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1,by:"daemon-shutdown"}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e,t){if(t?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:t.targetAgentId}).catch(s=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${s instanceof Error?s.message:String(s)}`)});let r=t.targetAgentId;(async()=>{try{let s=await this.store.read(e),o=await this.histories.load(e,{maxEntries:1/0});if(Ih(o)===0){this.logger?.info(`compaction: zero-turn fast-path swap sessionId=${e} target=${r}`),await this.dispatchSynthesisSwap(e,void 0,o.length,r);return}if(!s?.synopsis||s.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,t);return}if(o.length!==s.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,t);return}this.logger?.info(`compaction: fast-path swap sessionId=${e} target=${r} (reusing artifact @${s.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,s.synopsis,s.summarizedThroughEntry,r)}catch(s){this.logger?.warn(`scheduleCompaction: fast-path check failed for ${e}: ${s instanceof Error?s.message:String(s)} \u2014 falling back to synthesis`),this.synopsisCoordinator.scheduleCompaction(e,t)}})();return}this.synopsisCoordinator.scheduleCompaction(e,t)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getPendingAgentSwap(e){return(await this.store.read(e).catch(()=>{}))?.pendingAgentSwap}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async persistRollbackBreadcrumb(e,t){await this.mutateRecord(e,{},void 0,r=>{let s=r.rollbackBreadcrumb;return s!==void 0&&t.runId!==void 0&&s.runId===t.runId?(this.logger?.info(`compaction: keeping rollback breadcrumb pinned at ${s.previousUpstreamSessionId} for runId=${t.runId} sessionId=${e} (later swap of the same run)`),{}):{rollbackBreadcrumb:t}})}async getUpstreamGenerations(e){return(await this.store.read(e).catch(()=>{}))?.upstreamGenerations??[]}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,t,r){let s=this.get(e);if(s){if(t){let o=r.phase==="failed";s.broadcastPendingAgentSwap(o?null:t);return}s.broadcastCompactionPhase(r)}}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),t=0;for(let r of e){let s=r.attentionFlags??[],o=s.filter(i=>!(i.source==="daemon"&&i.reason.startsWith("permission:")));if(o.length!==s.length){let i=s.length-o.length;t+=i,await this.mutateRecord(r.sessionId,{attentionFlags:o}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let r of t){let s=r.compactionState;if(s!=null){if(!e.has(s.status)){this.logger?.info(`compaction: not resuming sessionId=${r.sessionId} status=${s.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${r.sessionId} status=${s.status} from prior daemon`);try{this.scheduleCompaction(r.sessionId)}catch(o){this.logger?.warn(`compaction: resume failed for sessionId=${r.sessionId}: ${o instanceof Error?o.message:String(o)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let t of e){let r=t.pendingAgentSwap;if(r)try{let s=await this.histories.load(t.sessionId).catch(()=>[]);t.synopsis!==void 0&&t.summarizedThroughEntry!==void 0&&t.summarizedThroughEntry>=s.length&&t.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${r} with persisted synopsis (history=${s.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??s.length,r)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${r} via fresh synthesis (history=${s.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:r}))}catch(s){this.logger?.warn(`agent-swap: resume failed for sessionId=${t.sessionId}: ${s instanceof Error?s.message:String(s)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let r=await zR(t.sessionId).catch(()=>[]);if(r.length===0)continue;let s=Date.now(),o=r.filter(d=>s-d.enqueuedAt<zA),i=r.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${zA/1e3}s)`),await wu(t.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await wu(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${o.length} prompt(s)`),d.replayPersistedQueue(o)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function yB(n,e){if(typeof n!="string"||n.length===0)return!1;let t=Nu.resolve(n),r=Nu.resolve(e);return t===r||t.startsWith(r+Nu.sep)}function wB(n){return n!==void 0&&/^\{\s*"session_id"\s*:\s*"[^"]*"\s*,\s*"(?:transcript_path|cwd|permission_mode|hook_event_name)"\s*:/.test(n)}function KA(n,e){if(n===void 0||n.length===0)return!0;let t=Yb(n);if(Yb(e.cwd)===t)return!0;let r=e.workspace?.sourceCwd;return r!==void 0&&Yb(r)===t}function Yb(n){return n.length>1&&n.endsWith("/")?n.replace(/\/+$/,""):n}function bB(n,e){let r=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(f=>f.description!==void 0?{name:f.name,description:f.description}:{name:f.name}):void 0)??e?.agentCommands,s=n.availableModes(),i=(s.length>0?s.map(f=>{let p={id:f.id};return f.name!==void 0&&(p.name=f.name),f.description!==void 0&&(p.description=f.description),p}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(f=>{let p={modelId:f.modelId};return f.name!==void 0&&(p.name=f.name),f.description!==void 0&&(p.description=f.description),p}):void 0)??e?.agentModels,l=n.extraConfigOptionValues(),u=Object.keys(l).length>0?l:e?.configOptionValues;return _b({sessionId:n.sessionId,lineageId:e?.lineageId??xu(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:QA(n.persistableUsage)??e?.currentUsage,agentCommands:r,agentModes:i,agentModels:c,configOptionValues:u,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,side:n.side??e?.side,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,workspace:n.workspace,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,upstreamGenerations:e?XA(e,n.agentId,n.upstreamSessionId):void 0,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function QA(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function kB(n){return n?{...n}:void 0}function vB(n){return(n.extendsChain??[n.id]).some(t=>t==="claude-acp"||t.startsWith("claude-acp-"))}var SB=[{type:"system",subtype:"background_tasks_changed"}];function Qb(n,e={}){if(!vB(n))return;let t={extraArgs:{"thinking-display":"summarized"}};return e.model&&(t.model=e.model),{claudeCode:{options:t,emitRawSDKMessages:SB}}}function _h(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let r=n[e.nestedKey];if(r&&typeof r=="object"&&!Array.isArray(r)){let i=e.fromObject(r);if(i!==void 0)return i}let s=n._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[i,a]of Object.entries(s))if(i!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let o=xB(n,e.configId);if(o){let i=e.fromConfig(o);if(i!==void 0)return i}}function Xb(n){return _h(n,{nestedKey:"models",configId:"model",fromObject:e=>qn(e.currentModelId)??qn(e.currentModel)??qn(e.modelId)??qn(e.model),fromConfig:e=>qn(e.currentValue)})}function Ci(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==G.AuthRequired)return n;let r=c=>!!c&&typeof c=="object"&&!Array.isArray(c),s=r(t.data)?t.data:{},o=r(s._meta)?s._meta:{},i=r(o["hydra-acp"])?o["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=G.AuthRequired,d.data={...s,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function GA(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function JA(n,e,t,r){if(n&&typeof n=="object"&&n.code===G.AuthRequired)return n;let s=n instanceof Error?n.message:String(n),o=s.includes("stderr:"),i=o?"":e.stderrTailText(),a=r?`to reproduce: (cd ${GA(r.cwd)} && ${[r.command,...r.args].map(GA).join(" ")})`:"";if(!i&&!a)return n;let d=[o?s:`agent ${t} failed to start: ${s}`];i&&d.push(`stderr: ${i}`),a&&d.push(a);let c=new Error(d.join(`
393
+ `)}async copyCarriedWork(e,t,r){let s=await this.patchFromSnapshot(r,t,e.provider);if(s===void 0)return!1;if(s.length===0)return!0;let o=We(e.provider);return o===void 0?!1:(await o.applyDelta(e.path,s)).ok}async patchFromSnapshot(e,t,r){let s=We(r);if(s===void 0)return;let o=await s.currentState(e);if(o!==void 0)return await s.captureDelta(e,o,t).catch(()=>{})}async unwindStartWorkspace(e){let{provider:t,ws:r,startRef:s,carried:o}=e;await t.unlock(r).catch(()=>{}),o!==void 0&&await t.dropSnapshotRef(r,s).catch(()=>{}),await t.removeWorkspace(r,{force:!0}).catch(()=>{})}async materializeNestedTrees(e,t){let r=We(e.provider);if(r?.capabilities().supports.nestedTrees!==!0)return;let s=await r.materializeNested({path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:r.kind},t).catch(o=>({ok:!1,count:0,reason:o instanceof Error?o.message:String(o)}));return s.ok?s.count>0?`populated ${s.count} nested tree(s)`:void 0:`nested trees FAILED: ${s.reason??"unknown"}`}async applyWorkspaceSetup(e,t){let r=await wh(e.sourceCwd).catch(()=>({})),s=[];if(r.carry!==void 0&&r.carry.length>0){let o=await Bb(e.sourceCwd,e.path,r.carry).catch(()=>{});o!==void 0&&o.copied.length>0&&s.push(`carried ${o.copied.length} config file(s)`)}if(r.postCreate!==void 0){let o=await bh(r.postCreate,{workspacePath:e.path,sourceCwd:e.sourceCwd,label:e.label,sessionId:t,...r.hookTimeoutSeconds!==void 0?{timeoutSeconds:r.hookTimeoutSeconds}:{}});s.push(o.ok?"ran postCreate":`postCreate FAILED: ${o.reason??"unknown"}`)}return s.length>0?s.join("; "):void 0}async deriveForkWorkspace(e,t){let r=We(e.provider);if(r===void 0)return;let s=r.capabilities(),o=s.sharedHistory?await r.currentState(e.path)??"":"",i=await r.createWorkspace({sourceCwd:e.sourceCwd,label:t,...o.length>0?{from:o}:{contentFrom:e.path}}).catch(d=>({ok:!1,reason:String(d)}));if(!i.ok){this.logger?.warn?.(`fork workspace: could not derive from ${e.path}: ${i.reason}`);return}let a=i.workspace;if(o.length>0&&s.supports.captureWorkingState){let d=await r.captureWorkingState(e.path,`hydra: fork carry from ${e.label}`).catch(()=>{});d!==void 0&&d!==o&&await this.copyUncommittedInto(e.path,a.path,o,d,a.provider).catch(()=>{})}return{path:a.path,sourceCwd:a.sourceCwd,label:a.label,provider:a.provider,...a.snapshot!==void 0?{snapshot:a.snapshot}:{},...a.line!==void 0?{line:a.line}:{},...a.vcs!==void 0?{vcs:{...a.vcs}}:{}}}async copyUncommittedInto(e,t,r,s,o){let i=We(o);if(i===void 0)return!1;let a=await i.captureDelta(e,r,s).catch(()=>{});return a===void 0||a.trim().length===0?!1:(await i.applyDelta(t,a,{stage:!0})).ok}async recoverWorkspace(e){let t=We(e.provider);if(t===void 0)return;let r={path:e.path,sourceCwd:e.sourceCwd,label:e.label,provider:e.provider,...e.snapshot!==void 0?{snapshot:e.snapshot}:{},...e.vcs!==void 0?{vcs:e.vcs}:{}};if(t.capabilities().supports.rematerialize){let o=await t.rematerialize(r).catch(i=>({ok:!1,reason:String(i)}));if(o.ok)return this.logger?.info?.(`session workspace: restored ${o.workspace.path} from retained state`),{...e,path:o.workspace.path};this.logger?.warn?.(`session workspace: could not restore: ${o.reason}`)}if(!await this.dirExists(e.sourceCwd))return;let s=await t.createWorkspace({sourceCwd:e.sourceCwd,label:`${e.label}-r`}).catch(o=>({ok:!1,reason:String(o)}));if(s.ok)return this.logger?.warn?.(`session workspace: ${e.path} is gone and could not be restored; resurrecting in a fresh workspace ${s.workspace.path} from ${e.sourceCwd}. Uncommitted work from the old workspace is not recoverable.`),{path:s.workspace.path,sourceCwd:s.workspace.sourceCwd,label:s.workspace.label,provider:s.workspace.provider,...s.workspace.snapshot!==void 0?{snapshot:s.workspace.snapshot}:{},...s.workspace.vcs!==void 0?{vcs:{...s.workspace.vcs}}:{}}}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let b=new Error(`agent ${e} not found in registry`);throw b.code=G.AgentNotInstalled,b}let r=await Fr(t,[],{npmRegistry:this.npmRegistry}),s=this.spawner({agentId:e,cwd:YA.homedir(),plan:r}),o;try{o=await s.connection.request("initialize",{protocolVersion:1,clientCapabilities:vc,clientInfo:{name:"hydra",version:Fe}})}catch(b){throw await s.kill().catch(()=>{}),Ci(b,s)}if(s.authMethods=Fu(o.authMethods),s.steeringSupported=Ou(o),(o.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await s.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(s)}catch(b){throw await s.kill().catch(()=>{}),b}await s.kill().catch(()=>{});let d=new Map,c=Hw(t);d.set(e,c);let l=new Set;for(let b of this.sessions.values()){let g=await this.agentStoreKey(b.agentId,d);l.add(`${g}::${b.upstreamSessionId}`)}let u=await this.store.list().catch(()=>[]);for(let b of u){l.add(`${await this.agentStoreKey(b.agentId,d)}::${b.upstreamSessionId}`);for(let g of b.upstreamGenerations??[])l.add(`${await this.agentStoreKey(g.agentId,d)}::${g.upstreamSessionId}`)}let f=D.sessionsDir(),p=[],m=0;for(let b of a){let g=`${c}::${b.sessionId}`;if(l.has(g)){m+=1;continue}if(yB(b.cwd,f)){m+=1;continue}let h=c,y=await this.tombstones.read(h,b.sessionId).catch(()=>{});if(!y&&c!==e&&(h=e,y=await this.tombstones.read(h,b.sessionId).catch(()=>{})),y){if(!xA(y,b.updatedAt)){m+=1;continue}await this.tombstones.remove(h,b.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${b.sessionId} (upstream updatedAt advanced past ${y.upstreamUpdatedAt??"<unset>"})`)}l.add(g);let k=`${Yt}${Ma()}`,S=new Date().toISOString(),I=b.updatedAt??S,x={sessionId:k,lineageId:xu(),upstreamSessionId:b.sessionId,agentId:e,cwd:b.cwd,pendingHistorySync:!0,interactive:!wB(b.title),createdAt:I,updatedAt:I};b.title!==void 0&&(x.title=b.title);let C=_b(x);await this.store.write(C),p.push({version:1,...C})}return{synced:p,skipped:m}}async listTombstones(e={}){let t=e.grep?.toLowerCase();return(await this.tombstones.list(e.agentId)).filter(s=>e.since===void 0||s.deletedAt>=e.since).filter(s=>t===void 0||[s.title,s.cwd,s.sessionId,s.upstreamSessionId].some(o=>o?.toLowerCase().includes(t))).sort((s,o)=>s.deletedAt<o.deletedAt?1:-1)}async undeleteSessions(e){let t=await this.tombstones.list(),r=[],s=[],o=[];for(let a of e){let d=t.filter(l=>l.upstreamSessionId===a),c=d.length>0?d:t.filter(l=>l.sessionId===a||l.sessionId===`${Yt}${a}`);if(c.length===0){s.push({id:a,reason:"no tombstone found"});continue}if(c.length>1){s.push({id:a,reason:"ambiguous: several tombstones match; pass an upstream id",candidates:c.map(l=>l.upstreamSessionId)});continue}o.push({id:a,tombstone:c[0]})}let i=new Map;for(let a of o){let d=i.get(a.tombstone.agentId)??[];d.push(a),i.set(a.tombstone.agentId,d)}for(let[a,d]of i){let c=u=>{let{version:f,...p}=u;return this.tombstones.add(p).catch(()=>{})};for(let u of d)await this.tombstones.remove(a,u.tombstone.upstreamSessionId);let l;try{l=(await this.syncFromAgent(a)).synced}catch(u){for(let f of d)await c(f.tombstone),s.push({id:f.id,reason:`agent sync failed: ${u.message}`});continue}for(let u of d){let f=l.find(p=>p.upstreamSessionId===u.tombstone.upstreamSessionId);if(!f){await c(u.tombstone),s.push({id:u.id,reason:`agent ${a} no longer lists this session`});continue}r.push({id:u.id,sessionId:f.sessionId,upstreamSessionId:u.tombstone.upstreamSessionId})}}return{restored:r,failed:s}}async collectAgentSessions(e){let t=[],r,s=new Set;for(let o=0;o<100;o+=1){let i={};r!==void 0&&(i.cursor=r);let a=await e.connection.request("session/list",i),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let l={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(l.title=c.title),typeof c.updatedAt=="string"&&(l.updatedAt=c.updatedAt),t.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||s.has(a.nextCursor))break;s.add(a.nextCursor),r=a.nextCursor}return t}async applySeedModel(e,t,r,s,o){try{let{verb:i,result:a}=await ki({request:(d,c)=>e.connection.request(d,c),sessionId:t,modelId:r,...o?{verb:o}:{},logger:this.logger});return this.logger?.info(`${s}: ${i} accepted`),{accepted:!0,result:a}}catch(i){return this.logger?.warn(`${s} rejected by agent (${i.message}); session will use the agent's own default`),{accepted:!1}}}async applySeedMode(e,t,r,s){try{let o=await e.connection.request("session/set_mode",{sessionId:t,modeId:r});return this.logger?.info(`${s}: session/set_mode accepted`),{accepted:!0,result:o}}catch(o){return this.logger?.warn(`${s} rejected by agent (${o.message}); session will use the agent's own default mode`),{accepted:!1}}}async restoreConfigOptionValues(e,t,r,s){if(!r||Object.keys(r).length===0)return s;let o=s;for(let[i,a]of Object.entries(r)){let d=`resurrect: persisted configOptionValues.${i}=${JSON.stringify(a)}`,c=o.find(f=>f.id===i);if(!c){this.logger?.warn(`${d}: agent does not currently advertise configId=${i}; skipping session/set_config_option`);continue}if(a===c.currentValue)continue;let l=Ec(a,c.options.map(f=>f.value));if(l.kind!=="exact"&&l.kind!=="resolved"){this.logger?.warn(`${d} ${l.kind}; skipping session/set_config_option`);continue}let u=l.kind==="resolved"?l.modelId:a;try{let f=await e.connection.request("session/set_config_option",{sessionId:t,configId:i,value:u});this.logger?.info(`${d}: session/set_config_option accepted`),o=_a(f)?$a(f):o.map(p=>p.id===i?{...p,currentValue:u}:p)}catch(f){this.logger?.warn(`${d}: session/set_config_option rejected by agent (${f.message})`)}}return o}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=G.AgentNotInstalled,i}let r=await Fr(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),s=Ap(e.selfSessionId,e.forwardedEnv),o=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...s?{extraEnv:s}:{}});try{let i=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:vc,clientInfo:{name:"hydra",version:Fe}}),a=i.agentCapabilities;o.authMethods=Fu(i.authMethods),o.steeringSupported=Ou(i);let d=Qb(t),c=await o.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[],...d&&{_meta:d}}),l=c.sessionId;if(typeof l!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let u=Xb(c),f=Zb(c),p=Ic(c),m=Or(this.sessionDefaults,t),b=m?.value,g=e.configDefaults,h=m?.from??e.agentId,y=e.model??g?.model??b?.model,k;if(y&&y!==u){let P=Tc(y,f),M=e.model!==void 0?`model=${JSON.stringify(y)}`:g?.model!==void 0?`configDefaults.model=${JSON.stringify(y)}`:`sessionDefaults[${h}].model=${JSON.stringify(y)}`;if(P.kind==="exact"||P.kind==="none"){let F=await this.applySeedModel(o,l,y,M,p);F.accepted&&(u=y,k=F.result)}else if(P.kind==="resolved")if(P.modelId===u)u=P.modelId;else{let F=await this.applySeedModel(o,l,P.modelId,`${M} resolved to ${JSON.stringify(P.modelId)}`,p);F.accepted&&(u=P.modelId,k=F.result)}else if(P.kind==="ambiguous")this.logger?.warn(`${M} is ambiguous (trailing-segment matches [${P.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(u)}`);else{let F=f.map(K=>K.modelId).join(", ");this.logger?.warn(`${M} not in agent's availableModels ([${F}]); skipping session/set_model, session will use ${JSON.stringify(u)}`)}}let S=ek(c),I=tk(c),x=g?.mode??b?.mode;if(x&&x!==I){let P=g?.mode!==void 0?`configDefaults.mode=${JSON.stringify(x)}`:`sessionDefaults[${h}].mode=${JSON.stringify(x)}`;if(S.length>0&&!S.some(M=>M.id===x)){let M=S.map(F=>F.id).join(", ");this.logger?.warn(`${P} not in agent's availableModes ([${M}]); skipping session/set_mode, session will use ${JSON.stringify(I)}`)}else{let M=await this.applySeedMode(o,l,x,P);M.accepted&&(I=x,_a(M.result)&&(k=M.result))}}let C={...b??{},...g??{}};if(delete C.model,delete C.mode,Object.keys(C).length>0){let P=$a(_a(k)?k:c);for(let[M,F]of Object.entries(C)){let K=`sessionDefaults[${h}].${M}=${JSON.stringify(F)}`,Y=P.find(Q=>Q.id===M);if(!Y){this.logger?.warn(`${K}: agent does not currently advertise configId=${M}; skipping session/set_config_option`);continue}let z=Ec(F,Y.options.map(Q=>Q.value));if(z.kind!=="exact"&&z.kind!=="resolved"){this.logger?.warn(`${K} ${z.kind}; skipping session/set_config_option`);continue}let re=z.kind==="resolved"?z.modelId:F;if(re!==Y.currentValue)try{let Q=await o.connection.request("session/set_config_option",{sessionId:l,configId:M,value:re});this.logger?.info(`${K}: session/set_config_option accepted`),_a(Q)&&(P=$a(Q),k=Q)}catch(Q){this.logger?.warn(`${K}: session/set_config_option rejected by agent (${Q.message})`)}}}let $=$a(_a(k)?k:c);return{agent:o,upstreamSessionId:l,agentMeta:c._meta,agentCapabilities:a,initialModel:u,initialModels:f.length>0?f:void 0,initialModes:S.length>0?S:void 0,initialMode:I,initialConfigOptions:$.length>0?$:void 0,modelVerb:p}}catch(i){throw await o.kill().catch(()=>{}),Ci(JA(i,o,e.agentId,{command:r.command,args:r.args,cwd:e.cwd}),o)}}async bootstrapAgentLoad(e,t){let r=await this.registry.getAgent(t.agentId);if(!r){let a=new Error(`agent ${t.agentId} not found in registry`);throw a.code=G.AgentNotInstalled,a}let s=await Fr(r,t.agentArgs??[],{npmRegistry:this.npmRegistry}),o=Ap(t.selfSessionId,t.forwardedEnv),i=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:s,...o?{extraEnv:o}:{}});try{let a=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:vc,clientInfo:{name:"hydra",version:Fe}}),d=a.agentCapabilities;i.authMethods=Fu(a.authMethods),i.steeringSupported=Ou(a);let c=Qb(r),l=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...c&&{_meta:c}}),u=Xb(l),f=Ii(Zb(l)),p=ek(l),m=tk(l),b=Ii($a(l));return{agent:i,upstreamSessionId:e,agentMeta:l._meta,agentCapabilities:d,initialModel:u,initialModels:f,initialModes:p.length>0?p:void 0,initialMode:m,initialConfigOptions:b,modelVerb:Ic(l)}}catch(a){throw await i.kill().catch(()=>{}),Ci(JA(a,i,t.agentId,{command:s.command,args:s.args,cwd:t.cwd}),i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)throw new Error("session is not live \u2014 cannot roll back a cold session");let r=await this.store.read(e);if(!r)throw new Error("session record not found");let s=r.rollbackBreadcrumb;if(!s)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let o=r.compactionState;if(o!=null)throw new Error(`compaction is in progress (status: ${o.status}) \u2014 wait for it to complete before rolling back`);if(!await t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:s.previousUpstreamSessionId,previousSummarizedThroughEntry:s.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:s.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let r=this.pendingAuthAgents.get(e);if(r&&r.isAlive())return r;let s=await this.registry.getAgent(e);if(!s){let d=new Error(`agent ${e} not found in registry`);throw d.code=G.AgentNotInstalled,d}let o=await Fr(s,[],{npmRegistry:this.npmRegistry}),i=t??Ze(this.defaultCwd),a=this.spawner({agentId:e,cwd:i,plan:o});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:vc,clientInfo:{name:"hydra",version:Fe}});a.authMethods=Fu(d.authMethods),a.steeringSupported=Ou(d)}catch(d){throw await a.kill().catch(()=>{}),Ci(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let r=new Error(`agent ${e} not found in registry`);throw r.code=G.AgentNotInstalled,r}return Fr(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.driftNoticed.delete(e.sessionId),this.invalidateListCache(),t||this.store.touch(e.sessionId).catch(()=>{}),t&&e.workspace!==void 0&&this.releaseWorkspace(e.workspace,e.sessionId).catch(()=>{}),t){if(e.upstreamSessionId){let s=Nc({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),o=this.tombstoneAllGenerations(e.sessionId,{agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,...e.title!==void 0?{title:e.title}:{},...s!==void 0?{interactive:s}:{}},"user").catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===o&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,o);return}let r=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===r&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,r);return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:r,...s})=>{this.persistAgentChange(e.sessionId,t,r,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:QA(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(r=>({name:r.name,...r.description!==void 0?{description:r.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(r=>({id:r.id,...r.name!==void 0?{name:r.name}:{},...r.description!==void 0?{description:r.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(r=>({modelId:r.modelId,...r.name!==void 0?{name:r.name}:{},...r.description!==void 0?{description:r.description}:{}}))}).catch(()=>{})}),e.onConfigOptionsChange(t=>{this.persistSnapshot(e.sessionId,{configOptionValues:Object.fromEntries(t.map(r=>[r.id,r.currentValue]))}).catch(()=>{})}),e.onAttentionFlagsChange(t=>{this.mutateRecord(e.sessionId,{attentionFlags:t}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),r=bB(e,t);await this.store.write(r)}).catch(t=>{this.logger?.warn(`failed to persist session record for ${e.sessionId}: ${t instanceof Error?t.message:String(t)}`)})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async pageHistory(e,t){let r=await this.store.read(e);if(!this.sessions.has(e)&&!r)return;let s=this.sessions.get(e)?.side??r?.side,o=await this.histories.pageBefore(e,{...t,skip:a=>bu(a.method,a.params)}),i=Sc(o.entries,s);return{entries:i,hasMore:o.hasMore&&i.length===o.entries.length}}async loadHistory(e,t={}){return this.histories.load(e,t)}async loadToolBlob(e,t){return au(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let r=t.title;return r||(r=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:r,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:kB(t.currentUsage),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,configOptionValues:t.configOptionValues,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,side:t.side,forkSynthesisState:t.forkSynthesisState,forwardedEnv:t.forwardedEnv,workspace:t.workspace,compactionState:t.compactionState,attentionFlags:t.attentionFlags?.filter(s=>!(s.source==="daemon"&&s.reason.startsWith("permission:")))}}async setForwardedEnv(e,t){if(t===void 0)return;let r=this.sessions.get(e);r&&(r.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);if(!s)return;let o={...s,forwardedEnv:t};await this.store.write(o)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let r={...t};delete r.pendingHistorySync,await this.store.write(r)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let r of t){let s=r.params;if(s?.update?.sessionUpdate!=="prompt_received")continue;let o=s.update.sentBy;if(typeof o?.fromSession=="string"||typeof o?.clientId=="string"&&o.clientId.startsWith("transformer:"))continue;let i=Ca(s.update.prompt),a=Cb(i,200);if(a&&!a.startsWith("/"))return a}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}setLiveConfig(e){e.sessionDefaults&&(this.sessionDefaults=e.sessionDefaults)}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let r=t.agent.installId,s=t.agent.version,o=e.get(r);o||(o=new Set,e.set(r,o)),o.add(s)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(Yt))return;let t=Yt+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let r=new Error(`session ${e} not found`);throw r.code=G.SessionNotFound,r}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,workspace:e.workspace,workspaceError:e.workspaceError,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,side:e.side,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,turnStartedAt:e.turnStartedAt,armedTasks:e.armedBackgroundTasks.length,...e.armedSince!==void 0?{armedSince:e.armedSince}:{},awaitingInput:e.awaitingInput,agentPid:e.agentPid}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await Lu(t.sessionId),d=Nc({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),c=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,side:t.side,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:d,priority:t.priority,createdAt:new Date(t.createdAt).toISOString(),updatedAt:c,attachedClients:t.attachedCount,status:"warm",agentPid:t.agentPid,busy:t.turnStartedAt!==void 0,turnStartedAt:t.turnStartedAt,armedTasks:t.armedBackgroundTasks.length,...t.armedSince!==void 0?{armedSince:t.armedSince}:{},awaitingInput:t.awaitingInput}}let r=await this.store.read(e).catch(()=>{});if(!r)return;let s=await Lu(r.sessionId),o=Nc(r,s.hasContent),i=s.mtime??r.updatedAt;return{sessionId:r.sessionId,upstreamSessionId:r.upstreamSessionId,cwd:r.cwd,title:r.title,agentId:r.agentId,currentModel:r.currentModel,currentUsage:Pa(r.currentUsage),importedFromMachine:r.importedFromMachine,importedFromUpstreamSessionId:r.importedFromUpstreamSessionId,parentSessionId:r.parentSessionId,forkedFromSessionId:r.forkedFromSessionId,forkedFromMessageId:r.forkedFromMessageId,side:r.side,forkSynthesisState:r.forkSynthesisState,originatingClient:r.originatingClient,interactive:o,priority:r.priority,createdAt:r.createdAt,updatedAt:i,attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1}}async list(e={}){return(await this.listing(e)).entries}async listing(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}|${e.status??""}`,r=Date.now(),s=this.listCache.get(t);if(s&&s.expiresAt>r)return s.promise;let o=this.listUncached(e);return this.listCache.set(t,{expiresAt:r+n.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(t);i&&i.promise===o&&this.listCache.delete(t)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=await this.store.cursor(),{entries:r,liveIds:s}=await this.warmRows(e);if(e.status==="warm")return{entries:r,cursor:t};let o=await this.store.list().catch(i=>{throw this.logger?.warn(`session list: store.list() failed: ${i?.message??String(i)}`),i});return r.push(...await this.coldRows(o,s,e)),r.sort((i,a)=>i.updatedAt<a.updatedAt?1:-1),{entries:r,cursor:t}}async listSince(e,t){let{entries:r,liveIds:s}=await this.warmRows(e);if(e.status==="warm")return{entries:r,removed:[],cursor:await this.store.cursor()};let o=await this.store.listChangedSince(t);return r.push(...await this.coldRows(o.records,s,e)),r.sort((i,a)=>i.updatedAt<a.updatedAt?1:-1),{entries:r,removed:o.removed,cursor:o.cursor}}async seedSessionIndex(){await this.store.ensureIndex();let e=await this.tombstones.list().catch(()=>[]);for(let t of e){if(t.sessionId===void 0)continue;let r=Date.parse(t.deletedAt);Number.isNaN(r)||await this.store.markDeleted(t.sessionId,r)}}static includeRow(e,t){return e.includeNonInteractive?!0:t===!0}async warmRows(e){let t=[],r=new Set,s=[...this.sessions.values()].filter(i=>KA(e.cwd,i));if(e.status==="cold"){for(let i of s)r.add(i.sessionId);return{entries:t,liveIds:r}}let o=await Promise.all(s.map(i=>Lu(i.sessionId)));for(let i=0;i<o.length;i+=1){let a=s[i],d=o[i];r.add(a.sessionId);let c=Nc({interactive:a.interactive,...a.originatingClient?{originatingClient:a.originatingClient}:{}},d.hasContent);if(!n.includeRow(e,c))continue;let l=d.mtime??new Date(a.updatedAt).toISOString();t.push({sessionId:a.sessionId,upstreamSessionId:a.upstreamSessionId,cwd:a.cwd,workspace:a.workspace,workspaceError:a.workspaceError,title:a.title,agentId:a.agentId,currentModel:a.currentModel,currentUsage:a.currentUsage,parentSessionId:a.parentSessionId,forkedFromSessionId:a.forkedFromSessionId,forkedFromMessageId:a.forkedFromMessageId,side:a.side,originatingClient:a.originatingClient,interactive:c,priority:a.priority,createdAt:new Date(a.createdAt).toISOString(),updatedAt:l,attachedClients:a.attachedCount,status:"warm",agentPid:a.agentPid,busy:a.turnStartedAt!==void 0,turnStartedAt:a.turnStartedAt,armedTasks:a.armedBackgroundTasks.length,...a.armedSince!==void 0?{armedSince:a.armedSince}:{},awaitingInput:a.awaitingInput,compactionState:a.compactionState,forkSynthesisState:a.forkSynthesisState})}return{entries:t,liveIds:r}}async coldRows(e,t,r){let s=[],o=e.filter(a=>!t.has(a.sessionId)&&KA(r.cwd,a)),i=await Promise.all(o.map(a=>Lu(a.sessionId)));for(let a=0;a<o.length;a+=1){let d=o[a],c=i[a],l=Nc(d,c.hasContent);if(!n.includeRow(r,l))continue;let u=c.mtime??d.updatedAt;s.push({sessionId:d.sessionId,upstreamSessionId:d.upstreamSessionId,cwd:d.cwd,workspace:d.workspace,title:d.title,agentId:d.agentId,currentModel:d.currentModel,currentUsage:Pa(d.currentUsage),importedFromMachine:d.importedFromMachine,importedFromUpstreamSessionId:d.importedFromUpstreamSessionId,parentSessionId:d.parentSessionId,forkedFromSessionId:d.forkedFromSessionId,forkedFromMessageId:d.forkedFromMessageId,side:d.side,originatingClient:d.originatingClient,interactive:l,priority:d.priority,createdAt:d.createdAt,updatedAt:u,attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1,compactionState:d.compactionState,forkSynthesisState:d.forkSynthesisState})}return s}async exportBundle(e,t={}){let r=await this.store.read(e);if(!r)return;let s;if(r.lineageId)s=r;else{let c=xu(),l={...r,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:c}))}).catch(()=>{}),s=l}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await VA(e);if(o!=="references")return{record:s,history:i,promptHistory:a};let d={};for(let c of HA(i)){let l=await iC(e,c);l&&(d[c]=l.toString("base64"))}return{record:s,history:i,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let r=await this.store.findByLineageId(e.session.lineageId);if(r){if(!t.replace){let i=new Error(`bundle already imported as ${r.sessionId}`);throw i.code=G.BundleAlreadyImported,i.existingSessionId=r.sessionId,i}let o=this.sessions.get(r.sessionId);return o&&await o.close({deleteRecord:!1,by:"bundle-import-overwrite"}).catch(()=>{}),await this.writeImportedRecord({sessionId:r.sessionId,bundle:e,preservedCreatedAt:r.createdAt,cwd:t.cwd}),{sessionId:r.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let s=`${Yt}${Ma()}`;return await this.writeImportedRecord({sessionId:s,bundle:e,cwd:t.cwd}),{sessionId:s,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let r=await this.store.read(e);if(!r){let x=new Error(`source session not found: ${e}`);throw x.code=G.SessionNotFound,x}let s=t.agentId??r.agentId,o=s!==r.agentId;if(o&&!await this.registry.getAgent(s)){let C=new Error(`agent ${s} not found in registry`);throw C.code=G.AgentNotInstalled,C}let i=await this.histories.load(e).catch(()=>[]),a=i,d,c=t.mode??(t.side?"verbatim":"synthesis"),l,u,f,p=12e4;if(c==="verbatim")if(t.forkAt!==void 0){let x=oh(i,t.forkAt);if(x<0){let C=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw C.code=G.InvalidParams,C}d=t.forkAt,a=i.slice(0,x+1)}else{let x=IB(i);x?(d=x.messageId,a=i.slice(0,x.index+1)):(d="",a=i.slice(0,0))}else{if(t.forkAt!==void 0&&t.forkAt!==""){let C=oh(i,t.forkAt);if(C<0){let $=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw $.code=G.InvalidParams,$}d=t.forkAt,a=i.slice(0,C+1)}else d="",a=i;let x=await this.registry.getAgent(s);if(!x){let C=new Error(`agent ${s} not found in registry`);throw C.code=G.AgentNotInstalled,C}f=x,u=r.currentModel,l="running"}let m=await VA(e),b=c==="synthesis",g={...r,lineageId:xu(),agentId:s,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...o?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},h=_u({record:g,history:a,promptHistory:m.length>0?m:void 0,hydraVersion:Fe,machine:Ys()}),y=`${Yt}${Ma()}`,k=t.cwd,S;if(t.cwd===void 0&&r.workspace!==void 0){let x=await this.deriveForkWorkspace(r.workspace,`${r.workspace.label}-fork-${y.slice(-6)}`);x!==void 0?(S=x,k=x.path):(k=r.workspace.sourceCwd,this.logger?.warn?.(`fork ${y}: could not derive an isolated workspace from ${r.workspace.path}; running unisolated in ${k}`))}await this.writeImportedRecord({sessionId:y,bundle:h,cwd:k,...S!==void 0?{workspace:S}:{},forkedFromSessionId:e,forkedFromMessageId:d,...t.side!==void 0?{side:{...t.side.selection!==void 0?{selection:t.side.selection}:{},...zC(a)}}:{},...l!==void 0?{forkSynthesisState:l}:{}});let I=b?(async()=>{try{let x=await Fr(f,[],{npmRegistry:this.npmRegistry}),C=await Sh({agentId:s,cwd:t.cwd??D.sessionDir(e),plan:x,history:a,modelId:u,sessionId:e,logger:this.logger,timeoutMs:p});C&&C.synopsis?await this.mutateRecord(y,{synopsis:C.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(y,{},["forkSynthesisState"]))}catch(x){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${x.message}`);try{await this.mutateRecord(y,{},["forkSynthesisState"])}catch(C){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${C.message}`)}}})():Promise.resolve();if(t.prompt!==void 0&&t.prompt.trim()!==""){let x=t.prompt;I.catch(()=>{}).then(()=>this.deliverHeadlessPrompt(y,x)).catch(C=>{this.logger?.warn(`forkSession(${e}): headless prompt delivery to ${y} failed: ${C.message}`)})}return{sessionId:y,forkedFromSessionId:e,forkedAt:d}}async deliverHeadlessPrompt(e,t){let r=await this.loadFromDisk(e);if(!r){this.logger?.warn(`deliverHeadlessPrompt: ${e} vanished before its prompt could be sent`);return}let s=this.sessions.get(e)??await this.resurrect(r),o=gB(),i={clientId:`fork-prompt-${Ma().slice(0,8)}`,connection:new pn(o),clientInfo:{name:"hydra-acp-fork",version:Fe}};await s.attach(i,"none");try{await s.prompt(i.clientId,{sessionId:e,prompt:[{type:"text",text:t}]})}finally{s.detach(i.clientId),o.close()}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await aC(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Oa.utimes(D.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Ta(D.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let r=new Date().toISOString(),s=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...s?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,...e.side!==void 0?{side:e.side}:{}}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,workspace:e.workspace,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??r,updatedAt:e.bundle.session.updatedAt})})}async agentStoreKey(e,t){let r=t.get(e);if(r!==void 0)return r;let s=e;try{let o=await this.registry.getAgent(e);o&&(s=Hw(o))}catch{}return t.set(e,s),s}async tombstoneAllGenerations(e,t,r){let s=await this.store.read(e).catch(()=>{}),o=new Map;for(let d of s?.upstreamGenerations??[])d.upstreamSessionId&&o.set(`${d.agentId}::${d.upstreamSessionId}`,{agentId:d.agentId,upstreamSessionId:d.upstreamSessionId});o.set(`${t.agentId}::${t.upstreamSessionId}`,{agentId:t.agentId,upstreamSessionId:t.upstreamSessionId});let i=new Date().toISOString(),a=new Map;for(let d of o.values())await this.tombstones.add({agentId:await this.agentStoreKey(d.agentId,a),upstreamSessionId:d.upstreamSessionId,sessionId:e,deletedAt:i,upstreamUpdatedAt:t.upstreamUpdatedAt,cwd:t.cwd,...t.title!==void 0?{title:t.title}:{},reason:r,...t.interactive!==void 0?{interactive:t.interactive}:{}}).catch(()=>{})}async deleteRecord(e,t="user"){let r=await this.store.read(e);if(!r)return!1;if(r.upstreamSessionId){let s=await Lu(e),o=Nc(r,s.hasContent);await this.tombstoneAllGenerations(e,{agentId:r.agentId,upstreamSessionId:r.upstreamSessionId,upstreamUpdatedAt:r.updatedAt,cwd:r.cwd,...r.title!==void 0?{title:r.title}:{},...o!==void 0?{interactive:o}:{}},t)}return r.workspace!==void 0&&await this.releaseWorkspace(r.workspace,e).catch(()=>{}),await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let t=this.pendingDeletions.get(e);t&&await t}async isTombstoned(e,t){let r=await this.agentStoreKey(e,new Map);return(await this.tombstones.read(r,t).catch(()=>{})??(r!==e?await this.tombstones.read(e,t).catch(()=>{}):void 0))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async isRetiredGeneration(e,t){let r=await this.store.read(e).catch(()=>{});return!r||r.upstreamSessionId===t?!1:(r.upstreamGenerations??[]).some(s=>s.upstreamSessionId===t)}async clearWorkspaceBinding(e){if(this.get(e)!==void 0)return"live";let t=await this.store.read(e).catch(()=>{});if(!t)return"missing";let r=t.workspace?.sourceCwd;return await this.mutateRecord(e,r!==void 0?{cwd:r}:{},["workspace"]),"cleared"}async setCwd(e,t){if(this.get(e)!==void 0)return"live";let r=await this.store.read(e).catch(()=>{});return r?r.workspace!==void 0?"bound":await this.dirExists(t)?(await this.mutateRecord(e,{cwd:t}),this.invalidateListCache(),"set"):"not-a-directory":"missing"}async setPriority(e,t){let r=this.get(e);if(r)return r.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let s=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,s),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let r=this.get(e);return r?(await r.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,r){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:r})}async persistAgentChange(e,t,r,s={}){await this.mutateRecord(e,{agentId:t,upstreamSessionId:r},void 0,o=>({upstreamGenerations:XA(o,t,r,void 0,s)}))}async persistSnapshot(e,t){let r={};t.currentModel!==void 0&&(r.currentModel=t.currentModel),t.currentMode!==void 0&&(r.currentMode=t.currentMode),t.currentUsage!==void 0&&(r.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(r.agentCommands=t.agentCommands),t.agentModes!==void 0&&(r.agentModes=t.agentModes),t.agentModels!==void 0&&(r.agentModels=t.agentModels),t.configOptionValues!==void 0&&(r.configOptionValues=t.configOptionValues),t.interactive!==void 0&&(r.interactive=t.interactive),t.cwd!==void 0&&(r.cwd=t.cwd),await this.mutateRecord(e,r)}async mutateRecord(e,t,r=[],s){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o,...t,...s?s(o):{},updatedAt:new Date().toISOString()};for(let a of r)delete i[a];await this.store.write(i)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,t){return(await this.store.read(e))?.extensionState?.[t]??{}}async getExtensionStateKey(e,t,r){return(await this.getExtensionState(e,t))[r]}async setExtensionStateKey(e,t,r,s){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o.extensionState??{}},a={...i[t]??{},[r]:s},d=Buffer.byteLength(JSON.stringify(a),"utf8");if(d>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${d} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);i[t]=a;let c={...o,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(c)})}async deleteExtensionStateKey(e,t,r){await this.enqueueMetaWrite(e,async()=>{let s=await this.store.read(e);if(!s?.extensionState?.[t])return;let o={...s.extensionState},i={...o[t]};if(!(r in i))return;delete i[r],Object.keys(i).length===0?delete o[t]:o[t]=i;let a={...s,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){return this.enqueueKeyed(this.metaWriteQueues,e,t)}enqueueKeyed(e,t,r){let o=(e.get(t)??Promise.resolve()).catch(()=>{}).then(r),i=o.catch(()=>{});return e.set(t,i),i.finally(()=>{e.get(t)===i&&e.delete(t)}),o}liveSessionsIn(e,t){let r=[];for(let s of this.sessions.values())s.sessionId!==t&&s.workspace?.path===e&&r.push(s);return r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1,by:"daemon-shutdown"}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e,t){if(t?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:t.targetAgentId}).catch(s=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${s instanceof Error?s.message:String(s)}`)});let r=t.targetAgentId;(async()=>{try{let s=await this.store.read(e),o=await this.histories.load(e,{maxEntries:1/0});if(Ih(o)===0){this.logger?.info(`compaction: zero-turn fast-path swap sessionId=${e} target=${r}`),await this.dispatchSynthesisSwap(e,void 0,o.length,r);return}if(!s?.synopsis||s.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,t);return}if(o.length!==s.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,t);return}this.logger?.info(`compaction: fast-path swap sessionId=${e} target=${r} (reusing artifact @${s.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,s.synopsis,s.summarizedThroughEntry,r)}catch(s){this.logger?.warn(`scheduleCompaction: fast-path check failed for ${e}: ${s instanceof Error?s.message:String(s)} \u2014 falling back to synthesis`),this.synopsisCoordinator.scheduleCompaction(e,t)}})();return}this.synopsisCoordinator.scheduleCompaction(e,t)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getPendingAgentSwap(e){return(await this.store.read(e).catch(()=>{}))?.pendingAgentSwap}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async persistRollbackBreadcrumb(e,t){await this.mutateRecord(e,{},void 0,r=>{let s=r.rollbackBreadcrumb;return s!==void 0&&t.runId!==void 0&&s.runId===t.runId?(this.logger?.info(`compaction: keeping rollback breadcrumb pinned at ${s.previousUpstreamSessionId} for runId=${t.runId} sessionId=${e} (later swap of the same run)`),{}):{rollbackBreadcrumb:t}})}async getUpstreamGenerations(e){return(await this.store.read(e).catch(()=>{}))?.upstreamGenerations??[]}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,t,r){let s=this.get(e);if(s){if(t){let o=r.phase==="failed";s.broadcastPendingAgentSwap(o?null:t);return}s.broadcastCompactionPhase(r)}}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),t=0;for(let r of e){let s=r.attentionFlags??[],o=s.filter(i=>!(i.source==="daemon"&&i.reason.startsWith("permission:")));if(o.length!==s.length){let i=s.length-o.length;t+=i,await this.mutateRecord(r.sessionId,{attentionFlags:o}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let r of t){let s=r.compactionState;if(s!=null){if(!e.has(s.status)){this.logger?.info(`compaction: not resuming sessionId=${r.sessionId} status=${s.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${r.sessionId} status=${s.status} from prior daemon`);try{this.scheduleCompaction(r.sessionId)}catch(o){this.logger?.warn(`compaction: resume failed for sessionId=${r.sessionId}: ${o instanceof Error?o.message:String(o)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let t of e){let r=t.pendingAgentSwap;if(r)try{let s=await this.histories.load(t.sessionId).catch(()=>[]);t.synopsis!==void 0&&t.summarizedThroughEntry!==void 0&&t.summarizedThroughEntry>=s.length&&t.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${r} with persisted synopsis (history=${s.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??s.length,r)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${r} via fresh synthesis (history=${s.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:r}))}catch(s){this.logger?.warn(`agent-swap: resume failed for sessionId=${t.sessionId}: ${s instanceof Error?s.message:String(s)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let r=await zR(t.sessionId).catch(()=>[]);if(r.length===0)continue;let s=Date.now(),o=r.filter(d=>s-d.enqueuedAt<zA),i=r.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${zA/1e3}s)`),await wu(t.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await wu(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${o.length} prompt(s)`),d.replayPersistedQueue(o)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function yB(n,e){if(typeof n!="string"||n.length===0)return!1;let t=Nu.resolve(n),r=Nu.resolve(e);return t===r||t.startsWith(r+Nu.sep)}function wB(n){return n!==void 0&&/^\{\s*"session_id"\s*:\s*"[^"]*"\s*,\s*"(?:transcript_path|cwd|permission_mode|hook_event_name)"\s*:/.test(n)}function KA(n,e){if(n===void 0||n.length===0)return!0;let t=Yb(n);if(Yb(e.cwd)===t)return!0;let r=e.workspace?.sourceCwd;return r!==void 0&&Yb(r)===t}function Yb(n){return n.length>1&&n.endsWith("/")?n.replace(/\/+$/,""):n}function bB(n,e){let r=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(f=>f.description!==void 0?{name:f.name,description:f.description}:{name:f.name}):void 0)??e?.agentCommands,s=n.availableModes(),i=(s.length>0?s.map(f=>{let p={id:f.id};return f.name!==void 0&&(p.name=f.name),f.description!==void 0&&(p.description=f.description),p}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(f=>{let p={modelId:f.modelId};return f.name!==void 0&&(p.name=f.name),f.description!==void 0&&(p.description=f.description),p}):void 0)??e?.agentModels,l=n.extraConfigOptionValues(),u=Object.keys(l).length>0?l:e?.configOptionValues;return _b({sessionId:n.sessionId,lineageId:e?.lineageId??xu(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:QA(n.persistableUsage)??e?.currentUsage,agentCommands:r,agentModes:i,agentModels:c,configOptionValues:u,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,side:n.side??e?.side,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,workspace:n.workspace,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,upstreamGenerations:e?XA(e,n.agentId,n.upstreamSessionId):void 0,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function QA(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function kB(n){return n?{...n}:void 0}function vB(n){return(n.extendsChain??[n.id]).some(t=>t==="claude-acp"||t.startsWith("claude-acp-"))}var SB=[{type:"system",subtype:"background_tasks_changed"}];function Qb(n,e={}){if(!vB(n))return;let t={extraArgs:{"thinking-display":"summarized"}};return e.model&&(t.model=e.model),{claudeCode:{options:t,emitRawSDKMessages:SB}}}function _h(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let r=n[e.nestedKey];if(r&&typeof r=="object"&&!Array.isArray(r)){let i=e.fromObject(r);if(i!==void 0)return i}let s=n._meta;if(s&&typeof s=="object"&&!Array.isArray(s)){for(let[i,a]of Object.entries(s))if(i!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let o=xB(n,e.configId);if(o){let i=e.fromConfig(o);if(i!==void 0)return i}}function Xb(n){return _h(n,{nestedKey:"models",configId:"model",fromObject:e=>qn(e.currentModelId)??qn(e.currentModel)??qn(e.modelId)??qn(e.model),fromConfig:e=>qn(e.currentValue)})}function Ci(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==G.AuthRequired)return n;let r=c=>!!c&&typeof c=="object"&&!Array.isArray(c),s=r(t.data)?t.data:{},o=r(s._meta)?s._meta:{},i=r(o["hydra-acp"])?o["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=G.AuthRequired,d.data={...s,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function GA(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function JA(n,e,t,r){if(n&&typeof n=="object"&&n.code===G.AuthRequired)return n;let s=n instanceof Error?n.message:String(n),o=s.includes("stderr:"),i=o?"":e.stderrTailText(),a=r?`to reproduce: (cd ${GA(r.cwd)} && ${[r.command,...r.args].map(GA).join(" ")})`:"";if(!i&&!a)return n;let d=[o?s:`agent ${t} failed to start: ${s}`];i&&d.push(`stderr: ${i}`),a&&d.push(a);let c=new Error(d.join(`
394
394
  `));if(n&&typeof n=="object"){let l=n;typeof l.code=="number"&&(c.code=l.code),l.data!==void 0&&(c.data=l.data)}return c}function Ou(n){return n._meta?.steering?.supported===!0}function Fu(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t;if(typeof r.id!="string")continue;let s=typeof r.description=="string"?r.description:"",o=r.type==="agent"||r.type==="terminal"?r.type:void 0,i=typeof r.name=="string"?r.name:void 0,a=r._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:r.id,description:s,...o&&{type:o},...i!==void 0&&{name:i},...d&&{_meta:d}})}return e.length>0?e:void 0}function qn(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function xB(n,e){let t=n.configOptions;if(Array.isArray(t))for(let r of t){if(!r||typeof r!="object"||Array.isArray(r))continue;let s=r;if(s.id===e)return s}}function _a(n){return!n||typeof n!="object"||Array.isArray(n)?!1:Array.isArray(n.configOptions)}function $a(n){let e=n.configOptions;if(!Array.isArray(e))return[];let t=[];for(let r of e){if(!r||typeof r!="object"||Array.isArray(r))continue;let s=r,o=qn(s.id);if(!o||o==="model"||o==="mode"||o==="agent")continue;let i=Ib(s.options);if(i.length===0)continue;let a=qn(s.description);t.push({id:o,name:qn(s.name)??o,...a?{description:a}:{},category:qn(s.category)??"other",type:"select",currentValue:qn(s.currentValue)??i[0].value,options:i})}return t}function Ii(n){return n.length>0?n:void 0}function Zb(n){return _h(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=ku(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=ku(e.options);return t.length>0?t:void 0}})??[]}function ek(n){return _h(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=sh(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=sh(e.options);return t.length>0?t:void 0}})??[]}function tk(n){return _h(n,{nestedKey:"modes",configId:"mode",fromObject:e=>qn(e.currentModeId)??qn(e.currentMode)??qn(e.modeId)??qn(e.mode),fromConfig:e=>qn(e.currentValue)})}function IB(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let r=t.params?.update;if(r?.sessionUpdate==="turn_complete"&&!(typeof r.messageId!="string"||r.messageId.length===0))return{index:e,messageId:r.messageId}}}async function VA(n){try{let e=await Oa.readFile(D.tuiHistoryFile(n),"utf8"),t=[];for(let r of e.split(`
395
395
  `))if(r.length!==0)try{let s=JSON.parse(r);typeof s=="string"&&t.push(s)}catch{}return t}catch{return[]}}function XA(n,e,t,r=new Date().toISOString(),s={}){let{retiredCost:o,retiredUsed:i,startedUsed:a,lifetimeCost:d,reason:c,runId:l}=s,u=m=>d!==void 0&&m.lifetimeCostAtStart!==void 0?Math.max(0,d-m.lifetimeCostAtStart):o,f=n.upstreamGenerations&&n.upstreamGenerations.length>0?[...n.upstreamGenerations]:n.upstreamSessionId?[{upstreamSessionId:n.upstreamSessionId,agentId:n.agentId}]:[],p=f[f.length-1];if(p&&p.upstreamSessionId===t){if(f.length>=2){let m=f[f.length-2];if(m){let b=u(m);f[f.length-2]={...m,...b!==void 0&&m.cost===void 0?{cost:b}:{},...i!==void 0&&m.usedAtEnd===void 0?{usedAtEnd:i}:{}}}}return(c!==void 0&&p.reason===void 0||a!==void 0&&p.usedAtStart===void 0||d!==void 0&&p.lifetimeCostAtStart===void 0)&&(f[f.length-1]={...p,...c!==void 0&&p.reason===void 0?{reason:c,...l!==void 0?{runId:l}:{}}:{},...a!==void 0&&p.usedAtStart===void 0?{usedAtStart:a}:{},...d!==void 0&&p.lifetimeCostAtStart===void 0?{lifetimeCostAtStart:d}:{}}),f}return p&&p.endedAt===void 0&&(f[f.length-1]={...p,endedAt:r,...(()=>{let m=u(p);return m!==void 0?{cost:m}:{}})(),...i!==void 0?{usedAtEnd:i}:{}}),f.push({upstreamSessionId:t,agentId:e,startedAt:r,...c!==void 0?{reason:c}:{},...l!==void 0?{runId:l}:{},...a!==void 0?{usedAtStart:a}:{},...d!==void 0?{lifetimeCostAtStart:d}:{}}),f}async function Lu(n){try{let e=await Oa.stat(D.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Nc(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Aa?!1:e?!0:void 0}import{spawn as RB}from"child_process";import*as Nh from"fs";import*as Wo from"fs/promises";import*as Dh from"path";import AB from"pino-roll";var $h=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,t,r){if(e===78){let i=`exited with code 78 (unrecoverable); fix and run \`${r}s start ${t}\``;return this.tripped_=i,{tripped:i}}let s=this.now();this.recentExits.push(s);let o=s-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<o;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let i=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${i}m (crash loop); fix and run \`${r}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};Lh();et();fc();Pp();var TB=1e3,EB=6e4,nk=3e3,Hc=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,r,s={}){this.adapter=t,this.context=r,this.tokenRegistry=s.tokenRegistry,this.breakerOptions=s.breakerOptions,this.restartBaseMs=s.restartBaseMs??TB,this.restartCapMs=s.restartCapMs??EB;for(let o of e)this.entries.set(o.name,this.makeEntry(o))}setContext(e){this.context=e}reportVersion(e,t){let r=this.entries.get(e);r&&(r.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await Wo.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();let e=[];for(let t of this.entries.values())t.config.enabled&&e.push(this.spawn(t,0));await Promise.all(e)}async stop(){this.stopping=!0;let e=[];for(let t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let r=t.child;if(r){try{r.kill("SIGTERM")}catch{}e.push(new Promise(s=>{if(r.exitCode!==null||r.signalCode!==null){s();return}let o=setTimeout(()=>{try{r.kill("SIGKILL")}catch{}s()},nk);r.on("exit",()=>{clearTimeout(o),s()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw Du(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw Du(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,await this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw Du(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let r=t.child;return r?(await this.terminate(t,r),this.infoFor(t)):this.infoFor(t)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw Du(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0).catch(r=>{t.failureReason=`spawn: ${r.message}`}),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw Du(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let r=t.child;r&&await this.terminate(t,r);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let r=new Promise(o=>{e.exitWaiters.push(o)});try{t.kill("SIGTERM")}catch{}let s=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},nk);typeof s.unref=="function"&&s.unref();try{await r}finally{clearTimeout(s)}}infoFor(e){let t;return e.failureReason!==void 0?t="failed":e.child?t="running":e.restartTimer?t="restarting":e.config.enabled?t="stopped":t="disabled",{name:e.config.name,status:t,pid:e.pid,enabled:e.config.enabled,restartCount:e.restartCount,startedAt:e.startedAt,lastExitCode:e.lastExitCode,logPath:this.adapter.paths.logFile(e.config.name),version:e.version,failureReason:e.failureReason}}makeEntry(e){return{config:e,child:void 0,logStream:void 0,restartTimer:void 0,pid:void 0,startedAt:void 0,restartCount:0,lastExitCode:void 0,manuallyStopped:!1,exitWaiters:[],version:void 0,processToken:void 0,breaker:new $h(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Wo.readdir(this.adapter.paths.dir(),{withFileTypes:!0})}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.isDirectory())continue;let r=this.adapter.paths.pidFile(t.name),s;try{let o=await Wo.readFile(r,"utf8"),i=Number.parseInt(o.trim(),10);Number.isInteger(i)&&i>0&&(s=i)}catch{}if(typeof s=="number"&&rk(s)){try{process.kill(s,"SIGTERM")}catch{}let o=Date.now()+nk;for(;Date.now()<o&&rk(s);)await new Promise(i=>setTimeout(i,50));if(rk(s))try{process.kill(s,"SIGKILL")}catch{}}await Wo.unlink(r).catch(()=>{})}}async spawn(e,t){if(this.stopping||e.manuallyStopped)return;let r=this.context;if(!r)throw new Error(`${this.managerName()}.spawn called before setContext`);let s=e.config,o=s.command.length>0?s.command:[s.name],i=Dh.dirname(this.adapter.paths.logFile(s.name)),a;try{await Wo.mkdir(i,{recursive:!0}),a=await AB({file:Dh.join(i,`${s.name}.log`),size:"5m",mkdir:!0,symlink:Fh,limit:{count:5}}),a.on("error",g=>{e.failureReason=`log stream: ${g.message}`})}catch(g){if(this.stopping||e.manuallyStopped)return;e.failureReason=`log setup: ${g.message}`,this.scheduleRestart(e,t+1);return}if(this.stopping||e.manuallyStopped){try{a.end()}catch{}return}a.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${s.name} (attempt ${t+1})
396
396
  `);let d=this.tokenRegistry?.mint(s.name,this.adapter.tokenRole)??r.serviceToken;e.processToken=d,e.version=void 0;let c={...uc(),HYDRA_ACP_DAEMON_URL:r.daemonUrl,HYDRA_ACP_DAEMON_HOST:r.daemonHost,HYDRA_ACP_DAEMON_PORT:String(r.daemonPort),HYDRA_ACP_TOKEN:d,HYDRA_ACP_WS_URL:r.daemonWsUrl,HYDRA_ACP_HOME:r.hydraHome,[this.adapter.nameEnvVar]:s.name,...s.env},[l,...u]=o;if(l===void 0){a.write(`[hydra-acp] ${this.adapter.kind} ${s.name} has empty command
@@ -408,14 +408,14 @@ ${C}`)}await this.mutateRecord(e.sessionId,{cwd:e.cwd,workspace:e.workspace}),th
408
408
  `),a}function dk(n,e){let t=n<0?e+n+1:n;return t<1?1:t>e?e:t}function YB(n,e){if(!(e.from!==void 0||e.to!==void 0||e.last!==void 0)&&e.sinceMs===void 0)return{events:n};let r=[],s=0;for(let{event:p}of n)p.kind==="user-text"&&(s+=1),r.push(s===0?1:s);let o=Math.max(s,1),i=1,a=o;if(e.last!==void 0&&e.last>0?i=dk(o-e.last+1,o):(e.from!==void 0&&(i=dk(e.from,o)),e.to!==void 0&&(a=dk(e.to,o))),i>a)return{events:[],window:{from:i,to:a,total:o}};let d=e.sinceMs,c=new Set;d!==void 0&&n.forEach((p,m)=>{p.recordedAt>=d&&c.add(r[m])});let l=[],u,f;return n.forEach((p,m)=>{let b=r[m];b<i||b>a||d!==void 0&&!c.has(b)||(l.push(p),u??=b,f=b)}),{events:l,window:{from:u??i,to:f??a,total:o}}}function QB(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let r=t.params;if(!r||typeof r!="object")continue;let s=Xs(r.update,{cwd:n.session.cwd});s!==null&&e.push({event:s,recordedAt:t.recordedAt})}return e}function XB(n){let e=new Map;for(let{event:t}of n){if(t.kind==="tool-call"){let r=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??r?.status??"pending"});continue}if(t.kind==="tool-call-update"){let r=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??r.title,status:t.status??r.status})}}return e}function ZB(n,e){let t=e.session,r=Qe(t.sessionId),s=t.title?.trim()||`Hydra session ${r}`;n.push(`# ${Wu(s)}`),n.push("");let o=[];o.push(`- **Session:** \`${r}\` (lineage \`${t.lineageId}\`)`);let i=[t.agentId];t.currentModel&&i.push(`model: ${t.currentModel}`),t.currentMode&&i.push(`mode: ${t.currentMode}`),o.push(`- **Agent:** ${i.filter(Boolean).join(" \xB7 ")}`),o.push(`- **Cwd:** ${t.cwd}`),o.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0||a.cumulativeCost!==void 0)){let d=[];if(a.used!==void 0){let l=a.size!==void 0?`${ck(a.size)}`:void 0;d.push(l?`${ck(a.used)} / ${l} tokens`:`${ck(a.used)} tokens`)}let c=$u(a);if(c!==void 0){let l=a.costCurrency??"USD";d.push(`$${c.toFixed(2)} ${l}`)}o.push(`- **Usage:** ${d.join(" \xB7 ")}`)}n.push(o.join(`
409
409
  `)),n.push("")}function eU(n,e,t,r){let{includeTools:s,includeThoughts:o}=r;if(!e.some(b=>tU(b.event,o))){n.push("_No conversation history recorded._"),n.push("");return}let i=0,a="",d="",c=[],l=new Set,u=!1,f=()=>{if(c.length!==0){for(let b of c)n.push(b);n.push(""),c=[]}},p=()=>{f(),d.length>0&&(bT(n,d.trimEnd(),"*"),n.push(""),d=""),a.length!==0&&(n.push(a.trimEnd()),n.push(""),a="")},m=()=>{u||(u=!0)};for(let{event:b}of e)switch(b.kind){case"user-text":{p(),n.push("---"),n.push(""),i+=1,bT(n,b.text,"**"),n.push(""),u=!0;break}case"agent-text":m(),a+=b.text;break;case"agent-thought":{if(!o)break;m(),a.length>0&&(n.push(a.trimEnd()),n.push(""),a=""),d+=b.text;break}case"tool-call":{if(!s||(m(),(a.length>0||d.length>0)&&p(),l.has(b.toolCallId)))break;l.add(b.toolCallId);let g=t.get(b.toolCallId)??{title:b.title,status:b.status??"pending"};c.push(`- ${rU(g.status)} ${nU(g)}`);break}case"tool-call-update":break;case"plan":{m(),p(),n.push("**Plan:**"),n.push("");for(let g of b.entries){let h=g.status==="completed"?"[x]":"[ ]";n.push(`- ${h} ${Wu(g.content)}`)}n.push("");break}case"mode-changed":m(),p(),n.push(`_mode: ${Wu(b.mode)}_`),n.push("");break;case"model-changed":m(),p(),n.push(`_model: ${Wu(b.model)}_`),n.push("");break;case"turn-complete":p();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}p()}function tU(n,e){switch(n.kind){case"agent-thought":return e;case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function nU(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Wu(n.title)}${t}`}function rU(n){switch(n){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}var kT=String.raw`<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^<>]*)?\/?>`,sU=new RegExp(kT);function bT(n,e,t){if(sU.test(e)){oU(n,e);return}let r=e.split(/\n\s*\n/);for(let s=0;s<r.length;s++){let o=r[s];if(o.trim().length===0)continue;let i=o.split(`
410
410
  `);for(let a=0;a<i.length;a++){let d=i[a];n.push(a===0&&a===i.length-1?`${t}${d}${t}`:a===0?`${t}${d}`:a===i.length-1?`${d}${t}`:d)}s<r.length-1&&n.push("")}}function oU(n,e){let t=e.replace(/\s+$/,"");if(t.length===0)return;let r=0;for(let o of t.match(/`+/g)??[])r=Math.max(r,o.length);let s="`".repeat(Math.max(3,r+1));n.push(s);for(let o of t.split(`
411
- `))n.push(o);n.push(s)}function Wu(n){return n.replace(new RegExp(kT,"g"),e=>e.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}function ck(n){return n.toLocaleString("en-US")}fn();rr();Mr();em();qd();import{randomBytes as ET}from"crypto";function TT(n){let e=ET(32).toString("hex");return n.tokenRegistry.reserve(e).complete(n.session),n.session.onClose(()=>{n.tokenRegistry.unbind(e)}),{name:n.name,type:"http",url:`${n.getOrigin()}/mcp/${n.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function lk(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async r=>{let s=[...n.baselineMcpServers??[]];n.stdinEnabled&&s.push(TT({name:"hydra-acp-stdin",session:r,tokenRegistry:e,getOrigin:t})),s.push(TT({name:"hydra-acp-recall",session:r,tokenRegistry:e,getOrigin:t}));let o=qc(n.deps);return o!==void 0&&(o.bindToSession(r),s=[...s,...o.descriptors]),s}}function qc(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=ET(32).toString("hex"),r=n.mcpTokenRegistry.reserve(t),s=n.getDaemonOrigin(),o=e.map(a=>({name:a,type:"http",url:`${s}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),i=n.mcpTokenRegistry;return{descriptors:o,bindToSession:a=>{r.complete(a),a.onClose(()=>{i.unbind(t)})},abandon:a=>r.abandon(a)}}et();Mr();mu();mr();var SU=new Set(["/v1/sessions/:id/history","/v1/sessions/:id/events"]);function PT(n,e){let t=e.fetchImpl??fetch;n.addHook("preHandler",async(r,s)=>{let o=r.routeOptions.url;if(!o||!o.startsWith("/v1/sessions/:id"))return;let i=r.params,a=i.id;if(typeof a!="string")return;let d=eo(a);if(!d){if(!e.localMiss||await e.localMiss.resolvesLocally(a))return;let h=e.localMiss.cache.findByLocalId(a);if(h.length===0)return;if(h.length>1){s.code(404).send({error:`Session "${a}" exists on more than one remote (${h.map(y=>y.name).join(", ")}). Address it as "<remote>:${a}".`});return}d=h[0]}let c=e.store.get(d.name);if(!c){s.code(404).send({error:`No remote named "${d.name}". Run \`hydra remote add\` first.`});return}let l=r.query;if(SU.has(o)&&IU(l?.follow)){let h=c.port===un?"":`:${c.port}`;s.code(501).send({error:`Streaming a federated session isn't supported yet. Attach directly with hydra://${c.host}${h}/${d.localId} instead.`});return}let u=CU(o,i,d.localId,r.url),p=`${Nt(c.host)?"http":"https"}://${c.host}:${c.port}${u}`,m;try{m=await t(p,{method:r.method,headers:{Authorization:`Bearer ${c.token}`,...r.body!==void 0?{"Content-Type":"application/json"}:{}},...r.body!==void 0&&r.method!=="GET"?{body:JSON.stringify(r.body)}:{}})}catch(h){s.code(502).send({error:`Could not reach remote "${d.name}" (${c.host}:${c.port}): ${h.message}`});return}if(r.method==="DELETE"&&o==="/v1/sessions/:id"&&(m.ok||m.status===404)&&e.localMiss?.cache.evict(d.name,d.localId),m.status===204){s.code(204).send();return}let b=await m.text(),g=m.headers.get("content-type");g&&s.header("content-type",g),s.code(m.status).send(b)})}var xU=5e3,tm=class{constructor(e,t={}){this.store=e;this.opts=t}store;opts;perPeer=new Map;timer;start(){this.timer||(this.refreshNow(),this.timer=setInterval(()=>{this.refreshNow()},this.opts.intervalMs??xU),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}async refreshNow(){let e=this.opts.fetchImpl??fetch,t=new Set(this.store.list().map(r=>r.name));for(let r of[...this.perPeer.keys()])t.has(r)||this.perPeer.delete(r);await Promise.allSettled(this.store.list().map(async r=>{let s=this.store.get(r.name);if(!s)return;let o=this.perPeer.get(r.name),i=Nt(s.host)?"http":"https",a=new URLSearchParams({includeNonInteractive:"1"}),d=o?.cursor!==void 0;d&&a.set("since",String(o.cursor));let c=`${i}://${s.host}:${s.port}/v1/sessions?${a.toString()}`,l;try{l=await e(c,{headers:{Authorization:`Bearer ${s.token}`}})}catch{return}if(!l.ok)return;let u=await l.json(),f=o?.sessions??new Map;if(d){for(let[p,m]of[...f])m.status!=="cold"&&f.delete(p);for(let p of u.removed??[])f.delete(Zs({name:r.name,localId:p}))}else f.clear();for(let p of u.sessions??[]){let m=Zs({name:r.name,localId:String(p.sessionId)});f.set(m,{...p,sessionId:m,remote:r.name})}this.perPeer.set(r.name,{cursor:u.cursor,sessions:f})}))}list(e){let t=[];for(let r of this.perPeer.values())t.push(...r.sessions.values());return t.filter(r=>!(e.status&&r.status!==e.status||!e.includeNonInteractive&&r.interactive!==!0))}evict(e,t){this.perPeer.get(e)?.sessions.delete(Zs({name:e,localId:t}))}findByLocalId(e){let t=e.startsWith(Yt)?[e]:[e,Yt+e],r=[];for(let[s,o]of this.perPeer)for(let i of t)if(o.sessions.has(Zs({name:s,localId:i}))){r.push({name:s,localId:i});break}return r}};async function MT(n,e,t,r=fetch){let s=n.get(e);if(!s)return{status:404,body:{error:`No remote named "${e}". Run \`hydra remote add\` first.`}};let i=`${Nt(s.host)?"http":"https"}://${s.host}:${s.port}/v1/sessions`,a;try{a=await r(i,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(u){return{status:502,body:{error:`Could not reach remote "${e}" (${s.host}:${s.port}): ${u.message}`}}}let d=await a.text(),c=null;try{c=d.length>0?JSON.parse(d):null}catch{c=null}if(!a.ok)return{status:a.status,body:c};let l=c;return l&&typeof l.sessionId=="string"?{status:a.status,body:{...l,sessionId:Zs({name:e,localId:l.sessionId})}}:{status:a.status,body:c}}async function _T(n,e,t=fetch){let r;if(e.sessionIds===void 0)r=n.list().map(a=>({name:a.name}));else{let a=new Map;for(let d of e.sessionIds){let c=eo(d);if(!c)continue;let l=a.get(c.name)??[];l.push(c.localId),a.set(c.name,l)}r=[...a.entries()].map(([d,c])=>({name:d,sessionIds:c}))}if(r.length===0)return{query:e.q,truncated:!1,results:[]};let s=await Promise.all(r.map(async a=>{let d=n.get(a.name);if(!d)return null;let l=`${Nt(d.host)?"http":"https"}://${d.host}:${d.port}/v1/sessions/search`,u;try{u=await t(l,{method:"POST",headers:{Authorization:`Bearer ${d.token}`,"Content-Type":"application/json"},body:JSON.stringify({q:e.q,...a.sessionIds?{sessionIds:a.sessionIds}:{},...e.snippetWidth!==void 0?{snippetWidth:e.snippetWidth}:{}})})}catch{return null}if(!u.ok)return null;let f;try{f=await u.json()}catch{return null}let p=f;if(!p||!Array.isArray(p.results))return null;let m=p.results.map(b=>({...b,sessionId:Zs({name:a.name,localId:b.sessionId})}));return{query:e.q,truncated:p.truncated===!0,results:m}})),o=[],i=!1;for(let a of s)a!==null&&(o.push(...a.results),i=i||a.truncated);return{query:e.q,truncated:i,results:o}}function IU(n){return n==="1"||n==="true"||n===!0}function CU(n,e,t,r){let s=n.replace(/:([A-Za-z_]+)/g,(i,a)=>encodeURIComponent(a==="id"?t:e[a]??"")),o=r.indexOf("?");return o===-1?s:s+r.slice(o)}var nm=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function $T(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Nt(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function FT(n,e,t,r={},s,o){n.get("/v1/sessions",async(f,p)=>{let m=f.query,b=m?.includeNonInteractive==="1"||m?.includeNonInteractive==="true",g;if(m?.since!==void 0&&(g=Number(m.since),!Number.isFinite(g)||g<0))return p.code(400).send({error:`since must be a non-negative number, got ${JSON.stringify(m.since)}`});let h=m?.status==="warm"||m?.status==="cold"?m.status:void 0,y={cwd:m?.cwd,includeNonInteractive:b,...h?{status:h}:{}},k=o&&!y.cwd?o.list({includeNonInteractive:b,...h?{status:h}:{}}):[];if(g!==void 0){let I=await e.listSince(y,g);return{sessions:[...I.entries,...k],removed:I.removed,cursor:I.cursor}}let S=await e.listing(y);return{sessions:[...S.entries,...k],removed:[],cursor:S.cursor}}),n.get("/v1/sessions/:id",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=await e.getOne(b);return g||(p.code(404).send({error:"session not found"}),p)}),n.post("/v1/sessions/search",async(f,p)=>{let m=f.body??{},b=typeof m.q=="string"?m.q:"";if(b.trim().length===0)return p.code(400).send({error:"q is required"}),p;let g=Array.isArray(m.sessionIds)?m.sessionIds.filter(S=>typeof S=="string"&&S.length>0):void 0,h={sessionIds:g};typeof m.snippetWidth=="number"&&(h.snippetWidth=m.snippetWidth);let y=await AT(e,b,h);if(!s)return y;let k=await _T(s,{q:b,...g?{sessionIds:g}:{},...h.snippetWidth!==void 0?{snippetWidth:h.snippetWidth}:{}});return{query:b,truncated:y.truncated||k.truncated,results:[...y.results,...k.results]}}),n.post("/v1/sessions",async(f,p)=>{let m=f.body??{};if(m.remote){if(!s)return p.code(404).send({error:`No remote named "${m.remote}". Run \`hydra remote add\` first.`});let S=await MT(s,m.remote,{cwd:m.cwd,agentId:m.agentId,mcpServers:m.mcpServers,workspace:m.workspace});return p.code(S.status).send(S.body)}let b=Ze(m.cwd??t.cwd),g=await jd(b),h=m.agentId??g.agentId??t.agentId,y=qc(r),k=y!==void 0?[...m.mcpServers??[],...y.descriptors]:m.mcpServers;try{let S=await e.create({cwd:b,agentId:h,mcpServers:k,...m.workspace!==void 0?{workspace:m.workspace}:{}});y!==void 0&&y.bindToSession(S),p.code(201).send({sessionId:S.sessionId,agentId:S.agentId,cwd:S.cwd,...S.workspace!==void 0?{workspace:S.workspace}:{},...S.workspaceError!==void 0?{workspaceError:S.workspaceError}:{}})}catch(S){y!==void 0&&y.abandon(S instanceof Error?S:void 0),p.code(500).send({error:S.message})}}),n.post("/v1/sessions/collect",async(f,p)=>{let m=f.body??{},b=typeof m.maxAgeDays=="number"&&m.maxAgeDays>0?m.maxAgeDays*24*60*60*1e3:0,g=typeof m.limit=="number"&&m.limit>0?m.limit:1e3,h=m.selection==="explicit"||m.selection==="unpromoted"?m.selection:"unpromoted";try{let y=await ok({manager:e,maxAgeMs:b,maxDeletions:g,selection:h,verbose:!1});p.code(200).send(y)}catch(y){p.code(500).send({error:y.message})}}),n.get("/v1/sessions/tombstones",async(f,p)=>{let m=f.query;if(m.since!==void 0&&Number.isNaN(Date.parse(m.since))){p.code(400).send({error:"since must be an ISO timestamp"});return}let b=await e.listTombstones({...m.agent?{agentId:m.agent}:{},...m.since?{since:m.since}:{},...m.grep?{grep:m.grep}:{}});p.code(200).send({tombstones:b})}),n.post("/v1/sessions/undelete",async(f,p)=>{let m=f.body??{};if(!Array.isArray(m.ids)||m.ids.length===0||!m.ids.every(b=>typeof b=="string"&&b.length>0)){p.code(400).send({error:"ids must be a non-empty array of strings"});return}try{p.code(200).send(await e.undeleteSessions(m.ids))}catch(b){p.code(500).send({error:b.message})}}),n.post("/v1/sessions/:id/kill",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=e.get(b);if(g){g.close({deleteRecord:!1,by:"REST POST /kill"}).catch(()=>{}),p.code(202).send();return}if(!await e.hasRecord(b)){p.code(404).send({error:"session not found"});return}p.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=e.get(b);if(!g)return p.code(404).send({error:"session not found"}),p;let h=f.body??{},y={};(h.mode==="memory"||h.mode==="file")&&(y.mode=h.mode),typeof h.capacityBytes=="number"&&(y.capacityBytes=h.capacityBytes),typeof h.fileCapBytes=="number"&&(y.fileCapBytes=h.fileCapBytes),(y.mode??"memory")==="file"&&(y.filePathFor=k=>rm.join(OT.tmpdir(),`hydra-acp-stdin-${k}.log`));try{return g.openStream(y)}catch(k){return p.code(409).send({error:k.message}),p}}),n.post("/v1/sessions/:id/stdin",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=e.get(b);if(!g)return p.code(404).send({error:"session not found"}),p;let h=f.body??{},y=typeof h.chunk=="string"?h.chunk:"",k=h.eof===!0;try{return g.streamWrite(y,k)}catch(S){return p.code(409).send({error:S.message}),p}}),n.patch("/v1/sessions/:id",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=f.body??{};if(g.cwd!==void 0){if(typeof g.cwd!="string"||!rm.isAbsolute(g.cwd)){p.code(400).send({error:"cwd must be an absolute path"});return}let y=await e.setCwd(b,g.cwd);if(y==="missing"){p.code(404).send({error:"session not found"});return}if(y==="not-a-directory"){p.code(400).send({error:`${g.cwd} is not a directory`});return}if(y==="live"){p.code(409).send({error:"session is live; its agent was spawned in its cwd and cannot change directory. Moving a live session is a swap \u2014 use `workspace start` in it."});return}if(y==="bound"){p.code(409).send({error:"session is isolated, so its cwd IS its workspace. Clear the binding first (PATCH { workspace: null }) or leave the workspace from inside the session."});return}p.code(204).send();return}if("workspace"in g){if(g.workspace!==null){p.code(400).send({error:"workspace may only be set to null (clear the binding)"});return}let y=await e.clearWorkspaceBinding(b);if(y==="missing"){p.code(404).send({error:"session not found"});return}if(y==="live"){p.code(409).send({error:"session is live; its cwd is the workspace. Use `workspace stop` or `workspace detach` in the session so the agent moves with the binding."});return}p.code(204).send();return}if(g.priority!==void 0){let y=g.priority,k;if(y===null||y===0)k=void 0;else if(typeof y=="number"&&Number.isInteger(y)&&y>0)k=y;else{p.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(b,k)){p.code(404).send({error:"session not found"});return}p.code(204).send();return}if(g.regen===!0){if(!(e.get(b)!==void 0||await e.hasRecord(b))){p.code(404).send({error:"session not found"});return}e.scheduleSynopsis(b),p.code(202).send();return}if(typeof g.title!="string"||g.title.trim().length===0){p.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(b,g.title)){p.code(404).send({error:"session not found"});return}p.code(204).send()}),n.delete("/v1/sessions/:id",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=e.get(b);if(g){await g.close({deleteRecord:!0,by:"REST DELETE /v1/sessions"}),await e.waitForDeletion(b),await e.hasRecord(b)&&await e.deleteRecord(b),p.code(204).send();return}if(!await e.deleteRecord(b)){p.code(404).send({error:"session not found"});return}p.code(204).send()}),n.get("/v1/sessions/:id/export",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=f.query?.tools,h=g==="references"?"references":LA(g),y=await e.exportBundle(b,h==="references"?{tools:"references"}:{});if(!y){p.code(404).send({error:"session not found"});return}let k=_u({record:y.record,history:h==="summary"?NA(y.history,"summary"):y.history,promptHistory:y.promptHistory.length>0?y.promptHistory:void 0,...y.toolBlobs!==void 0?{toolBlobs:y.toolBlobs}:{},hydraVersion:Fe,machine:Ys(),hydraHost:$T(t)}),S=new Date().toISOString().replace(/[:.]/g,"-");p.header("Content-Disposition",`attachment; filename="${b}-${S}.hydra"`),p.code(200).send(k)}),n.get("/v1/sessions/:id/diff",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=await e.exportBundle(b);if(!g){p.code(404).send({error:"session not found"});return}let h=f.query??{},y=h.fold==="true"||h.fold==="1",k=typeof h.paths=="string"&&h.paths.length>0?new Set(h.paths.split(",").map(I=>I.trim()).filter(I=>I.length>0)):void 0,S=Uc(g.history);k&&(S=S.filter(I=>k.has(I.path))),y&&(S=S.map(I=>({...I,hunks:Wc(I.hunks)}))),p.code(200).send(S)}),n.get("/v1/sessions/:id/tools/:hash",async(f,p)=>{let m=f.params,b=await e.resolveCanonicalId(m.id)??m.id,g=await e.loadToolBlob(b,m.hash);if(g===null){p.code(404).send({error:"tool blob not found"});return}p.header("Content-Type","text/plain; charset=utf-8"),p.code(200).send(g)}),n.get("/v1/sessions/:id/transcript",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=await e.exportBundle(b);if(!g){p.code(404).send({error:"session not found"});return}let h=_u({record:g.record,history:g.history,promptHistory:g.promptHistory.length>0?g.promptHistory:void 0,hydraVersion:Fe,machine:Ys(),hydraHost:$T(t)}),y=f.query,k=x=>x==="1"||x==="true"||x==="yes",S=x=>{let C=y?.[x];if(C===void 0||C==="")return;let $=Number(C);return Number.isFinite($)?$:"bad"},I={};for(let x of["from","to","last","since"]){let C=S(x);if(C==="bad"){p.code(400).send({error:`${x} must be a number`});return}C!==void 0&&(I[x==="since"?"sinceMs":x]=C)}p.header("Content-Type","text/markdown; charset=utf-8"),p.code(200).send(Qh(h,{includeTools:k(y?.tools),includeThoughts:k(y?.thoughts),...I}))});let i=f=>async(p,m)=>{let b=p.params.id,g=await e.resolveCanonicalId(b)??b,h=p.body??{},y={};if(h.forkAt!==void 0){if(typeof h.forkAt!="string"||h.forkAt.length===0){m.code(400).send({error:"forkAt must be a non-empty string"});return}y.forkAt=h.forkAt}if(h.cwd!==void 0){if(typeof h.cwd!="string"||h.cwd.length===0){m.code(400).send({error:"cwd must be a non-empty string"});return}y.cwd=Ze(h.cwd)}if(h.agentId!==void 0){if(typeof h.agentId!="string"||h.agentId.length===0){m.code(400).send({error:"agentId must be a non-empty string"});return}y.agentId=h.agentId}if(h.title!==void 0){if(typeof h.title!="string"){m.code(400).send({error:"title must be a string"});return}y.title=h.title}if(f){let k=h.selection;if(k!==void 0){if(typeof k.text!="string"||k.text.length===0){m.code(400).send({error:"selection.text must be a non-empty string"});return}y.side={selection:{text:k.text,...typeof k.responsePartId=="string"?{responsePartId:k.responsePartId}:{}}}}else y.side={}}if(h.mode!==void 0&&!f){if(h.mode!=="verbatim"&&h.mode!=="synthesis"){m.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}y.mode=h.mode}if(h.model!==void 0){if(typeof h.model!="string"||h.model.length===0){m.code(400).send({error:"model must be a non-empty string"});return}y.model=h.model}try{let k=await e.forkSession(g,y);m.code(201).send(k)}catch(k){let S=k;if(S.code===G.SessionNotFound){m.code(404).send({error:S.message});return}if(S.code===G.InvalidParams||S.code===G.AgentNotInstalled){m.code(400).send({error:S.message});return}m.code(500).send({error:S.message})}};n.post("/v1/sessions/:id/fork",i(!1)),n.post("/v1/sessions/:id/side",i(!0)),n.post("/v1/sessions/import",async(f,p)=>{let m=f.body??{};if(m.bundle===void 0){p.code(400).send({error:"missing bundle"});return}let b;if(m.cwd!==void 0){if(typeof m.cwd!="string"||m.cwd.length===0){p.code(400).send({error:"cwd must be a non-empty string"});return}b=m.cwd}let g;try{g=ys(m.bundle)}catch(h){p.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(g,{replace:m.replace===!0,...b!==void 0?{cwd:b}:{}});p.code(201).send(h)}catch(h){let y=h;if(y.code===G.BundleAlreadyImported){p.code(409).send({error:"bundle already imported",existingSessionId:y.existingSessionId});return}p.code(500).send({error:y.message})}}),n.get("/v1/sessions/:id/compact/status",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=e.get(b),h;if(g?h=g.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(b),h===void 0&&!await e.hasRecord(b))return p.code(404).send({error:"session not found"}),p;let y=await e.getCompactionState(b),k=await e.getRollbackBreadcrumb(b),S=await e.getPendingAgentSwap(b),I=!1,x,C=g?.currentUsage,$=typeof C?.used=="number"&&typeof C?.size=="number"&&C.size>0?{used:C.used,size:C.size}:void 0,E=await e.loadHistory(b,{tools:"references",maxEntries:1/0}).catch(()=>[]);if(E.length>0&&t.compaction){let M=h??0,F=E.length,K=M<=E.length?M:0,Y=E.slice(K),z=gT(Y);x=ik(z);let re=g?.currentModel,Q=E.at(-1).recordedAt;I=yT({summarizedThroughEntry:M,totalEntries:F,unsummarizedChars:z,compactionInFlight:e.getCompactionInFlight(),currentModel:re,lastActivityMs:Q,nowMs:Date.now(),config:t.compaction,...typeof C?.used=="number"?{agentReportedUsed:C.used}:{},...typeof C?.size=="number"?{agentReportedSize:C.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:I,...x!=null?{approxTokens:x}:{},...$!=null?{currentUsage:$}:{},...y!=null?{compactionState:y}:{},...k!=null?{rollbackBreadcrumb:k}:{},...S!=null?{pendingAgentSwap:S}:{}}}),n.post("/v1/sessions/:id/compact",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m;if(e.get(b)){e.scheduleCompaction(b),p.code(202).send({scheduled:!0});return}if(!await e.hasRecord(b)){p.code(404).send({error:"session not found"});return}e.scheduleCompaction(b),p.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m;if(!await e.hasRecord(b)){p.code(404).send({error:"session not found"});return}try{await e.performUncompact(b),p.code(202).send({rolledBack:!0})}catch(g){let h=g instanceof Error?g.message:String(g);p.code(409).send({error:h})}}),n.post("/v1/sessions/:id/workspace/clean",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=f.body??{};if(g.deep!==void 0&&typeof g.deep!="boolean"){p.code(400).send({error:"deep must be a boolean"});return}if(!await e.hasRecord(b)){p.code(404).send({error:"session not found"});return}if(e.get(b)===void 0){p.code(409).send({error:"session is not live. Cleaning rewrites the workspace under a running agent, so it is only available inside a live session (`/hydra workspace clean`). For a cold workspace use `hydra workspace remove` instead."});return}try{let h=await e.runWorkspaceAction(b,"clean",void 0,{deep:g.deep===!0});p.code(202).send({report:h})}catch(h){p.code(409).send({error:h instanceof Error?h.message:String(h)})}}),n.get("/v1/sessions/:id/history/page",async(f,p)=>{let m=f.params.id,b=f.query,g=Number(b?.beforeSeq);if(b?.beforeSeq===void 0||b.beforeSeq===""||!Number.isFinite(g)){p.code(400).send({error:"beforeSeq must be a number"});return}let h=b.turns===void 0||b.turns===""?10:Number(b.turns);if(!Number.isInteger(h)||h<1){p.code(400).send({error:"turns must be a positive integer"});return}let y=await e.resolveCanonicalId(m)??m,k=await e.pageHistory(y,{beforeSeq:g,turns:Math.min(h,100)});if(!k){p.code(404).send({error:"session not found"});return}p.code(200).send({entries:Zp(k.entries),hasMore:k.hasMore})}),n.get("/v1/sessions/:id/history",async(f,p)=>{let m=f.params.id,b=f.query,g=b?.follow==="1"||b?.follow==="true",h=await e.resolveCanonicalId(m)??m,y=e.get(h),k,S,I=!1,x=1e4,C=[];if(y){g&&(S=y.onBroadcast(E=>{p.raw.writableEnded||(I?p.raw.write(JSON.stringify(E)+`
412
- `):(C.push(E),C.length>x&&C.shift()))})),f.raw.on("close",()=>{S?.(),p.raw.writableEnded||p.raw.end()});try{k=await y.getHistorySnapshot()}catch(E){throw S?.(),E}}else{let E=await e.getHistory(h);if(E===void 0)return p.code(404).send({error:"session not found"}),p;k=E}p.raw.setHeader("Content-Type","application/x-ndjson"),p.raw.setHeader("Cache-Control","no-cache"),p.raw.statusCode=200;let $=new Set;for(let E of k??[]){p.raw.write(JSON.stringify(E)+`
413
- `);let M=E;typeof M.recordedAt=="number"&&$.add(String(M.recordedAt))}for(;C.length>0;){let E=C.splice(0,C.length);for(let M of E){let F=M,K=typeof F.recordedAt=="number"?String(F.recordedAt):"";K&&$.has(K)||p.raw.write(JSON.stringify(M)+`
414
- `)}}return I=!0,S||p.raw.end(),p});function a(f,p,m){let b=typeof f=="string"?f.trim():"";if(b.length===0)return null;let g;try{g=JSON.parse(b)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!g||typeof g!="object"||Array.isArray(g))return console.debug("events endpoint: skipping non-object JSONL line"),null;let h=g;if(typeof h.recordedAt!="number"||m!==void 0&&h.recordedAt<m||typeof h.params!="object"||h.params===null||Array.isArray(h.params))return null;let y=h.params;if(typeof y.update!="object"||y.update===null||Array.isArray(y.update))return null;let S=y.update.sessionUpdate;return typeof S!="string"||!p.has(S)?null:{recordedAt:h.recordedAt,entry:g}}function d(f,p,m){let g=p.params.update,h={sessionId:f,ts:new Date(p.recordedAt).toISOString(),kind:m,update:g};return g.messageId!==void 0&&g.messageId!==null&&(h.messageId=g.messageId),h}async function*c(f,p,m,b){for await(let g of p){let h=a(g,m,b);if(h){let y=h.entry.params.update.sessionUpdate;yield{ts:h.recordedAt,row:d(f,h.entry,y)}}}}async function l(f,p,m,b){let g=fk.createInterface({input:uk.createReadStream(p),crlfDelay:1/0}),h=c(f,g,m,b),y=await h.next(),k=y.done?null:y.value;return{sessionId:f,rl:g,gen:h,current:k,exhausted:k===null}}async function u(f){let p=await f.gen.next();p.done?(f.exhausted=!0,f.current=null):f.current=p.value}n.get("/v1/sessions/events",async(f,p)=>{let m=f.query,b=m.kinds;if(!b||b.trim().length===0)return p.code(400).send({error:"kinds parameter is required"}),p;let g=b.split(",").map(x=>x.trim());if(g.length===0)return p.code(400).send({error:"kinds parameter is required"}),p;for(let x of g)if(!nm.has(x))return p.code(400).send({error:`kind "${x}" is not queryable; allowed kinds: ${[...nm].join(", ")}`}),p;let h=new Set(g),y;if(m.since!==void 0&&m.since.trim().length>0){let x=new Date(m.since);if(isNaN(x.getTime()))return p.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),p;y=x.getTime()}let k=await e.list({includeNonInteractive:!0}),S=y!==void 0?k.filter(x=>new Date(x.updatedAt).getTime()>=y):k;p.raw.setHeader("content-type","application/x-ndjson"),p.raw.statusCode=200;let I=[];for(let x of S)try{let C=D.historyFile(x.sessionId),$=await l(x.sessionId,C,h,y);$.exhausted||I.push($)}catch(C){if(C.code==="ENOENT")continue;throw C}f.raw.on("close",()=>{for(let x of I)try{x.rl.close()}catch{}p.raw.writableEnded||p.raw.end()});try{for(;I.length>0;){let x=-1,C=1/0;for(let E=0;E<I.length;E++){let M=I[E];M.current!==null&&M.current.ts<C&&(C=M.current.ts,x=E)}if(x===-1)break;let $=I[x];if(p.raw.write(JSON.stringify($.current.row)+`
415
- `),await u($),$.exhausted){try{$.rl.close()}catch{}I.splice(x,1)}}}catch(x){for(let C of I)try{C.rl.close()}catch{}throw x}return p.raw.end(),p}),n.get("/v1/sessions/:id/events",async(f,p)=>{let m=f.params.id,b=f.query,g=await e.resolveCanonicalId(m)??m;if(!e.get(g)&&!await e.hasRecord(g))return p.code(404).send({error:"session not found"}),p;let y=b.kinds;if(!y||y.trim().length===0)return p.code(400).send({error:"kinds parameter is required"}),p;let k=y.split(",").map(E=>E.trim());if(k.length===0)return p.code(400).send({error:"kinds parameter is required"}),p;for(let E of k)if(!nm.has(E))return p.code(400).send({error:`kind "${E}" is not queryable; allowed kinds: ${[...nm].join(", ")}`}),p;let S=new Set(k),I;if(b.since!==void 0&&b.since.trim().length>0){let E=new Date(b.since);if(isNaN(E.getTime()))return p.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),p;I=E.getTime()}let x=D.historyFile(g),C=uk.createReadStream(x),$=fk.createInterface({input:C,crlfDelay:1/0});p.raw.setHeader("content-type","application/x-ndjson"),p.raw.statusCode=200;try{for await(let E of $){let M=typeof E=="string"?E.trim():"";if(M.length===0)continue;let F;try{F=JSON.parse(M)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",x);continue}if(!F||typeof F!="object"||Array.isArray(F)){console.debug("events endpoint: skipping non-object JSONL line in %s",x);continue}let K=F;if(typeof K.recordedAt!="number"||typeof K.params!="object"||K.params===null||Array.isArray(K.params))continue;let Y=K.params;if(typeof Y.update!="object"||Y.update===null||Array.isArray(Y.update))continue;let z=Y.update,re=z.sessionUpdate;if(typeof re!="string"||!S.has(re)||I!==void 0&&K.recordedAt<I)continue;let Q={ts:new Date(K.recordedAt).toISOString(),kind:re,update:z};z.messageId!==void 0&&z.messageId!==null&&(Q.messageId=z.messageId),p.raw.write(JSON.stringify(Q)+`
416
- `)}}catch(E){if(E.code==="ENOENT")return p.raw.end(),p;throw E}return p.raw.end(),p}),n.post("/v1/sessions/:id/prompt/:messageId/notify",async(f,p)=>{let m=f.params,b=m.id,g=await e.resolveCanonicalId(b)??b,h=m.messageId,y=f.body,k=typeof y?.callbackUrl=="string"?y.callbackUrl:"",S=typeof y?.secret=="string"?y.secret:"";if(!h||!k||!S){p.code(400).send({error:"messageId, callbackUrl, and secret are all required"});return}let I;try{I=new URL(k)}catch{p.code(400).send({error:"callbackUrl must be a valid absolute URL"});return}if(I.protocol!=="https:"&&I.protocol!=="http:"){p.code(400).send({error:"callbackUrl must be http or https"});return}let x=e.get(g);if(!x){p.code(404).send({error:"session not found or not warm"});return}let C=x.registerTurnNotify(h,k,S);if(C.alreadyTerminal){p.code(200).send({status:"already_terminal",stopReason:C.stopReason});return}p.code(202).send({status:"registered"})}),n.get("/v1/sessions/:id/attention",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=e.get(b);return!g&&!await e.hasRecord(b)?(p.code(404).send({error:"session not found"}),p):g?{flags:g.listAttentionFlags()}:{flags:(await e.store.read(b))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(f,p)=>{let m=f.query;if(!m.source||m.source.trim().length===0)return p.code(400).send({error:"source query parameter is required"}),p;let b=await e.list({includeNonInteractive:!0}),g=[];for(let h of b){let y=e.get(h.sessionId),k;y?k=y.listAttentionFlags():k=(await e.store.read(h.sessionId))?.attentionFlags??[];for(let S of k)S.source===m.source&&g.push({...S,sessionId:h.sessionId})}return{flags:g}}),n.post("/v1/sessions/:id/attention/clear",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,h=f.body??{},y=typeof h.source=="string"?h.source:"",k=typeof h.reason=="string"?h.reason:"";if((y.length>0||k.length>0)&&!(y.length>0&&k.length>0)){p.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}y.length===0&&k.length;let S=e.get(b);if(S){if(y.length>0&&k.length>0)S.clearAttentionFlag(y,k);else{let E=Array.from(S.listAttentionFlags()).map(M=>`${M.source}::${M.reason}`);for(let M of E)S.clearAttentionFlag(M.split("::")[0],M.split("::").slice(1).join("::"))}p.code(204).send();return}if(!await e.hasRecord(b)){p.code(404).send({error:"session not found"});return}let I=e.store,x=await I.read(b);if(!x){p.code(404).send({error:"session not found"});return}let C=x.attentionFlags??[],$;if(y.length>0&&k.length>0){let E=`${y}::${k}`;$=C.filter(M=>`${M.source}::${M.reason}`!==E)}else $=[];if($.length===C.length&&$.every((E,M)=>E.source===C[M].source&&E.reason===C[M].reason)){p.code(204).send();return}await I.write({...x,attentionFlags:$}),p.code(204).send()})}Gs();fn();function LT(n,e,t,r={}){n.get("/v1/agents",async()=>wc(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let s=await e.refresh();return{version:s.version,agentCount:s.agents.length}}),n.post("/v1/agents/:id/install",async(s,o)=>{let i=s.params.id,a=await e.getAgent(i);if(!a){o.code(404).send({error:`agent ${i} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){o.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await Fr(a,[],{npmRegistry:r.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:d.version,distribution:c,installed:!0,command:d.command})}catch(d){o.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(s,o)=>{let i=s.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(i);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===G.AgentNotInstalled){o.code(404).send({error:d.message});return}o.code(409).send({error:d.message})}})}Se();function NT(n,e,t,r=()=>[]){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t,home:D.home(),driftedKeys:r()}))}rr();xc();import*as UT from"os";Se();cs();var ju=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,sm=class n{data;constructor(e){this.data=e}static async load(){let e=await jt(D.peers());return new n(RU(e))}get(e){return this.data.entries[e]}async set(e){this.data.entries[e.name]=e,await DT(this.data)}async delete(e){return e in this.data.entries?(delete this.data.entries[e],await DT(this.data),!0):!1}list(){return Object.values(this.data.entries).map(({name:e,host:t,port:r,expiresAt:s,label:o,addedAt:i,pinnedFingerprint:a,pinnedAt:d})=>({name:e,host:t,port:r,expiresAt:s,label:o,addedAt:i,pinnedFingerprint:a,pinnedAt:d})).sort((e,t)=>e.addedAt.localeCompare(t.addedAt))}};function RU(n){if(!n||typeof n!="object")return{version:1,entries:{}};let e=n,t=e.entries&&typeof e.entries=="object"?e.entries:{},r={};for(let[s,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||typeof i.host!="string"||typeof i.port!="number"||typeof i.token!="string"||typeof i.expiresAt!="string"||typeof i.addedAt!="string")continue;let a={name:i.name,host:i.host,port:i.port,token:i.token,expiresAt:i.expiresAt,addedAt:i.addedAt};typeof i.label=="string"&&(a.label=i.label),typeof i.pinnedFingerprint=="string"&&(a.pinnedFingerprint=i.pinnedFingerprint),typeof i.pinnedAt=="string"&&(a.pinnedAt=i.pinnedAt),r[s]=a}return{version:1,entries:r}}async function DT(n){await on(D.peers(),n,{mode:384})}Mr();var AU=3600*24*365,so=class extends Error{status;constructor(e,t){super(e),this.name="PeerLoginError",this.status=t}};function om(n,e){return`${Nt(n)?"http":"https"}://${n}:${e}`}async function HT(n){let e=n.fetchImpl??fetch,t=`${n.host}:${n.port}`,r=om(n.host,n.port),s;try{s=await e(`${r}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:n.password,label:n.label,ttlSec:n.ttlSec??AU})})}catch(i){throw new so(`Could not reach ${t}: ${i.message}`,502)}if(s.status===401)throw new so(`Wrong password for ${t}.`,401);if(s.status===403)throw new so(`No password is configured on ${t}. Run \`hydra-acp auth password\` on that daemon first.`,502);if(s.status===429)throw new so(`Too many failed login attempts on ${t}; try again later.`,429);if(!s.ok)throw new so(`Login to ${t} failed: HTTP ${s.status}`,502);let o=await s.json();if(!o.session_token||!o.expires_at)throw new so(`Login to ${t} returned a malformed response.`,502);return{token:o.session_token,expiresAt:o.expires_at}}async function pk(n){let e=n.fetchImpl??fetch,t=om(n.host,n.port);try{await e(`${t}/v1/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch{}}function WT(n){return{machine:Ys(),hydraVersion:Fe,startedAt:n,os:{platform:process.platform,release:UT.release(),arch:process.arch},node:process.version}}async function im(n){let e=n.fetchImpl??fetch,t;try{t=await e(`${om(n.host,n.port)}/v1/system`,{headers:{Authorization:`Bearer ${n.token}`},signal:n.signal})}catch(r){return{kind:"error",message:r.message}}if(t.status===401||t.status===403)return{kind:"unauthorized"};if(t.status===404)return{kind:"unsupported"};if(!t.ok)return{kind:"error",message:`HTTP ${t.status}`};try{let r=await t.json();return typeof r?.machine=="string"?{kind:"ok",system:r}:{kind:"ok"}}catch{return{kind:"ok"}}}function BT(n){return n!==void 0&&n.length<=64&&ju.test(n)}function jT(n,e){if(BT(n))return n;if(/^[\d.]+$/.test(e)||e.includes(":"))return;let t=e.split(".")[0];return BT(t)?t:void 0}function qT(n,e){n.get("/v1/system",async()=>WT(e))}var TU=/^[A-Za-z0-9._-]+$/;function am(n,e,t){let r=e==="extension"?"extensions":"transformers",s=`/v1/${r}`;n.get(s,async()=>({[r]:t.list()})),n.get(`${s}/:name`,async(o,i)=>{let a=o.params.name,d=t.get(a);if(!d){i.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),n.post(s,async(o,i)=>{let a=o.body??{},d=EU(a);if("error"in d){i.code(400).send({error:d.error});return}try{let c=t.register(d.config);i.code(201).send(c)}catch(c){qu(i,c)}}),n.delete(`${s}/:name`,async(o,i)=>{let a=o.params.name;try{await t.unregister(a),i.code(204).send()}catch(d){qu(i,d)}}),n.post(`${s}/:name/start`,async(o,i)=>{let a=o.params.name;try{let d=await t.startByName(a);i.code(200).send(d)}catch(d){qu(i,d)}}),n.post(`${s}/:name/stop`,async(o,i)=>{let a=o.params.name;try{let d=await t.stopByName(a);i.code(200).send(d)}catch(d){qu(i,d)}}),n.post(`${s}/:name/restart`,async(o,i)=>{let a=o.params.name;try{let d=await t.restartByName(a);i.code(200).send(d)}catch(d){qu(i,d)}})}function qu(n,e){let t=e.code,r=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:r});return}if(t==="CONFLICT"){n.code(409).send({error:r});return}n.code(500).send({error:r})}function EU(n){let e=n.name;if(typeof e!="string"||!TU.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(i=>typeof i!="string")))return{error:"command must be string[]"};let r=n.args;if(r!==void 0&&(!Array.isArray(r)||r.some(i=>typeof i!="string")))return{error:"args must be string[]"};let s=n.env;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))return{error:"env must be an object of string\u2192string"};if(s&&Object.values(s).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=n.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:r??[],env:s??{},enabled:o===void 0?!0:o}}}function zT(n,e){am(n,"extension",e)}function KT(n,e){am(n,"transformer",e)}function GT(n,e){n.get("/v1/config",async()=>e())}import{z as Ti}from"zod";Se();import*as Ai from"fs/promises";import*as QT from"path";import{randomBytes as PU,scrypt as MU,timingSafeEqual as _U}from"crypto";import{promisify as $U}from"util";var XT=$U(MU);function hk(){return QT.join(D.home(),"password-hash")}var JT=32768,VT=8,YT=1,OU=64,FU=16,ZT=128*1024*1024;async function dm(n){if(typeof n!="string"||n.length===0)throw new Error("password must be a non-empty string");let e=PU(FU),t=await XT(n,e,OU,{N:JT,r:VT,p:YT,maxmem:ZT}),r=`scrypt$${JT}$${VT}$${YT}$${e.toString("hex")}$${t.toString("hex")}
417
- `;await Ai.mkdir(D.home(),{recursive:!0}),await Ai.writeFile(hk(),r,{encoding:"utf8",mode:384})}async function zc(){try{return(await Ai.readFile(hk(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function cm(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await Ai.readFile(hk(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let r=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let d=await XT(n,i,a.length,{N:r,r:s,p:o,maxmem:ZT});return d.length!==a.length?!1:_U(d,a)}var LU=Ti.object({password:Ti.string().min(1),label:Ti.string().min(1).max(256).optional(),ttlSec:Ti.number().int().positive().optional()}),NU=Ti.object({id:Ti.string().optional()}).optional(),DU=Ti.object({token:Ti.string().min(32)});function e0(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,r)=>{let s=HU(t);if(e.rateLimiter.isBlocked(s))return r.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=LU.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}if(!await zc())return r.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await cm(o.password))return e.rateLimiter.recordFailure(s),r.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(s);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return r.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,r)=>{let s;try{s=NU.parse(t.body??void 0)}catch{return r.code(400).send({error:"Invalid request body"})}let o=s?.id??t.authIdentity;if(!o||o==="service")return r.code(200).send({revoked:!1});let i=await e.store.revoke(o);return r.code(200).send({revoked:i})}),n.get("/v1/auth/verify",async(t,r)=>r.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,r)=>r.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions",async(t,r)=>{let s=await e.store.revokeAll();return r.code(200).send({revoked:s})}),n.delete("/v1/auth/sessions/:id",async(t,r)=>{let s=t.params.id;return await e.store.revoke(s)?r.code(204).send():r.code(404).send({error:"Not found"})}),n.post("/v1/auth/rotate-token",async(t,r)=>{if(t.authIdentity!=="service")return r.code(403).send({error:"Requires the service token"});let s;try{s=DU.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}return e.staticTokenValidator.rotate(s.token),r.code(200).send({rotated:!0})})}function HU(n){return n.ip||"unknown"}et();import{z as Ei}from"zod";Lo();Mr();var BU=Ei.object({name:Ei.string().min(1).max(64).regex(ju).optional(),host:Ei.string().min(1),port:Ei.number().int().positive().optional(),password:Ei.string().min(1),label:Ei.string().min(1).max(256).optional(),ttlSec:Ei.number().int().positive().optional(),pinnedFingerprint:Ei.string().min(1).optional()});function t0(n,e){n.post("/v1/remotes",async(t,r)=>{let s;try{s=BU.parse(t.body)}catch{return r.code(400).send({error:`Invalid request body (name must match ${ju} and the rest is a normal login request)`})}let o=s.port??un;s.pinnedFingerprint&&mi(s.host,o,s.pinnedFingerprint);let i;try{i=await HT({host:s.host,port:o,password:s.password,label:s.label,ttlSec:s.ttlSec})}catch(f){if(f instanceof so)return r.code(f.status).send({error:f.message});throw f}let a=await im({host:s.host,port:o,token:i.token}),d=a.kind==="ok"?a.system:void 0,c=s.name;if(c===void 0){c=jT(d?.machine,s.host);let f=c!==void 0?e.store.get(c):void 0,p=f!==void 0&&(f.host!==s.host||f.port!==o);if(c===void 0||p){await pk({host:s.host,port:o,token:i.token});let m=c===void 0?`Couldn't derive a remote name for ${s.host}`:`A remote named ${c} already points at ${f.host}:${f.port}`;return r.code(c===void 0?400:409).send({error:`${m}. Pass a name: hydra-acp remote add <name> ${s.host}`})}}let l=new Date().toISOString(),u={name:c,host:s.host,port:o,token:i.token,expiresAt:i.expiresAt,addedAt:l,...s.label!==void 0?{label:s.label}:{},...s.pinnedFingerprint!==void 0?{pinnedFingerprint:s.pinnedFingerprint,pinnedAt:l}:{}};return await e.store.set(u),e.health?.markOk(u.name,d),r.code(201).send({name:u.name,host:u.host,port:u.port,expiresAt:u.expiresAt,label:u.label,addedAt:u.addedAt,pinnedFingerprint:u.pinnedFingerprint,status:e.health?.get(u.name)?.status??"unknown"})}),n.get("/v1/remotes",async(t,r)=>{let s=e.store.list().map(o=>{let i=e.health?.get(o.name);return{...o,status:i?.status??"unknown",...i?.checkedAt?{lastCheckedAt:i.checkedAt}:{},...i?.system?{system:i.system}:{}}});return r.code(200).send({remotes:s})}),n.get("/v1/remotes/:name/agents",async(t,r)=>{let s=e.store.get(t.params.name);if(!s)return r.code(404).send({error:"Not found"});let i=`${Nt(s.host)?"http":"https"}://${s.host}:${s.port}`,a={Authorization:`Bearer ${s.token}`};try{let[d,c]=await Promise.all([fetch(`${i}/v1/agents`,{headers:a}),fetch(`${i}/v1/config`,{headers:a}).catch(()=>null)]);if(!d.ok)return r.code(d.status).header("content-type","application/json").send(await d.text());let l=await d.json(),u={};if(c?.ok){let f=await c.json();u={defaultAgent:f.defaultAgent,sessionDefaults:f.sessionDefaults}}return r.code(200).send({...l,...u})}catch(d){return r.code(502).send({error:`Could not reach remote "${s.name}": ${d.message}`})}}),n.delete("/v1/remotes/:name",async(t,r)=>{let s=t.params.name,o=e.store.get(s);return o?(await pk({host:o.host,port:o.port,token:o.token}),await e.store.delete(s),e.health?.forget(s),e.store.list().some(a=>a.host===o.host&&a.port===o.port)||Xy(o.host,o.port),r.code(204).send()):r.code(404).send({error:"Not found"})})}Do();La();ec();Mr();mu();fn();var UU=new Set(["session/attach","session/detach","session/prompt","session/cancel","session/close","session/delete","hydra-acp/session/delete","session/set_model","session/set_mode","session/set_config_option","_session/steering","hydra-acp/prompt/cancel","hydra-acp/prompt/update","hydra-acp/prompt/amend","hydra-acp/session/tool_content","hydra-acp/session/force_cancel"]);function WU(n){return UU.has(n)}function r0(n,e,t,r){let s=[],o=a=>{for(let d of s)d(a)},i=(a,d)=>{e.handleLocalMessage(a,d,{connection:t.connection,clientId:r}).then(c=>c?n.send(c):void 0).catch(()=>{})};return n.onMessage(a=>{if("method"in a&&WU(a.method)){let d=a.params,c=typeof d?.sessionId=="string"?d.sessionId:void 0;if(c){if(eo(c)){i(a,c);return}if(a.method==="session/attach"){let l="id"in a;e.resolveLocalMiss(c).then(u=>{if(u.ok){i(a,u.foreignId);return}if(u.ambiguous&&l){n.send(zu(a.id,G.SessionNotFound,`Session "${c}" exists on more than one remote (${u.ambiguous.join(", ")}). Address it as "<remote>:${c}".`));return}o(a)});return}}}o(a)}),{send:a=>n.send(a),onMessage:a=>s.push(a),onClose:a=>n.onClose(a),close:()=>n.close()}}var lm=class{constructor(e,t=qU,r){this.store=e;this.dial=t;this.localMiss=r}store;dial;localMiss;attachments=new Map;async resolveLocalMiss(e){if(!this.localMiss)return{ok:!1};if(await this.localMiss.resolvesLocally(e))return{ok:!1};let t=this.localMiss.cache.findByLocalId(e);return t.length===0?{ok:!1}:t.length>1?{ok:!1,ambiguous:t.map(r=>r.name)}:{ok:!0,foreignId:Zs(t[0])}}async handleLocalMessage(e,t,r){let s="id"in e,o=s?e.id:void 0,i=eo(t);if(!i)return s?zu(o,G.SessionNotFound,`not a federated session id: ${t}`):void 0;let a=n0(r.clientId,t),d={...e.params,sessionId:i.localId};if(e.method==="session/attach"){let l=this.store.get(i.name);if(!l)return s?zu(o,G.SessionNotFound,`No remote named "${i.name}". Run \`hydra remote add\` first.`):void 0;let u=this.attachments.get(a);u&&(this.attachments.delete(a),u.peerConnection.close().catch(()=>{}));let f;try{f=await this.dial(l)}catch(g){return s?zu(o,G.InternalError,`Could not reach remote "${i.name}": ${g.message}`):void 0}let p={peerConnection:f,localId:i.localId,target:r};this.wireAttachment(i.name,p);let m;try{m=await f.request("session/attach",d)}catch(g){return f.close().catch(()=>{}),s?mk(o,g):void 0}this.attachments.set(a,p);let b=m&&typeof m.sessionId=="string"?{...m,sessionId:t}:m;return s?{jsonrpc:"2.0",id:o,result:b}:void 0}let c=this.attachments.get(a);if(!c)return s?zu(o,G.SessionNotFound,`"${t}" is not attached through this daemon.`):void 0;if(e.method==="session/detach"){let l,u;try{l=await c.peerConnection.request("session/detach",d)}catch(f){u=f}return this.attachments.delete(a),c.peerConnection.close().catch(()=>{}),u?s?mk(o,u):void 0:s?{jsonrpc:"2.0",id:o,result:l??{}}:void 0}if(s)try{let l=await c.peerConnection.request(e.method,d);return{jsonrpc:"2.0",id:o,result:l}}catch(l){return mk(o,l)}await c.peerConnection.notify(e.method,d).catch(()=>{})}detachClient(e){for(let[t,r]of[...this.attachments.entries()])r.target.clientId===e&&(this.attachments.delete(t),r.peerConnection.request("session/detach",{sessionId:r.localId}).catch(()=>{}),r.peerConnection.close().catch(()=>{}))}wireAttachment(e,t){let{peerConnection:r,localId:s,target:o}=t,i=Zs({name:e,localId:s}),a=()=>{this.attachments.delete(n0(o.clientId,i))};r.onAnyNotification((d,c)=>{let l=d;!l||l.sessionId!==s||(c==="hydra-acp/session/closed"&&a(),o.connection.notify(c,{...l,sessionId:i}).catch(()=>{}))}),r.onRequest("hydra-acp/session/request_permission",async d=>{let c=d;if(!c||c.sessionId!==s)throw{code:G.MethodNotFound,message:"unexpected sessionId"};return o.connection.request("hydra-acp/session/request_permission",{...c,sessionId:i})}),r.onClose(()=>{a(),o.connection.notify("hydra-acp/session/closed",{sessionId:i}).catch(()=>{})})}};function n0(n,e){return`${n} ${e}`}function zu(n,e,t){return{jsonrpc:"2.0",id:n,error:{code:e,message:t}}}function mk(n,e){let t=e,r=typeof t?.code=="number"?t.code:G.InternalError,s=typeof t?.message=="string"?t.message:String(e??"forward failed");return{jsonrpc:"2.0",id:n,error:{code:r,message:s,...t?.data!==void 0?{data:t.data}:{}}}}var jU=1e4;async function qU(n){let t=`${Nt(n.host)?"ws":"wss"}://${n.host}:${n.port}/acp`,r=await No(t,["acp.v1",`hydra-acp-token.${n.token}`],jU);return new pn(Nr(r))}Mr();var zU=3e4,KU=5e3,um=class{constructor(e,t={}){this.store=e;this.opts=t}store;opts;snapshots=new Map;timer;start(){this.timer||(this.checkAll(),this.timer=setInterval(()=>{this.checkAll()},this.opts.intervalMs??zU),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}get(e){return this.snapshots.get(e)}markOk(e,t){this.snapshots.set(e,{status:"ok",checkedAt:new Date().toISOString(),...t?{system:t}:{}})}forget(e){this.snapshots.delete(e)}async checkAll(){let e=this.opts.fetchImpl??fetch;await Promise.allSettled(this.store.list().map(async t=>{let r=this.store.get(t.name);if(!r)return;let s=new AbortController,o=setTimeout(()=>s.abort(),KU);try{let i=await im({host:r.host,port:r.port,token:r.token,fetchImpl:e,signal:s.signal});if(i.kind==="ok"){this.snapshots.set(t.name,{status:"ok",checkedAt:new Date().toISOString(),...i.system?{system:i.system}:{}});return}if(i.kind==="unauthorized"){this.snapshots.set(t.name,{status:"unauthorized",checkedAt:new Date().toISOString()});return}if(i.kind==="error")throw new Error(i.message);let d=`${Nt(r.host)?"http":"https"}://${r.host}:${r.port}/v1/auth/verify`,c=await e(d,{headers:{Authorization:`Bearer ${r.token}`},signal:s.signal});this.snapshots.set(t.name,{status:c.ok?"ok":"unauthorized",checkedAt:new Date().toISOString()})}catch(i){this.snapshots.set(t.name,{status:"unreachable",checkedAt:new Date().toISOString(),error:i.message})}finally{clearTimeout(o)}}))}};Lo();import{z as s0}from"zod";var GU=s0.object({sessionLabel:s0.string().min(1).max(256)});function o0(n,e){n.post("/v1/process-tokens",async(t,r)=>{if(t.authIdentity!=="service")return r.code(403).send({error:"Requires the service token"});let s;try{s=GU.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}let o=e.processRegistry.mint(s.sessionLabel,"script");return r.code(201).send({token:o})}),n.delete("/v1/process-tokens/:sessionLabel",async(t,r)=>t.authIdentity!=="service"?r.code(403).send({error:"Requires the service token"}):(e.processRegistry.revoke(t.params.sessionLabel),r.code(204).send()))}Bp();Do();Lc();La();import{nanoid as gk}from"nanoid";Qp();fn();Gs();qd();rr();import{randomBytes as l0}from"crypto";import*as u0 from"os";import*as f0 from"path";kc();var JU=200;function VU(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e[pt];if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.sentBy;if(!r||typeof r!="object"||Array.isArray(r))return;let s=r,o={};if(typeof s.sessionId=="string"&&s.sessionId.length>0&&(o.sessionId=s.sessionId),typeof s.label=="string"&&s.label.length>0&&(o.label=s.label.slice(0,JU)),s.awaiting===!0&&(o.awaiting=!0),!(o.sessionId===void 0&&o.label===void 0))return o}async function i0(n,e,t){let r=VU(n);if(!r)return;let s={};if(r.label!==void 0&&(s.fromLabel=r.label),r.awaiting===!0&&(s.awaiting=!0),r.sessionId!==void 0){let o=await e.resolveCanonicalId(r.sessionId)??r.sessionId,i=await e.getOne(o);if(i){s.fromSession=o,i.title&&(s.fromSessionTitle=i.title);let a=e.get(o)?.currentPromptDepth;s.depth=(a??0)+1}else t?.(r.sessionId)}if(!(s.fromSession===void 0&&s.fromLabel===void 0))return s}var Ku=new Map;function a0(n,e){let t=Ku.get(n);t||(t=new Set,Ku.set(n,t)),t.add(e);let r=!1;return()=>{if(r)return;r=!0;let s=Ku.get(n);s&&(s.delete(e),s.size===0&&Ku.delete(n))}}function d0(n,e){if(n===e)return!0;let t=new Set,r=[e];for(;r.length>0;){let s=r.pop();if(t.has(s))continue;t.add(s);let o=Ku.get(s);if(o){if(o.has(n))return!0;for(let i of o)r.push(i)}}return!1}function he(n,e,t){let r=new Error(e);return r.code=n,t!==void 0&&(r.data=t),r}function eW(n){if(!n||typeof n!="object")return 512;let r=n.params?.update;if(!r)return 512;let s=512,o=r.content;if(typeof o=="string")s+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(s+=a.text.length),typeof a.data=="string"&&(s+=a.data.length)}let i=r.toolCall;if(i&&(typeof i.rawInput=="string"?s+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(s+=256),typeof i.rawOutput=="string"?s+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(s+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(s+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(s+=c.text.length)}}return s}function yr(n,e,t){let r=n.get(e);if(!r)throw he(G.SessionNotFound,t??`session ${e} not found`);return r}async function Na(n,e){let t=qc(n),r,s,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(r=l0(32).toString("hex"),s=n.mcpTokenRegistry.reserve(r),o={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${r}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],d=lk({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),c;try{c=await n.manager.resurrect({...e,mcpServers:a,...d?{mintMcpServersForSwap:d}:{}})}catch(l){throw t!==void 0&&t.abandon(l instanceof Error?l:void 0),s!==void 0&&s.abandon(l instanceof Error?l:void 0),l}if(t!==void 0&&t.bindToSession(c),r!==void 0&&s!==void 0&&n.mcpTokenRegistry!==void 0){let l=r,u=n.mcpTokenRegistry;s.complete(c),c.onClose(()=>{u.unbind(l)})}return lW(c,n),h0(c.sessionId,n),c}function p0(n,e){n.get("/acp",{websocket:!0},async(t,r)=>{let s=hT({headers:r.headers,url:r.url});if(!s||!await e.validator.validate(s)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(s),i=`hydra_client_${gk(12)}`,a=Nr(t),d={},c=e.foreignSessions?r0(a,e.foreignSessions,d,i):a,l=new pn(c);d.connection=l;let u={clientId:i,processIdentity:o,attached:new Map};l.onClose(()=>{for(let g of u.attached.values())e.manager.get(g.sessionId)?.detach(g.clientId);u.attached.clear(),e.foreignSessions?.detachClient(i)});let f=(g,h)=>{if(u.attached.get(g)?.readonly)throw he(G.PermissionDenied,`${h} not permitted on a read-only attachment`)};if(l.onRequest("initialize",async g=>{let h=RC.parse(g??{});h.clientInfo?.name&&(u.clientInfo={name:h.clientInfo.name,...h.clientInfo.version!==void 0?{version:h.clientInfo.version}:{}});let y=h.clientInfo?.version;return y&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,y):e.onTransformerVersion?.(o.name,y)),cW()}),o&&e.extensionCommands){let g=e.extensionCommands;l.onRequest("hydra-acp/commands/register",async h=>{let y=h??{},k=Array.isArray(y.commands)?y.commands.map(S=>{if(!S||typeof S!="object")return;let I=S;if(typeof I.verb!="string")return;let x={verb:I.verb};return typeof I.argsHint=="string"&&(x.argsHint=I.argsHint),typeof I.description=="string"&&(x.description=I.description),x}).filter(S=>S!==void 0):[];return g.register(o.name,l,k),{ok:!0,registered:k.length}}),l.onClose(()=>{g.clear(o.name)})}if(o&&e.extensionMcp){let g=e.extensionMcp;l.onRequest("hydra-acp/mcp_tools/register",async y=>{let k=y??{},S=typeof k.instructions=="string"?k.instructions:void 0,I=Array.isArray(k.tools)?k.tools.map(x=>{if(!x||typeof x!="object")return;let C=x;if(typeof C.name!="string"||C.name.length===0||typeof C.description!="string"||C.inputSchema===null||typeof C.inputSchema!="object")return;let $={name:C.name,description:C.description,inputSchema:C.inputSchema};return C.outputSchema!==null&&typeof C.outputSchema=="object"&&($.outputSchema=C.outputSchema),$}).filter(x=>x!==void 0):[];if(I.length===0)throw new Error("register_mcp_tools requires at least one tool");return g.register(o.name,l,S,I),{ok:!0,registered:I.length}});let h=y=>{let k=y??{};if(typeof k.sessionId!="string"||k.sessionId.length===0)throw he(G.InvalidParams,"sessionId is required");return k.sessionId};if(l.onRequest("hydra-acp/session/extension_state/get",async y=>{let k=h(y),S=y??{};if(typeof S.key!="string"||S.key.length===0)throw he(G.InvalidParams,"key is required");if(!e.manager)throw he(G.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(k,o.name,S.key)??null}}),l.onRequest("hydra-acp/session/extension_state/list",async y=>{let k=h(y);if(!e.manager)throw he(G.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(k,o.name)}}),l.onRequest("hydra-acp/session/extension_state/set",async y=>{let k=h(y),S=y??{};if(typeof S.key!="string"||S.key.length===0)throw he(G.InvalidParams,"key is required");if(S.value===void 0)throw he(G.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw he(G.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(k,o.name,S.key,S.value)}catch(I){throw he(G.InvalidParams,I.message)}return{ok:!0}}),l.onRequest("hydra-acp/session/extension_state/delete",async y=>{let k=h(y),S=y??{};if(typeof S.key!="string"||S.key.length===0)throw he(G.InvalidParams,"key is required");if(!e.manager)throw he(G.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(k,o.name,S.key),{ok:!0}}),e.extensionMcpControls){let y=e.extensionMcpControls;l.onRequest("hydra-acp/mcp_tools/refresh_session",async k=>{let S=k??{};if(typeof S.sessionId!="string"||S.sessionId.length===0)throw he(G.InvalidParams,"refresh_session requires sessionId");return await y.notifyToolListChanged(S.sessionId,o.name),{ok:!0}})}l.onClose(()=>{g.clear(o.name)})}o?.kind==="transformer"&&(l.onRequest("hydra-acp/transformer/initialize",async g=>{let h=g??{},y=Array.isArray(h.intercepts)?h.intercepts.filter(k=>typeof k=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,l,y),e.manager?.defaultTransformers.includes(o.name))){let k=e.transformers.resolveChain([o.name])[0];if(k)for(let S of e.manager.liveSessions())S.addTransformer(k)}return{ack:!0}}),l.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),l.onRequest("hydra-acp/message/emit",async g=>{let h=g??{},y=typeof h.sessionId=="string"?h.sessionId:void 0,k=typeof h.method=="string"?h.method:void 0,S=h.envelope,I=h.route;if(!y)throw he(-32602,"emit_message requires sessionId");if(!k&&I!=="client_broadcast")throw he(-32602,"emit_message requires method");let x=yr(e.manager,y),C=typeof h.respondsTo=="string"?h.respondsTo:void 0;if(C)return x.dischargeClaim(C,S),{ok:!0};if(I==="chain")return{ok:!0,response:await x.emitToChain(o.name,k,S)};if(I==="queue"){if(k!=="session/prompt")throw he(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await x.emitToQueue(o.name,S)}}if(I==="daemon")return{ok:!0,response:await x.emitToChain(o.name,k,S)};if(I==="client_broadcast"){if(!S||typeof S!="object")throw he(-32602,"client_broadcast requires an envelope object");return x.broadcastClientUpdate(S),{ok:!0}}throw he(-32602,`unsupported route: ${JSON.stringify(I)}`)}),l.onRequest("hydra-acp/session/request_permission",async g=>{let h=g??{},y=typeof h.sessionId=="string"?h.sessionId:void 0;if(!y)throw he(-32602,"hydra-acp/session/request_permission requires sessionId");return yr(e.manager,y).requestPermissionFromClients(h)}),l.onRequest("hydra-acp/transformer/attach",async g=>oW(g,o.name,e)),l.onRequest("hydra-acp/child_session/spawn",async g=>{let h=g??{},y=typeof h.agentId=="string"?h.agentId:void 0,k=typeof h.cwd=="string"?h.cwd:void 0,S=typeof h.parentSessionId=="string"?h.parentSessionId:void 0,I=Pn(h._meta??void 0),x=I.title,C=I.model,$=I.workspace;if(!k&&S){let Q=e.manager.get(S);Q&&(k=Q.cwd)}if(!k)throw he(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let E=await jd(k),M=y??E.agentId??e.defaultAgent,F=await e.registry?.getAgent(M),K=Or(E.configDefaults,F??{id:M})?.value,Y=C??K?.model,z=typeof h.interactive=="boolean"?h.interactive:!1,re=await e.manager.create({agentId:M,cwd:k,parentSessionId:S,interactive:z,transformChain:[],title:x,model:Y,configDefaults:K,...$!==void 0?{workspace:$}:{}});return{childSessionId:re.sessionId,...re.workspace!==void 0||re.workspaceError!==void 0?{_meta:{[pt]:{...re.workspace!==void 0?{workspaceInfo:re.workspace}:{},...re.workspaceError!==void 0?{workspaceError:re.workspaceError}:{}}}}:{}}}));let p=async(g,h)=>{let y=g??{};if(typeof y.sessionId!="string")throw he(G.InvalidParams,"fork_session requires sessionId");let k=typeof y.forkAt=="string"?y.forkAt:void 0,S=typeof y.cwd=="string"?y.cwd:void 0,I=typeof y.agentId=="string"?y.agentId:void 0,x=h?void 0:typeof y.mode=="string"&&(y.mode==="verbatim"||y.mode==="synthesis")?y.mode:void 0,C=typeof y.model=="string"&&y.model.length>0?y.model:void 0,$;if(h){let Y=y.selection;if(Y!==void 0&&(typeof Y.text!="string"||Y.text.length===0))throw he(G.InvalidParams,"selection.text must be a non-empty string");$={...Y!==void 0?{selection:{text:Y.text,...typeof Y.responsePartId=="string"?{responsePartId:Y.responsePartId}:{}}}:{}}}let E=await e.manager.forkSession(y.sessionId,{...$!==void 0?{side:$}:{},...k!==void 0?{forkAt:k}:{},...S!==void 0?{cwd:S}:{},...I!==void 0?{agentId:I}:{},...x!==void 0?{mode:x}:{},...C!==void 0?{model:C}:{}}),M=e.manager.get(E.sessionId);if(!M){let Y=await e.manager.loadFromDisk(E.sessionId);if(!Y)throw he(G.InternalError,`fork ${E.sessionId} vanished before it could be attached`);M=await Na(e,{...Y,onInstallProgress:fm(l)})}Kc(u,M,M.sessionId);let F=Pi(l,M,u),{entries:K}=await M.attach(F,"full");u.attached.set(M.sessionId,{sessionId:M.sessionId,clientId:F.clientId,readonly:!1});for(let Y of K){if(l.isClosed())break;await l.notify(Y.method,Vs(Js(Y.params,Y.recordedAt),Y.seq)).catch(()=>{})}return{...E,sessionId:M.sessionId}};l.onRequest("hydra-acp/session/fork",g=>p(g,!1)),l.onRequest("hydra-acp/session/side",g=>p(g,!0)),l.onRequest("session/fork",async g=>{let h=g??{};if(typeof h.sessionId!="string")throw he(G.InvalidParams,"session/fork requires sessionId");let y=typeof h.cwd=="string"?h.cwd:void 0,k=await e.manager.forkSession(h.sessionId,{...y!==void 0?{cwd:y}:{},mode:"verbatim"}),S=e.manager.get(k.sessionId);if(!S){let C=await e.manager.loadFromDisk(k.sessionId);if(!C)throw he(G.InternalError,`fork ${k.sessionId} vanished before it could be attached`);S=await Na(e,{...C,onInstallProgress:fm(l)})}Kc(u,S,S.sessionId);let I=Pi(l,S,u),{entries:x}=await S.attach(I,"full");u.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:I.clientId,readonly:!1});for(let C of x){if(l.isClosed())break;await l.notify(C.method,Vs(Js(C.params,C.recordedAt),C.seq)).catch(()=>{})}return{sessionId:S.sessionId}});let m=async(g,h)=>{let y=g??{};if(typeof y.sessionId!="string")throw he(G.InvalidParams,`${h} requires sessionId`);let k=await e.manager.resolveCanonicalId(y.sessionId)??y.sessionId,S=e.manager.get(k);if(S)return await S.close({deleteRecord:!0,by:`session/delete ${u.clientId}`}),await e.manager.waitForDeletion(k),await e.manager.hasRecord(k)&&await e.manager.deleteRecord(k),{id:k,existed:!0};let I=await e.manager.deleteRecord(k);return{id:k,existed:I}};l.onRequest("session/delete",async g=>(await m(g,"session/delete"),{})),l.onRequest("session/close",async g=>{let h=g??{};if(typeof h.sessionId!="string")throw he(G.InvalidParams,"session/close requires sessionId");f(h.sessionId,"session/close");let y=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,k=e.manager.get(y);if(k)return await k.close({deleteRecord:!1,by:`session/close ${u.clientId}`+(u.processIdentity?` (${u.processIdentity.name})`:"")}),{};if(await e.manager.hasRecord(y))return{};throw he(G.SessionNotFound,`session ${y} not found`)}),l.onRequest("hydra-acp/session/delete",async g=>{let{id:h,existed:y}=await m(g,"hydra-acp/session/delete");if(!y)throw he(G.SessionNotFound,`session ${h} not found`);return{deleted:!0,sessionId:h}}),o?.kind==="transformer"&&(l.onRequest("hydra-acp/child_session/await",async g=>{let h=g??{},y=typeof h.childSessionId=="string"?h.childSessionId:void 0,k=h.until==="idle"?"idle":"turn_complete",S=typeof h.timeoutMs=="number"?Math.min(h.timeoutMs,18e5):3e5;if(!y)throw he(-32602,"await_child requires childSessionId");let I=yr(e.manager,y,`child session ${y} not found`);return new Promise(x=>{let E=[],M=[],F=0,K=!1,Y,z,re=!1,Q=()=>{re||(re=!0,clearTimeout(ke),Y?.(),z?.(),x(K?{entries:E,truncated:!0}:{entries:E}))};Y=I.onBroadcast(xe=>{let je=eW(xe);for(E.push(xe),M.push(je),F+=je;E.length>0&&(E.length>1e3||F>1048576);)E.shift(),F-=M.shift()??0,K=!0;k==="turn_complete"&&xe.params?.update?.sessionUpdate==="turn_complete"&&Q()});let ke=setTimeout(Q,S);typeof ke.unref=="function"&&ke.unref(),z=I.onClose(()=>Q())})}),l.onRequest("hydra-acp/child_session/close",async g=>{let h=g??{},y=typeof h.childSessionId=="string"?h.childSessionId:void 0;if(!y)throw he(-32602,"close_child_session requires childSessionId");let k=e.manager.get(y);return k&&await k.close({deleteRecord:!1,by:`child_session/close ${u.clientId}`}),{ok:!0}}),l.onRequest("hydra-acp/attention/set",async g=>iW(g,o.name,e)),l.onRequest("hydra-acp/attention/clear",async g=>aW(g,o.name,e)),l.onRequest("hydra-acp/connection/keep_alive",async g=>{let h=g??{},y=typeof h.token=="string"?h.token:void 0,k=typeof h.sessionId=="string"?h.sessionId:void 0,S=typeof h.estimatedRemainingMs=="number"?h.estimatedRemainingMs:void 0;return y&&k&&e.manager.get(k)?.keepAliveClaim(y,S),{ok:!0}})),l.onRequest("hydra-acp/session/tool_content",async g=>{let h=g??{};if(typeof h.sessionId!="string"||typeof h.hash!="string")throw he(G.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let y=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,k=await e.manager.loadToolBlob(y,h.hash);if(k===null)throw he(G.SessionNotFound,"tool content not found");return{content:k}}),l.onRequest("authenticate",async g=>tW(g,e)),l.onRequest("logout",async g=>nW(g,e)),l.onRequest("session/new",async g=>{let h=AC.parse(g),y=Pn(g?._meta),k=Array.isArray(y.transformers)&&y.transformers.every(ue=>typeof ue=="string")?y.transformers:e.manager.defaultTransformers??[],S=e.transformers?.resolveChain(k)??[],I=await jd(h.cwd),x=y.agentId??I.agentId??e.defaultAgent,C=await e.registry?.getAgent(x),$=Or(I.configDefaults,C??{id:x})?.value,E,M,F=h.mcpServers;if(y.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){E=l0(32).toString("hex"),M=e.mcpTokenRegistry.reserve(E);let oe={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${E}`}]};F=[...h.mcpServers??[],oe]}let K,Y,z=qc(e);z!==void 0&&(F=[...F??[],...z.descriptors]);let re=lk({baselineMcpServers:h.mcpServers,stdinEnabled:y.mcpStdin===!0,deps:e}),Q;try{Q=await e.manager.create({cwd:h.cwd,agentId:x,mcpServers:F,title:y.title,agentArgs:y.agentArgs,model:y.model??$?.model,configDefaults:$,onInstallProgress:fm(l),transformChain:S,originatingClient:u.clientInfo,...y.interactive!==void 0?{interactive:y.interactive}:{},...y.env!==void 0?{forwardedEnv:y.env}:{},...y.workspace!==void 0?{workspace:y.workspace}:{},...re?{mintMcpServersForSwap:re}:{}})}catch(ue){throw M!==void 0&&M.abandon(ue instanceof Error?ue:void 0),Y!==void 0&&Y.abandon(ue instanceof Error?ue:void 0),z!==void 0&&z.abandon(ue instanceof Error?ue:void 0),ue}if(E!==void 0&&M!==void 0&&e.mcpTokenRegistry!==void 0){let ue=E,oe=e.mcpTokenRegistry;M.complete(Q),Q.onClose(()=>{oe.unbind(ue)})}if(K!==void 0&&Y!==void 0&&e.mcpTokenRegistry!==void 0){let ue=K,oe=e.mcpTokenRegistry;Y.complete(Q),Q.onClose(()=>{oe.unbind(ue)})}z!==void 0&&z.bindToSession(Q),h0(Q.sessionId,e);let ke,xe;try{Kc(u,Q,Q.sessionId),ke=Pi(l,Q,u),{entries:xe}=await Q.attach(ke,"full")}catch(ue){throw await Q.close({deleteRecord:!1,by:"session/new attach-failed"}).catch(()=>{}),ue}u.attached.set(Q.sessionId,{sessionId:Q.sessionId,clientId:ke.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let ue of xe){if(l.isClosed())break;await l.notify(ue.method,Vs(Js(ue.params,ue.recordedAt),ue.seq)).catch(()=>{})}})()});let je=pm(Q),Ge=hm(Q);return{sessionId:Q.sessionId,...je?{modes:je}:{},...Ge?{models:Ge}:{},configOptions:Q.buildConfigOptions(),_meta:mm(e.manager,Q,{clientId:ke.clientId})}}),l.onRequest("session/attach",async g=>{let h=EC.parse(g),y=h.clientInfo?.version;y&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,y):e.onTransformerVersion?.(o.name,y));let k=Pn(h._meta),S=k.resume,I=k.readonly===!0,x=k.env;n.log.info(`session/attach sessionId=${h.sessionId} hasResumeHints=${!!S} readonly=${I}`);let C=S?h.sessionId:await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,$=e.manager.get(C);if(!$&&I){let Q=await e.manager.loadFromDisk(C);if(!Q)throw he(G.SessionNotFound,`session ${h.sessionId} not found`);let ke=Sc(await e.manager.loadHistory(C,{...k.historyLimit!==void 0?{maxEntries:k.historyLimit}:{}}),Q.side),xe=h.clientId??`cli_${gk(8)}`;u.attached.set(Q.hydraSessionId,{sessionId:Q.hydraSessionId,clientId:xe,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${Q.hydraSessionId} clientId=${xe} attachedCount=${u.attached.size} replayed=${ke.length}`);for(let je of ke)await l.notify(je.method,Vs(Js(je.params,je.recordedAt),je.seq)).catch(()=>{});return{sessionId:Q.hydraSessionId,clientId:xe,connectedClients:[xe],historyPolicy:"full",replayed:ke.length,_meta:dW(Q)}}let E=!$;if(!$){let Q=await e.manager.loadFromDisk(C),ke=await rW(C,S,Q?.upstreamSessionId,e.manager);ke.kind==="ignore"&&n.log.warn(ke.logMessage);let xe=Q;if(S&&ke.kind==="honor"&&(xe={...Q,hydraSessionId:h.sessionId,upstreamSessionId:S.upstreamSessionId,agentId:S.agentId,cwd:Q?.workspace?.path??S.cwd,...S.title!==void 0?{title:S.title}:{},...S.agentArgs!==void 0?{agentArgs:S.agentArgs}:{}}),!xe)throw he(G.SessionNotFound,`session ${h.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(xe.agentId,xe.upstreamSessionId))throw he(G.SessionNotFound,`session ${h.sessionId} was deleted`);let je=xe.originatingClient?xe:{...xe,originatingClient:u.clientInfo},Ge=x!==void 0?{...je,forwardedEnv:x}:je;$=await Na(e,{...Ge,onInstallProgress:fm(l)})}Kc(u,$,$.sessionId);let M=Pi(l,$,u,h.clientInfo,h.clientId),F=k.replayMode==="drip",{entries:K,appliedPolicy:Y}=await $.attach(M,h.historyPolicy,{afterMessageId:h.afterMessageId,afterSeq:h.afterSeq,raw:F,...k.historyLimit!==void 0?{historyLimit:k.historyLimit}:{},...k.toolContent!==void 0?{toolContent:k.toolContent}:{}});if(u.attached.set($.sessionId,{sessionId:$.sessionId,clientId:M.clientId,readonly:I}),x!==void 0&&await e.manager.setForwardedEnv($.sessionId,x).catch(()=>{}),n.log.info(`session/attach OK sessionId=${$.sessionId} clientId=${M.clientId} attachedCount=${u.attached.size} requestedPolicy=${h.historyPolicy} appliedPolicy=${Y} replayed=${K.length} readonly=${I}${F?" replayMode=drip":""}`),F){let Q=k.dripSpeed&&k.dripSpeed>0?k.dripSpeed:1,ke=750;(async()=>{let xe=null;for(let je of K){let Ge=typeof je.recordedAt=="number"?je.recordedAt:null;if(xe!==null&&Ge!==null){let ue=Math.min(ke,Math.max(0,(Ge-xe)/Q));ue>0&&await new Promise(oe=>setTimeout(oe,ue))}Ge!==null&&(xe=Ge);try{await l.notify(je.method,Vs(Js(je.params,Ge??void 0),je.seq))}catch{return}}})()}else for(let Q=0;Q<K.length&&!l.isClosed();Q++){let ke=K[Q],xe=l.notify(ke.method,Vs(Js(ke.params,ke.recordedAt),ke.seq)).catch(()=>{});(Q+1)%200===0&&await xe}$.replayPendingPermissions(M);let z=pm($),re=hm($);return{sessionId:$.sessionId,clientId:M.clientId,connectedClients:$.connectedClients(M.clientId),historyPolicy:Y,replayed:K.length,...z?{modes:z}:{},...re?{models:re}:{},configOptions:$.buildConfigOptions(),_meta:mm(e.manager,$,{resurrected:E})}}),l.onRequest("session/detach",async g=>{let h=PC.parse(g),y=u.attached.get(h.sessionId);if(!y)throw he(G.SessionNotFound,"client not attached to that session");let k=e.manager.get(h.sessionId);return k?.detach(y.clientId),u.attached.delete(h.sessionId),k&&e.manager.reapIfOrphanedNonInteractive(h.sessionId),{sessionId:h.sessionId,_meta:{[pt]:{detachStatus:"detached"}}}}),l.onRequest("session/list",async g=>{let h=MC.parse(g??{});return{sessions:(await e.manager.list({cwd:h.cwd})).filter(I=>I.originatingClient?.name!==Aa).map(_C)}}),l.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw he(G.InternalError,"agent registry unavailable");return wc(e.registry)}),l.onRequest("hydra-acp/agents/auth_methods",async g=>{let h=g??{};if(typeof h.agentId!="string"||h.agentId.length===0)throw he(G.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(h.agentId)).authMethods??[]}}),l.onRequest("session/prompt",async g=>{let h=OC.parse(g);f(h.sessionId,"session/prompt");let y=await i0(h,e.manager,x=>{n.log.warn(`session/prompt: dropping unknown sentBy.sessionId=${x} sessionId=${h.sessionId}`)});if(y?.fromSession!==void 0){if((y.depth??0)>3)throw n.log.warn(`session/prompt: refusing depth ${y.depth} chain from ${y.fromSession} to ${h.sessionId}`),he(G.InvalidRequest,`message chain too deep (${y.depth} hops, max ${3}): refusing to continue a session-to-session loop`);if(y.awaiting===!0&&d0(y.fromSession,h.sessionId))throw n.log.warn(`session/prompt: refusing deadlock ${y.fromSession} -> ${h.sessionId}`),he(G.InvalidRequest,`would deadlock: ${h.sessionId} is already blocked waiting on ${y.fromSession}. Send with --no-wait, or let the other turn finish first.`)}let k=u.attached.get(h.sessionId);if(!k)throw n.log.warn(`session/prompt rejected: not attached sessionId=${h.sessionId} attachedKeys=[${[...u.attached.keys()].join(",")}]`),he(G.SessionNotFound,"not attached to session");let S=e.manager.get(h.sessionId);if(!S){let x=await e.manager.loadFromDisk(h.sessionId);if(!x)throw he(G.SessionNotFound,`session ${h.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${h.sessionId}`),S=await Na(e,x);let C=Pi(l,S,u,void 0,k.clientId);await S.attach(C,"none")}let I=y?.awaiting===!0&&y.fromSession!==void 0?a0(y.fromSession,h.sessionId):void 0;try{return await S.prompt(k.clientId,h,y)}finally{I?.()}});let b=g=>{let h;try{h=Lp.parse(g)}catch(S){n.log.warn(`session/cancel: invalid params: ${S.message}`);return}let y=u.attached.get(h.sessionId);if(!y)return;if(y.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${h.sessionId}`);return}let k=e.manager.get(h.sessionId);k&&k.cancel(y.clientId).catch(S=>{n.log.warn(`session/cancel for ${h.sessionId}: ${S.message}`)})};l.onNotification("session/cancel",b),l.onRequest("session/cancel",async g=>{let h=Lp.parse(g);return f(h.sessionId,"session/cancel"),b(g),null}),l.onRequest("hydra-acp/prompt/cancel",async g=>{let h=LC.parse(g);return f(h.sessionId,"hydra-acp/prompt/cancel"),yr(e.manager,h.sessionId).cancelQueuedPrompt(h.messageId)}),l.onRequest("hydra-acp/session/force_cancel",async g=>{let h=Lp.parse(g);return f(h.sessionId,"hydra-acp/session/force_cancel"),yr(e.manager,h.sessionId).forceCancel()}),l.onRequest("hydra-acp/prompt/update",async g=>{let h=NC.parse(g);return f(h.sessionId,"hydra-acp/prompt/update"),yr(e.manager,h.sessionId).updateQueuedPrompt(h.messageId,h.prompt)}),l.onRequest("hydra-acp/prompt/amend",async g=>{let h=DC.parse(g);f(h.sessionId,"hydra-acp/prompt/amend");let y=u.attached.get(h.sessionId);if(!y)throw he(G.SessionNotFound,"not attached to session");return yr(e.manager,h.sessionId).amendPrompt(y.clientId,h)}),l.onRequest("_session/steering",async g=>{let h=HC.parse(g);f(h.sessionId,"_session/steering");let y=u.attached.get(h.sessionId);if(!y)throw he(G.SessionNotFound,"not attached to session");let k=e.manager.get(h.sessionId);if(!k){let S=await e.manager.loadFromDisk(h.sessionId);if(!S)throw he(G.SessionNotFound,`session ${h.sessionId} not found`);k=await Na(e,S);let I=Pi(l,k,u,void 0,y.clientId);await k.attach(I,"none")}return k.steer(y.clientId,h)}),l.onRequest("session/resume",async g=>{let h=g??{},y=typeof h.sessionId=="string"?h.sessionId:void 0;if(!y)throw he(G.InvalidParams,"session/resume requires sessionId");let k=await e.manager.resolveCanonicalId(y)??y,S=e.manager.get(k);if(!S){let $=await e.manager.loadFromDisk(k);if(!$)throw he(G.SessionNotFound,`session ${y} not found in memory or on disk`);S=await Na(e,$)}Kc(u,S,S.sessionId);let I=Pi(l,S,u);await S.attach(I,"pending_only"),u.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:I.clientId,readonly:!1}),S.replayPendingPermissions(I);let x=pm(S),C=hm(S);return{sessionId:S.sessionId,...x?{modes:x}:{},...C?{models:C}:{},configOptions:S.buildConfigOptions(),_meta:mm(e.manager,S,{clientId:I.clientId})}}),l.onRequest("session/load",async g=>{let h=g??{},y=typeof h.sessionId=="string"?h.sessionId:void 0;if(!y)throw he(G.InvalidParams,"session/load requires sessionId");let k=await e.manager.resolveCanonicalId(y)??y,S=e.manager.get(k);if(!S){let E=await e.manager.loadFromDisk(k);if(!E)throw he(G.SessionNotFound,`session ${y} not found in memory or on disk`);S=await Na(e,E)}Kc(u,S,S.sessionId);let I=Pi(l,S,u),{entries:x}=await S.attach(I,"full");u.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:I.clientId,readonly:!1});for(let E of x){if(l.isClosed())break;await l.notify(E.method,Vs(Js(E.params,E.recordedAt),E.seq)).catch(()=>{})}S.replayPendingPermissions(I);let C=pm(S),$=hm(S);return{sessionId:S.sessionId,...C?{modes:C}:{},...$?{models:$}:{},configOptions:S.buildConfigOptions(),_meta:mm(e.manager,S,{clientId:I.clientId})}}),l.onRequest("session/set_model",async g=>{let h=g?.sessionId;typeof h=="string"&&f(h,"session/set_model");let y=sW(g,e.manager);if(y.kind==="error")throw n.log.warn(y.logMessage),he(y.code,y.message);if(y.kind==="no_op")return n.log.warn(y.logMessage),await l.notify("session/update",{sessionId:y.sessionId,update:{sessionUpdate:"_hydra_current_model_update",currentModel:y.currentModel}}).catch(()=>{}),null;n.log.info(y.logMessage);let{modelId:k}=y,S=await y.session.forwardModelChange(k,g);return y.session.applyAgentConfigOptionResponse(S,"model"),y.session.applyModelChange(k),S}),l.onRequest("session/set_mode",async g=>{let h=g,y=h?.sessionId;if(typeof y=="string"&&f(y,"session/set_mode"),!h||typeof h.sessionId!="string")throw he(G.InvalidParams,"session/set_mode requires string sessionId");if(typeof h.modeId!="string")throw he(G.InvalidParams,"session/set_mode requires string modeId");let k=yr(e.manager,h.sessionId),S=await k.forwardRequest("session/set_mode",g);return k.applyModeChange(h.modeId),S}),l.onRequest("session/set_config_option",async g=>{let h=g,y=x=>he(G.InvalidParams,x),k=h?.sessionId;if(typeof k=="string"&&f(k,"session/set_config_option"),!h||typeof h.sessionId!="string")throw y("session/set_config_option requires string sessionId");if(typeof h.configId!="string")throw y("session/set_config_option requires string configId");if(typeof h.value!="string")throw y("session/set_config_option requires string value");let S=yr(e.manager,h.sessionId),I=S.buildConfigOptions().find(x=>x.id===h.configId);if(!I)throw y(`unknown configId ${JSON.stringify(h.configId)} for this session`);if(!I.options.some(x=>x.value===h.value))throw y(`value ${JSON.stringify(h.value)} is not valid for configId ${JSON.stringify(h.configId)}`);switch(h.configId){case"model":{if(h.value!==S.currentModel){let x=await S.forwardModelChange(h.value);S.applyAgentConfigOptionResponse(x,"model")}S.applyModelChange(h.value);break}case"mode":{h.value!==S.currentMode&&await S.forwardRequest("session/set_mode",{sessionId:h.sessionId,modeId:h.value}),S.applyModeChange(h.value);break}case"agent":{h.value!==S.agentId&&await S.setAgent(h.value);break}default:{let x=await S.forwardRequest("session/set_config_option",{sessionId:h.sessionId,configId:h.configId,value:h.value});S.applyAgentConfigOptionResponse(x,h.configId)&&S.broadcastConfigOptions()}}return{configOptions:S.buildConfigOptions()}}),l.setDefaultHandler(async(g,h)=>{let y=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),k=h.startsWith("session/"),S=h.startsWith("hydra-acp/");if(!k&&!S||g===null||typeof g!="object"||y.has(h))throw he(G.MethodNotFound,`Method not found: ${h}`);let I=g.sessionId;if(typeof I!="string")throw he(G.MethodNotFound,`Method not found: ${h}`);return f(I,h),yr(e.manager,I).forwardRequest(h,g)})})}async function tW(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw he(G.InvalidParams,"authenticate requires a non-empty methodId string");let r=t.methodId,s=t._meta?.["hydra-acp"],o=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let p=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let d=a.authMethods??[],c=d.find(p=>p.id===r);if(!c){let p=d.map(m=>m.id);throw he(G.InvalidParams,`authenticate: methodId ${JSON.stringify(r)} is not advertised by agent ${a.agentId}; valid: [${p.map(m=>JSON.stringify(m)).join(", ")}]`)}let l=c._meta?.type,u=(()=>{let p=c._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((c.type??(l==="agent"||l==="terminal"?l:u!==void 0?"terminal":"agent"))==="terminal"){let p=(k,S)=>{if(!Array.isArray(k))throw he(G.InvalidParams,`authenticate: method ${JSON.stringify(r)} ${S} must be a string[]; got ${k===null?"null":typeof k}`);for(let I of k)if(typeof I!="string")throw he(G.InvalidParams,`authenticate: method ${JSON.stringify(r)} ${S} must be string[]; got non-string entry ${JSON.stringify(I)}`);return k},m=await e.manager.planSpawnForAgent(a.agentId),b,g;if(u?.args!==void 0){let k=typeof u.command=="string"?u.command:void 0;b=k!==void 0&&f0.isAbsolute(k)?k:m.command,g=p(u.args,'_meta["terminal-auth"].args')}else{let k=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,S=k!==void 0?p(k.raw,k.label):[];b=m.command,g=[...m.args,...S]}let h={};for(let[k,S]of Object.entries(process.env))typeof S=="string"&&(h[k]=S);Object.assign(h,m.env);let y=u0.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${r}`),{kind:"terminal",command:b,args:g,env:h,cwd:y}}try{return await a.connection.request("authenticate",{methodId:r})}catch(p){throw Ci(p,a)}}async function nW(n,e){let r=(n??{})._meta?.["hydra-acp"],s=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,i=s!==void 0?e.manager.getAgentForSession(s):void 0;if(!i||!i.isAlive()){let a=o??e.defaultAgent;i=await e.manager.bootstrapAgentForAuth(a)}return await i.connection.request("logout",{})}function fm(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(Np,t).catch(()=>{})}}function pm(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(s=>{let o={id:s.id,name:s.name??s.id};return s.description!==void 0&&(o.description=s.description),o});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function hm(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(s=>{let o={modelId:s.modelId};return s.name!==void 0&&(o.name=s.name),s.description!==void 0&&(o.description=s.description),o});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}async function rW(n,e,t,r){return e?await r.isRetiredGeneration(n,e.upstreamSessionId)?{kind:"ignore",logMessage:`session/attach ignoring stale resume hint sessionId=${n} hintUpstream=${e.upstreamSessionId} recordUpstream=${t} (retired generation)`}:{kind:"honor"}:{kind:"none"}}function sW(n,e){if(!n||typeof n!="object")return{kind:"error",code:G.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:G.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:G.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let r=e.get(t.sessionId);if(!r)return{kind:"error",code:G.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let s=r.availableModels(),o=Tc(t.modelId,s);if(o.kind==="none")return{kind:"ok",session:r,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:r,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:r,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=s.map(d=>d.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return r.currentModel!==void 0&&r.currentModel.length>0?{kind:"no_op",session:r,sessionId:t.sessionId,currentModel:r.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(r.currentModel)} agentId=${r.agentId} known=[${i}]`}:{kind:"error",code:G.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${r.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${r.agentId} known=[${i}] (no current model to fall back to)`}}async function oW(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0;if(!s)throw he(G.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw he(G.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw he(G.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return yr(t.manager,s).addTransformer(o),{ok:!0}}async function iW(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0,o=typeof r.reason=="string"?r.reason:void 0;if(!s)throw he(G.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw he(G.InvalidParams,"hydra-acp/attention/set requires string reason");return yr(t.manager,s).setAttentionFlag(e,o,r.payload),{ok:!0}}async function aW(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0,o=typeof r.reason=="string"?r.reason:void 0;if(!s)throw he(G.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw he(G.InvalidParams,"hydra-acp/attention/clear requires string reason");return yr(t.manager,s).clearAttentionFlag(e,o),{ok:!0}}function dW(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,workspace:n.workspace,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:Pa(n.currentUsage),forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels,armedTaskList:[]};return{[pt]:Op(e,t)}}function mm(n,e,t={}){let r=n.liveListEntry(e),s={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),armedTaskList:e.armedBackgroundTasks,...t.resurrected===!0?{resurrected:!0}:{}};return lu(e.agentMeta,Op(r,s))}function cW(){return{protocolVersion:1,agentInfo:{name:"hydra",version:Fe},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:{...lu(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0},side:{selection:!0}}}),steering:{supported:!0}}}}function lW(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let r=e.transformers.resolveChain([t])[0];r&&n.addTransformer(r)}}function h0(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let r of t)r.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function Pi(n,e,t,r,s){return{clientId:s??`cli_${gk(8)}`,connection:n,clientInfo:r}}function Kc(n,e,t){let r=n.attached.get(t);r&&(e.detach(r.clientId),n.attached.delete(t))}var gm=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,r,s=new Promise((i,a)=>{t=i,r=a});s.catch(()=>{});let o={session:void 0,sessionReady:s,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),r(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:r}=this.reserve(e);r(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let r=this.byToken.get(e);r!==void 0&&r.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let r of t.disposers)try{await r()}catch{}}}size(){return this.byToken.size}};import{randomUUID as uW}from"crypto";import{McpServer as fW}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as pW}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Mn}from"zod";function yk(n){if(n.method!=="session/update")return null;let t=n.params?.update;return!t||typeof t.sessionUpdate!="string"?null:{kind:t.sessionUpdate,update:t}}function sr(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var m0="Bearer ";function Gc(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(m0))return;let t=e.slice(m0.length).trim();return t.length>0?t:void 0}function hW(n){let e=new fW({name:"hydra-acp-stdin",version:"1.0.0"},{instructions:"Piped input from `hydra cat --stream` is exposed here as a byte stream. Use `tail` for the latest N bytes (good for finding the end of a log), `head` for the first N bytes (good for headers/preamble), `read` for windowed reads against an absolute byte cursor, `wait_for_more` to block until new bytes arrive past a cursor, and `info` for the current cursors/capacity/closed status. Byte payloads come back base64-encoded."});return e.registerTool("tail",{description:"Return the most recent `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means older bytes existed but have been evicted from the ring.",inputSchema:{bytes:Mn.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let r=n.streamTail(t);return sr(r)}),e.registerTool("head",{description:"Return the first `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means the head has already been evicted from the ring and the returned bytes start at the oldest still-resident cursor.",inputSchema:{bytes:Mn.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let r=n.streamHead(t);return sr(r)}),e.registerTool("read",{description:"Read up to `max_bytes` bytes starting at absolute byte `cursor`. Returns `{bytes, nextCursor, gap?, eof?}` \u2014 `gap` is the number of bytes silently skipped because the ring had evicted them; `eof:true` means the producer closed and there is nothing left to read.",inputSchema:{cursor:Mn.number().int().min(0).describe("Absolute byte offset to start reading from. Use 0 to read from the very beginning (may produce a gap if old bytes have been evicted)."),max_bytes:Mn.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Mn.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:r,wait_ms:s})=>{let o=await n.streamRead(t,r,s);return sr(o)}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:Mn.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Mn.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:r})=>{let s=await n.streamWaitFor(t,r),o=n.streamInfo();return sr({outcome:s,writeCursor:o.writeCursor,closed:o.closed})}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:Mn.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Mn.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Mn.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Mn.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Mn.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Mn.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Mn.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Mn.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Mn.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let r={pattern:t.pattern};t.regex!==void 0&&(r.regex=t.regex),t.case_insensitive!==void 0&&(r.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(r.invert=t.invert),t.max_matches!==void 0&&(r.maxMatches=t.max_matches),t.max_bytes!==void 0&&(r.maxBytes=t.max_bytes),t.context_before!==void 0&&(r.contextBefore=t.context_before),t.context_after!==void 0&&(r.contextAfter=t.context_after),t.cursor!==void 0&&(r.cursor=t.cursor);let s=n.streamGrep(r);return sr(s)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return sr(t)}),e}var mW=1e4;function g0(n,e){let t=new Map;async function r(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=hW(a),l=new pW({sessionIdGenerator:()=>uW()});await c.connect(l);let u={server:c,transport:l};return t.set(i,u),e.addDisposer(i,async()=>{t.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function s(i,a){let d=Gc(i);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(c.session!==void 0)l=c.session;else{let f,p=new Promise(b=>{f=setTimeout(()=>b(void 0),mW)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),m===void 0){a.code(503).send({error:"session not ready"});return}l=m}let u=await r(d,l);a.hijack(),await u.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)}),n.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)}),n.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)})}th();import{randomUUID as gW}from"crypto";import{McpServer as yW}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as wW}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as oo}from"zod";function bW(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}var y0=2e3,w0=2e4;function kW(n,e,t){if(e!=="tool_call"&&e!=="tool_call_update")return Pc([n]);let r=[],s=gu(t);s!==void 0?r.push(`Tool: ${s}`):typeof t.title=="string"&&t.title.length>0&&r.push(`Tool: ${t.title}`);let o=t.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[a,d]of Object.entries(o))typeof d=="string"&&d.length>0&&r.push(`${a}=${d}`);if(Array.isArray(t.locations))for(let a of t.locations)typeof a?.path=="string"&&a.path.length>0&&r.push(a.path);let i=eh(t);return i!==void 0&&r.push(i),r.join(`
418
- `)}function vW(n,e){if(n.length<=148)return n;let s=Math.floor(148/2),o=e-s;o<0&&(o=0);let i=o+148;i>n.length&&(o=n.length-148,o<0&&(o=0));let a=n.slice(o,i);return o>0&&(a="\u2026"+a),i<n.length&&(a=a+"\u2026"),a}function SW(n){let e=new yW({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Covers assistant and user messages, the arguments of every tool call including full shell commands, and what those calls printed. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:oo.string().min(1).describe("Case-insensitive substring to search for."),limit:oo.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:oo.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:r=10,include_tool_calls:s=!0})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return sr({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let i=[],a=t.toLowerCase();for await(let{entryId:c,entry:l}of o.iterRecallNewestFirst()){let u=yk(l);if(!u)continue;let{kind:f,update:p}=u;if((f==="tool_call"||f==="tool_call_update")&&!s)continue;let m=kW(l,f,p),b=m.toLowerCase().indexOf(a);if(b<0)continue;let g=bW(f),h=vW(m,b),y=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(i.push({entryId:c,speaker:g,snippet:h,timestamp:y}),i.length>=r)break}i.sort((c,l)=>c.entryId-l.entryId);let d=i.length>=r;return sr({matches:i,total_matched:i.length,truncated:d})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history, including each tool call's arguments and what it printed. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:oo.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:oo.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:r})=>{let s=await n();if(!s.summarizedThroughEntry||s.summarizedThroughEntry===0)return sr({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. `range` retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(r<t)throw new Error(`range: to_entry (${r}) must be >= from_entry (${t})`);let o=r-t+1;if(o>50)throw new Error(`range: range size (${o}) exceeds maximum of 50 entries`);let i=await s.getRecallTotalCount();if(i===0)return sr({text:"",entry_count:0,truncated:!1});let a=Math.min(t,i-1),d=Math.min(r,i-1),c=a>t||d<r;if(a>d)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:c}};let l=await s.sliceRecallHistory(a,d),u=Pc(l,{toolOutput:{maxPerCall:y0,maxTotal:w0}});return{content:[{type:"text",text:u}],structuredContent:{text:u,entry_count:l.length,truncated:c}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name, ACP kind, and/or file path. Returns when each tool was called, its arguments (including the full shell command), the result status, and what the call printed. Use this to recall which files were read/edited, what shell commands ran, and what they output.",inputSchema:{tool_name:oo.string().optional().describe("Case-insensitive substring of the tool name. Names vary by agent for the same tool (Bash, Terminal, bash), so prefer `kind` when you want every shell invocation."),kind:oo.string().optional().describe("ACP tool kind: execute (shell), read, edit, think, other. Agent-independent, unlike tool_name."),file_path:oo.string().optional(),limit:oo.number().int().min(1).max(100).optional(),include_output:oo.boolean().optional().describe("Include what each call printed (default true). Set false when you only need the commands and not their results.")}},async({tool_name:t,kind:r,file_path:s,limit:o=20,include_output:i=!0})=>{let a=await n();if(!a.summarizedThroughEntry||a.summarizedThroughEntry===0)return sr({calls:[],truncated:!1,note:"This session has no compacted history. `tool_calls` retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let d=typeof t=="string"&&t.length>0,c=typeof r=="string"&&r.length>0,l=typeof s=="string"&&s.length>0;if(!d&&!c&&!l)throw new Error("tool_calls: at least one of tool_name, kind, or file_path must be provided");let u=new Map,f=Math.max(o*4,200);for await(let{entryId:y,entry:k}of a.iterRecallNewestFirst()){let S=yk(k);if(!S)continue;let{kind:I,update:x}=S;if(I!=="tool_call"&&I!=="tool_call_update")continue;let C=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:`__noid_${y}`,$=u.get(C);if($||($={entryId:y,toolName:"(unnamed)",nameAuthoritative:!1,rawInput:{},locations:[],status:"in_progress"},u.set(C,$)),y<$.entryId&&($.entryId=y),!$.nameAuthoritative){let M=gu(x);M!==void 0?($.toolName=M,$.nameAuthoritative=!0):typeof x.name=="string"&&x.name.length>0?($.toolName=x.name,$.nameAuthoritative=!0):I==="tool_call"&&typeof x.title=="string"&&x.title.length>0&&($.toolName=x.title,$.nameAuthoritative=!0)}if($.kind===void 0&&typeof x.kind=="string"&&x.kind.length>0&&($.kind=x.kind),$.output===void 0){let M=eh(x);M!==void 0&&($.output=M)}let E=x.rawInput;if(E&&typeof E=="object"&&!Array.isArray(E)&&Object.keys(E).length>0)for(let[M,F]of Object.entries(E))$.rawInput[M]===void 0&&($.rawInput[M]=F);if(Array.isArray(x.locations))for(let M of x.locations){let F=M?.path;typeof F=="string"&&F.length>0&&!$.locations.includes(F)&&$.locations.push(F)}if(typeof x.status=="string"&&$.status==="in_progress"&&($.status=x.status),k.recordedAt!==void 0&&$.timestamp===void 0&&($.timestamp=String(k.recordedAt)),u.size>=f)break}let p=[...u.keys()].sort((y,k)=>u.get(y).entryId-u.get(k).entryId),m=[],b=w0,g=!1;for(let y of p){let k=u.get(y);if(k.toolName=ub({name:k.toolName,rawInput:k.rawInput,...k.kind!==void 0?{kind:k.kind}:{}}),d&&!k.toolName.toLowerCase().includes(t.toLowerCase())||c&&(k.kind??"").toLowerCase()!==r.toLowerCase())continue;if(l){let x=s.toLowerCase(),C=["file_path","filePath","path"],$=!1;for(let E of C){let M=k.rawInput[E];if(typeof M=="string"&&M.toLowerCase().includes(x)){$=!0;break}}if(!$){for(let E of k.locations)if(E.toLowerCase().includes(x)){$=!0;break}}if(!$)continue}let S={};for(let[x,C]of Object.entries(k.rawInput))typeof C=="string"?S[x]=C.length>500?C.slice(0,497)+"\u2026":C:(typeof C=="number"||typeof C=="boolean")&&(S[x]=C);k.locations.length>0&&S.locations===void 0&&(S.locations=k.locations);let I={entryId:k.entryId,tool:k.toolName,args:S,status:k.status,timestamp:k.timestamp};if(k.kind!==void 0&&(I.kind=k.kind),i&&k.output!==void 0){let x=k.output,C=Math.min(y0,b);if(C<=0)g=!0;else{let $=x.length<=C?x:x.slice(0,C-1)+"\u2026";I.output=$,I.outputBytes=x.length,I.outputTruncated=$.length<x.length,b-=$.length}}if(m.push(I),m.length>=o)break}let h=m.length>=o;return sr({calls:m,truncated:h,...g?{outputBudgetExhausted:g}:{}})}),e}var xW=1e4;function b0(n,e){let t=new Map;async function r(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=SW(a),l=new wW({sessionIdGenerator:()=>gW()});await c.connect(l);let u={server:c,transport:l};return t.set(i,u),e.addDisposer(i,async()=>{t.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function s(i,a){let d=Gc(i);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown recall token"});return}let u=await r(d,async()=>{if(c.session!==void 0)return c.session;let f,p=new Promise(b=>{f=setTimeout(()=>b(void 0),xW)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await u.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)}),n.get("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)}),n.delete("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)})}var ym=class{byName=new Map;changeHandlers=[];register(e,t,r,s){this.byName.set(e,{connection:t,instructions:r,tools:[...s]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let r of this.changeHandlers)try{r(e,t)}catch{}}};import{StreamableHTTPServerTransport as MW}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as _W}from"crypto";import{Server as IW}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as CW,ListToolsRequestSchema as RW}from"@modelcontextprotocol/sdk/types.js";function k0(n,e,t,r){let s=typeof t=="function"?async()=>t():async()=>t,o=new IW({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return o.setRequestHandler(RW,async()=>{let a=r?.peekSessionId?.();if(a!==void 0&&r?.fetchSessionTools!==void 0)try{let d=await r.fetchSessionTools(a);if(d!==void 0)return{tools:d.map(i)}}catch{}return{tools:e.tools.map(i)}}),o.setRequestHandler(CW,async(a,d)=>{let c=a.params.name,l=d._meta?.progressToken??d.requestId,u=TW(l,d.sendNotification);try{let f=await s(),p=await EW(e.connection,n,c,a.params.arguments??{},f);return PW(p,c)}catch(f){return wk(f instanceof Error?f.message:String(f))}finally{u()}}),o}var AW=15e3;function TW(n,e,t=AW){if(n===void 0)return()=>{};let r=0,s=setInterval(()=>{r+=1,e({method:"notifications/progress",params:{progressToken:n,progress:r}}).catch(()=>{})},t);return s.unref?.(),()=>clearInterval(s)}async function EW(n,e,t,r,s){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:r,sessionId:s})}function PW(n,e){if(n===null||typeof n!="object")return wk(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:wk(`extension ${e} omitted content array`)}function wk(n){return{content:[{type:"text",text:n}],isError:!0}}var $W=1e4;function v0(n,e,t){let r=new Map;async function s(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function o(l){for(let u of r.values()){let f=u.get(l);f!==void 0&&(u.delete(l),s(f))}}async function i(l,u){for(let[f,p]of r){if(e.lookup(f)?.session?.sessionId!==l)continue;let b=p.get(u);if(b!==void 0)try{await b.server.sendToolListChanged()}catch{}}}t.onChange(l=>{o(l)});async function a(l,u){let f=r.get(l);f===void 0&&(f=new Map,r.set(l,f),e.addDisposer(l,async()=>{let S=r.get(l);if(S!==void 0){r.delete(l);for(let I of S.values())await s(I)}}));let p=f.get(u);if(p!==void 0)return p.transport;let m=t.lookup(u);if(m===void 0)return;let y=k0(u,m,async()=>{let S=e.lookup(l);if(S===void 0)throw new Error("mcp token no longer bound");if(S.session!==void 0)return S.session.sessionId;let I,x=new Promise($=>{I=setTimeout(()=>$(void 0),$W)}),C=await Promise.race([S.sessionReady.catch(()=>{}),x]);if(I!==void 0&&clearTimeout(I),C===void 0)throw new Error("session not ready");return C.sessionId},{peekSessionId:()=>e.lookup(l)?.session?.sessionId,fetchSessionTools:async S=>{let I=await m.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:S});if(!I||typeof I!="object")return;let x=I.tools;if(!Array.isArray(x))return;let C=[];for(let $ of x){if(!$||typeof $!="object")continue;let E=$;if(typeof E.name!="string"||E.name.length===0||typeof E.description!="string"||E.inputSchema===null||typeof E.inputSchema!="object")continue;let M={name:E.name,description:E.description,inputSchema:E.inputSchema};E.outputSchema!==null&&typeof E.outputSchema=="object"&&(M.outputSchema=E.outputSchema),C.push(M)}return C}}),k=new MW({sessionIdGenerator:()=>_W()});return await y.connect(k),f.set(u,{server:y,transport:k}),k}async function d(l,u){let f=Gc(l);if(f===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){u.code(404).send({error:"unknown mcp token"});return}let m=l.params.name,b=await a(f,m);if(b===void 0){u.code(404).send({error:`unknown mcp server: ${m}`});return}u.hijack(),await b.handleRequest(l.raw,u.raw,l.body)}let c={config:{skipAuth:!0}};return n.post("/mcp/:name",c,async(l,u)=>{await d(l,u)}),n.get("/mcp/:name",c,async(l,u)=>{await d(l,u)}),n.delete("/mcp/:name",c,async(l,u)=>{await d(l,u)}),{notifyToolListChanged:i}}async function A0(n,e){BW(n),iu(n.daemon.scrubEnv);let t=n,r=n.daemon.tls?await io.readFile(Ze(n.daemon.tls.key)):void 0,s=n.daemon.tls?await io.readFile(Ze(n.daemon.tls.cert)):void 0;await io.mkdir(D.home(),{recursive:!0});let{stream:o,fileStream:i}=await DW(n.daemon.logLevel),a=OW({logger:{level:n.daemon.logLevel,stream:o},bodyLimit:256*1024*1024});await a.register(FW,{options:{handleProtocols:ZI}}),$w(X=>{a.log.info(X)}),Lw(X=>{a.log.info(X)});let d=await jh.load(),c=await sm.load();Ql(),tw(c);let l=new um(c);l.start();let u=new tm(c);u.start();let f=new Jh,p=new Gh,m=new qh(e),b=new Kh([m,new zh(d),p]),g=pT({validator:b});a.addHook("onRequest",async(X,Et)=>{X.routeOptions.config?.skipAuth||X.url==="/acp"||X.url?.startsWith("/acp?")||(await g(X,Et),!Et.sent&&X.authIdentity?.startsWith("script:")&&!mT(X.method,X.routeOptions.url)&&Et.code(403).send({error:"script tokens may only access read-only session data"}))});let h=setInterval(()=>{d.sweepExpired()},300*1e3);h.unref();let y=setInterval(()=>{f.sweepExpired()},300*1e3);y.unref();let k=new Mp(n,{onFetched:()=>{eT(k,C)},onStaleFallback:(X,Et)=>{let Sr=Math.round(Et/36e5),gn=Sr>=48?`${Math.round(Sr/24)}d`:`${Sr}h`;a.log.warn(`registry fetch failed (${X.message}); serving stale cache last synced ${gn} ago; agent versions may be outdated ('hydra registry refresh' to retry)`)}});sk(X=>a.log.info(X));let S={info:X=>a.log.info(X),warn:X=>a.log.warn(X)},I=X=>bi.spawn({...X,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:S});oC(n.compressToolContent);let x=new Uh,C=new Mh(k,I,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,orphanTimeoutMs:n.daemon.nonInteractiveOrphanTimeoutSeconds*1e3,sessionDefaults:n.sessionDefaults,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,compactionAgent:n.compaction?.agent,compactionModel:n.compaction?.model,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,sessionHistoryArchiveMaxBytes:n.daemon.sessionHistoryArchiveMaxBytes,sessionHistoryArchiveTiers:n.daemon.sessionHistoryArchiveTiers,logger:S,npmRegistry:n.npmRegistry,extensionCommands:x,defaultCwd:n.defaultCwd,disableWorkspaceSnapshots:n.disableWorkspaceSnapshots}),$=new lm(c,void 0,{resolvesLocally:async X=>await C.resolveCanonicalId(X)!==void 0,cache:u}),E=new Hh(Uy(n),void 0,{tokenRegistry:p}),M=new Bh(Wy(n),void 0,{tokenRegistry:p}),F=[];NT(a,Fe,Ri(n),()=>F);let K=new Date().toISOString();qT(a,K);let Y=new gm,z=new ym,re,Q=()=>{if(re!==void 0)return re;let X=a.server.address();return re=`http://127.0.0.1:${X&&typeof X=="object"?X.port:n.daemon.port}`,re},ke={agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction};FT(a,C,ke,{extensionMcp:z,mcpTokenRegistry:Y,getDaemonOrigin:Q},c,u),PT(a,{store:c,localMiss:{resolvesLocally:async X=>await C.resolveCanonicalId(X)!==void 0,cache:u}}),LT(a,k,C,{npmRegistry:n.npmRegistry}),zT(a,E),KT(a,M);let xe={host:n.daemon.host,port:n.daemon.port,...n.daemon.publicHost!==void 0?{publicHost:n.daemon.publicHost}:{},...n.daemon.tls?{tls:{cert:Ze(n.daemon.tls.cert),key:Ze(n.daemon.tls.key)}}:{}};GT(a,()=>({defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,sessionDefaults:{...t.sessionDefaults},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers],listen:xe})),e0(a,{store:d,rateLimiter:f,staticTokenValidator:m}),t0(a,{store:c,health:l}),o0(a,{processRegistry:p}),g0(a,Y),b0(a,Y);let je=v0(a,Y,z);p0(a,{validator:b,manager:C,defaultAgent:n.defaultAgent,processRegistry:p,onExtensionVersion:(X,Et)=>E.reportVersion(X,Et),onTransformerVersion:(X,Et)=>M.reportVersion(X,Et),transformers:M,extensionCommands:x,mcpTokenRegistry:Y,extensionMcp:z,extensionMcpControls:je,getDaemonOrigin:Q,registry:k,foreignSessions:$});let Ge=!!n.daemon.tls;await a.listen({host:Ge?"127.0.0.1":n.daemon.host,port:Ge?0:n.daemon.port});let ue=a.server.address(),oe=ue&&typeof ue=="object"?ue.port:n.daemon.port,$e,lt=n.daemon.host,Tt=oe;if(Ge&&r&&s){$e=await HW({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:oe,tlsOptions:{key:r,cert:s},logger:a.log});let X=$e.address();X&&typeof X=="object"&&(Tt=X.port)}await io.mkdir(D.home(),{recursive:!0}),await tI({pid:process.pid,host:lt,port:Tt,loopbackPort:oe,startedAt:K});let Me={daemonUrl:`http://127.0.0.1:${oe}`,daemonHost:"127.0.0.1",daemonPort:oe,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${oe}/acp`,hydraHome:D.home()};E.setContext(Me),M.setContext(Me),await E.start(),await M.start();try{await C.reconcilePermissionFlags()}catch(X){a.log.warn(`permission flag reconcile failed: ${X.message}`)}try{await C.seedSessionIndex()}catch(X){a.log.warn(`session index seed failed: ${X.message}`)}C.resurrectPendingQueues().catch(X=>{a.log.warn(`queue replay scan failed: ${X.message}`)}),C.resumePendingCompactions().catch(X=>{a.log.warn(`compaction resume scan failed: ${X.message}`)}),C.resumePendingAgentSwaps().catch(X=>{a.log.warn(`agent-swap resume scan failed: ${X.message}`)});let Jt=n.daemon.agentSyncIntervalMinutes*60*1e3,Ye=Jt>0?tT({registry:k,manager:C,intervalMs:Jt,logger:S}):void 0,As=n.daemon.sessionGcIntervalMinutes*60*1e3,Ki=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Kn=As>0?nT({manager:C,intervalMs:As,maxAgeMs:Ki,logger:S}):void 0,Ts=iT({bootConfig:n,apply:X=>{t=X,k.setConfig(X),C.setLiveConfig({sessionDefaults:X.sessionDefaults}),ke.agentId=X.defaultAgent,ke.cwd=X.defaultCwd,iu(X.daemon.scrubEnv)},onDrift:X=>{F=X},logger:S});return{app:a,manager:C,registry:k,extensions:E,transformers:M,mcpTokenRegistry:Y,extensionMcp:z,processRegistry:p,shutdown:async()=>{l.stop(),u.stop(),Ts(),Kn&&Kn(),Ye&&Ye(),clearInterval(h),clearInterval(y);let X=async(Et,Sr)=>{try{await Sr()}catch(gn){a.log.warn(`shutdown step ${Et} failed: ${gn instanceof Error?gn.message:String(gn)}`)}};await X("sessionTokenStore.flush",()=>d.flush()),await X("extensions.stop",()=>E.stop()),await X("transformers.stop",()=>M.stop()),await X("manager.closeAll",()=>C.closeAll()),await X("manager.flushSynopsis",()=>C.flushSynopsis(3e4)),await X("manager.shutdownSynopsis",()=>C.shutdownSynopsis()),await X("manager.flushMetaWrites",()=>C.flushMetaWrites()),await X("manager.flushHistoryWrites",()=>C.flushHistoryWrites()),$w(null),Lw(null),sk(null),$e&&await X("tlsTerminator.close",()=>new Promise(Et=>$e.close(()=>Et()))),await X("app.close",()=>a.close());try{I0.unlinkSync(D.pidFile())}catch{}await X("fileStream.flushSync",()=>i.flushSync())}}}var x0=20;async function NW(n,e){let t=Jc.dirname(n),r=Jc.basename(n,".log"),s=new RegExp(`^${r}\\.(\\d+)\\.log$`),o;try{o=await io.readdir(t)}catch{return}let i=[];for(let d of o){let c=d.match(s);c&&i.push({name:d,n:Number(c[1])})}if(i.length<=e)return;i.sort((d,c)=>d.n-c.n);let a=i.slice(0,i.length-e);await Promise.allSettled(a.map(d=>io.unlink(Jc.join(t,d.name))))}async function DW(n){await NW(D.logFile(),x0);let e=await LW({file:D.logFile(),size:"10m",mkdir:!0,symlink:Fh,limit:{count:x0,removeOtherLogFiles:!0}}),t=S0.destination(2);return{stream:S0.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}async function HW(n){let e=R0.createServer(n.tlsOptions,t=>{let r=C0.connect({host:n.upstreamHost,port:n.upstreamPort}),s=!1,o=i=>{if(!s){s=!0,i&&n.logger.warn(`tls terminator forwarder error: ${i.message??String(i)}`);try{t.destroy()}catch{}try{r.destroy()}catch{}}};t.on("error",o),r.on("error",o),t.on("close",()=>o()),r.on("close",()=>o()),t.pipe(r),r.pipe(t)});return e.on("tlsClientError",t=>{n.logger.warn(`tls handshake error: ${t.message}`)}),await new Promise((t,r)=>{let s=o=>{r(new Error(`TLS listener could not bind ${n.listenHost}:${n.listenPort}: ${o.message}`))};e.once("error",s),e.listen({host:n.listenHost,port:n.listenPort},()=>{e.off("error",s),t()})}),e.on("error",t=>{n.logger.warn(`tls terminator error: ${t.message}`)}),e}function BW(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}Ba();rr();Bc();Gu();async function $0(n={}){let e=await Pr(),t=await Wl();if(await wm(e)){let s=await Qc();process.stdout.write(`Daemon already running${s?` (pid ${s.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
411
+ `))n.push(o);n.push(s)}function Wu(n){return n.replace(new RegExp(kT,"g"),e=>e.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}function ck(n){return n.toLocaleString("en-US")}fn();rr();Mr();em();qd();import{randomBytes as ET}from"crypto";function TT(n){let e=ET(32).toString("hex");return n.tokenRegistry.reserve(e).complete(n.session),n.session.onClose(()=>{n.tokenRegistry.unbind(e)}),{name:n.name,type:"http",url:`${n.getOrigin()}/mcp/${n.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function lk(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async r=>{let s=[...n.baselineMcpServers??[]];n.stdinEnabled&&s.push(TT({name:"hydra-acp-stdin",session:r,tokenRegistry:e,getOrigin:t})),s.push(TT({name:"hydra-acp-recall",session:r,tokenRegistry:e,getOrigin:t}));let o=qc(n.deps);return o!==void 0&&(o.bindToSession(r),s=[...s,...o.descriptors]),s}}function qc(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=ET(32).toString("hex"),r=n.mcpTokenRegistry.reserve(t),s=n.getDaemonOrigin(),o=e.map(a=>({name:a,type:"http",url:`${s}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),i=n.mcpTokenRegistry;return{descriptors:o,bindToSession:a=>{r.complete(a),a.onClose(()=>{i.unbind(t)})},abandon:a=>r.abandon(a)}}et();Mr();mu();mr();var SU=new Set(["/v1/sessions/:id/history","/v1/sessions/:id/events"]);function PT(n,e){let t=e.fetchImpl??fetch;n.addHook("preHandler",async(r,s)=>{let o=r.routeOptions.url;if(!o||!o.startsWith("/v1/sessions/:id"))return;let i=r.params,a=i.id;if(typeof a!="string")return;let d=eo(a);if(!d){if(!e.localMiss||await e.localMiss.resolvesLocally(a))return;let h=e.localMiss.cache.findByLocalId(a);if(h.length===0)return;if(h.length>1){s.code(404).send({error:`Session "${a}" exists on more than one remote (${h.map(y=>y.name).join(", ")}). Address it as "<remote>:${a}".`});return}d=h[0]}let c=e.store.get(d.name);if(!c){s.code(404).send({error:`No remote named "${d.name}". Run \`hydra remote add\` first.`});return}let l=r.query;if(SU.has(o)&&IU(l?.follow)){let h=c.port===un?"":`:${c.port}`;s.code(501).send({error:`Streaming a federated session isn't supported yet. Attach directly with hydra://${c.host}${h}/${d.localId} instead.`});return}let u=CU(o,i,d.localId,r.url),p=`${Nt(c.host)?"http":"https"}://${c.host}:${c.port}${u}`,m;try{m=await t(p,{method:r.method,headers:{Authorization:`Bearer ${c.token}`,...r.body!==void 0?{"Content-Type":"application/json"}:{}},...r.body!==void 0&&r.method!=="GET"?{body:JSON.stringify(r.body)}:{}})}catch(h){s.code(502).send({error:`Could not reach remote "${d.name}" (${c.host}:${c.port}): ${h.message}`});return}if(r.method==="DELETE"&&o==="/v1/sessions/:id"&&(m.ok||m.status===404)&&e.localMiss?.cache.evict(d.name,d.localId),m.status===204){s.code(204).send();return}let b=await m.text(),g=m.headers.get("content-type");g&&s.header("content-type",g),s.code(m.status).send(b)})}var xU=5e3,tm=class{constructor(e,t={}){this.store=e;this.opts=t}store;opts;perPeer=new Map;timer;start(){this.timer||(this.refreshNow(),this.timer=setInterval(()=>{this.refreshNow()},this.opts.intervalMs??xU),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}async refreshNow(){let e=this.opts.fetchImpl??fetch,t=new Set(this.store.list().map(r=>r.name));for(let r of[...this.perPeer.keys()])t.has(r)||this.perPeer.delete(r);await Promise.allSettled(this.store.list().map(async r=>{let s=this.store.get(r.name);if(!s)return;let o=this.perPeer.get(r.name),i=Nt(s.host)?"http":"https",a=new URLSearchParams({includeNonInteractive:"1"}),d=o?.cursor!==void 0;d&&a.set("since",String(o.cursor));let c=`${i}://${s.host}:${s.port}/v1/sessions?${a.toString()}`,l;try{l=await e(c,{headers:{Authorization:`Bearer ${s.token}`}})}catch{return}if(!l.ok)return;let u=await l.json(),f=o?.sessions??new Map;if(d){for(let[p,m]of[...f])m.status!=="cold"&&f.delete(p);for(let p of u.removed??[])f.delete(Zs({name:r.name,localId:p}))}else f.clear();for(let p of u.sessions??[]){let m=Zs({name:r.name,localId:String(p.sessionId)});f.set(m,{...p,sessionId:m,remote:r.name})}this.perPeer.set(r.name,{cursor:u.cursor,sessions:f})}))}list(e){let t=[];for(let r of this.perPeer.values())t.push(...r.sessions.values());return t.filter(r=>!(e.status&&r.status!==e.status||!e.includeNonInteractive&&r.interactive!==!0))}evict(e,t){this.perPeer.get(e)?.sessions.delete(Zs({name:e,localId:t}))}findByLocalId(e){let t=e.startsWith(Yt)?[e]:[e,Yt+e],r=[];for(let[s,o]of this.perPeer)for(let i of t)if(o.sessions.has(Zs({name:s,localId:i}))){r.push({name:s,localId:i});break}return r}};async function MT(n,e,t,r=fetch){let s=n.get(e);if(!s)return{status:404,body:{error:`No remote named "${e}". Run \`hydra remote add\` first.`}};let i=`${Nt(s.host)?"http":"https"}://${s.host}:${s.port}/v1/sessions`,a;try{a=await r(i,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(u){return{status:502,body:{error:`Could not reach remote "${e}" (${s.host}:${s.port}): ${u.message}`}}}let d=await a.text(),c=null;try{c=d.length>0?JSON.parse(d):null}catch{c=null}if(!a.ok)return{status:a.status,body:c};let l=c;return l&&typeof l.sessionId=="string"?{status:a.status,body:{...l,sessionId:Zs({name:e,localId:l.sessionId})}}:{status:a.status,body:c}}async function _T(n,e,t=fetch){let r;if(e.sessionIds===void 0)r=n.list().map(a=>({name:a.name}));else{let a=new Map;for(let d of e.sessionIds){let c=eo(d);if(!c)continue;let l=a.get(c.name)??[];l.push(c.localId),a.set(c.name,l)}r=[...a.entries()].map(([d,c])=>({name:d,sessionIds:c}))}if(r.length===0)return{query:e.q,truncated:!1,results:[]};let s=await Promise.all(r.map(async a=>{let d=n.get(a.name);if(!d)return null;let l=`${Nt(d.host)?"http":"https"}://${d.host}:${d.port}/v1/sessions/search`,u;try{u=await t(l,{method:"POST",headers:{Authorization:`Bearer ${d.token}`,"Content-Type":"application/json"},body:JSON.stringify({q:e.q,...a.sessionIds?{sessionIds:a.sessionIds}:{},...e.snippetWidth!==void 0?{snippetWidth:e.snippetWidth}:{}})})}catch{return null}if(!u.ok)return null;let f;try{f=await u.json()}catch{return null}let p=f;if(!p||!Array.isArray(p.results))return null;let m=p.results.map(b=>({...b,sessionId:Zs({name:a.name,localId:b.sessionId})}));return{query:e.q,truncated:p.truncated===!0,results:m}})),o=[],i=!1;for(let a of s)a!==null&&(o.push(...a.results),i=i||a.truncated);return{query:e.q,truncated:i,results:o}}function IU(n){return n==="1"||n==="true"||n===!0}function CU(n,e,t,r){let s=n.replace(/:([A-Za-z_]+)/g,(i,a)=>encodeURIComponent(a==="id"?t:e[a]??"")),o=r.indexOf("?");return o===-1?s:s+r.slice(o)}var nm=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function $T(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Nt(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function FT(n,e,t,r={},s,o){n.get("/v1/sessions",async(f,p)=>{let m=f.query,b=m?.includeNonInteractive==="1"||m?.includeNonInteractive==="true",g;if(m?.since!==void 0&&(g=Number(m.since),!Number.isFinite(g)||g<0))return p.code(400).send({error:`since must be a non-negative number, got ${JSON.stringify(m.since)}`});let h=m?.status==="warm"||m?.status==="cold"?m.status:void 0,y={cwd:m?.cwd,includeNonInteractive:b,...h?{status:h}:{}},k=o&&!y.cwd?o.list({includeNonInteractive:b,...h?{status:h}:{}}):[];if(g!==void 0){let I=await e.listSince(y,g);return{sessions:[...I.entries,...k],removed:I.removed,cursor:I.cursor}}let S=await e.listing(y);return{sessions:[...S.entries,...k],removed:[],cursor:S.cursor}}),n.get("/v1/sessions/:id",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=await e.getOne(b);return g||(p.code(404).send({error:"session not found"}),p)}),n.post("/v1/sessions/search",async(f,p)=>{let m=f.body??{},b=typeof m.q=="string"?m.q:"";if(b.trim().length===0)return p.code(400).send({error:"q is required"}),p;let g=Array.isArray(m.sessionIds)?m.sessionIds.filter(S=>typeof S=="string"&&S.length>0):void 0,h={sessionIds:g};typeof m.snippetWidth=="number"&&(h.snippetWidth=m.snippetWidth);let y=await AT(e,b,h);if(!s)return y;let k=await _T(s,{q:b,...g?{sessionIds:g}:{},...h.snippetWidth!==void 0?{snippetWidth:h.snippetWidth}:{}});return{query:b,truncated:y.truncated||k.truncated,results:[...y.results,...k.results]}}),n.post("/v1/sessions",async(f,p)=>{let m=f.body??{};if(m.remote){if(!s)return p.code(404).send({error:`No remote named "${m.remote}". Run \`hydra remote add\` first.`});let S=await MT(s,m.remote,{cwd:m.cwd,agentId:m.agentId,mcpServers:m.mcpServers,workspace:m.workspace});return p.code(S.status).send(S.body)}let b=Ze(m.cwd??t.cwd),g=await jd(b),h=m.agentId??g.agentId??t.agentId,y=qc(r),k=y!==void 0?[...m.mcpServers??[],...y.descriptors]:m.mcpServers;try{let S=await e.create({cwd:b,agentId:h,mcpServers:k,...m.workspace!==void 0?{workspace:m.workspace}:{}});y!==void 0&&y.bindToSession(S),p.code(201).send({sessionId:S.sessionId,agentId:S.agentId,cwd:S.cwd,...S.workspace!==void 0?{workspace:S.workspace}:{},...S.workspaceError!==void 0?{workspaceError:S.workspaceError}:{}})}catch(S){y!==void 0&&y.abandon(S instanceof Error?S:void 0),p.code(500).send({error:S.message})}}),n.post("/v1/sessions/collect",async(f,p)=>{let m=f.body??{},b=typeof m.maxAgeDays=="number"&&m.maxAgeDays>0?m.maxAgeDays*24*60*60*1e3:0,g=typeof m.limit=="number"&&m.limit>0?m.limit:1e3,h=m.selection==="explicit"||m.selection==="unpromoted"?m.selection:"unpromoted";try{let y=await ok({manager:e,maxAgeMs:b,maxDeletions:g,selection:h,verbose:!1});p.code(200).send(y)}catch(y){p.code(500).send({error:y.message})}}),n.get("/v1/sessions/tombstones",async(f,p)=>{let m=f.query;if(m.since!==void 0&&Number.isNaN(Date.parse(m.since))){p.code(400).send({error:"since must be an ISO timestamp"});return}let b=await e.listTombstones({...m.agent?{agentId:m.agent}:{},...m.since?{since:m.since}:{},...m.grep?{grep:m.grep}:{}});p.code(200).send({tombstones:b})}),n.post("/v1/sessions/undelete",async(f,p)=>{let m=f.body??{};if(!Array.isArray(m.ids)||m.ids.length===0||!m.ids.every(b=>typeof b=="string"&&b.length>0)){p.code(400).send({error:"ids must be a non-empty array of strings"});return}try{p.code(200).send(await e.undeleteSessions(m.ids))}catch(b){p.code(500).send({error:b.message})}}),n.post("/v1/sessions/:id/kill",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=e.get(b);if(g){g.close({deleteRecord:!1,by:"REST POST /kill"}).catch(()=>{}),p.code(202).send();return}if(!await e.hasRecord(b)){p.code(404).send({error:"session not found"});return}p.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=e.get(b);if(!g)return p.code(404).send({error:"session not found"}),p;let h=f.body??{},y={};(h.mode==="memory"||h.mode==="file")&&(y.mode=h.mode),typeof h.capacityBytes=="number"&&(y.capacityBytes=h.capacityBytes),typeof h.fileCapBytes=="number"&&(y.fileCapBytes=h.fileCapBytes),(y.mode??"memory")==="file"&&(y.filePathFor=k=>rm.join(OT.tmpdir(),`hydra-acp-stdin-${k}.log`));try{return g.openStream(y)}catch(k){return p.code(409).send({error:k.message}),p}}),n.post("/v1/sessions/:id/stdin",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=e.get(b);if(!g)return p.code(404).send({error:"session not found"}),p;let h=f.body??{},y=typeof h.chunk=="string"?h.chunk:"",k=h.eof===!0;try{return g.streamWrite(y,k)}catch(S){return p.code(409).send({error:S.message}),p}}),n.patch("/v1/sessions/:id",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=f.body??{};if(g.cwd!==void 0){if(typeof g.cwd!="string"||!rm.isAbsolute(g.cwd)){p.code(400).send({error:"cwd must be an absolute path"});return}let y=await e.setCwd(b,g.cwd);if(y==="missing"){p.code(404).send({error:"session not found"});return}if(y==="not-a-directory"){p.code(400).send({error:`${g.cwd} is not a directory`});return}if(y==="live"){p.code(409).send({error:"session is live; its agent was spawned in its cwd and cannot change directory. Moving a live session is a swap \u2014 use `workspace start` in it."});return}if(y==="bound"){p.code(409).send({error:"session is isolated, so its cwd IS its workspace. Clear the binding first (PATCH { workspace: null }) or leave the workspace from inside the session."});return}p.code(204).send();return}if("workspace"in g){if(g.workspace!==null){p.code(400).send({error:"workspace may only be set to null (clear the binding)"});return}let y=await e.clearWorkspaceBinding(b);if(y==="missing"){p.code(404).send({error:"session not found"});return}if(y==="live"){p.code(409).send({error:"session is live; its cwd is the workspace. Use `workspace stop` or `workspace detach` in the session so the agent moves with the binding."});return}p.code(204).send();return}if(g.priority!==void 0){let y=g.priority,k;if(y===null||y===0)k=void 0;else if(typeof y=="number"&&Number.isInteger(y)&&y>0)k=y;else{p.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(b,k)){p.code(404).send({error:"session not found"});return}p.code(204).send();return}if(g.regen===!0){if(!(e.get(b)!==void 0||await e.hasRecord(b))){p.code(404).send({error:"session not found"});return}e.scheduleSynopsis(b),p.code(202).send();return}if(typeof g.title!="string"||g.title.trim().length===0){p.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(b,g.title)){p.code(404).send({error:"session not found"});return}p.code(204).send()}),n.delete("/v1/sessions/:id",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=e.get(b);if(g){await g.close({deleteRecord:!0,by:"REST DELETE /v1/sessions"}),await e.waitForDeletion(b),await e.hasRecord(b)&&await e.deleteRecord(b),p.code(204).send();return}if(!await e.deleteRecord(b)){p.code(404).send({error:"session not found"});return}p.code(204).send()}),n.get("/v1/sessions/:id/export",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=f.query?.tools,h=g==="references"?"references":LA(g),y=await e.exportBundle(b,h==="references"?{tools:"references"}:{});if(!y){p.code(404).send({error:"session not found"});return}let k=_u({record:y.record,history:h==="summary"?NA(y.history,"summary"):y.history,promptHistory:y.promptHistory.length>0?y.promptHistory:void 0,...y.toolBlobs!==void 0?{toolBlobs:y.toolBlobs}:{},hydraVersion:Fe,machine:Ys(),hydraHost:$T(t)}),S=new Date().toISOString().replace(/[:.]/g,"-");p.header("Content-Disposition",`attachment; filename="${b}-${S}.hydra"`),p.code(200).send(k)}),n.get("/v1/sessions/:id/diff",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=await e.exportBundle(b);if(!g){p.code(404).send({error:"session not found"});return}let h=f.query??{},y=h.fold==="true"||h.fold==="1",k=typeof h.paths=="string"&&h.paths.length>0?new Set(h.paths.split(",").map(I=>I.trim()).filter(I=>I.length>0)):void 0,S=Uc(g.history);k&&(S=S.filter(I=>k.has(I.path))),y&&(S=S.map(I=>({...I,hunks:Wc(I.hunks)}))),p.code(200).send(S)}),n.get("/v1/sessions/:id/tools/:hash",async(f,p)=>{let m=f.params,b=await e.resolveCanonicalId(m.id)??m.id,g=await e.loadToolBlob(b,m.hash);if(g===null){p.code(404).send({error:"tool blob not found"});return}p.header("Content-Type","text/plain; charset=utf-8"),p.code(200).send(g)}),n.get("/v1/sessions/:id/transcript",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=await e.exportBundle(b);if(!g){p.code(404).send({error:"session not found"});return}let h=_u({record:g.record,history:g.history,promptHistory:g.promptHistory.length>0?g.promptHistory:void 0,hydraVersion:Fe,machine:Ys(),hydraHost:$T(t)}),y=f.query,k=x=>x==="1"||x==="true"||x==="yes",S=x=>{let C=y?.[x];if(C===void 0||C==="")return;let $=Number(C);return Number.isFinite($)?$:"bad"},I={};for(let x of["from","to","last","since"]){let C=S(x);if(C==="bad"){p.code(400).send({error:`${x} must be a number`});return}C!==void 0&&(I[x==="since"?"sinceMs":x]=C)}p.header("Content-Type","text/markdown; charset=utf-8"),p.code(200).send(Qh(h,{includeTools:k(y?.tools),includeThoughts:k(y?.thoughts),...I}))});let i=f=>async(p,m)=>{let b=p.params.id,g=await e.resolveCanonicalId(b)??b,h=p.body??{},y={};if(h.forkAt!==void 0){if(typeof h.forkAt!="string"||h.forkAt.length===0){m.code(400).send({error:"forkAt must be a non-empty string"});return}y.forkAt=h.forkAt}if(h.cwd!==void 0){if(typeof h.cwd!="string"||h.cwd.length===0){m.code(400).send({error:"cwd must be a non-empty string"});return}y.cwd=Ze(h.cwd)}if(h.agentId!==void 0){if(typeof h.agentId!="string"||h.agentId.length===0){m.code(400).send({error:"agentId must be a non-empty string"});return}y.agentId=h.agentId}if(h.title!==void 0){if(typeof h.title!="string"){m.code(400).send({error:"title must be a string"});return}y.title=h.title}if(f){let k=h.selection;if(k!==void 0){if(typeof k.text!="string"||k.text.length===0){m.code(400).send({error:"selection.text must be a non-empty string"});return}y.side={selection:{text:k.text,...typeof k.responsePartId=="string"?{responsePartId:k.responsePartId}:{}}}}else y.side={}}if(h.mode!==void 0&&!f){if(h.mode!=="verbatim"&&h.mode!=="synthesis"){m.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}y.mode=h.mode}if(h.model!==void 0){if(typeof h.model!="string"||h.model.length===0){m.code(400).send({error:"model must be a non-empty string"});return}y.model=h.model}try{let k=await e.forkSession(g,y);m.code(201).send(k)}catch(k){let S=k;if(S.code===G.SessionNotFound){m.code(404).send({error:S.message});return}if(S.code===G.InvalidParams||S.code===G.AgentNotInstalled){m.code(400).send({error:S.message});return}m.code(500).send({error:S.message})}};n.post("/v1/sessions/:id/fork",i(!1)),n.post("/v1/sessions/:id/side",i(!0)),n.post("/v1/sessions/import",async(f,p)=>{let m=f.body??{};if(m.bundle===void 0){p.code(400).send({error:"missing bundle"});return}let b;if(m.cwd!==void 0){if(typeof m.cwd!="string"||m.cwd.length===0){p.code(400).send({error:"cwd must be a non-empty string"});return}b=m.cwd}let g;try{g=ys(m.bundle)}catch(h){p.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(g,{replace:m.replace===!0,...b!==void 0?{cwd:b}:{}});p.code(201).send(h)}catch(h){let y=h;if(y.code===G.BundleAlreadyImported){p.code(409).send({error:"bundle already imported",existingSessionId:y.existingSessionId});return}p.code(500).send({error:y.message})}}),n.get("/v1/sessions/:id/compact/status",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=e.get(b),h;if(g?h=g.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(b),h===void 0&&!await e.hasRecord(b))return p.code(404).send({error:"session not found"}),p;let y=await e.getCompactionState(b),k=await e.getRollbackBreadcrumb(b),S=await e.getPendingAgentSwap(b),I=!1,x,C=g?.currentUsage,$=typeof C?.used=="number"&&typeof C?.size=="number"&&C.size>0?{used:C.used,size:C.size}:void 0,P=await e.loadHistory(b,{tools:"references",maxEntries:1/0}).catch(()=>[]);if(P.length>0&&t.compaction){let M=h??0,F=P.length,K=M<=P.length?M:0,Y=P.slice(K),z=gT(Y);x=ik(z);let re=g?.currentModel,Q=P.at(-1).recordedAt;I=yT({summarizedThroughEntry:M,totalEntries:F,unsummarizedChars:z,compactionInFlight:e.getCompactionInFlight(),currentModel:re,lastActivityMs:Q,nowMs:Date.now(),config:t.compaction,...typeof C?.used=="number"?{agentReportedUsed:C.used}:{},...typeof C?.size=="number"?{agentReportedSize:C.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:I,...x!=null?{approxTokens:x}:{},...$!=null?{currentUsage:$}:{},...y!=null?{compactionState:y}:{},...k!=null?{rollbackBreadcrumb:k}:{},...S!=null?{pendingAgentSwap:S}:{}}}),n.post("/v1/sessions/:id/compact",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m;if(e.get(b)){e.scheduleCompaction(b),p.code(202).send({scheduled:!0});return}if(!await e.hasRecord(b)){p.code(404).send({error:"session not found"});return}e.scheduleCompaction(b),p.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m;if(!await e.hasRecord(b)){p.code(404).send({error:"session not found"});return}try{await e.performUncompact(b),p.code(202).send({rolledBack:!0})}catch(g){let h=g instanceof Error?g.message:String(g);p.code(409).send({error:h})}}),n.post("/v1/sessions/:id/workspace/clean",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=f.body??{};if(g.deep!==void 0&&typeof g.deep!="boolean"){p.code(400).send({error:"deep must be a boolean"});return}if(!await e.hasRecord(b)){p.code(404).send({error:"session not found"});return}if(e.get(b)===void 0){p.code(409).send({error:"session is not live. Cleaning rewrites the workspace under a running agent, so it is only available inside a live session (`/hydra workspace clean`). For a cold workspace use `hydra workspace remove` instead."});return}try{let h=await e.runWorkspaceAction(b,"clean",void 0,{deep:g.deep===!0});p.code(202).send({report:h})}catch(h){p.code(409).send({error:h instanceof Error?h.message:String(h)})}}),n.get("/v1/sessions/:id/history/page",async(f,p)=>{let m=f.params.id,b=f.query,g=Number(b?.beforeSeq);if(b?.beforeSeq===void 0||b.beforeSeq===""||!Number.isFinite(g)){p.code(400).send({error:"beforeSeq must be a number"});return}let h=b.turns===void 0||b.turns===""?10:Number(b.turns);if(!Number.isInteger(h)||h<1){p.code(400).send({error:"turns must be a positive integer"});return}let y=await e.resolveCanonicalId(m)??m,k=await e.pageHistory(y,{beforeSeq:g,turns:Math.min(h,100)});if(!k){p.code(404).send({error:"session not found"});return}p.code(200).send({entries:Zp(k.entries),hasMore:k.hasMore})}),n.get("/v1/sessions/:id/history",async(f,p)=>{let m=f.params.id,b=f.query,g=b?.follow==="1"||b?.follow==="true",h=await e.resolveCanonicalId(m)??m,y=e.get(h),k,S,I=!1,x=1e4,C=[];if(y){g&&(S=y.onBroadcast(P=>{p.raw.writableEnded||(I?p.raw.write(JSON.stringify(P)+`
412
+ `):(C.push(P),C.length>x&&C.shift()))})),f.raw.on("close",()=>{S?.(),p.raw.writableEnded||p.raw.end()});try{k=await y.getHistorySnapshot()}catch(P){throw S?.(),P}}else{let P=await e.getHistory(h);if(P===void 0)return p.code(404).send({error:"session not found"}),p;k=P}p.raw.setHeader("Content-Type","application/x-ndjson"),p.raw.setHeader("Cache-Control","no-cache"),p.raw.statusCode=200;let $=new Set;for(let P of k??[]){p.raw.write(JSON.stringify(P)+`
413
+ `);let M=P;typeof M.recordedAt=="number"&&$.add(String(M.recordedAt))}for(;C.length>0;){let P=C.splice(0,C.length);for(let M of P){let F=M,K=typeof F.recordedAt=="number"?String(F.recordedAt):"";K&&$.has(K)||p.raw.write(JSON.stringify(M)+`
414
+ `)}}return I=!0,S||p.raw.end(),p});function a(f,p,m){let b=typeof f=="string"?f.trim():"";if(b.length===0)return null;let g;try{g=JSON.parse(b)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!g||typeof g!="object"||Array.isArray(g))return console.debug("events endpoint: skipping non-object JSONL line"),null;let h=g;if(typeof h.recordedAt!="number"||m!==void 0&&h.recordedAt<m||typeof h.params!="object"||h.params===null||Array.isArray(h.params))return null;let y=h.params;if(typeof y.update!="object"||y.update===null||Array.isArray(y.update))return null;let S=y.update.sessionUpdate;return typeof S!="string"||!p.has(S)?null:{recordedAt:h.recordedAt,entry:g}}function d(f,p,m){let g=p.params.update,h={sessionId:f,ts:new Date(p.recordedAt).toISOString(),kind:m,update:g};return g.messageId!==void 0&&g.messageId!==null&&(h.messageId=g.messageId),h}async function*c(f,p,m,b){for await(let g of p){let h=a(g,m,b);if(h){let y=h.entry.params.update.sessionUpdate;yield{ts:h.recordedAt,row:d(f,h.entry,y)}}}}async function l(f,p,m,b){let g=fk.createInterface({input:uk.createReadStream(p),crlfDelay:1/0}),h=c(f,g,m,b),y=await h.next(),k=y.done?null:y.value;return{sessionId:f,rl:g,gen:h,current:k,exhausted:k===null}}async function u(f){let p=await f.gen.next();p.done?(f.exhausted=!0,f.current=null):f.current=p.value}n.get("/v1/sessions/events",async(f,p)=>{let m=f.query,b=m.kinds;if(!b||b.trim().length===0)return p.code(400).send({error:"kinds parameter is required"}),p;let g=b.split(",").map(x=>x.trim());if(g.length===0)return p.code(400).send({error:"kinds parameter is required"}),p;for(let x of g)if(!nm.has(x))return p.code(400).send({error:`kind "${x}" is not queryable; allowed kinds: ${[...nm].join(", ")}`}),p;let h=new Set(g),y;if(m.since!==void 0&&m.since.trim().length>0){let x=new Date(m.since);if(isNaN(x.getTime()))return p.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),p;y=x.getTime()}let k=await e.list({includeNonInteractive:!0}),S=y!==void 0?k.filter(x=>new Date(x.updatedAt).getTime()>=y):k;p.raw.setHeader("content-type","application/x-ndjson"),p.raw.statusCode=200;let I=[];for(let x of S)try{let C=D.historyFile(x.sessionId),$=await l(x.sessionId,C,h,y);$.exhausted||I.push($)}catch(C){if(C.code==="ENOENT")continue;throw C}f.raw.on("close",()=>{for(let x of I)try{x.rl.close()}catch{}p.raw.writableEnded||p.raw.end()});try{for(;I.length>0;){let x=-1,C=1/0;for(let P=0;P<I.length;P++){let M=I[P];M.current!==null&&M.current.ts<C&&(C=M.current.ts,x=P)}if(x===-1)break;let $=I[x];if(p.raw.write(JSON.stringify($.current.row)+`
415
+ `),await u($),$.exhausted){try{$.rl.close()}catch{}I.splice(x,1)}}}catch(x){for(let C of I)try{C.rl.close()}catch{}throw x}return p.raw.end(),p}),n.get("/v1/sessions/:id/events",async(f,p)=>{let m=f.params.id,b=f.query,g=await e.resolveCanonicalId(m)??m;if(!e.get(g)&&!await e.hasRecord(g))return p.code(404).send({error:"session not found"}),p;let y=b.kinds;if(!y||y.trim().length===0)return p.code(400).send({error:"kinds parameter is required"}),p;let k=y.split(",").map(P=>P.trim());if(k.length===0)return p.code(400).send({error:"kinds parameter is required"}),p;for(let P of k)if(!nm.has(P))return p.code(400).send({error:`kind "${P}" is not queryable; allowed kinds: ${[...nm].join(", ")}`}),p;let S=new Set(k),I;if(b.since!==void 0&&b.since.trim().length>0){let P=new Date(b.since);if(isNaN(P.getTime()))return p.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),p;I=P.getTime()}let x=D.historyFile(g),C=uk.createReadStream(x),$=fk.createInterface({input:C,crlfDelay:1/0});p.raw.setHeader("content-type","application/x-ndjson"),p.raw.statusCode=200;try{for await(let P of $){let M=typeof P=="string"?P.trim():"";if(M.length===0)continue;let F;try{F=JSON.parse(M)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",x);continue}if(!F||typeof F!="object"||Array.isArray(F)){console.debug("events endpoint: skipping non-object JSONL line in %s",x);continue}let K=F;if(typeof K.recordedAt!="number"||typeof K.params!="object"||K.params===null||Array.isArray(K.params))continue;let Y=K.params;if(typeof Y.update!="object"||Y.update===null||Array.isArray(Y.update))continue;let z=Y.update,re=z.sessionUpdate;if(typeof re!="string"||!S.has(re)||I!==void 0&&K.recordedAt<I)continue;let Q={ts:new Date(K.recordedAt).toISOString(),kind:re,update:z};z.messageId!==void 0&&z.messageId!==null&&(Q.messageId=z.messageId),p.raw.write(JSON.stringify(Q)+`
416
+ `)}}catch(P){if(P.code==="ENOENT")return p.raw.end(),p;throw P}return p.raw.end(),p}),n.post("/v1/sessions/:id/prompt/:messageId/notify",async(f,p)=>{let m=f.params,b=m.id,g=await e.resolveCanonicalId(b)??b,h=m.messageId,y=f.body,k=typeof y?.callbackUrl=="string"?y.callbackUrl:"",S=typeof y?.secret=="string"?y.secret:"";if(!h||!k||!S){p.code(400).send({error:"messageId, callbackUrl, and secret are all required"});return}let I;try{I=new URL(k)}catch{p.code(400).send({error:"callbackUrl must be a valid absolute URL"});return}if(I.protocol!=="https:"&&I.protocol!=="http:"){p.code(400).send({error:"callbackUrl must be http or https"});return}let x=e.get(g);if(!x){p.code(404).send({error:"session not found or not warm"});return}let C=x.registerTurnNotify(h,k,S);if(C.alreadyTerminal){p.code(200).send({status:"already_terminal",stopReason:C.stopReason});return}p.code(202).send({status:"registered"})}),n.get("/v1/sessions/:id/attention",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,g=e.get(b);return!g&&!await e.hasRecord(b)?(p.code(404).send({error:"session not found"}),p):g?{flags:g.listAttentionFlags()}:{flags:(await e.store.read(b))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(f,p)=>{let m=f.query;if(!m.source||m.source.trim().length===0)return p.code(400).send({error:"source query parameter is required"}),p;let b=await e.list({includeNonInteractive:!0}),g=[];for(let h of b){let y=e.get(h.sessionId),k;y?k=y.listAttentionFlags():k=(await e.store.read(h.sessionId))?.attentionFlags??[];for(let S of k)S.source===m.source&&g.push({...S,sessionId:h.sessionId})}return{flags:g}}),n.post("/v1/sessions/:id/attention/clear",async(f,p)=>{let m=f.params.id,b=await e.resolveCanonicalId(m)??m,h=f.body??{},y=typeof h.source=="string"?h.source:"",k=typeof h.reason=="string"?h.reason:"";if((y.length>0||k.length>0)&&!(y.length>0&&k.length>0)){p.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}y.length===0&&k.length;let S=e.get(b);if(S){if(y.length>0&&k.length>0)S.clearAttentionFlag(y,k);else{let P=Array.from(S.listAttentionFlags()).map(M=>`${M.source}::${M.reason}`);for(let M of P)S.clearAttentionFlag(M.split("::")[0],M.split("::").slice(1).join("::"))}p.code(204).send();return}if(!await e.hasRecord(b)){p.code(404).send({error:"session not found"});return}let I=e.store,x=await I.read(b);if(!x){p.code(404).send({error:"session not found"});return}let C=x.attentionFlags??[],$;if(y.length>0&&k.length>0){let P=`${y}::${k}`;$=C.filter(M=>`${M.source}::${M.reason}`!==P)}else $=[];if($.length===C.length&&$.every((P,M)=>P.source===C[M].source&&P.reason===C[M].reason)){p.code(204).send();return}await I.write({...x,attentionFlags:$}),p.code(204).send()})}Gs();fn();function LT(n,e,t,r={}){n.get("/v1/agents",async()=>wc(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let s=await e.refresh();return{version:s.version,agentCount:s.agents.length}}),n.post("/v1/agents/:id/install",async(s,o)=>{let i=s.params.id,a=await e.getAgent(i);if(!a){o.code(404).send({error:`agent ${i} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){o.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await Fr(a,[],{npmRegistry:r.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:d.version,distribution:c,installed:!0,command:d.command})}catch(d){o.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(s,o)=>{let i=s.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(i);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===G.AgentNotInstalled){o.code(404).send({error:d.message});return}o.code(409).send({error:d.message})}})}Se();function NT(n,e,t,r=()=>[]){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t,home:D.home(),driftedKeys:r()}))}rr();xc();import*as UT from"os";Se();cs();var ju=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,sm=class n{data;constructor(e){this.data=e}static async load(){let e=await jt(D.peers());return new n(RU(e))}get(e){return this.data.entries[e]}async set(e){this.data.entries[e.name]=e,await DT(this.data)}async delete(e){return e in this.data.entries?(delete this.data.entries[e],await DT(this.data),!0):!1}list(){return Object.values(this.data.entries).map(({name:e,host:t,port:r,expiresAt:s,label:o,addedAt:i,pinnedFingerprint:a,pinnedAt:d})=>({name:e,host:t,port:r,expiresAt:s,label:o,addedAt:i,pinnedFingerprint:a,pinnedAt:d})).sort((e,t)=>e.addedAt.localeCompare(t.addedAt))}};function RU(n){if(!n||typeof n!="object")return{version:1,entries:{}};let e=n,t=e.entries&&typeof e.entries=="object"?e.entries:{},r={};for(let[s,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||typeof i.host!="string"||typeof i.port!="number"||typeof i.token!="string"||typeof i.expiresAt!="string"||typeof i.addedAt!="string")continue;let a={name:i.name,host:i.host,port:i.port,token:i.token,expiresAt:i.expiresAt,addedAt:i.addedAt};typeof i.label=="string"&&(a.label=i.label),typeof i.pinnedFingerprint=="string"&&(a.pinnedFingerprint=i.pinnedFingerprint),typeof i.pinnedAt=="string"&&(a.pinnedAt=i.pinnedAt),r[s]=a}return{version:1,entries:r}}async function DT(n){await on(D.peers(),n,{mode:384})}Mr();var AU=3600*24*365,so=class extends Error{status;constructor(e,t){super(e),this.name="PeerLoginError",this.status=t}};function om(n,e){return`${Nt(n)?"http":"https"}://${n}:${e}`}async function HT(n){let e=n.fetchImpl??fetch,t=`${n.host}:${n.port}`,r=om(n.host,n.port),s;try{s=await e(`${r}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:n.password,label:n.label,ttlSec:n.ttlSec??AU})})}catch(i){throw new so(`Could not reach ${t}: ${i.message}`,502)}if(s.status===401)throw new so(`Wrong password for ${t}.`,401);if(s.status===403)throw new so(`No password is configured on ${t}. Run \`hydra-acp auth password\` on that daemon first.`,502);if(s.status===429)throw new so(`Too many failed login attempts on ${t}; try again later.`,429);if(!s.ok)throw new so(`Login to ${t} failed: HTTP ${s.status}`,502);let o=await s.json();if(!o.session_token||!o.expires_at)throw new so(`Login to ${t} returned a malformed response.`,502);return{token:o.session_token,expiresAt:o.expires_at}}async function pk(n){let e=n.fetchImpl??fetch,t=om(n.host,n.port);try{await e(`${t}/v1/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({})})}catch{}}function WT(n){return{machine:Ys(),hydraVersion:Fe,startedAt:n,os:{platform:process.platform,release:UT.release(),arch:process.arch},node:process.version}}async function im(n){let e=n.fetchImpl??fetch,t;try{t=await e(`${om(n.host,n.port)}/v1/system`,{headers:{Authorization:`Bearer ${n.token}`},signal:n.signal})}catch(r){return{kind:"error",message:r.message}}if(t.status===401||t.status===403)return{kind:"unauthorized"};if(t.status===404)return{kind:"unsupported"};if(!t.ok)return{kind:"error",message:`HTTP ${t.status}`};try{let r=await t.json();return typeof r?.machine=="string"?{kind:"ok",system:r}:{kind:"ok"}}catch{return{kind:"ok"}}}function BT(n){return n!==void 0&&n.length<=64&&ju.test(n)}function jT(n,e){if(BT(n))return n;if(/^[\d.]+$/.test(e)||e.includes(":"))return;let t=e.split(".")[0];return BT(t)?t:void 0}function qT(n,e){n.get("/v1/system",async()=>WT(e))}var TU=/^[A-Za-z0-9._-]+$/;function am(n,e,t){let r=e==="extension"?"extensions":"transformers",s=`/v1/${r}`;n.get(s,async()=>({[r]:t.list()})),n.get(`${s}/:name`,async(o,i)=>{let a=o.params.name,d=t.get(a);if(!d){i.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),n.post(s,async(o,i)=>{let a=o.body??{},d=EU(a);if("error"in d){i.code(400).send({error:d.error});return}try{let c=t.register(d.config);i.code(201).send(c)}catch(c){qu(i,c)}}),n.delete(`${s}/:name`,async(o,i)=>{let a=o.params.name;try{await t.unregister(a),i.code(204).send()}catch(d){qu(i,d)}}),n.post(`${s}/:name/start`,async(o,i)=>{let a=o.params.name;try{let d=await t.startByName(a);i.code(200).send(d)}catch(d){qu(i,d)}}),n.post(`${s}/:name/stop`,async(o,i)=>{let a=o.params.name;try{let d=await t.stopByName(a);i.code(200).send(d)}catch(d){qu(i,d)}}),n.post(`${s}/:name/restart`,async(o,i)=>{let a=o.params.name;try{let d=await t.restartByName(a);i.code(200).send(d)}catch(d){qu(i,d)}})}function qu(n,e){let t=e.code,r=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:r});return}if(t==="CONFLICT"){n.code(409).send({error:r});return}n.code(500).send({error:r})}function EU(n){let e=n.name;if(typeof e!="string"||!TU.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(i=>typeof i!="string")))return{error:"command must be string[]"};let r=n.args;if(r!==void 0&&(!Array.isArray(r)||r.some(i=>typeof i!="string")))return{error:"args must be string[]"};let s=n.env;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))return{error:"env must be an object of string\u2192string"};if(s&&Object.values(s).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=n.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:r??[],env:s??{},enabled:o===void 0?!0:o}}}function zT(n,e){am(n,"extension",e)}function KT(n,e){am(n,"transformer",e)}function GT(n,e){n.get("/v1/config",async()=>e())}import{z as Ti}from"zod";Se();import*as Ai from"fs/promises";import*as QT from"path";import{randomBytes as PU,scrypt as MU,timingSafeEqual as _U}from"crypto";import{promisify as $U}from"util";var XT=$U(MU);function hk(){return QT.join(D.home(),"password-hash")}var JT=32768,VT=8,YT=1,OU=64,FU=16,ZT=128*1024*1024;async function dm(n){if(typeof n!="string"||n.length===0)throw new Error("password must be a non-empty string");let e=PU(FU),t=await XT(n,e,OU,{N:JT,r:VT,p:YT,maxmem:ZT}),r=`scrypt$${JT}$${VT}$${YT}$${e.toString("hex")}$${t.toString("hex")}
417
+ `;await Ai.mkdir(D.home(),{recursive:!0}),await Ai.writeFile(hk(),r,{encoding:"utf8",mode:384})}async function zc(){try{return(await Ai.readFile(hk(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function cm(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await Ai.readFile(hk(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let r=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let d=await XT(n,i,a.length,{N:r,r:s,p:o,maxmem:ZT});return d.length!==a.length?!1:_U(d,a)}var LU=Ti.object({password:Ti.string().min(1),label:Ti.string().min(1).max(256).optional(),ttlSec:Ti.number().int().positive().optional()}),NU=Ti.object({id:Ti.string().optional()}).optional(),DU=Ti.object({token:Ti.string().min(32)});function e0(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,r)=>{let s=HU(t);if(e.rateLimiter.isBlocked(s))return r.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=LU.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}if(!await zc())return r.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await cm(o.password))return e.rateLimiter.recordFailure(s),r.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(s);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return r.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,r)=>{let s;try{s=NU.parse(t.body??void 0)}catch{return r.code(400).send({error:"Invalid request body"})}let o=s?.id??t.authIdentity;if(!o||o==="service")return r.code(200).send({revoked:!1});let i=await e.store.revoke(o);return r.code(200).send({revoked:i})}),n.get("/v1/auth/verify",async(t,r)=>r.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,r)=>r.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions",async(t,r)=>{let s=await e.store.revokeAll();return r.code(200).send({revoked:s})}),n.delete("/v1/auth/sessions/:id",async(t,r)=>{let s=t.params.id;return await e.store.revoke(s)?r.code(204).send():r.code(404).send({error:"Not found"})}),n.post("/v1/auth/rotate-token",async(t,r)=>{if(t.authIdentity!=="service")return r.code(403).send({error:"Requires the service token"});let s;try{s=DU.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}return e.staticTokenValidator.rotate(s.token),r.code(200).send({rotated:!0})})}function HU(n){return n.ip||"unknown"}et();import{z as Ei}from"zod";Lo();Mr();var BU=Ei.object({name:Ei.string().min(1).max(64).regex(ju).optional(),host:Ei.string().min(1),port:Ei.number().int().positive().optional(),password:Ei.string().min(1),label:Ei.string().min(1).max(256).optional(),ttlSec:Ei.number().int().positive().optional(),pinnedFingerprint:Ei.string().min(1).optional()});function t0(n,e){n.post("/v1/remotes",async(t,r)=>{let s;try{s=BU.parse(t.body)}catch{return r.code(400).send({error:`Invalid request body (name must match ${ju} and the rest is a normal login request)`})}let o=s.port??un;s.pinnedFingerprint&&mi(s.host,o,s.pinnedFingerprint);let i;try{i=await HT({host:s.host,port:o,password:s.password,label:s.label,ttlSec:s.ttlSec})}catch(f){if(f instanceof so)return r.code(f.status).send({error:f.message});throw f}let a=await im({host:s.host,port:o,token:i.token}),d=a.kind==="ok"?a.system:void 0,c=s.name;if(c===void 0){c=jT(d?.machine,s.host);let f=c!==void 0?e.store.get(c):void 0,p=f!==void 0&&(f.host!==s.host||f.port!==o);if(c===void 0||p){await pk({host:s.host,port:o,token:i.token});let m=c===void 0?`Couldn't derive a remote name for ${s.host}`:`A remote named ${c} already points at ${f.host}:${f.port}`;return r.code(c===void 0?400:409).send({error:`${m}. Pass a name: hydra-acp remote add <name> ${s.host}`})}}let l=new Date().toISOString(),u={name:c,host:s.host,port:o,token:i.token,expiresAt:i.expiresAt,addedAt:l,...s.label!==void 0?{label:s.label}:{},...s.pinnedFingerprint!==void 0?{pinnedFingerprint:s.pinnedFingerprint,pinnedAt:l}:{}};return await e.store.set(u),e.health?.markOk(u.name,d),r.code(201).send({name:u.name,host:u.host,port:u.port,expiresAt:u.expiresAt,label:u.label,addedAt:u.addedAt,pinnedFingerprint:u.pinnedFingerprint,status:e.health?.get(u.name)?.status??"unknown"})}),n.get("/v1/remotes",async(t,r)=>{let s=e.store.list().map(o=>{let i=e.health?.get(o.name);return{...o,status:i?.status??"unknown",...i?.checkedAt?{lastCheckedAt:i.checkedAt}:{},...i?.system?{system:i.system}:{}}});return r.code(200).send({remotes:s})}),n.get("/v1/remotes/:name/agents",async(t,r)=>{let s=e.store.get(t.params.name);if(!s)return r.code(404).send({error:"Not found"});let i=`${Nt(s.host)?"http":"https"}://${s.host}:${s.port}`,a={Authorization:`Bearer ${s.token}`};try{let[d,c]=await Promise.all([fetch(`${i}/v1/agents`,{headers:a}),fetch(`${i}/v1/config`,{headers:a}).catch(()=>null)]);if(!d.ok)return r.code(d.status).header("content-type","application/json").send(await d.text());let l=await d.json(),u={};if(c?.ok){let f=await c.json();u={defaultAgent:f.defaultAgent,sessionDefaults:f.sessionDefaults}}return r.code(200).send({...l,...u})}catch(d){return r.code(502).send({error:`Could not reach remote "${s.name}": ${d.message}`})}}),n.delete("/v1/remotes/:name",async(t,r)=>{let s=t.params.name,o=e.store.get(s);return o?(await pk({host:o.host,port:o.port,token:o.token}),await e.store.delete(s),e.health?.forget(s),e.store.list().some(a=>a.host===o.host&&a.port===o.port)||Xy(o.host,o.port),r.code(204).send()):r.code(404).send({error:"Not found"})})}Do();La();ec();Mr();mu();fn();var UU=new Set(["session/attach","session/detach","session/prompt","session/cancel","session/close","session/delete","hydra-acp/session/delete","session/set_model","session/set_mode","session/set_config_option","_session/steering","hydra-acp/prompt/cancel","hydra-acp/prompt/update","hydra-acp/prompt/amend","hydra-acp/session/tool_content","hydra-acp/session/force_cancel"]);function WU(n){return UU.has(n)}function r0(n,e,t,r){let s=[],o=a=>{for(let d of s)d(a)},i=(a,d)=>{e.handleLocalMessage(a,d,{connection:t.connection,clientId:r}).then(c=>c?n.send(c):void 0).catch(()=>{})};return n.onMessage(a=>{if("method"in a&&WU(a.method)){let d=a.params,c=typeof d?.sessionId=="string"?d.sessionId:void 0;if(c){if(eo(c)){i(a,c);return}if(a.method==="session/attach"){let l="id"in a;e.resolveLocalMiss(c).then(u=>{if(u.ok){i(a,u.foreignId);return}if(u.ambiguous&&l){n.send(zu(a.id,G.SessionNotFound,`Session "${c}" exists on more than one remote (${u.ambiguous.join(", ")}). Address it as "<remote>:${c}".`));return}o(a)});return}}}o(a)}),{send:a=>n.send(a),onMessage:a=>s.push(a),onClose:a=>n.onClose(a),close:()=>n.close()}}var lm=class{constructor(e,t=qU,r){this.store=e;this.dial=t;this.localMiss=r}store;dial;localMiss;attachments=new Map;async resolveLocalMiss(e){if(!this.localMiss)return{ok:!1};if(await this.localMiss.resolvesLocally(e))return{ok:!1};let t=this.localMiss.cache.findByLocalId(e);return t.length===0?{ok:!1}:t.length>1?{ok:!1,ambiguous:t.map(r=>r.name)}:{ok:!0,foreignId:Zs(t[0])}}async handleLocalMessage(e,t,r){let s="id"in e,o=s?e.id:void 0,i=eo(t);if(!i)return s?zu(o,G.SessionNotFound,`not a federated session id: ${t}`):void 0;let a=n0(r.clientId,t),d={...e.params,sessionId:i.localId};if(e.method==="session/attach"){let l=this.store.get(i.name);if(!l)return s?zu(o,G.SessionNotFound,`No remote named "${i.name}". Run \`hydra remote add\` first.`):void 0;let u=this.attachments.get(a);u&&(this.attachments.delete(a),u.peerConnection.close().catch(()=>{}));let f;try{f=await this.dial(l)}catch(g){return s?zu(o,G.InternalError,`Could not reach remote "${i.name}": ${g.message}`):void 0}let p={peerConnection:f,localId:i.localId,target:r};this.wireAttachment(i.name,p);let m;try{m=await f.request("session/attach",d)}catch(g){return f.close().catch(()=>{}),s?mk(o,g):void 0}this.attachments.set(a,p);let b=m&&typeof m.sessionId=="string"?{...m,sessionId:t}:m;return s?{jsonrpc:"2.0",id:o,result:b}:void 0}let c=this.attachments.get(a);if(!c)return s?zu(o,G.SessionNotFound,`"${t}" is not attached through this daemon.`):void 0;if(e.method==="session/detach"){let l,u;try{l=await c.peerConnection.request("session/detach",d)}catch(f){u=f}return this.attachments.delete(a),c.peerConnection.close().catch(()=>{}),u?s?mk(o,u):void 0:s?{jsonrpc:"2.0",id:o,result:l??{}}:void 0}if(s)try{let l=await c.peerConnection.request(e.method,d);return{jsonrpc:"2.0",id:o,result:l}}catch(l){return mk(o,l)}await c.peerConnection.notify(e.method,d).catch(()=>{})}detachClient(e){for(let[t,r]of[...this.attachments.entries()])r.target.clientId===e&&(this.attachments.delete(t),r.peerConnection.request("session/detach",{sessionId:r.localId}).catch(()=>{}),r.peerConnection.close().catch(()=>{}))}wireAttachment(e,t){let{peerConnection:r,localId:s,target:o}=t,i=Zs({name:e,localId:s}),a=()=>{this.attachments.delete(n0(o.clientId,i))};r.onAnyNotification((d,c)=>{let l=d;!l||l.sessionId!==s||(c==="hydra-acp/session/closed"&&a(),o.connection.notify(c,{...l,sessionId:i}).catch(()=>{}))}),r.onRequest("hydra-acp/session/request_permission",async d=>{let c=d;if(!c||c.sessionId!==s)throw{code:G.MethodNotFound,message:"unexpected sessionId"};return o.connection.request("hydra-acp/session/request_permission",{...c,sessionId:i})}),r.onClose(()=>{a(),o.connection.notify("hydra-acp/session/closed",{sessionId:i}).catch(()=>{})})}};function n0(n,e){return`${n} ${e}`}function zu(n,e,t){return{jsonrpc:"2.0",id:n,error:{code:e,message:t}}}function mk(n,e){let t=e,r=typeof t?.code=="number"?t.code:G.InternalError,s=typeof t?.message=="string"?t.message:String(e??"forward failed");return{jsonrpc:"2.0",id:n,error:{code:r,message:s,...t?.data!==void 0?{data:t.data}:{}}}}var jU=1e4;async function qU(n){let t=`${Nt(n.host)?"ws":"wss"}://${n.host}:${n.port}/acp`,r=await No(t,["acp.v1",`hydra-acp-token.${n.token}`],jU);return new pn(Nr(r))}Mr();var zU=3e4,KU=5e3,um=class{constructor(e,t={}){this.store=e;this.opts=t}store;opts;snapshots=new Map;timer;start(){this.timer||(this.checkAll(),this.timer=setInterval(()=>{this.checkAll()},this.opts.intervalMs??zU),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}get(e){return this.snapshots.get(e)}markOk(e,t){this.snapshots.set(e,{status:"ok",checkedAt:new Date().toISOString(),...t?{system:t}:{}})}forget(e){this.snapshots.delete(e)}async checkAll(){let e=this.opts.fetchImpl??fetch;await Promise.allSettled(this.store.list().map(async t=>{let r=this.store.get(t.name);if(!r)return;let s=new AbortController,o=setTimeout(()=>s.abort(),KU);try{let i=await im({host:r.host,port:r.port,token:r.token,fetchImpl:e,signal:s.signal});if(i.kind==="ok"){this.snapshots.set(t.name,{status:"ok",checkedAt:new Date().toISOString(),...i.system?{system:i.system}:{}});return}if(i.kind==="unauthorized"){this.snapshots.set(t.name,{status:"unauthorized",checkedAt:new Date().toISOString()});return}if(i.kind==="error")throw new Error(i.message);let d=`${Nt(r.host)?"http":"https"}://${r.host}:${r.port}/v1/auth/verify`,c=await e(d,{headers:{Authorization:`Bearer ${r.token}`},signal:s.signal});this.snapshots.set(t.name,{status:c.ok?"ok":"unauthorized",checkedAt:new Date().toISOString()})}catch(i){this.snapshots.set(t.name,{status:"unreachable",checkedAt:new Date().toISOString(),error:i.message})}finally{clearTimeout(o)}}))}};Lo();import{z as s0}from"zod";var GU=s0.object({sessionLabel:s0.string().min(1).max(256)});function o0(n,e){n.post("/v1/process-tokens",async(t,r)=>{if(t.authIdentity!=="service")return r.code(403).send({error:"Requires the service token"});let s;try{s=GU.parse(t.body)}catch{return r.code(400).send({error:"Invalid request body"})}let o=e.processRegistry.mint(s.sessionLabel,"script");return r.code(201).send({token:o})}),n.delete("/v1/process-tokens/:sessionLabel",async(t,r)=>t.authIdentity!=="service"?r.code(403).send({error:"Requires the service token"}):(e.processRegistry.revoke(t.params.sessionLabel),r.code(204).send()))}Bp();Do();Lc();La();import{nanoid as gk}from"nanoid";Qp();fn();Gs();qd();rr();import{randomBytes as l0}from"crypto";import*as u0 from"os";import*as f0 from"path";kc();var JU=200;function VU(n){if(!n||typeof n!="object")return;let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e[pt];if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.sentBy;if(!r||typeof r!="object"||Array.isArray(r))return;let s=r,o={};if(typeof s.sessionId=="string"&&s.sessionId.length>0&&(o.sessionId=s.sessionId),typeof s.label=="string"&&s.label.length>0&&(o.label=s.label.slice(0,JU)),s.awaiting===!0&&(o.awaiting=!0),!(o.sessionId===void 0&&o.label===void 0))return o}async function i0(n,e,t){let r=VU(n);if(!r)return;let s={};if(r.label!==void 0&&(s.fromLabel=r.label),r.awaiting===!0&&(s.awaiting=!0),r.sessionId!==void 0){let o=await e.resolveCanonicalId(r.sessionId)??r.sessionId,i=await e.getOne(o);if(i){s.fromSession=o,i.title&&(s.fromSessionTitle=i.title);let a=e.get(o)?.currentPromptDepth;s.depth=(a??0)+1}else t?.(r.sessionId)}if(!(s.fromSession===void 0&&s.fromLabel===void 0))return s}var Ku=new Map;function a0(n,e){let t=Ku.get(n);t||(t=new Set,Ku.set(n,t)),t.add(e);let r=!1;return()=>{if(r)return;r=!0;let s=Ku.get(n);s&&(s.delete(e),s.size===0&&Ku.delete(n))}}function d0(n,e){if(n===e)return!0;let t=new Set,r=[e];for(;r.length>0;){let s=r.pop();if(t.has(s))continue;t.add(s);let o=Ku.get(s);if(o){if(o.has(n))return!0;for(let i of o)r.push(i)}}return!1}function he(n,e,t){let r=new Error(e);return r.code=n,t!==void 0&&(r.data=t),r}function eW(n){if(!n||typeof n!="object")return 512;let r=n.params?.update;if(!r)return 512;let s=512,o=r.content;if(typeof o=="string")s+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(s+=a.text.length),typeof a.data=="string"&&(s+=a.data.length)}let i=r.toolCall;if(i&&(typeof i.rawInput=="string"?s+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(s+=256),typeof i.rawOutput=="string"?s+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(s+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(s+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(s+=c.text.length)}}return s}function yr(n,e,t){let r=n.get(e);if(!r)throw he(G.SessionNotFound,t??`session ${e} not found`);return r}async function Na(n,e){let t=qc(n),r,s,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(r=l0(32).toString("hex"),s=n.mcpTokenRegistry.reserve(r),o={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${r}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],d=lk({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),c;try{c=await n.manager.resurrect({...e,mcpServers:a,...d?{mintMcpServersForSwap:d}:{}})}catch(l){throw t!==void 0&&t.abandon(l instanceof Error?l:void 0),s!==void 0&&s.abandon(l instanceof Error?l:void 0),l}if(t!==void 0&&t.bindToSession(c),r!==void 0&&s!==void 0&&n.mcpTokenRegistry!==void 0){let l=r,u=n.mcpTokenRegistry;s.complete(c),c.onClose(()=>{u.unbind(l)})}return lW(c,n),h0(c.sessionId,n),c}function p0(n,e){n.get("/acp",{websocket:!0},async(t,r)=>{let s=hT({headers:r.headers,url:r.url});if(!s||!await e.validator.validate(s)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(s),i=`hydra_client_${gk(12)}`,a=Nr(t),d={},c=e.foreignSessions?r0(a,e.foreignSessions,d,i):a,l=new pn(c);d.connection=l;let u={clientId:i,processIdentity:o,attached:new Map};l.onClose(()=>{for(let g of u.attached.values())e.manager.get(g.sessionId)?.detach(g.clientId);u.attached.clear(),e.foreignSessions?.detachClient(i)});let f=(g,h)=>{if(u.attached.get(g)?.readonly)throw he(G.PermissionDenied,`${h} not permitted on a read-only attachment`)};if(l.onRequest("initialize",async g=>{let h=RC.parse(g??{});h.clientInfo?.name&&(u.clientInfo={name:h.clientInfo.name,...h.clientInfo.version!==void 0?{version:h.clientInfo.version}:{}});let y=h.clientInfo?.version;return y&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,y):e.onTransformerVersion?.(o.name,y)),cW()}),o&&e.extensionCommands){let g=e.extensionCommands;l.onRequest("hydra-acp/commands/register",async h=>{let y=h??{},k=Array.isArray(y.commands)?y.commands.map(S=>{if(!S||typeof S!="object")return;let I=S;if(typeof I.verb!="string")return;let x={verb:I.verb};return typeof I.argsHint=="string"&&(x.argsHint=I.argsHint),typeof I.description=="string"&&(x.description=I.description),x}).filter(S=>S!==void 0):[];return g.register(o.name,l,k),{ok:!0,registered:k.length}}),l.onClose(()=>{g.clear(o.name)})}if(o&&e.extensionMcp){let g=e.extensionMcp;l.onRequest("hydra-acp/mcp_tools/register",async y=>{let k=y??{},S=typeof k.instructions=="string"?k.instructions:void 0,I=Array.isArray(k.tools)?k.tools.map(x=>{if(!x||typeof x!="object")return;let C=x;if(typeof C.name!="string"||C.name.length===0||typeof C.description!="string"||C.inputSchema===null||typeof C.inputSchema!="object")return;let $={name:C.name,description:C.description,inputSchema:C.inputSchema};return C.outputSchema!==null&&typeof C.outputSchema=="object"&&($.outputSchema=C.outputSchema),$}).filter(x=>x!==void 0):[];if(I.length===0)throw new Error("register_mcp_tools requires at least one tool");return g.register(o.name,l,S,I),{ok:!0,registered:I.length}});let h=y=>{let k=y??{};if(typeof k.sessionId!="string"||k.sessionId.length===0)throw he(G.InvalidParams,"sessionId is required");return k.sessionId};if(l.onRequest("hydra-acp/session/extension_state/get",async y=>{let k=h(y),S=y??{};if(typeof S.key!="string"||S.key.length===0)throw he(G.InvalidParams,"key is required");if(!e.manager)throw he(G.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(k,o.name,S.key)??null}}),l.onRequest("hydra-acp/session/extension_state/list",async y=>{let k=h(y);if(!e.manager)throw he(G.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(k,o.name)}}),l.onRequest("hydra-acp/session/extension_state/set",async y=>{let k=h(y),S=y??{};if(typeof S.key!="string"||S.key.length===0)throw he(G.InvalidParams,"key is required");if(S.value===void 0)throw he(G.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw he(G.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(k,o.name,S.key,S.value)}catch(I){throw he(G.InvalidParams,I.message)}return{ok:!0}}),l.onRequest("hydra-acp/session/extension_state/delete",async y=>{let k=h(y),S=y??{};if(typeof S.key!="string"||S.key.length===0)throw he(G.InvalidParams,"key is required");if(!e.manager)throw he(G.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(k,o.name,S.key),{ok:!0}}),e.extensionMcpControls){let y=e.extensionMcpControls;l.onRequest("hydra-acp/mcp_tools/refresh_session",async k=>{let S=k??{};if(typeof S.sessionId!="string"||S.sessionId.length===0)throw he(G.InvalidParams,"refresh_session requires sessionId");return await y.notifyToolListChanged(S.sessionId,o.name),{ok:!0}})}l.onClose(()=>{g.clear(o.name)})}o?.kind==="transformer"&&(l.onRequest("hydra-acp/transformer/initialize",async g=>{let h=g??{},y=Array.isArray(h.intercepts)?h.intercepts.filter(k=>typeof k=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,l,y),e.manager?.defaultTransformers.includes(o.name))){let k=e.transformers.resolveChain([o.name])[0];if(k)for(let S of e.manager.liveSessions())S.addTransformer(k)}return{ack:!0}}),l.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),l.onRequest("hydra-acp/message/emit",async g=>{let h=g??{},y=typeof h.sessionId=="string"?h.sessionId:void 0,k=typeof h.method=="string"?h.method:void 0,S=h.envelope,I=h.route;if(!y)throw he(-32602,"emit_message requires sessionId");if(!k&&I!=="client_broadcast")throw he(-32602,"emit_message requires method");let x=yr(e.manager,y),C=typeof h.respondsTo=="string"?h.respondsTo:void 0;if(C)return x.dischargeClaim(C,S),{ok:!0};if(I==="chain")return{ok:!0,response:await x.emitToChain(o.name,k,S)};if(I==="queue"){if(k!=="session/prompt")throw he(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await x.emitToQueue(o.name,S)}}if(I==="daemon")return{ok:!0,response:await x.emitToChain(o.name,k,S)};if(I==="client_broadcast"){if(!S||typeof S!="object")throw he(-32602,"client_broadcast requires an envelope object");return x.broadcastClientUpdate(S),{ok:!0}}throw he(-32602,`unsupported route: ${JSON.stringify(I)}`)}),l.onRequest("hydra-acp/session/request_permission",async g=>{let h=g??{},y=typeof h.sessionId=="string"?h.sessionId:void 0;if(!y)throw he(-32602,"hydra-acp/session/request_permission requires sessionId");return yr(e.manager,y).requestPermissionFromClients(h)}),l.onRequest("hydra-acp/transformer/attach",async g=>oW(g,o.name,e)),l.onRequest("hydra-acp/child_session/spawn",async g=>{let h=g??{},y=typeof h.agentId=="string"?h.agentId:void 0,k=typeof h.cwd=="string"?h.cwd:void 0,S=typeof h.parentSessionId=="string"?h.parentSessionId:void 0,I=Pn(h._meta??void 0),x=I.title,C=I.model,$=I.workspace;if(!k&&S){let Q=e.manager.get(S);Q&&(k=Q.cwd)}if(!k)throw he(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let P=await jd(k),M=y??P.agentId??e.defaultAgent,F=await e.registry?.getAgent(M),K=Or(P.configDefaults,F??{id:M})?.value,Y=C??K?.model,z=typeof h.interactive=="boolean"?h.interactive:!1,re=await e.manager.create({agentId:M,cwd:k,parentSessionId:S,interactive:z,transformChain:[],title:x,model:Y,configDefaults:K,...$!==void 0?{workspace:$}:{}});return{childSessionId:re.sessionId,...re.workspace!==void 0||re.workspaceError!==void 0?{_meta:{[pt]:{...re.workspace!==void 0?{workspaceInfo:re.workspace}:{},...re.workspaceError!==void 0?{workspaceError:re.workspaceError}:{}}}}:{}}}));let p=async(g,h)=>{let y=g??{};if(typeof y.sessionId!="string")throw he(G.InvalidParams,"fork_session requires sessionId");let k=typeof y.forkAt=="string"?y.forkAt:void 0,S=typeof y.cwd=="string"?y.cwd:void 0,I=typeof y.agentId=="string"?y.agentId:void 0,x=h?void 0:typeof y.mode=="string"&&(y.mode==="verbatim"||y.mode==="synthesis")?y.mode:void 0,C=typeof y.model=="string"&&y.model.length>0?y.model:void 0,$;if(h){let Y=y.selection;if(Y!==void 0&&(typeof Y.text!="string"||Y.text.length===0))throw he(G.InvalidParams,"selection.text must be a non-empty string");$={...Y!==void 0?{selection:{text:Y.text,...typeof Y.responsePartId=="string"?{responsePartId:Y.responsePartId}:{}}}:{}}}let P=await e.manager.forkSession(y.sessionId,{...$!==void 0?{side:$}:{},...k!==void 0?{forkAt:k}:{},...S!==void 0?{cwd:S}:{},...I!==void 0?{agentId:I}:{},...x!==void 0?{mode:x}:{},...C!==void 0?{model:C}:{}}),M=e.manager.get(P.sessionId);if(!M){let Y=await e.manager.loadFromDisk(P.sessionId);if(!Y)throw he(G.InternalError,`fork ${P.sessionId} vanished before it could be attached`);M=await Na(e,{...Y,onInstallProgress:fm(l)})}Kc(u,M,M.sessionId);let F=Pi(l,M,u),{entries:K}=await M.attach(F,"full");u.attached.set(M.sessionId,{sessionId:M.sessionId,clientId:F.clientId,readonly:!1});for(let Y of K){if(l.isClosed())break;await l.notify(Y.method,Vs(Js(Y.params,Y.recordedAt),Y.seq)).catch(()=>{})}return{...P,sessionId:M.sessionId}};l.onRequest("hydra-acp/session/fork",g=>p(g,!1)),l.onRequest("hydra-acp/session/side",g=>p(g,!0)),l.onRequest("session/fork",async g=>{let h=g??{};if(typeof h.sessionId!="string")throw he(G.InvalidParams,"session/fork requires sessionId");let y=typeof h.cwd=="string"?h.cwd:void 0,k=await e.manager.forkSession(h.sessionId,{...y!==void 0?{cwd:y}:{},mode:"verbatim"}),S=e.manager.get(k.sessionId);if(!S){let C=await e.manager.loadFromDisk(k.sessionId);if(!C)throw he(G.InternalError,`fork ${k.sessionId} vanished before it could be attached`);S=await Na(e,{...C,onInstallProgress:fm(l)})}Kc(u,S,S.sessionId);let I=Pi(l,S,u),{entries:x}=await S.attach(I,"full");u.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:I.clientId,readonly:!1});for(let C of x){if(l.isClosed())break;await l.notify(C.method,Vs(Js(C.params,C.recordedAt),C.seq)).catch(()=>{})}return{sessionId:S.sessionId}});let m=async(g,h)=>{let y=g??{};if(typeof y.sessionId!="string")throw he(G.InvalidParams,`${h} requires sessionId`);let k=await e.manager.resolveCanonicalId(y.sessionId)??y.sessionId,S=e.manager.get(k);if(S)return await S.close({deleteRecord:!0,by:`session/delete ${u.clientId}`}),await e.manager.waitForDeletion(k),await e.manager.hasRecord(k)&&await e.manager.deleteRecord(k),{id:k,existed:!0};let I=await e.manager.deleteRecord(k);return{id:k,existed:I}};l.onRequest("session/delete",async g=>(await m(g,"session/delete"),{})),l.onRequest("session/close",async g=>{let h=g??{};if(typeof h.sessionId!="string")throw he(G.InvalidParams,"session/close requires sessionId");f(h.sessionId,"session/close");let y=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,k=e.manager.get(y);if(k)return await k.close({deleteRecord:!1,by:`session/close ${u.clientId}`+(u.processIdentity?` (${u.processIdentity.name})`:"")}),{};if(await e.manager.hasRecord(y))return{};throw he(G.SessionNotFound,`session ${y} not found`)}),l.onRequest("hydra-acp/session/delete",async g=>{let{id:h,existed:y}=await m(g,"hydra-acp/session/delete");if(!y)throw he(G.SessionNotFound,`session ${h} not found`);return{deleted:!0,sessionId:h}}),o?.kind==="transformer"&&(l.onRequest("hydra-acp/child_session/await",async g=>{let h=g??{},y=typeof h.childSessionId=="string"?h.childSessionId:void 0,k=h.until==="idle"?"idle":"turn_complete",S=typeof h.timeoutMs=="number"?Math.min(h.timeoutMs,18e5):3e5;if(!y)throw he(-32602,"await_child requires childSessionId");let I=yr(e.manager,y,`child session ${y} not found`);return new Promise(x=>{let P=[],M=[],F=0,K=!1,Y,z,re=!1,Q=()=>{re||(re=!0,clearTimeout(ke),Y?.(),z?.(),x(K?{entries:P,truncated:!0}:{entries:P}))};Y=I.onBroadcast(xe=>{let je=eW(xe);for(P.push(xe),M.push(je),F+=je;P.length>0&&(P.length>1e3||F>1048576);)P.shift(),F-=M.shift()??0,K=!0;k==="turn_complete"&&xe.params?.update?.sessionUpdate==="turn_complete"&&Q()});let ke=setTimeout(Q,S);typeof ke.unref=="function"&&ke.unref(),z=I.onClose(()=>Q())})}),l.onRequest("hydra-acp/child_session/close",async g=>{let h=g??{},y=typeof h.childSessionId=="string"?h.childSessionId:void 0;if(!y)throw he(-32602,"close_child_session requires childSessionId");let k=e.manager.get(y);return k&&await k.close({deleteRecord:!1,by:`child_session/close ${u.clientId}`}),{ok:!0}}),l.onRequest("hydra-acp/attention/set",async g=>iW(g,o.name,e)),l.onRequest("hydra-acp/attention/clear",async g=>aW(g,o.name,e)),l.onRequest("hydra-acp/connection/keep_alive",async g=>{let h=g??{},y=typeof h.token=="string"?h.token:void 0,k=typeof h.sessionId=="string"?h.sessionId:void 0,S=typeof h.estimatedRemainingMs=="number"?h.estimatedRemainingMs:void 0;return y&&k&&e.manager.get(k)?.keepAliveClaim(y,S),{ok:!0}})),l.onRequest("hydra-acp/session/tool_content",async g=>{let h=g??{};if(typeof h.sessionId!="string"||typeof h.hash!="string")throw he(G.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let y=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,k=await e.manager.loadToolBlob(y,h.hash);if(k===null)throw he(G.SessionNotFound,"tool content not found");return{content:k}}),l.onRequest("authenticate",async g=>tW(g,e)),l.onRequest("logout",async g=>nW(g,e)),l.onRequest("session/new",async g=>{let h=AC.parse(g),y=Pn(g?._meta),k=Array.isArray(y.transformers)&&y.transformers.every(ue=>typeof ue=="string")?y.transformers:e.manager.defaultTransformers??[],S=e.transformers?.resolveChain(k)??[],I=await jd(h.cwd),x=y.agentId??I.agentId??e.defaultAgent,C=await e.registry?.getAgent(x),$=Or(I.configDefaults,C??{id:x})?.value,P,M,F=h.mcpServers;if(y.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){P=l0(32).toString("hex"),M=e.mcpTokenRegistry.reserve(P);let oe={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${P}`}]};F=[...h.mcpServers??[],oe]}let K,Y,z=qc(e);z!==void 0&&(F=[...F??[],...z.descriptors]);let re=lk({baselineMcpServers:h.mcpServers,stdinEnabled:y.mcpStdin===!0,deps:e}),Q;try{Q=await e.manager.create({cwd:h.cwd,agentId:x,mcpServers:F,title:y.title,agentArgs:y.agentArgs,model:y.model??$?.model,configDefaults:$,onInstallProgress:fm(l),transformChain:S,originatingClient:u.clientInfo,...y.interactive!==void 0?{interactive:y.interactive}:{},...y.env!==void 0?{forwardedEnv:y.env}:{},...y.workspace!==void 0?{workspace:y.workspace}:{},...re?{mintMcpServersForSwap:re}:{}})}catch(ue){throw M!==void 0&&M.abandon(ue instanceof Error?ue:void 0),Y!==void 0&&Y.abandon(ue instanceof Error?ue:void 0),z!==void 0&&z.abandon(ue instanceof Error?ue:void 0),ue}if(P!==void 0&&M!==void 0&&e.mcpTokenRegistry!==void 0){let ue=P,oe=e.mcpTokenRegistry;M.complete(Q),Q.onClose(()=>{oe.unbind(ue)})}if(K!==void 0&&Y!==void 0&&e.mcpTokenRegistry!==void 0){let ue=K,oe=e.mcpTokenRegistry;Y.complete(Q),Q.onClose(()=>{oe.unbind(ue)})}z!==void 0&&z.bindToSession(Q),h0(Q.sessionId,e);let ke,xe;try{Kc(u,Q,Q.sessionId),ke=Pi(l,Q,u),{entries:xe}=await Q.attach(ke,"full")}catch(ue){throw await Q.close({deleteRecord:!1,by:"session/new attach-failed"}).catch(()=>{}),ue}u.attached.set(Q.sessionId,{sessionId:Q.sessionId,clientId:ke.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let ue of xe){if(l.isClosed())break;await l.notify(ue.method,Vs(Js(ue.params,ue.recordedAt),ue.seq)).catch(()=>{})}})()});let je=pm(Q),Ge=hm(Q);return{sessionId:Q.sessionId,...je?{modes:je}:{},...Ge?{models:Ge}:{},configOptions:Q.buildConfigOptions(),_meta:mm(e.manager,Q,{clientId:ke.clientId})}}),l.onRequest("session/attach",async g=>{let h=EC.parse(g),y=h.clientInfo?.version;y&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,y):e.onTransformerVersion?.(o.name,y));let k=Pn(h._meta),S=k.resume,I=k.readonly===!0,x=k.env;n.log.info(`session/attach sessionId=${h.sessionId} hasResumeHints=${!!S} readonly=${I}`);let C=S?h.sessionId:await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,$=e.manager.get(C);if(!$&&I){let Q=await e.manager.loadFromDisk(C);if(!Q)throw he(G.SessionNotFound,`session ${h.sessionId} not found`);let ke=Sc(await e.manager.loadHistory(C,{...k.historyLimit!==void 0?{maxEntries:k.historyLimit}:{}}),Q.side),xe=h.clientId??`cli_${gk(8)}`;u.attached.set(Q.hydraSessionId,{sessionId:Q.hydraSessionId,clientId:xe,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${Q.hydraSessionId} clientId=${xe} attachedCount=${u.attached.size} replayed=${ke.length}`);for(let je of ke)await l.notify(je.method,Vs(Js(je.params,je.recordedAt),je.seq)).catch(()=>{});return{sessionId:Q.hydraSessionId,clientId:xe,connectedClients:[xe],historyPolicy:"full",replayed:ke.length,_meta:dW(Q)}}let P=!$;if(!$){let Q=await e.manager.loadFromDisk(C),ke=await rW(C,S,Q?.upstreamSessionId,e.manager);ke.kind==="ignore"&&n.log.warn(ke.logMessage);let xe=Q;if(S&&ke.kind==="honor"&&(xe={...Q,hydraSessionId:h.sessionId,upstreamSessionId:S.upstreamSessionId,agentId:S.agentId,cwd:Q?.workspace?.path??S.cwd,...S.title!==void 0?{title:S.title}:{},...S.agentArgs!==void 0?{agentArgs:S.agentArgs}:{}}),!xe)throw he(G.SessionNotFound,`session ${h.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(xe.agentId,xe.upstreamSessionId))throw he(G.SessionNotFound,`session ${h.sessionId} was deleted`);let je=xe.originatingClient?xe:{...xe,originatingClient:u.clientInfo},Ge=x!==void 0?{...je,forwardedEnv:x}:je;$=await Na(e,{...Ge,onInstallProgress:fm(l)})}Kc(u,$,$.sessionId);let M=Pi(l,$,u,h.clientInfo,h.clientId),F=k.replayMode==="drip",{entries:K,appliedPolicy:Y}=await $.attach(M,h.historyPolicy,{afterMessageId:h.afterMessageId,afterSeq:h.afterSeq,raw:F,...k.historyLimit!==void 0?{historyLimit:k.historyLimit}:{},...k.toolContent!==void 0?{toolContent:k.toolContent}:{}});if(u.attached.set($.sessionId,{sessionId:$.sessionId,clientId:M.clientId,readonly:I}),x!==void 0&&await e.manager.setForwardedEnv($.sessionId,x).catch(()=>{}),n.log.info(`session/attach OK sessionId=${$.sessionId} clientId=${M.clientId} attachedCount=${u.attached.size} requestedPolicy=${h.historyPolicy} appliedPolicy=${Y} replayed=${K.length} readonly=${I}${F?" replayMode=drip":""}`),F){let Q=k.dripSpeed&&k.dripSpeed>0?k.dripSpeed:1,ke=750;(async()=>{let xe=null;for(let je of K){let Ge=typeof je.recordedAt=="number"?je.recordedAt:null;if(xe!==null&&Ge!==null){let ue=Math.min(ke,Math.max(0,(Ge-xe)/Q));ue>0&&await new Promise(oe=>setTimeout(oe,ue))}Ge!==null&&(xe=Ge);try{await l.notify(je.method,Vs(Js(je.params,Ge??void 0),je.seq))}catch{return}}})()}else for(let Q=0;Q<K.length&&!l.isClosed();Q++){let ke=K[Q],xe=l.notify(ke.method,Vs(Js(ke.params,ke.recordedAt),ke.seq)).catch(()=>{});(Q+1)%200===0&&await xe}$.replayPendingPermissions(M);let z=pm($),re=hm($);return{sessionId:$.sessionId,clientId:M.clientId,connectedClients:$.connectedClients(M.clientId),historyPolicy:Y,replayed:K.length,...z?{modes:z}:{},...re?{models:re}:{},configOptions:$.buildConfigOptions(),_meta:mm(e.manager,$,{resurrected:P})}}),l.onRequest("session/detach",async g=>{let h=PC.parse(g),y=u.attached.get(h.sessionId);if(!y)throw he(G.SessionNotFound,"client not attached to that session");let k=e.manager.get(h.sessionId);return k?.detach(y.clientId),u.attached.delete(h.sessionId),k&&e.manager.reapIfOrphanedNonInteractive(h.sessionId),{sessionId:h.sessionId,_meta:{[pt]:{detachStatus:"detached"}}}}),l.onRequest("session/list",async g=>{let h=MC.parse(g??{});return{sessions:(await e.manager.list({cwd:h.cwd})).filter(I=>I.originatingClient?.name!==Aa).map(_C)}}),l.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw he(G.InternalError,"agent registry unavailable");return wc(e.registry)}),l.onRequest("hydra-acp/agents/auth_methods",async g=>{let h=g??{};if(typeof h.agentId!="string"||h.agentId.length===0)throw he(G.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(h.agentId)).authMethods??[]}}),l.onRequest("session/prompt",async g=>{let h=OC.parse(g);f(h.sessionId,"session/prompt");let y=await i0(h,e.manager,x=>{n.log.warn(`session/prompt: dropping unknown sentBy.sessionId=${x} sessionId=${h.sessionId}`)});if(y?.fromSession!==void 0){if((y.depth??0)>3)throw n.log.warn(`session/prompt: refusing depth ${y.depth} chain from ${y.fromSession} to ${h.sessionId}`),he(G.InvalidRequest,`message chain too deep (${y.depth} hops, max ${3}): refusing to continue a session-to-session loop`);if(y.awaiting===!0&&d0(y.fromSession,h.sessionId))throw n.log.warn(`session/prompt: refusing deadlock ${y.fromSession} -> ${h.sessionId}`),he(G.InvalidRequest,`would deadlock: ${h.sessionId} is already blocked waiting on ${y.fromSession}. Send with --no-wait, or let the other turn finish first.`)}let k=u.attached.get(h.sessionId);if(!k)throw n.log.warn(`session/prompt rejected: not attached sessionId=${h.sessionId} attachedKeys=[${[...u.attached.keys()].join(",")}]`),he(G.SessionNotFound,"not attached to session");let S=e.manager.get(h.sessionId);if(!S){let x=await e.manager.loadFromDisk(h.sessionId);if(!x)throw he(G.SessionNotFound,`session ${h.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${h.sessionId}`),S=await Na(e,x);let C=Pi(l,S,u,void 0,k.clientId);await S.attach(C,"none")}let I=y?.awaiting===!0&&y.fromSession!==void 0?a0(y.fromSession,h.sessionId):void 0;try{return await S.prompt(k.clientId,h,y)}finally{I?.()}});let b=g=>{let h;try{h=Lp.parse(g)}catch(S){n.log.warn(`session/cancel: invalid params: ${S.message}`);return}let y=u.attached.get(h.sessionId);if(!y)return;if(y.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${h.sessionId}`);return}let k=e.manager.get(h.sessionId);k&&k.cancel(y.clientId).catch(S=>{n.log.warn(`session/cancel for ${h.sessionId}: ${S.message}`)})};l.onNotification("session/cancel",b),l.onRequest("session/cancel",async g=>{let h=Lp.parse(g);return f(h.sessionId,"session/cancel"),b(g),null}),l.onRequest("hydra-acp/prompt/cancel",async g=>{let h=LC.parse(g);return f(h.sessionId,"hydra-acp/prompt/cancel"),yr(e.manager,h.sessionId).cancelQueuedPrompt(h.messageId)}),l.onRequest("hydra-acp/session/force_cancel",async g=>{let h=Lp.parse(g);return f(h.sessionId,"hydra-acp/session/force_cancel"),yr(e.manager,h.sessionId).forceCancel()}),l.onRequest("hydra-acp/prompt/update",async g=>{let h=NC.parse(g);return f(h.sessionId,"hydra-acp/prompt/update"),yr(e.manager,h.sessionId).updateQueuedPrompt(h.messageId,h.prompt)}),l.onRequest("hydra-acp/prompt/amend",async g=>{let h=DC.parse(g);f(h.sessionId,"hydra-acp/prompt/amend");let y=u.attached.get(h.sessionId);if(!y)throw he(G.SessionNotFound,"not attached to session");return yr(e.manager,h.sessionId).amendPrompt(y.clientId,h)}),l.onRequest("_session/steering",async g=>{let h=HC.parse(g);f(h.sessionId,"_session/steering");let y=u.attached.get(h.sessionId);if(!y)throw he(G.SessionNotFound,"not attached to session");let k=e.manager.get(h.sessionId);if(!k){let S=await e.manager.loadFromDisk(h.sessionId);if(!S)throw he(G.SessionNotFound,`session ${h.sessionId} not found`);k=await Na(e,S);let I=Pi(l,k,u,void 0,y.clientId);await k.attach(I,"none")}return k.steer(y.clientId,h)}),l.onRequest("session/resume",async g=>{let h=g??{},y=typeof h.sessionId=="string"?h.sessionId:void 0;if(!y)throw he(G.InvalidParams,"session/resume requires sessionId");let k=await e.manager.resolveCanonicalId(y)??y,S=e.manager.get(k);if(!S){let $=await e.manager.loadFromDisk(k);if(!$)throw he(G.SessionNotFound,`session ${y} not found in memory or on disk`);S=await Na(e,$)}Kc(u,S,S.sessionId);let I=Pi(l,S,u);await S.attach(I,"pending_only"),u.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:I.clientId,readonly:!1}),S.replayPendingPermissions(I);let x=pm(S),C=hm(S);return{sessionId:S.sessionId,...x?{modes:x}:{},...C?{models:C}:{},configOptions:S.buildConfigOptions(),_meta:mm(e.manager,S,{clientId:I.clientId})}}),l.onRequest("session/load",async g=>{let h=g??{},y=typeof h.sessionId=="string"?h.sessionId:void 0;if(!y)throw he(G.InvalidParams,"session/load requires sessionId");let k=await e.manager.resolveCanonicalId(y)??y,S=e.manager.get(k);if(!S){let P=await e.manager.loadFromDisk(k);if(!P)throw he(G.SessionNotFound,`session ${y} not found in memory or on disk`);S=await Na(e,P)}Kc(u,S,S.sessionId);let I=Pi(l,S,u),{entries:x}=await S.attach(I,"full");u.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:I.clientId,readonly:!1});for(let P of x){if(l.isClosed())break;await l.notify(P.method,Vs(Js(P.params,P.recordedAt),P.seq)).catch(()=>{})}S.replayPendingPermissions(I);let C=pm(S),$=hm(S);return{sessionId:S.sessionId,...C?{modes:C}:{},...$?{models:$}:{},configOptions:S.buildConfigOptions(),_meta:mm(e.manager,S,{clientId:I.clientId})}}),l.onRequest("session/set_model",async g=>{let h=g?.sessionId;typeof h=="string"&&f(h,"session/set_model");let y=sW(g,e.manager);if(y.kind==="error")throw n.log.warn(y.logMessage),he(y.code,y.message);if(y.kind==="no_op")return n.log.warn(y.logMessage),await l.notify("session/update",{sessionId:y.sessionId,update:{sessionUpdate:"_hydra_current_model_update",currentModel:y.currentModel}}).catch(()=>{}),null;n.log.info(y.logMessage);let{modelId:k}=y,S=await y.session.forwardModelChange(k,g);return y.session.applyAgentConfigOptionResponse(S,"model"),y.session.applyModelChange(k),S}),l.onRequest("session/set_mode",async g=>{let h=g,y=h?.sessionId;if(typeof y=="string"&&f(y,"session/set_mode"),!h||typeof h.sessionId!="string")throw he(G.InvalidParams,"session/set_mode requires string sessionId");if(typeof h.modeId!="string")throw he(G.InvalidParams,"session/set_mode requires string modeId");let k=yr(e.manager,h.sessionId),S=await k.forwardRequest("session/set_mode",g);return k.applyModeChange(h.modeId),S}),l.onRequest("session/set_config_option",async g=>{let h=g,y=x=>he(G.InvalidParams,x),k=h?.sessionId;if(typeof k=="string"&&f(k,"session/set_config_option"),!h||typeof h.sessionId!="string")throw y("session/set_config_option requires string sessionId");if(typeof h.configId!="string")throw y("session/set_config_option requires string configId");if(typeof h.value!="string")throw y("session/set_config_option requires string value");let S=yr(e.manager,h.sessionId),I=S.buildConfigOptions().find(x=>x.id===h.configId);if(!I)throw y(`unknown configId ${JSON.stringify(h.configId)} for this session`);if(!I.options.some(x=>x.value===h.value))throw y(`value ${JSON.stringify(h.value)} is not valid for configId ${JSON.stringify(h.configId)}`);switch(h.configId){case"model":{if(h.value!==S.currentModel){let x=await S.forwardModelChange(h.value);S.applyAgentConfigOptionResponse(x,"model")}S.applyModelChange(h.value);break}case"mode":{h.value!==S.currentMode&&await S.forwardRequest("session/set_mode",{sessionId:h.sessionId,modeId:h.value}),S.applyModeChange(h.value);break}case"agent":{h.value!==S.agentId&&await S.setAgent(h.value);break}default:{let x=await S.forwardRequest("session/set_config_option",{sessionId:h.sessionId,configId:h.configId,value:h.value});S.applyAgentConfigOptionResponse(x,h.configId)&&S.broadcastConfigOptions()}}return{configOptions:S.buildConfigOptions()}}),l.setDefaultHandler(async(g,h)=>{let y=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),k=h.startsWith("session/"),S=h.startsWith("hydra-acp/");if(!k&&!S||g===null||typeof g!="object"||y.has(h))throw he(G.MethodNotFound,`Method not found: ${h}`);let I=g.sessionId;if(typeof I!="string")throw he(G.MethodNotFound,`Method not found: ${h}`);return f(I,h),yr(e.manager,I).forwardRequest(h,g)})})}async function tW(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw he(G.InvalidParams,"authenticate requires a non-empty methodId string");let r=t.methodId,s=t._meta?.["hydra-acp"],o=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let p=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let d=a.authMethods??[],c=d.find(p=>p.id===r);if(!c){let p=d.map(m=>m.id);throw he(G.InvalidParams,`authenticate: methodId ${JSON.stringify(r)} is not advertised by agent ${a.agentId}; valid: [${p.map(m=>JSON.stringify(m)).join(", ")}]`)}let l=c._meta?.type,u=(()=>{let p=c._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((c.type??(l==="agent"||l==="terminal"?l:u!==void 0?"terminal":"agent"))==="terminal"){let p=(k,S)=>{if(!Array.isArray(k))throw he(G.InvalidParams,`authenticate: method ${JSON.stringify(r)} ${S} must be a string[]; got ${k===null?"null":typeof k}`);for(let I of k)if(typeof I!="string")throw he(G.InvalidParams,`authenticate: method ${JSON.stringify(r)} ${S} must be string[]; got non-string entry ${JSON.stringify(I)}`);return k},m=await e.manager.planSpawnForAgent(a.agentId),b,g;if(u?.args!==void 0){let k=typeof u.command=="string"?u.command:void 0;b=k!==void 0&&f0.isAbsolute(k)?k:m.command,g=p(u.args,'_meta["terminal-auth"].args')}else{let k=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,S=k!==void 0?p(k.raw,k.label):[];b=m.command,g=[...m.args,...S]}let h={};for(let[k,S]of Object.entries(process.env))typeof S=="string"&&(h[k]=S);Object.assign(h,m.env);let y=u0.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${r}`),{kind:"terminal",command:b,args:g,env:h,cwd:y}}try{return await a.connection.request("authenticate",{methodId:r})}catch(p){throw Ci(p,a)}}async function nW(n,e){let r=(n??{})._meta?.["hydra-acp"],s=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,i=s!==void 0?e.manager.getAgentForSession(s):void 0;if(!i||!i.isAlive()){let a=o??e.defaultAgent;i=await e.manager.bootstrapAgentForAuth(a)}return await i.connection.request("logout",{})}function fm(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(Np,t).catch(()=>{})}}function pm(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(s=>{let o={id:s.id,name:s.name??s.id};return s.description!==void 0&&(o.description=s.description),o});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function hm(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(s=>{let o={modelId:s.modelId};return s.name!==void 0&&(o.name=s.name),s.description!==void 0&&(o.description=s.description),o});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}async function rW(n,e,t,r){return e?await r.isRetiredGeneration(n,e.upstreamSessionId)?{kind:"ignore",logMessage:`session/attach ignoring stale resume hint sessionId=${n} hintUpstream=${e.upstreamSessionId} recordUpstream=${t} (retired generation)`}:{kind:"honor"}:{kind:"none"}}function sW(n,e){if(!n||typeof n!="object")return{kind:"error",code:G.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:G.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:G.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let r=e.get(t.sessionId);if(!r)return{kind:"error",code:G.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let s=r.availableModels(),o=Tc(t.modelId,s);if(o.kind==="none")return{kind:"ok",session:r,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:r,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:r,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=s.map(d=>d.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return r.currentModel!==void 0&&r.currentModel.length>0?{kind:"no_op",session:r,sessionId:t.sessionId,currentModel:r.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(r.currentModel)} agentId=${r.agentId} known=[${i}]`}:{kind:"error",code:G.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${r.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${r.agentId} known=[${i}] (no current model to fall back to)`}}async function oW(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0;if(!s)throw he(G.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw he(G.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw he(G.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return yr(t.manager,s).addTransformer(o),{ok:!0}}async function iW(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0,o=typeof r.reason=="string"?r.reason:void 0;if(!s)throw he(G.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw he(G.InvalidParams,"hydra-acp/attention/set requires string reason");return yr(t.manager,s).setAttentionFlag(e,o,r.payload),{ok:!0}}async function aW(n,e,t){let r=n??{},s=typeof r.sessionId=="string"?r.sessionId:void 0,o=typeof r.reason=="string"?r.reason:void 0;if(!s)throw he(G.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw he(G.InvalidParams,"hydra-acp/attention/clear requires string reason");return yr(t.manager,s).clearAttentionFlag(e,o),{ok:!0}}function dW(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,workspace:n.workspace,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:Pa(n.currentUsage),forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,armedTasks:0,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels,armedTaskList:[]};return{[pt]:Op(e,t)}}function mm(n,e,t={}){let r=n.liveListEntry(e),s={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),armedTaskList:e.armedBackgroundTasks,...t.resurrected===!0?{resurrected:!0}:{}};return lu(e.agentMeta,Op(r,s))}function cW(){return{protocolVersion:1,agentInfo:{name:"hydra",version:Fe},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:{...lu(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0},side:{selection:!0}}}),steering:{supported:!0}}}}function lW(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let r=e.transformers.resolveChain([t])[0];r&&n.addTransformer(r)}}function h0(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let r of t)r.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function Pi(n,e,t,r,s){return{clientId:s??`cli_${gk(8)}`,connection:n,clientInfo:r}}function Kc(n,e,t){let r=n.attached.get(t);r&&(e.detach(r.clientId),n.attached.delete(t))}var gm=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,r,s=new Promise((i,a)=>{t=i,r=a});s.catch(()=>{});let o={session:void 0,sessionReady:s,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),r(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:r}=this.reserve(e);r(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let r=this.byToken.get(e);r!==void 0&&r.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let r of t.disposers)try{await r()}catch{}}}size(){return this.byToken.size}};import{randomUUID as uW}from"crypto";import{McpServer as fW}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as pW}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Mn}from"zod";function yk(n){if(n.method!=="session/update")return null;let t=n.params?.update;return!t||typeof t.sessionUpdate!="string"?null:{kind:t.sessionUpdate,update:t}}function sr(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var m0="Bearer ";function Gc(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(m0))return;let t=e.slice(m0.length).trim();return t.length>0?t:void 0}function hW(n){let e=new fW({name:"hydra-acp-stdin",version:"1.0.0"},{instructions:"Piped input from `hydra cat --stream` is exposed here as a byte stream. Use `tail` for the latest N bytes (good for finding the end of a log), `head` for the first N bytes (good for headers/preamble), `read` for windowed reads against an absolute byte cursor, `wait_for_more` to block until new bytes arrive past a cursor, and `info` for the current cursors/capacity/closed status. Byte payloads come back base64-encoded."});return e.registerTool("tail",{description:"Return the most recent `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means older bytes existed but have been evicted from the ring.",inputSchema:{bytes:Mn.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let r=n.streamTail(t);return sr(r)}),e.registerTool("head",{description:"Return the first `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means the head has already been evicted from the ring and the returned bytes start at the oldest still-resident cursor.",inputSchema:{bytes:Mn.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let r=n.streamHead(t);return sr(r)}),e.registerTool("read",{description:"Read up to `max_bytes` bytes starting at absolute byte `cursor`. Returns `{bytes, nextCursor, gap?, eof?}` \u2014 `gap` is the number of bytes silently skipped because the ring had evicted them; `eof:true` means the producer closed and there is nothing left to read.",inputSchema:{cursor:Mn.number().int().min(0).describe("Absolute byte offset to start reading from. Use 0 to read from the very beginning (may produce a gap if old bytes have been evicted)."),max_bytes:Mn.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Mn.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:r,wait_ms:s})=>{let o=await n.streamRead(t,r,s);return sr(o)}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:Mn.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Mn.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:r})=>{let s=await n.streamWaitFor(t,r),o=n.streamInfo();return sr({outcome:s,writeCursor:o.writeCursor,closed:o.closed})}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:Mn.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Mn.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Mn.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Mn.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Mn.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Mn.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Mn.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Mn.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Mn.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let r={pattern:t.pattern};t.regex!==void 0&&(r.regex=t.regex),t.case_insensitive!==void 0&&(r.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(r.invert=t.invert),t.max_matches!==void 0&&(r.maxMatches=t.max_matches),t.max_bytes!==void 0&&(r.maxBytes=t.max_bytes),t.context_before!==void 0&&(r.contextBefore=t.context_before),t.context_after!==void 0&&(r.contextAfter=t.context_after),t.cursor!==void 0&&(r.cursor=t.cursor);let s=n.streamGrep(r);return sr(s)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return sr(t)}),e}var mW=1e4;function g0(n,e){let t=new Map;async function r(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=hW(a),l=new pW({sessionIdGenerator:()=>uW()});await c.connect(l);let u={server:c,transport:l};return t.set(i,u),e.addDisposer(i,async()=>{t.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function s(i,a){let d=Gc(i);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(c.session!==void 0)l=c.session;else{let f,p=new Promise(b=>{f=setTimeout(()=>b(void 0),mW)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),m===void 0){a.code(503).send({error:"session not ready"});return}l=m}let u=await r(d,l);a.hijack(),await u.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)}),n.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)}),n.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await s(i,a)})}th();import{randomUUID as gW}from"crypto";import{McpServer as yW}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as wW}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as oo}from"zod";function bW(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}var y0=2e3,w0=2e4;function kW(n,e,t){if(e!=="tool_call"&&e!=="tool_call_update")return Pc([n]);let r=[],s=gu(t);s!==void 0?r.push(`Tool: ${s}`):typeof t.title=="string"&&t.title.length>0&&r.push(`Tool: ${t.title}`);let o=t.rawInput;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[a,d]of Object.entries(o))typeof d=="string"&&d.length>0&&r.push(`${a}=${d}`);if(Array.isArray(t.locations))for(let a of t.locations)typeof a?.path=="string"&&a.path.length>0&&r.push(a.path);let i=eh(t);return i!==void 0&&r.push(i),r.join(`
418
+ `)}function vW(n,e){if(n.length<=148)return n;let s=Math.floor(148/2),o=e-s;o<0&&(o=0);let i=o+148;i>n.length&&(o=n.length-148,o<0&&(o=0));let a=n.slice(o,i);return o>0&&(a="\u2026"+a),i<n.length&&(a=a+"\u2026"),a}function SW(n){let e=new yW({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Covers assistant and user messages, the arguments of every tool call including full shell commands, and what those calls printed. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:oo.string().min(1).describe("Case-insensitive substring to search for."),limit:oo.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:oo.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:r=10,include_tool_calls:s=!0})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return sr({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let i=[],a=t.toLowerCase();for await(let{entryId:c,entry:l}of o.iterRecallNewestFirst()){let u=yk(l);if(!u)continue;let{kind:f,update:p}=u;if((f==="tool_call"||f==="tool_call_update")&&!s)continue;let m=kW(l,f,p),b=m.toLowerCase().indexOf(a);if(b<0)continue;let g=bW(f),h=vW(m,b),y=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(i.push({entryId:c,speaker:g,snippet:h,timestamp:y}),i.length>=r)break}i.sort((c,l)=>c.entryId-l.entryId);let d=i.length>=r;return sr({matches:i,total_matched:i.length,truncated:d})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history, including each tool call's arguments and what it printed. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:oo.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:oo.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:r})=>{let s=await n();if(!s.summarizedThroughEntry||s.summarizedThroughEntry===0)return sr({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. `range` retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(r<t)throw new Error(`range: to_entry (${r}) must be >= from_entry (${t})`);let o=r-t+1;if(o>50)throw new Error(`range: range size (${o}) exceeds maximum of 50 entries`);let i=await s.getRecallTotalCount();if(i===0)return sr({text:"",entry_count:0,truncated:!1});let a=Math.min(t,i-1),d=Math.min(r,i-1),c=a>t||d<r;if(a>d)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:c}};let l=await s.sliceRecallHistory(a,d),u=Pc(l,{toolOutput:{maxPerCall:y0,maxTotal:w0}});return{content:[{type:"text",text:u}],structuredContent:{text:u,entry_count:l.length,truncated:c}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name, ACP kind, and/or file path. Returns when each tool was called, its arguments (including the full shell command), the result status, and what the call printed. Use this to recall which files were read/edited, what shell commands ran, and what they output.",inputSchema:{tool_name:oo.string().optional().describe("Case-insensitive substring of the tool name. Names vary by agent for the same tool (Bash, Terminal, bash), so prefer `kind` when you want every shell invocation."),kind:oo.string().optional().describe("ACP tool kind: execute (shell), read, edit, think, other. Agent-independent, unlike tool_name."),file_path:oo.string().optional(),limit:oo.number().int().min(1).max(100).optional(),include_output:oo.boolean().optional().describe("Include what each call printed (default true). Set false when you only need the commands and not their results.")}},async({tool_name:t,kind:r,file_path:s,limit:o=20,include_output:i=!0})=>{let a=await n();if(!a.summarizedThroughEntry||a.summarizedThroughEntry===0)return sr({calls:[],truncated:!1,note:"This session has no compacted history. `tool_calls` retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let d=typeof t=="string"&&t.length>0,c=typeof r=="string"&&r.length>0,l=typeof s=="string"&&s.length>0;if(!d&&!c&&!l)throw new Error("tool_calls: at least one of tool_name, kind, or file_path must be provided");let u=new Map,f=Math.max(o*4,200);for await(let{entryId:y,entry:k}of a.iterRecallNewestFirst()){let S=yk(k);if(!S)continue;let{kind:I,update:x}=S;if(I!=="tool_call"&&I!=="tool_call_update")continue;let C=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:`__noid_${y}`,$=u.get(C);if($||($={entryId:y,toolName:"(unnamed)",nameAuthoritative:!1,rawInput:{},locations:[],status:"in_progress"},u.set(C,$)),y<$.entryId&&($.entryId=y),!$.nameAuthoritative){let M=gu(x);M!==void 0?($.toolName=M,$.nameAuthoritative=!0):typeof x.name=="string"&&x.name.length>0?($.toolName=x.name,$.nameAuthoritative=!0):I==="tool_call"&&typeof x.title=="string"&&x.title.length>0&&($.toolName=x.title,$.nameAuthoritative=!0)}if($.kind===void 0&&typeof x.kind=="string"&&x.kind.length>0&&($.kind=x.kind),$.output===void 0){let M=eh(x);M!==void 0&&($.output=M)}let P=x.rawInput;if(P&&typeof P=="object"&&!Array.isArray(P)&&Object.keys(P).length>0)for(let[M,F]of Object.entries(P))$.rawInput[M]===void 0&&($.rawInput[M]=F);if(Array.isArray(x.locations))for(let M of x.locations){let F=M?.path;typeof F=="string"&&F.length>0&&!$.locations.includes(F)&&$.locations.push(F)}if(typeof x.status=="string"&&$.status==="in_progress"&&($.status=x.status),k.recordedAt!==void 0&&$.timestamp===void 0&&($.timestamp=String(k.recordedAt)),u.size>=f)break}let p=[...u.keys()].sort((y,k)=>u.get(y).entryId-u.get(k).entryId),m=[],b=w0,g=!1;for(let y of p){let k=u.get(y);if(k.toolName=ub({name:k.toolName,rawInput:k.rawInput,...k.kind!==void 0?{kind:k.kind}:{}}),d&&!k.toolName.toLowerCase().includes(t.toLowerCase())||c&&(k.kind??"").toLowerCase()!==r.toLowerCase())continue;if(l){let x=s.toLowerCase(),C=["file_path","filePath","path"],$=!1;for(let P of C){let M=k.rawInput[P];if(typeof M=="string"&&M.toLowerCase().includes(x)){$=!0;break}}if(!$){for(let P of k.locations)if(P.toLowerCase().includes(x)){$=!0;break}}if(!$)continue}let S={};for(let[x,C]of Object.entries(k.rawInput))typeof C=="string"?S[x]=C.length>500?C.slice(0,497)+"\u2026":C:(typeof C=="number"||typeof C=="boolean")&&(S[x]=C);k.locations.length>0&&S.locations===void 0&&(S.locations=k.locations);let I={entryId:k.entryId,tool:k.toolName,args:S,status:k.status,timestamp:k.timestamp};if(k.kind!==void 0&&(I.kind=k.kind),i&&k.output!==void 0){let x=k.output,C=Math.min(y0,b);if(C<=0)g=!0;else{let $=x.length<=C?x:x.slice(0,C-1)+"\u2026";I.output=$,I.outputBytes=x.length,I.outputTruncated=$.length<x.length,b-=$.length}}if(m.push(I),m.length>=o)break}let h=m.length>=o;return sr({calls:m,truncated:h,...g?{outputBudgetExhausted:g}:{}})}),e}var xW=1e4;function b0(n,e){let t=new Map;async function r(i,a){let d=t.get(i);if(d!==void 0)return d.transport;let c=SW(a),l=new wW({sessionIdGenerator:()=>gW()});await c.connect(l);let u={server:c,transport:l};return t.set(i,u),e.addDisposer(i,async()=>{t.delete(i);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function s(i,a){let d=Gc(i);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown recall token"});return}let u=await r(d,async()=>{if(c.session!==void 0)return c.session;let f,p=new Promise(b=>{f=setTimeout(()=>b(void 0),xW)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await u.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)}),n.get("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)}),n.delete("/mcp/hydra-acp-recall",o,async(i,a)=>{await s(i,a)})}var ym=class{byName=new Map;changeHandlers=[];register(e,t,r,s){this.byName.set(e,{connection:t,instructions:r,tools:[...s]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let r of this.changeHandlers)try{r(e,t)}catch{}}};import{StreamableHTTPServerTransport as MW}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as _W}from"crypto";import{Server as IW}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as CW,ListToolsRequestSchema as RW}from"@modelcontextprotocol/sdk/types.js";function k0(n,e,t,r){let s=typeof t=="function"?async()=>t():async()=>t,o=new IW({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return o.setRequestHandler(RW,async()=>{let a=r?.peekSessionId?.();if(a!==void 0&&r?.fetchSessionTools!==void 0)try{let d=await r.fetchSessionTools(a);if(d!==void 0)return{tools:d.map(i)}}catch{}return{tools:e.tools.map(i)}}),o.setRequestHandler(CW,async(a,d)=>{let c=a.params.name,l=d._meta?.progressToken??d.requestId,u=TW(l,d.sendNotification);try{let f=await s(),p=await EW(e.connection,n,c,a.params.arguments??{},f);return PW(p,c)}catch(f){return wk(f instanceof Error?f.message:String(f))}finally{u()}}),o}var AW=15e3;function TW(n,e,t=AW){if(n===void 0)return()=>{};let r=0,s=setInterval(()=>{r+=1,e({method:"notifications/progress",params:{progressToken:n,progress:r}}).catch(()=>{})},t);return s.unref?.(),()=>clearInterval(s)}async function EW(n,e,t,r,s){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:r,sessionId:s})}function PW(n,e){if(n===null||typeof n!="object")return wk(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:wk(`extension ${e} omitted content array`)}function wk(n){return{content:[{type:"text",text:n}],isError:!0}}var $W=1e4;function v0(n,e,t){let r=new Map;async function s(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function o(l){for(let u of r.values()){let f=u.get(l);f!==void 0&&(u.delete(l),s(f))}}async function i(l,u){for(let[f,p]of r){if(e.lookup(f)?.session?.sessionId!==l)continue;let b=p.get(u);if(b!==void 0)try{await b.server.sendToolListChanged()}catch{}}}t.onChange(l=>{o(l)});async function a(l,u){let f=r.get(l);f===void 0&&(f=new Map,r.set(l,f),e.addDisposer(l,async()=>{let S=r.get(l);if(S!==void 0){r.delete(l);for(let I of S.values())await s(I)}}));let p=f.get(u);if(p!==void 0)return p.transport;let m=t.lookup(u);if(m===void 0)return;let y=k0(u,m,async()=>{let S=e.lookup(l);if(S===void 0)throw new Error("mcp token no longer bound");if(S.session!==void 0)return S.session.sessionId;let I,x=new Promise($=>{I=setTimeout(()=>$(void 0),$W)}),C=await Promise.race([S.sessionReady.catch(()=>{}),x]);if(I!==void 0&&clearTimeout(I),C===void 0)throw new Error("session not ready");return C.sessionId},{peekSessionId:()=>e.lookup(l)?.session?.sessionId,fetchSessionTools:async S=>{let I=await m.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:S});if(!I||typeof I!="object")return;let x=I.tools;if(!Array.isArray(x))return;let C=[];for(let $ of x){if(!$||typeof $!="object")continue;let P=$;if(typeof P.name!="string"||P.name.length===0||typeof P.description!="string"||P.inputSchema===null||typeof P.inputSchema!="object")continue;let M={name:P.name,description:P.description,inputSchema:P.inputSchema};P.outputSchema!==null&&typeof P.outputSchema=="object"&&(M.outputSchema=P.outputSchema),C.push(M)}return C}}),k=new MW({sessionIdGenerator:()=>_W()});return await y.connect(k),f.set(u,{server:y,transport:k}),k}async function d(l,u){let f=Gc(l);if(f===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){u.code(404).send({error:"unknown mcp token"});return}let m=l.params.name,b=await a(f,m);if(b===void 0){u.code(404).send({error:`unknown mcp server: ${m}`});return}u.hijack(),await b.handleRequest(l.raw,u.raw,l.body)}let c={config:{skipAuth:!0}};return n.post("/mcp/:name",c,async(l,u)=>{await d(l,u)}),n.get("/mcp/:name",c,async(l,u)=>{await d(l,u)}),n.delete("/mcp/:name",c,async(l,u)=>{await d(l,u)}),{notifyToolListChanged:i}}async function A0(n,e){BW(n),iu(n.daemon.scrubEnv);let t=n,r=n.daemon.tls?await io.readFile(Ze(n.daemon.tls.key)):void 0,s=n.daemon.tls?await io.readFile(Ze(n.daemon.tls.cert)):void 0;await io.mkdir(D.home(),{recursive:!0});let{stream:o,fileStream:i}=await DW(n.daemon.logLevel),a=OW({logger:{level:n.daemon.logLevel,stream:o},bodyLimit:256*1024*1024});await a.register(FW,{options:{handleProtocols:ZI}}),$w(X=>{a.log.info(X)}),Lw(X=>{a.log.info(X)});let d=await jh.load(),c=await sm.load();Ql(),tw(c);let l=new um(c);l.start();let u=new tm(c);u.start();let f=new Jh,p=new Gh,m=new qh(e),b=new Kh([m,new zh(d),p]),g=pT({validator:b});a.addHook("onRequest",async(X,Et)=>{X.routeOptions.config?.skipAuth||X.url==="/acp"||X.url?.startsWith("/acp?")||(await g(X,Et),!Et.sent&&X.authIdentity?.startsWith("script:")&&!mT(X.method,X.routeOptions.url)&&Et.code(403).send({error:"script tokens may only access read-only session data"}))});let h=setInterval(()=>{d.sweepExpired()},300*1e3);h.unref();let y=setInterval(()=>{f.sweepExpired()},300*1e3);y.unref();let k=new Mp(n,{onFetched:()=>{eT(k,C)},onStaleFallback:(X,Et)=>{let Sr=Math.round(Et/36e5),gn=Sr>=48?`${Math.round(Sr/24)}d`:`${Sr}h`;a.log.warn(`registry fetch failed (${X.message}); serving stale cache last synced ${gn} ago; agent versions may be outdated ('hydra registry refresh' to retry)`)}});sk(X=>a.log.info(X));let S={info:X=>a.log.info(X),warn:X=>a.log.warn(X)},I=X=>bi.spawn({...X,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:S});oC(n.compressToolContent);let x=new Uh,C=new Mh(k,I,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,orphanTimeoutMs:n.daemon.nonInteractiveOrphanTimeoutSeconds*1e3,sessionDefaults:n.sessionDefaults,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,compactionAgent:n.compaction?.agent,compactionModel:n.compaction?.model,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,sessionHistoryArchiveMaxBytes:n.daemon.sessionHistoryArchiveMaxBytes,sessionHistoryArchiveTiers:n.daemon.sessionHistoryArchiveTiers,logger:S,npmRegistry:n.npmRegistry,extensionCommands:x,defaultCwd:n.defaultCwd,disableWorkspaceSnapshots:n.disableWorkspaceSnapshots}),$=new lm(c,void 0,{resolvesLocally:async X=>await C.resolveCanonicalId(X)!==void 0,cache:u}),P=new Hh(Uy(n),void 0,{tokenRegistry:p}),M=new Bh(Wy(n),void 0,{tokenRegistry:p}),F=[];NT(a,Fe,Ri(n),()=>F);let K=new Date().toISOString();qT(a,K);let Y=new gm,z=new ym,re,Q=()=>{if(re!==void 0)return re;let X=a.server.address();return re=`http://127.0.0.1:${X&&typeof X=="object"?X.port:n.daemon.port}`,re},ke={agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction};FT(a,C,ke,{extensionMcp:z,mcpTokenRegistry:Y,getDaemonOrigin:Q},c,u),PT(a,{store:c,localMiss:{resolvesLocally:async X=>await C.resolveCanonicalId(X)!==void 0,cache:u}}),LT(a,k,C,{npmRegistry:n.npmRegistry}),zT(a,P),KT(a,M);let xe={host:n.daemon.host,port:n.daemon.port,...n.daemon.publicHost!==void 0?{publicHost:n.daemon.publicHost}:{},...n.daemon.tls?{tls:{cert:Ze(n.daemon.tls.cert),key:Ze(n.daemon.tls.key)}}:{}};GT(a,()=>({defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,sessionDefaults:{...t.sessionDefaults},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers],listen:xe})),e0(a,{store:d,rateLimiter:f,staticTokenValidator:m}),t0(a,{store:c,health:l}),o0(a,{processRegistry:p}),g0(a,Y),b0(a,Y);let je=v0(a,Y,z);p0(a,{validator:b,manager:C,defaultAgent:n.defaultAgent,processRegistry:p,onExtensionVersion:(X,Et)=>P.reportVersion(X,Et),onTransformerVersion:(X,Et)=>M.reportVersion(X,Et),transformers:M,extensionCommands:x,mcpTokenRegistry:Y,extensionMcp:z,extensionMcpControls:je,getDaemonOrigin:Q,registry:k,foreignSessions:$});let Ge=!!n.daemon.tls;await a.listen({host:Ge?"127.0.0.1":n.daemon.host,port:Ge?0:n.daemon.port});let ue=a.server.address(),oe=ue&&typeof ue=="object"?ue.port:n.daemon.port,$e,lt=n.daemon.host,Tt=oe;if(Ge&&r&&s){$e=await HW({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:oe,tlsOptions:{key:r,cert:s},logger:a.log});let X=$e.address();X&&typeof X=="object"&&(Tt=X.port)}await io.mkdir(D.home(),{recursive:!0}),await tI({pid:process.pid,host:lt,port:Tt,loopbackPort:oe,startedAt:K});let Me={daemonUrl:`http://127.0.0.1:${oe}`,daemonHost:"127.0.0.1",daemonPort:oe,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${oe}/acp`,hydraHome:D.home()};P.setContext(Me),M.setContext(Me),await P.start(),await M.start();try{await C.reconcilePermissionFlags()}catch(X){a.log.warn(`permission flag reconcile failed: ${X.message}`)}try{await C.seedSessionIndex()}catch(X){a.log.warn(`session index seed failed: ${X.message}`)}C.resurrectPendingQueues().catch(X=>{a.log.warn(`queue replay scan failed: ${X.message}`)}),C.resumePendingCompactions().catch(X=>{a.log.warn(`compaction resume scan failed: ${X.message}`)}),C.resumePendingAgentSwaps().catch(X=>{a.log.warn(`agent-swap resume scan failed: ${X.message}`)});let Jt=n.daemon.agentSyncIntervalMinutes*60*1e3,Ye=Jt>0?tT({registry:k,manager:C,intervalMs:Jt,logger:S}):void 0,As=n.daemon.sessionGcIntervalMinutes*60*1e3,Ki=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Kn=As>0?nT({manager:C,intervalMs:As,maxAgeMs:Ki,logger:S}):void 0,Ts=iT({bootConfig:n,apply:X=>{t=X,k.setConfig(X),C.setLiveConfig({sessionDefaults:X.sessionDefaults}),ke.agentId=X.defaultAgent,ke.cwd=X.defaultCwd,iu(X.daemon.scrubEnv)},onDrift:X=>{F=X},logger:S});return{app:a,manager:C,registry:k,extensions:P,transformers:M,mcpTokenRegistry:Y,extensionMcp:z,processRegistry:p,shutdown:async()=>{l.stop(),u.stop(),Ts(),Kn&&Kn(),Ye&&Ye(),clearInterval(h),clearInterval(y);let X=async(Et,Sr)=>{try{await Sr()}catch(gn){a.log.warn(`shutdown step ${Et} failed: ${gn instanceof Error?gn.message:String(gn)}`)}};await X("sessionTokenStore.flush",()=>d.flush()),await X("extensions.stop",()=>P.stop()),await X("transformers.stop",()=>M.stop()),await X("manager.closeAll",()=>C.closeAll()),await X("manager.flushSynopsis",()=>C.flushSynopsis(3e4)),await X("manager.shutdownSynopsis",()=>C.shutdownSynopsis()),await X("manager.flushMetaWrites",()=>C.flushMetaWrites()),await X("manager.flushHistoryWrites",()=>C.flushHistoryWrites()),$w(null),Lw(null),sk(null),$e&&await X("tlsTerminator.close",()=>new Promise(Et=>$e.close(()=>Et()))),await X("app.close",()=>a.close());try{I0.unlinkSync(D.pidFile())}catch{}await X("fileStream.flushSync",()=>i.flushSync())}}}var x0=20;async function NW(n,e){let t=Jc.dirname(n),r=Jc.basename(n,".log"),s=new RegExp(`^${r}\\.(\\d+)\\.log$`),o;try{o=await io.readdir(t)}catch{return}let i=[];for(let d of o){let c=d.match(s);c&&i.push({name:d,n:Number(c[1])})}if(i.length<=e)return;i.sort((d,c)=>d.n-c.n);let a=i.slice(0,i.length-e);await Promise.allSettled(a.map(d=>io.unlink(Jc.join(t,d.name))))}async function DW(n){await NW(D.logFile(),x0);let e=await LW({file:D.logFile(),size:"10m",mkdir:!0,symlink:Fh,limit:{count:x0,removeOtherLogFiles:!0}}),t=S0.destination(2);return{stream:S0.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}async function HW(n){let e=R0.createServer(n.tlsOptions,t=>{let r=C0.connect({host:n.upstreamHost,port:n.upstreamPort}),s=!1,o=i=>{if(!s){s=!0,i&&n.logger.warn(`tls terminator forwarder error: ${i.message??String(i)}`);try{t.destroy()}catch{}try{r.destroy()}catch{}}};t.on("error",o),r.on("error",o),t.on("close",()=>o()),r.on("close",()=>o()),t.pipe(r),r.pipe(t)});return e.on("tlsClientError",t=>{n.logger.warn(`tls handshake error: ${t.message}`)}),await new Promise((t,r)=>{let s=o=>{r(new Error(`TLS listener could not bind ${n.listenHost}:${n.listenPort}: ${o.message}`))};e.once("error",s),e.listen({host:n.listenHost,port:n.listenPort},()=>{e.off("error",s),t()})}),e.on("error",t=>{n.logger.warn(`tls terminator error: ${t.message}`)}),e}function BW(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}Ba();rr();Bc();Gu();async function $0(n={}){let e=await Pr(),t=await Wl();if(await wm(e)){let s=await Qc();process.stdout.write(`Daemon already running${s?` (pid ${s.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
419
419
  `);return}if(Oo(n,"foreground")){process.title="hydra-acp-daemon";let s=await A0(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
420
420
  `);let o=1e4,i=!1,a=async()=>{i&&(process.stderr.write(`Second signal received; exiting immediately.
421
421
  `),process.exit(1)),i=!0,process.stdout.write(`Shutting down...
@@ -676,10 +676,10 @@ ${r.join(`
676
676
  `),process.exit(2);return}if(!n.sessionId&&n.cwd===void 0&&process.stdin.isTTY!==!0){let d=Bq(jq(Wq(),"hydra-cat-"));n.cwd=d,n.detach||process.once("exit",()=>{try{Uq(d,{recursive:!0,force:!0})}catch{}})}let e=await He(),t=n.target??await an(e);t.isLocal&&!n.target&&await Mi(e,t);let r=["acp.v1",`hydra-acp-token.${t.token}`],s=await No(t.wsUrl,r),o=Nr(s),i=new pn(o),a=await Yq({conn:i,opts:n,stdin:process.stdin,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0,stdout:d=>process.stdout.write(d),stderr:d=>{process.stderr.write(d)},streamClient:Vq(t.baseUrl,t.token)});process.exit(a.exitCode)}function Vq(n,e){let t={"Content-Type":"application/json",Authorization:`Bearer ${e}`},r=(s,o)=>`${n}/v1/sessions/${encodeURIComponent(s)}/stdin${o}`;return{async open(s,o){let i=await fetch(r(s,"/open"),{method:"POST",headers:t,body:JSON.stringify(o)});if(!i.ok)throw new Error(`stdin/open HTTP ${i.status}`);return await i.json()},async write(s,o,i){let a=await fetch(r(s,""),{method:"POST",headers:t,body:JSON.stringify({chunk:o,eof:i})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function Yq(n){let{conn:e,opts:t,stdin:r,stdinIsTty:s,stdoutIsTty:o,stdout:i,stderr:a}=n,d=RI({isTTY:o})?"ansi":"plain",c=t.raw===!0,l=!s&&t.sessionId===void 0&&t.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async oe=>t.dangerouslySkipPermissions?Qa(oe):Jq(oe)?Qa(oe):KP(oe));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:Aa,version:Fe}})}catch{}let{sessionId:u,clientId:f}=await Zq(e,t,l),p=!1,m=!0,b="",g=0,h=oe=>{oe.length!==0&&(i(oe),m=oe.charCodeAt(oe.length-1)===10,p=!0)},y=()=>{if(c||b.length===0)return;let oe=XP(b,d);if(b="",oe.length===0)return;let $e=g>0?`
677
677
  `:"";h($e+oe),g+=1},k=()=>{y(),p&&!m&&h(`
678
678
  `),p=!1};e.onNotification("session/update",oe=>{let $e=oe?.update,lt=Xs($e,{cwd:t.cwd});if(lt){if(lt.kind==="agent-text"){c?h(lt.text):b+=lt.text;return}if(lt.kind==="turn-complete"){k();return}switch(lt.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":y();return;default:return}}});let S=!1,I=5e3,x=[];t.noWait&&e.onNotification("hydra-acp/prompt_queue/added",oe=>{let $e=oe?.originator;if(f!==void 0&&$e?.clientId!==f)return;let lt=x.shift();lt&&lt()});let C=async oe=>{let $e=()=>{},lt=new Promise(Jt=>{$e=Jt}),Tt=()=>{let Jt=x.indexOf(Tt);Jt!==-1&&x.splice(Jt,1),$e()};x.push(Tt);let Me=setTimeout(Tt,I);typeof Me.unref=="function"&&Me.unref();try{let{response:Jt}=e.requestWithId("session/prompt",gv(u,oe,t));Jt.catch(()=>{}),S=!0}catch(Jt){a(`hydra-acp cat: prompt failed: ${Jt.message}
679
- `),clearTimeout(Me),Tt();return}await lt,clearTimeout(Me)},$=Kq(t),E=async oe=>{let $e=[];if(t.prompt&&!S&&$e.push({type:"text",text:t.prompt}),oe.length>0&&$e.push({type:"text",text:oe}),$e.length!==0){if($&&!S&&$e.unshift({type:"text",text:$}),t.noWait){await C($e);return}try{let lt=e.request("session/prompt",gv(u,$e,t));t.timeoutSeconds!==void 0?await zq(lt,t.timeoutSeconds):await lt,S=!0}catch(lt){let Tt=lt instanceof og;a(Tt?`hydra-acp cat: ${lt.message}
679
+ `),clearTimeout(Me),Tt();return}await lt,clearTimeout(Me)},$=Kq(t),P=async oe=>{let $e=[];if(t.prompt&&!S&&$e.push({type:"text",text:t.prompt}),oe.length>0&&$e.push({type:"text",text:oe}),$e.length!==0){if($&&!S&&$e.unshift({type:"text",text:$}),t.noWait){await C($e);return}try{let lt=e.request("session/prompt",gv(u,$e,t));t.timeoutSeconds!==void 0?await zq(lt,t.timeoutSeconds):await lt,S=!0}catch(lt){let Tt=lt instanceof og;a(Tt?`hydra-acp cat: ${lt.message}
680
680
  `:`hydra-acp cat: prompt failed: ${lt.message}
681
681
  `),M=1;return}k()}},M=0,F,K=new Promise(oe=>{F=oe}),Y=!1,z=async oe=>{Y||(Y=!0,k(),t.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:u}))().catch(()=>{}),new Promise(lt=>setTimeout(lt,500))]),await e.close().catch(()=>{}),F({exitCode:oe}))};e.onClose(oe=>{oe&&(a(`hydra-acp cat: ${oe.message}
682
- `),M=1),Y||(Y=!0,k(),F({exitCode:M}))});let re=[],Q=!1,ke=!1,xe=async()=>{if(!Q){Q=!0;try{for(;re.length>0;){let oe=re.shift();if(oe===void 0)break;await E(oe)}}finally{Q=!1,ke&&re.length===0&&await z(M)}}},je=()=>{t.prompt&&!S&&re.push("")};if(s&&!t.sessionId)return t.prompt&&await E(""),await z(0),K;if(l)return typeof r.setEncoding=="function"&&r.setEncoding("utf8"),Qq({conn:e,streamClient:n.streamClient,sessionId:u,opts:t,stdin:r,stderr:a,sendInline:E,onEof:()=>{ke=!0,!Q&&re.length===0&&z(M)},onError:oe=>{a(`hydra-acp cat: stdin error: ${oe.message}
682
+ `),M=1),Y||(Y=!0,k(),F({exitCode:M}))});let re=[],Q=!1,ke=!1,xe=async()=>{if(!Q){Q=!0;try{for(;re.length>0;){let oe=re.shift();if(oe===void 0)break;await P(oe)}}finally{Q=!1,ke&&re.length===0&&await z(M)}}},je=()=>{t.prompt&&!S&&re.push("")};if(s&&!t.sessionId)return t.prompt&&await P(""),await z(0),K;if(l)return typeof r.setEncoding=="function"&&r.setEncoding("utf8"),Qq({conn:e,streamClient:n.streamClient,sessionId:u,opts:t,stdin:r,stderr:a,sendInline:P,onEof:()=>{ke=!0,!Q&&re.length===0&&z(M)},onError:oe=>{a(`hydra-acp cat: stdin error: ${oe.message}
683
683
  `),M=1,ke=!0,!Q&&re.length===0&&z(M)},onPromptFailed:oe=>{a(`hydra-acp cat: ${oe.message}
684
684
  `),M=1,ke=!0,!Q&&re.length===0&&z(M)}}),K;if(typeof r.setEncoding=="function"&&r.setEncoding("utf8"),t.follow===!0||s&&!!t.sessionId){let oe=QP({scheduleFlushCheck:$e=>{let lt=setImmediate($e);return()=>clearImmediate(lt)},onChunk:$e=>{re.push($e),xe()}});return r.on("data",$e=>{oe.feed(typeof $e=="string"?$e:$e.toString("utf8"))}),r.on("end",()=>{oe.eof(),ke=!0,je(),xe()}),r.on("error",$e=>{a(`hydra-acp cat: stdin error: ${$e.message}
685
685
  `),M=1,ke=!0,!Q&&re.length===0&&z(M)}),K}let ue="";return r.on("data",oe=>{ue+=typeof oe=="string"?oe:oe.toString("utf8")}),r.on("end",()=>{ke=!0,ue.length>0?re.push(ue):je(),xe()}),r.on("error",oe=>{a(`hydra-acp cat: stdin error: ${oe.message}
@@ -724,10 +724,10 @@ ${n}:
724
724
  `),process.exit(2))}async function s6(){process.stdout.on("error",h=>{throw h.code==="EPIPE"&&process.exit(0),h});let{installGlobalTlsTrust:n}=await Promise.resolve().then(()=>(Lo(),aI));n();{let{applyDirectoryConfig:h,formatDirectoryConfigNotices:y}=await Promise.resolve().then(()=>(qd(),Jx)),k=await h(process.cwd());for(let S of y(k.notices))process.stderr.write(S+`
725
725
  `)}let e=process.argv.slice(2),t=e.indexOf("launch");if(t!==-1){let h=e.slice(0,t),y=e.slice(t+1),k=y[0],S=y.slice(1),{flags:I}=Ey(h);if(hF(I),I.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
726
726
  `),process.exit(2);return}let x=k??Ke(I,"agent");if(!x){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
727
- `),process.exit(2);return}let C=await mF(iw(I),{allowPrompt:!1}),$=Ke(I,"name"),E=Ke(I,"model");zi=!0;let M=I["dangerously-skip-permissions"]===!0;fF(I),fx(M);let F={agentId:x,agentArgs:S,name:$,model:E,dangerouslySkipPermissions:M};C?.sessionId!==void 0&&(F.sessionId=C.sessionId),C?.target!==void 0&&C.fromUrl&&(F.target=C.target),await sg(F);return}cx(e)===void 0&&!e.some(h=>h==="--prompt"||h.startsWith("--prompt="))&&uM(e);let{positional:r,flags:s}=Ey(e);if(hF(s),s.version===!0||r[0]==="--version"){process.stdout.write(`hydra-acp ${o6()}
727
+ `),process.exit(2);return}let C=await mF(iw(I),{allowPrompt:!1}),$=Ke(I,"name"),P=Ke(I,"model");zi=!0;let M=I["dangerously-skip-permissions"]===!0;fF(I),fx(M);let F={agentId:x,agentArgs:S,name:$,model:P,dangerouslySkipPermissions:M};C?.sessionId!==void 0&&(F.sessionId=C.sessionId),C?.target!==void 0&&C.fromUrl&&(F.target=C.target),await sg(F);return}cx(e)===void 0&&!e.some(h=>h==="--prompt"||h.startsWith("--prompt="))&&uM(e);let{positional:r,flags:s}=Ey(e);if(hF(s),s.version===!0||r[0]==="--version"){process.stdout.write(`hydra-acp ${o6()}
728
728
  `);return}if(s.help===!0){px(r[0]);return}let o=cx(e)!==void 0||typeof s.prompt=="string",i=r[0],a=i!==void 0&&!i.startsWith("-")?i:o?"cat":i,d=Ke(s,"name"),c=Ke(s,"agent"),l=Ke(s,"model"),u=s["dangerously-skip-permissions"]===!0;fF(s),fx(u);let f=iw(s),p=a==="tui"||a===void 0&&process.stdout.isTTY,m=await mF(f,{allowPrompt:p});m!==void 0&&m.sessionId!==void 0&&s.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
729
729
  `),process.exit(2));let b=m?.sessionId,g=m?.fromUrl?m.target:void 0;if(!a){if(process.stdout.isTTY){zi=!0,await pF(s,{sessionId:b,agentId:c,name:d,model:l,target:g,dangerouslySkipPermissions:u});return}zi=!0;let h={name:d,model:l,agentId:c,dangerouslySkipPermissions:u};b!==void 0&&(h.sessionId=b),g!==void 0&&(h.target=g),await sg(h);return}switch(a){case"acp":case"shim":{zi=!0;let h={name:d,model:l,agentId:c,dangerouslySkipPermissions:u};b!==void 0&&(h.sessionId=b),g!==void 0&&(h.target=g),await sg(h);return}case"cat":{let h=cx(e),y=typeof s.prompt=="string"?s.prompt:void 0,k=h??y,S=Ke(s,"cwd"),I={prompt:k,sessionId:b,name:d,model:l,agentId:c,detach:s.detach===!0,follow:s.follow===!0,raw:s.raw===!0,noWait:s["no-wait"]===!0,noFromNote:s["no-from-note"]===!0,dangerouslySkipPermissions:u};S!==void 0&&(I.cwd=S);let x=Ke(s,"from-session")??process.env.HYDRA_ACP_SESSION;x!==void 0&&x.length>0&&(I.fromSession=x);let C=Ke(s,"from-label");C!==void 0&&C.length>0&&(I.fromLabel=C);let $=Ke(s,"timeout");if($!==void 0){let F=Number($);(!Number.isFinite(F)||F<=0)&&(process.stderr.write(`hydra-acp: --timeout takes a positive number of seconds
730
- `),process.exit(2)),I.timeoutSeconds=F}g!==void 0&&(I.target=g);let E=iy(s,"stream-threshold");E!==void 0&&(I.streamThreshold=E);let M=iy(s,"stream-bytes");M!==void 0&&(I.streamBufferBytes=M),c!==void 0&&await jm(c),zi=!0,await eM(I);return}case"version":{zi=!0,await lM({json:s.json===!0});return}case"init":await wI(s);return;case"daemon":{let h=e.indexOf("daemon"),y=e.slice(h+1),k=y[0];if(k===void 0||k==="status"){await L0();return}if(k==="start"){await $0(s);return}if(k==="stop"){await O0();return}if(k==="restart"){await Sm();return}if(k==="log"||k==="logs"){await F0(y.slice(1));return}if(k==="listen"){await G0(r[2],s);return}process.stderr.write(`Unknown daemon subcommand: ${k}
730
+ `),process.exit(2)),I.timeoutSeconds=F}g!==void 0&&(I.target=g);let P=iy(s,"stream-threshold");P!==void 0&&(I.streamThreshold=P);let M=iy(s,"stream-bytes");M!==void 0&&(I.streamBufferBytes=M),c!==void 0&&await jm(c),zi=!0,await eM(I);return}case"version":{zi=!0,await lM({json:s.json===!0});return}case"init":await wI(s);return;case"daemon":{let h=e.indexOf("daemon"),y=e.slice(h+1),k=y[0];if(k===void 0||k==="status"){await L0();return}if(k==="start"){await $0(s);return}if(k==="stop"){await O0();return}if(k==="restart"){await Sm();return}if(k==="log"||k==="logs"){await F0(y.slice(1));return}if(k==="listen"){await G0(r[2],s);return}process.stderr.write(`Unknown daemon subcommand: ${k}
731
731
  `),process.exit(2);return}case"workspace":case"workspaces":{let h=r[1];if(h===void 0||h==="list"){await PE({json:s.json===!0,inactive:s.inactive===!0});return}if(h==="prune"){await _E({force:s.force===!0});return}if(h==="clean"){try{await ME({...r[2]!==void 0?{target:r[2]}:{},deep:s.deep===!0})}catch(y){process.stderr.write(`${y.message}
732
732
  `),process.exit(1)}return}if(h==="remove"||h==="rm"){try{await AE({...r[2]!==void 0?{target:r[2]}:{},force:s.force===!0})}catch(y){process.stderr.write(`${y.message}
733
733
  `),process.exit(1)}return}if(h==="merge"||h==="apply"){let y=r[2];try{h==="merge"?await CE({...y!==void 0?{target:y}:{},...Ke(s,"message")!==void 0?{message:Ke(s,"message")}:{},...Ke(s,"into")!==void 0?{into:Ke(s,"into")}:{},remove:s.remove===!0}):await RE({...y!==void 0?{target:y}:{},...Ke(s,"into")!==void 0?{into:Ke(s,"into")}:{}})}catch(k){process.stderr.write(`${k.message}
@@ -738,8 +738,8 @@ Usage: hydra workspace [list|prune|merge|apply|clean|remove] [<session>] [--json
738
738
  `),process.exit(2);return}await XE(r[2],{json:s.json===!0,files:s.files===!0,...typeof s.host=="string"?{host:s.host}:{},...y!==void 0?{columns:y}:{}});return}if(h==="kill"){await pE(r[2]);return}if(h==="remove"||h==="delete"){await hE(r[2]);return}if(h==="undelete"){await gE(r.slice(2),{...Ke(s,"agent")!==void 0?{agent:Ke(s,"agent")}:{},...Ke(s,"grep")!==void 0?{grep:Ke(s,"grep")}:{},...Ke(s,"since")!==void 0?{since:Ke(s,"since")}:{},json:s.json===!0});return}if(h==="collect"){let y=Ke(s,"max-age-days"),k=Ke(s,"limit"),S={json:s.json===!0,keepUndecided:s["keep-undecided"]===!0};if(y!==void 0){let I=Number(y);if(!Number.isFinite(I)||I<0){process.stderr.write(`--max-age-days must be a non-negative number
739
739
  `),process.exit(2);return}S.maxAgeDays=I}if(k!==void 0){let I=Number(k);if(!Number.isFinite(I)||I<=0){process.stderr.write(`--limit must be a positive number
740
740
  `),process.exit(2);return}S.limit=I}await mE(S);return}if(h==="export"){let y=Ke(s,"out"),k=Ke(s,"tools");await yE(r[2],y,k);return}if(h==="transcript"){let y=Ke(s,"out"),k=s.tools===!0,S=s.thoughts===!0,I=F=>{let K=s[F];if(K===void 0)return;let Y=typeof K=="string"?Number(K):Number.NaN;return(!Number.isInteger(Y)||Y===0)&&(process.stderr.write(`hydra-acp: --${F} takes a non-zero integer turn number (negatives count from the end)
741
- `),process.exit(2)),Y},x={includeTools:k,includeThoughts:S},C=I("from");C!==void 0&&(x.from=C);let $=I("to");$!==void 0&&(x.to=$);let E=I("last");E!==void 0&&(E<0&&(process.stderr.write(`hydra-acp: --last takes a positive count
742
- `),process.exit(2)),x.last=E);let M=Ke(s,"since");if(M!==void 0){let F=_k(M);F===void 0&&(process.stderr.write(`hydra-acp: --since takes a duration (45s, 10m, 2h, 3d) or epoch millis
741
+ `),process.exit(2)),Y},x={includeTools:k,includeThoughts:S},C=I("from");C!==void 0&&(x.from=C);let $=I("to");$!==void 0&&(x.to=$);let P=I("last");P!==void 0&&(P<0&&(process.stderr.write(`hydra-acp: --last takes a positive count
742
+ `),process.exit(2)),x.last=P);let M=Ke(s,"since");if(M!==void 0){let F=_k(M);F===void 0&&(process.stderr.write(`hydra-acp: --since takes a duration (45s, 10m, 2h, 3d) or epoch millis
743
743
  `),process.exit(2)),x.sinceMs=F}await wE(r[2],y,x);return}if(h==="import"){let y=Ke(s,"cwd");await bE(r[2],{replace:s.replace===!0,info:s.info===!0,...y!==void 0?{cwd:y}:{}});return}if(h==="share"){let y=Ke(s,"host"),k=Ke(s,"cwd");await kE(r[2],{...y!==void 0?{host:y}:{},...k!==void 0?{cwd:k}:{}});return}process.stderr.write(`Unknown session subcommand: ${h}
744
744
  `),process.exit(2);return}case"extension":case"extensions":{let h=e.indexOf(a),y=e.slice(h+1),k=y[0],S=y[1],I=y.slice(2);if(k===void 0||k==="list"){await eP();return}if(k==="add"){await tP(S,I);return}if(k==="remove"){await nP(S);return}if(k==="start"){await rP(S);return}if(k==="stop"){await sP(S);return}if(k==="restart"){await oP(S);return}if(k==="log"||k==="logs"){await iP(y.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${k}
745
745
  `),process.exit(2);return}case"transformer":case"transformers":{let h=e.indexOf(a),y=e.slice(h+1),k=y[0],S=y[1],I=y.slice(2);if(k===void 0||k==="list"){await aP();return}if(k==="add"){await dP(S,I);return}if(k==="remove"){await cP(S);return}if(k==="start"){await lP(S);return}if(k==="stop"){await uP(S);return}if(k==="restart"){await fP(S);return}if(k==="log"||k==="logs"){await pP(y.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${k}