@hydra-acp/cli 0.1.96 → 0.1.98

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,34 +1,34 @@
1
1
  #!/usr/bin/env node
2
- var fv=Object.defineProperty;var J=(t,e)=>()=>(t&&(e=t(t=0)),e);var Zc=(t,e)=>{for(var n in e)fv(t,n,{get:e[n],enumerable:!0})};import*as we from"path";import*as tl from"os";function Ze(t){let e=tl.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function wv(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function Te(){let t=process.env[yv];if(t&&t.length>0)return we.resolve(t);let e=wv();if(e)throw new Error(`HYDRA_ACP_HOME is unset under a test runner (${e}); refusing to fall back to ~/.hydra-acp. The harness must set HYDRA_ACP_HOME \u2014 vitest.setup.ts does this, but \`bun test\` bypasses the vitest config and does not. Run the suite with \`npx vitest run\`, not \`bun test\`.`);return we.join(tl.homedir(),".hydra-acp")}var yv,_,he=J(()=>{"use strict";yv="HYDRA_ACP_HOME";_={home:Te,config:()=>we.join(Te(),"config.json"),authToken:()=>we.join(Te(),"auth-token"),remotes:()=>we.join(Te(),"remotes.json"),pidFile:()=>we.join(Te(),"daemon.pid"),logFile:()=>we.join(Te(),"daemon.log"),currentLogFile:()=>we.join(Te(),"current.log"),registryCache:()=>we.join(Te(),"registry.json"),agentsDir:()=>we.join(Te(),"agents"),agentLogFile:t=>we.join(Te(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>we.join(Te(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>we.join(Te(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>we.join(Te(),"sessions"),sessionDir:t=>we.join(Te(),"sessions",t),sessionFile:t=>we.join(Te(),"sessions",t,"meta.json"),historyFile:t=>we.join(Te(),"sessions",t,"history.jsonl"),toolsDir:t=>we.join(Te(),"sessions",t,"tools"),toolBlobFile:(t,e)=>we.join(Te(),"sessions",t,"tools",e),queueFile:t=>we.join(Te(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>we.join(Te(),"sessions",".tombstones"),tombstoneAgentDir:t=>we.join(Te(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>we.join(Te(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>we.join(Te(),"extensions"),extensionLogFile:t=>we.join(Te(),"extensions",`${t}.log`),extensionPidFile:t=>we.join(Te(),"extensions",`${t}.pid`),transformersDir:()=>we.join(Te(),"transformers"),transformerLogFile:t=>we.join(Te(),"transformers",`${t}.log`),transformerPidFile:t=>we.join(Te(),"transformers",`${t}.pid`),transformerState:(t,e)=>we.join(Te(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>we.join(Te(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>we.join(Te(),"prompt-history"),tuiLogFile:()=>we.join(Te(),"tui.log"),shimWireLogFile:()=>we.join(Te(),"shim-wire.log")}});import*as li from"fs/promises";function ui(){let t=new Uint8Array(32);crypto.getRandomValues(t);let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function fi(){try{let e=(await li.readFile(_.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function vr(){let t=await fi();if(!t)throw new Error(`No service token found at ${_.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function pi(t){await li.mkdir(_.home(),{recursive:!0}),await li.writeFile(_.authToken(),t+`
3
- `,{encoding:"utf8",mode:384})}async function Ro(){let t=await fi();if(t)return t;let e=ui();return await pi(e),process.stderr.write(`hydra-acp: initialized ${_.authToken()} with a fresh service token.
4
- `),e}var fs=J(()=>{"use strict";he()});import*as Ct from"fs/promises";import*as pp from"fs";import*as En from"path";import{randomBytes as bv}from"crypto";async function Xt(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
- `;await vv(t,r,n)}async function vv(t,e,n={}){let s=await Sv(t),r=kv(s);await Ct.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${Iv()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await Ct.writeFile(i,e,o),await Ct.rename(i,s)}catch(o){throw await Ct.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{pp.chmodSync(s,n.mode)}catch{}}async function Sv(t){let e;try{e=await Ct.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await Ct.readlink(t),s=En.isAbsolute(n)?n:En.resolve(En.dirname(t),n);try{let r=await Ct.realpath(En.dirname(s));return En.join(r,En.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function yn(t){let e;try{e=await Ct.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function kv(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function Iv(){return bv(4).toString("hex")}var Sr=J(()=>{"use strict"});import*as Ls from"fs/promises";import{homedir as nl}from"os";import{z as q}from"zod";function gp(t){return t.tui.inAppSelection??t.tui.mouse}function yp(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function wp(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function Ha(){return await _v(),await yn(_.config())??{}}async function _v(){let t;try{t=await Ls.lstat(_.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await Ls.stat(_.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await Ls.readlink(_.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${_.config()} is a broken symlink (-> ${n}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function Ua(){let t=await Ha(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await Ls.access(_.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${_.authToken()} and ${_.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await pi(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await Xt(_.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${_.config()} to ${_.authToken()}.
6
- `)}async function be(){return await Ua(),sl.parse(await Ha())}async function ps(t){await Ua();let e=await Ha();t(e),sl.parse(e),await Xt(_.config(),e,{mode:384})}async function To(t,e){await ps(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function ja(t){await ps(e=>{e.defaultAgent=t})}async function bp(t,e){await ps(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function vp(t,e){await ps(n=>{let s=n.agentOverrides&&typeof n.agentOverrides=="object"?n.agentOverrides:{};e===void 0?delete s[t]:s[t]={packageSpec:e},n.agentOverrides=s})}async function rl(t,e){await ps(n=>{let s=n.agents&&typeof n.agents=="object"?n.agents:{};e===void 0?delete s[t]:s[t]=e,n.agents=s})}async function Sp(t){await ps(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function kp(){let t=await Ha();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function et(t){return t==="~"||t==="$HOME"?nl():t.startsWith("~/")?nl()+t.slice(1):t.startsWith("$HOME/")?nl()+t.slice(5):t}var mp,xv,Pn,Av,Cv,Rv,Tv,Ev,hp,Pv,Mv,sl,Ve=J(()=>{"use strict";he();fs();Sr();mp="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",xv=q.object({cert:q.string(),key:q.string()}),Pn=55514,Av=q.object({host:q.string().default("127.0.0.1"),port:q.number().int().positive().default(Pn),logLevel:q.enum(["debug","info","warn","error"]).default("info"),tls:xv.optional(),sessionIdleTimeoutSeconds:q.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:q.number().int().positive().default(1e4),agentStderrTailBytes:q.number().int().positive().default(4096),publicHost:q.string().optional(),agentSyncIntervalMinutes:q.number().nonnegative().default(60),sessionGcIntervalMinutes:q.number().nonnegative().default(60),sessionGcMaxAgeDays:q.number().positive().default(2)}),Cv=q.object({url:q.string().url().default(mp),ttlHours:q.number().positive().default(24),pinned:q.boolean().default(!1)}),Rv=q.object({name:q.string().optional(),description:q.string().optional(),command:q.string().optional(),args:q.array(q.string()).optional(),env:q.record(q.string()).optional()}),Tv=q.object({packageSpec:q.string().optional()}),Ev=q.object({repaintThrottleMs:q.number().int().nonnegative().default(1e3),maxScrollbackLines:q.number().int().positive().default(1e4),mouse:q.boolean().default(!0),inAppSelection:q.boolean().optional(),selectionClipboard:q.enum(["primary","clipboard","both"]).default("both"),openFileCommand:q.union([q.string(),q.array(q.string())]).optional(),logMaxBytes:q.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:q.number().int().positive().default(32),progressIndicator:q.boolean().default(!0),defaultEnterAction:q.enum(["enqueue","amend"]).default("amend"),showThoughts:q.boolean().default(!0),ambiguousWidth:q.enum(["auto","narrow","wide"]).default("auto"),toolContent:q.enum(["inline","references"]).default("references"),diffContextLines:q.number().int().min(0).default(3),promptHistoryMaxEntries:q.number().int().positive().default(2e3),maxToolItems:q.number().int().nonnegative().default(5),maxPlanItems:q.number().int().nonnegative().default(5),showFileUpdates:q.enum(["none","edit","diff"]).default("edit"),sessionColumns:q.array(q.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),hp=q.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Pv=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),Mv=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),sl=q.object({daemon:Av.default({}),registry:Cv.default({url:mp,ttlHours:24,pinned:!1}),agents:q.record(q.string(),Rv).default({}),agentOverrides:q.record(q.string(),Tv).default({}),defaultAgent:q.string().default("opencode"),defaultModels:q.record(q.string(),q.string()).default({}),synopsisAgent:q.string().optional(),synopsisModel:q.string().optional(),compaction:q.object({agent:q.string().optional(),model:q.string().optional(),tailK:q.number().int().nonnegative().default(20),maxIterations:q.number().int().positive().default(3),contextFraction:q.number().min(0).max(1).default(.5),hardCeilingFraction:q.number().min(0).max(1).default(.85),absoluteFallback:q.number().int().positive().default(12e4),idleBeforePromptMs:q.number().int().nonnegative().default(3e5),modelContextWindows:q.record(q.string(),q.number().int().positive()).default({})}).default({}),defaultCwd:q.string().default("~"),compressToolContent:q.boolean().default(!0),sessionListColdLimit:q.number().int().nonnegative().default(20),extensions:q.record(hp,Pv).default({}),transformers:q.record(hp,Mv).default({}),defaultTransformers:q.array(q.string()).default([]),npmRegistry:q.string().url().optional(),tui:Ev.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!0,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"auto",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})})});function kr(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function il(t){return{httpScheme:"https",wsScheme:"wss"}}function ol(t){if(typeof t!="string"||t.length===0)throw new Error("expected a hydra:// URL");if(!t.startsWith("hydra://"))throw new Error(`expected hydra:// URL, got ${qa(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${qa(t)}`);let n=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(n){let d=Number(n[1]);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${n[1]}`)}let s=$v(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${qa(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${qa(t)}`);let i=kr(r),o;if(s.port){let d=Number(s.port);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);o=d}else o=Pn;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function Ip(t){let e=t.port!==void 0&&t.port!==Pn?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function $v(t){try{return new URL(t)}catch{return null}}function qa(t){return t.length>80?`${t.slice(0,77)}...`:t}var Eo=J(()=>{"use strict";Ve()});function Ir(t,e){return`${t}:${e}`}function xp(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function Fv(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}async function Ov(){let t=await yn(_.remotes());return t===void 0?{version:1,entries:{}}:Lv(t)}function Lv(t){if(!t||typeof t!="object")return{version:1,entries:{}};let e=t,n=e.entries&&typeof e.entries=="object"?e.entries:{},s={};for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let o=i;if(typeof o.token!="string"||typeof o.expiresAt!="string")continue;let a={token:o.token,expiresAt:o.expiresAt};typeof o.label=="string"&&(a.label=o.label),typeof o.pinnedFingerprint=="string"&&(a.pinnedFingerprint=o.pinnedFingerprint),typeof o.pinnedAt=="string"&&(a.pinnedAt=o.pinnedAt),s[r]=a}return{version:1,entries:s}}async function al(t){await Xt(_.remotes(),t,{mode:384})}var Wa,dl=J(()=>{"use strict";he();Sr();Wa=class t{data;constructor(e){this.data=e}static async load(){let e=await Ov(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(xp(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await al(i),new t(i)}get(e,n){let s=this.data.entries[Ir(e,n)];if(s&&!xp(s,Date.now()))return s}async set(e,n,s){this.data.entries[Ir(e,n)]=s,await al(this.data)}async delete(e,n){let s=Ir(e,n);return s in this.data.entries?(delete this.data.entries[s],await al(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=Fv(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function hi(t){return process.stdout.write(t),process.stdin.isTTY?new Promise((e,n)=>{let s=process.stdin,r=s.isRaw===!0,i="",o=()=>{s.removeListener("data",a),s.removeListener("error",c),r||s.setRawMode(!1),s.pause()},a=d=>{for(let l of d){if(l===10||l===13){process.stdout.write(`
7
- `),o(),e(i);return}if(l===3){o(),n(new Error("password entry cancelled"));return}if(l===127||l===8){i=i.slice(0,-1);continue}i+=String.fromCharCode(l)}},c=d=>{o(),n(d)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",c)}):Bv()}function Bv(){return new Promise((t,e)=>{let n="";process.stdin.setEncoding("utf8");let s=i=>{n+=i;let o=n.indexOf(`
8
- `);o!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),t(n.slice(0,o).replace(/\r$/,"")))},r=i=>{process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),e(i)};process.stdin.on("data",s),process.stdin.on("error",r)})}var cl=J(()=>{"use strict"});import*as Ap from"path";function Dn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=Ap.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Po=J(()=>{"use strict"});import*as za from"fs/promises";async function hs(){try{let t=await za.readFile(_.pidFile(),"utf8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.host!="string"||typeof e.port!="number"?void 0:{pid:e.pid,host:e.host,port:e.port,loopbackPort:typeof e.loopbackPort=="number"?e.loopbackPort:e.port,startedAt:typeof e.startedAt=="string"?e.startedAt:""}}catch(t){if(t.code==="ENOENT")return;throw t}}async function Cp(t){await za.writeFile(_.pidFile(),JSON.stringify(t)+`
9
- `,{encoding:"utf8",mode:384})}function Mn(t){try{return process.kill(t,0),!0}catch{return!1}}var mi=J(()=>{"use strict";he()});var _p={};Zc(_p,{_resetForTests:()=>Kv,clearPin:()=>Wv,fetchPeerFingerprint:()=>pl,formatFingerprint:()=>Ka,getPin:()=>ul,installGlobalTlsTrust:()=>ml,loadPinsFromStore:()=>fl,setPin:()=>Mo,sha256Hex:()=>hl,wsTlsOptions:()=>_o});import{createHash as Nv}from"crypto";import*as Rp from"tls";import{Agent as Dv,Dispatcher as Hv,buildConnector as Uv,getGlobalDispatcher as jv,setGlobalDispatcher as qv}from"undici";function Mo(t,e,n){xr.set(Ir(t,e),Tp(n))}function Wv(t,e){xr.delete(Ir(t,e))}function ul(t,e){return xr.get(Ir(t,e))}function fl(t){xr.clear();for(let e of t.list())e.entry.pinnedFingerprint&&Mo(e.host,e.port,e.entry.pinnedFingerprint)}async function pl(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=Rp.connect({host:t,port:e,servername:t,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,u)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):u&&r(u)}},d=setTimeout(()=>{c(new Error(`TLS connect to ${t}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){c(new Error(`${t}:${e} did not present a TLS certificate`));return}c(null,hl(l.raw))}),o.once("error",l=>c(l))})}function hl(t){return Nv("sha256").update(t).digest("hex")}function Ka(t){let e=Tp(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function Tp(t){return t.replace(/:/g,"").toLowerCase()}function ml(){if(ll)return;ll=!0;let t=jv(),e=new Dv({connect:Uv({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>Pp(s,r)})}),n=new Hv;n.dispatch=(s,r)=>{let i=zv(s.origin);return(i&&Ep(i)?e:t).dispatch(s,r)},n.close=(()=>Promise.all([e.close(),t.close()]).then(()=>{})),n.destroy=(s=>Promise.all([e.destroy(s??null),t.destroy(s??null)]).then(()=>{})),qv(n)}function zv(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function Ep(t){for(let e of xr.keys())if(Mp(e)?.host===t)return!0;return!1}function Pp(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=hl(e.raw);for(let[s,r]of xr.entries()){let i=Mp(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${Ka(n)})`)}function Mp(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}function _o(t){return Ep(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>Pp(e,n)}:{autoSelectFamily:!0}}function Kv(){xr.clear(),ll=!1}var xr,ll,$o=J(()=>{"use strict";dl();xr=new Map,ll=!1});import*as Lp from"os";async function Ft(t){let e=await Ro(),n=await hs();if(n&&Mn(n.pid))return{baseUrl:`http://127.0.0.1:${n.loopbackPort}`,wsUrl:`ws://127.0.0.1:${n.loopbackPort}/acp`,token:e,display:`${n.host}:${n.port}`,isLocal:!0};let s=t.daemon.host,r=s==="0.0.0.0"||s==="::"||s==="0.0.0.0/0"?"127.0.0.1":s,i=t.daemon.port;return{baseUrl:`http://${r}:${i}`,wsUrl:`ws://${r}:${i}/acp`,token:e,display:`${s}:${i}`,isLocal:kr(r)}}function $p(t,e){let{httpScheme:n,wsScheme:s}=il(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:Np(t),isLocal:t.isLoopback}}async function Bp(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??hi,r=e.confirmImpl??Qv,i=e.tlsHandshakeImpl??Jv,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let b=await fi();if(b)return Vv(t,b)}let c=e.store??await Wa.load();fl(c),ml();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&Mo(t.host,t.port,d.pinnedFingerprint),$p(t,d.token);if(!a)throw new gl(t.host,t.port);let l=Np(t),{httpScheme:u}=il(t.host),f;if(u==="https"&&ul(t.host,t.port)===void 0){let b=await i(t.host,t.port);if(b.kind==="untrusted"){let v=b.subject||b.issuer?`
2
+ var mv=Object.defineProperty;var J=(t,e)=>()=>(t&&(e=t(t=0)),e);var el=(t,e)=>{for(var n in e)mv(t,n,{get:e[n],enumerable:!0})};import*as we from"path";import*as nl from"os";function Ze(t){let e=nl.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function Sv(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function Te(){let t=process.env[vv];if(t&&t.length>0)return we.resolve(t);let e=Sv();if(e)throw new Error(`HYDRA_ACP_HOME is unset under a test runner (${e}); refusing to fall back to ~/.hydra-acp. The harness must set HYDRA_ACP_HOME \u2014 vitest.setup.ts does this, but \`bun test\` bypasses the vitest config and does not. Run the suite with \`npx vitest run\`, not \`bun test\`.`);return we.join(nl.homedir(),".hydra-acp")}var vv,_,he=J(()=>{"use strict";vv="HYDRA_ACP_HOME";_={home:Te,config:()=>we.join(Te(),"config.json"),authToken:()=>we.join(Te(),"auth-token"),remotes:()=>we.join(Te(),"remotes.json"),pidFile:()=>we.join(Te(),"daemon.pid"),logFile:()=>we.join(Te(),"daemon.log"),currentLogFile:()=>we.join(Te(),"current.log"),registryCache:()=>we.join(Te(),"registry.json"),agentsDir:()=>we.join(Te(),"agents"),agentLogFile:t=>we.join(Te(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>we.join(Te(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>we.join(Te(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>we.join(Te(),"sessions"),sessionDir:t=>we.join(Te(),"sessions",t),sessionFile:t=>we.join(Te(),"sessions",t,"meta.json"),historyFile:t=>we.join(Te(),"sessions",t,"history.jsonl"),toolsDir:t=>we.join(Te(),"sessions",t,"tools"),toolBlobFile:(t,e)=>we.join(Te(),"sessions",t,"tools",e),queueFile:t=>we.join(Te(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>we.join(Te(),"sessions",".tombstones"),tombstoneAgentDir:t=>we.join(Te(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>we.join(Te(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>we.join(Te(),"extensions"),extensionLogFile:t=>we.join(Te(),"extensions",`${t}.log`),extensionPidFile:t=>we.join(Te(),"extensions",`${t}.pid`),transformersDir:()=>we.join(Te(),"transformers"),transformerLogFile:t=>we.join(Te(),"transformers",`${t}.log`),transformerPidFile:t=>we.join(Te(),"transformers",`${t}.pid`),transformerState:(t,e)=>we.join(Te(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>we.join(Te(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>we.join(Te(),"prompt-history"),tuiLogFile:()=>we.join(Te(),"tui.log"),shimWireLogFile:()=>we.join(Te(),"shim-wire.log")}});import*as li from"fs/promises";function ui(){let t=new Uint8Array(32);crypto.getRandomValues(t);let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function fi(){try{let e=(await li.readFile(_.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function vr(){let t=await fi();if(!t)throw new Error(`No service token found at ${_.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function pi(t){await li.mkdir(_.home(),{recursive:!0}),await li.writeFile(_.authToken(),t+`
3
+ `,{encoding:"utf8",mode:384})}async function To(){let t=await fi();if(t)return t;let e=ui();return await pi(e),process.stderr.write(`hydra-acp: initialized ${_.authToken()} with a fresh service token.
4
+ `),e}var ps=J(()=>{"use strict";he()});import*as Ct from"fs/promises";import*as hp from"fs";import*as En from"path";import{randomBytes as kv}from"crypto";async function Xt(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
+ `;await Iv(t,r,n)}async function Iv(t,e,n={}){let s=await xv(t),r=Av(s);await Ct.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${Cv()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await Ct.writeFile(i,e,o),await Ct.rename(i,s)}catch(o){throw await Ct.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{hp.chmodSync(s,n.mode)}catch{}}async function xv(t){let e;try{e=await Ct.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await Ct.readlink(t),s=En.isAbsolute(n)?n:En.resolve(En.dirname(t),n);try{let r=await Ct.realpath(En.dirname(s));return En.join(r,En.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function yn(t){let e;try{e=await Ct.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function Av(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function Cv(){return kv(4).toString("hex")}var Sr=J(()=>{"use strict"});import*as Ls from"fs/promises";import{homedir as sl}from"os";import{z as q}from"zod";function yp(t){return t.tui.inAppSelection??t.tui.mouse}function wp(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function bp(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function Ua(){return await Fv(),await yn(_.config())??{}}async function Fv(){let t;try{t=await Ls.lstat(_.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await Ls.stat(_.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await Ls.readlink(_.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${_.config()} is a broken symlink (-> ${n}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function ja(){let t=await Ua(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await Ls.access(_.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${_.authToken()} and ${_.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await pi(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await Xt(_.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${_.config()} to ${_.authToken()}.
6
+ `)}async function be(){return await ja(),rl.parse(await Ua())}async function hs(t){await ja();let e=await Ua();t(e),rl.parse(e),await Xt(_.config(),e,{mode:384})}async function Eo(t,e){await hs(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function qa(t){await hs(e=>{e.defaultAgent=t})}async function vp(t,e){await hs(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function Sp(t,e){await hs(n=>{let s=n.agentOverrides&&typeof n.agentOverrides=="object"?n.agentOverrides:{};e===void 0?delete s[t]:s[t]={packageSpec:e},n.agentOverrides=s})}async function il(t,e){await hs(n=>{let s=n.agents&&typeof n.agents=="object"?n.agents:{};e===void 0?delete s[t]:s[t]=e,n.agents=s})}async function kp(t){await hs(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function Ip(){let t=await Ua();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function et(t){return t==="~"||t==="$HOME"?sl():t.startsWith("~/")?sl()+t.slice(1):t.startsWith("$HOME/")?sl()+t.slice(5):t}var gp,Rv,Pn,Tv,Ev,Pv,Mv,_v,mp,$v,Ov,rl,Ge=J(()=>{"use strict";he();ps();Sr();gp="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Rv=q.object({cert:q.string(),key:q.string()}),Pn=55514,Tv=q.object({host:q.string().default("127.0.0.1"),port:q.number().int().positive().default(Pn),logLevel:q.enum(["debug","info","warn","error"]).default("info"),tls:Rv.optional(),sessionIdleTimeoutSeconds:q.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:q.number().int().positive().default(1e4),agentStderrTailBytes:q.number().int().positive().default(4096),publicHost:q.string().optional(),agentSyncIntervalMinutes:q.number().nonnegative().default(60),sessionGcIntervalMinutes:q.number().nonnegative().default(60),sessionGcMaxAgeDays:q.number().positive().default(2)}),Ev=q.object({url:q.string().url().default(gp),ttlHours:q.number().positive().default(24),pinned:q.boolean().default(!1)}),Pv=q.object({name:q.string().optional(),description:q.string().optional(),command:q.string().optional(),args:q.array(q.string()).optional(),env:q.record(q.string()).optional()}),Mv=q.object({packageSpec:q.string().optional()}),_v=q.object({repaintThrottleMs:q.number().int().nonnegative().default(1e3),maxScrollbackLines:q.number().int().positive().default(1e4),mouse:q.boolean().default(!0),inAppSelection:q.boolean().optional(),selectionClipboard:q.enum(["primary","clipboard","both"]).default("both"),openFileCommand:q.union([q.string(),q.array(q.string())]).optional(),logMaxBytes:q.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:q.number().int().positive().default(32),progressIndicator:q.boolean().default(!0),defaultEnterAction:q.enum(["enqueue","amend"]).default("amend"),showThoughts:q.boolean().default(!0),ambiguousWidth:q.enum(["auto","narrow","wide"]).default("auto"),toolContent:q.enum(["inline","references"]).default("references"),diffContextLines:q.number().int().min(0).default(3),promptHistoryMaxEntries:q.number().int().positive().default(2e3),maxToolItems:q.number().int().nonnegative().default(5),maxPlanItems:q.number().int().nonnegative().default(5),showFileUpdates:q.enum(["none","edit","diff"]).default("edit"),sessionColumns:q.array(q.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),mp=q.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),$v=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),Ov=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),rl=q.object({daemon:Tv.default({}),registry:Ev.default({url:gp,ttlHours:24,pinned:!1}),agents:q.record(q.string(),Pv).default({}),agentOverrides:q.record(q.string(),Mv).default({}),defaultAgent:q.string().default("opencode"),defaultModels:q.record(q.string(),q.string()).default({}),synopsisAgent:q.string().optional(),synopsisModel:q.string().optional(),compaction:q.object({agent:q.string().optional(),model:q.string().optional(),tailK:q.number().int().nonnegative().default(20),maxIterations:q.number().int().positive().default(3),contextFraction:q.number().min(0).max(1).default(.5),hardCeilingFraction:q.number().min(0).max(1).default(.85),absoluteFallback:q.number().int().positive().default(12e4),idleBeforePromptMs:q.number().int().nonnegative().default(3e5),modelContextWindows:q.record(q.string(),q.number().int().positive()).default({})}).default({}),defaultCwd:q.string().default("~"),compressToolContent:q.boolean().default(!0),sessionListColdLimit:q.number().int().nonnegative().default(20),extensions:q.record(mp,$v).default({}),transformers:q.record(mp,Ov).default({}),defaultTransformers:q.array(q.string()).default([]),npmRegistry:q.string().url().optional(),tui:_v.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!0,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"auto",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})})});function kr(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function ol(t){return{httpScheme:"https",wsScheme:"wss"}}function al(t){if(typeof t!="string"||t.length===0)throw new Error("expected a hydra:// URL");if(!t.startsWith("hydra://"))throw new Error(`expected hydra:// URL, got ${Wa(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${Wa(t)}`);let n=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(n){let d=Number(n[1]);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${n[1]}`)}let s=Lv(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${Wa(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${Wa(t)}`);let i=kr(r),o;if(s.port){let d=Number(s.port);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);o=d}else o=Pn;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function xp(t){let e=t.port!==void 0&&t.port!==Pn?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function Lv(t){try{return new URL(t)}catch{return null}}function Wa(t){return t.length>80?`${t.slice(0,77)}...`:t}var Po=J(()=>{"use strict";Ge()});function Ir(t,e){return`${t}:${e}`}function Ap(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function Bv(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}async function Nv(){let t=await yn(_.remotes());return t===void 0?{version:1,entries:{}}:Dv(t)}function Dv(t){if(!t||typeof t!="object")return{version:1,entries:{}};let e=t,n=e.entries&&typeof e.entries=="object"?e.entries:{},s={};for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let o=i;if(typeof o.token!="string"||typeof o.expiresAt!="string")continue;let a={token:o.token,expiresAt:o.expiresAt};typeof o.label=="string"&&(a.label=o.label),typeof o.pinnedFingerprint=="string"&&(a.pinnedFingerprint=o.pinnedFingerprint),typeof o.pinnedAt=="string"&&(a.pinnedAt=o.pinnedAt),s[r]=a}return{version:1,entries:s}}async function dl(t){await Xt(_.remotes(),t,{mode:384})}var za,cl=J(()=>{"use strict";he();Sr();za=class t{data;constructor(e){this.data=e}static async load(){let e=await Nv(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(Ap(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await dl(i),new t(i)}get(e,n){let s=this.data.entries[Ir(e,n)];if(s&&!Ap(s,Date.now()))return s}async set(e,n,s){this.data.entries[Ir(e,n)]=s,await dl(this.data)}async delete(e,n){let s=Ir(e,n);return s in this.data.entries?(delete this.data.entries[s],await dl(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=Bv(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function hi(t){return process.stdout.write(t),process.stdin.isTTY?new Promise((e,n)=>{let s=process.stdin,r=s.isRaw===!0,i="",o=()=>{s.removeListener("data",a),s.removeListener("error",c),r||s.setRawMode(!1),s.pause()},a=d=>{for(let l of d){if(l===10||l===13){process.stdout.write(`
7
+ `),o(),e(i);return}if(l===3){o(),n(new Error("password entry cancelled"));return}if(l===127||l===8){i=i.slice(0,-1);continue}i+=String.fromCharCode(l)}},c=d=>{o(),n(d)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",c)}):Hv()}function Hv(){return new Promise((t,e)=>{let n="";process.stdin.setEncoding("utf8");let s=i=>{n+=i;let o=n.indexOf(`
8
+ `);o!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),t(n.slice(0,o).replace(/\r$/,"")))},r=i=>{process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),e(i)};process.stdin.on("data",s),process.stdin.on("error",r)})}var ll=J(()=>{"use strict"});import*as Cp from"path";function Dn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=Cp.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Mo=J(()=>{"use strict"});import*as Ka from"fs/promises";async function ms(){try{let t=await Ka.readFile(_.pidFile(),"utf8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.host!="string"||typeof e.port!="number"?void 0:{pid:e.pid,host:e.host,port:e.port,loopbackPort:typeof e.loopbackPort=="number"?e.loopbackPort:e.port,startedAt:typeof e.startedAt=="string"?e.startedAt:""}}catch(t){if(t.code==="ENOENT")return;throw t}}async function Rp(t){await Ka.writeFile(_.pidFile(),JSON.stringify(t)+`
9
+ `,{encoding:"utf8",mode:384})}function Mn(t){try{return process.kill(t,0),!0}catch{return!1}}var mi=J(()=>{"use strict";he()});var $p={};el($p,{_resetForTests:()=>Yv,clearPin:()=>Jv,fetchPeerFingerprint:()=>hl,formatFingerprint:()=>Ja,getPin:()=>fl,installGlobalTlsTrust:()=>gl,loadPinsFromStore:()=>pl,setPin:()=>_o,sha256Hex:()=>ml,wsTlsOptions:()=>$o});import{createHash as Uv}from"crypto";import*as Tp from"tls";import{Agent as jv,Dispatcher as qv,buildConnector as Wv,getGlobalDispatcher as zv,setGlobalDispatcher as Kv}from"undici";function _o(t,e,n){xr.set(Ir(t,e),Ep(n))}function Jv(t,e){xr.delete(Ir(t,e))}function fl(t,e){return xr.get(Ir(t,e))}function pl(t){xr.clear();for(let e of t.list())e.entry.pinnedFingerprint&&_o(e.host,e.port,e.entry.pinnedFingerprint)}async function hl(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=Tp.connect({host:t,port:e,servername:t,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,u)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):u&&r(u)}},d=setTimeout(()=>{c(new Error(`TLS connect to ${t}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){c(new Error(`${t}:${e} did not present a TLS certificate`));return}c(null,ml(l.raw))}),o.once("error",l=>c(l))})}function ml(t){return Uv("sha256").update(t).digest("hex")}function Ja(t){let e=Ep(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function Ep(t){return t.replace(/:/g,"").toLowerCase()}function gl(){if(ul)return;ul=!0;let t=zv(),e=new jv({connect:Wv({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>Mp(s,r)})}),n=new qv;n.dispatch=(s,r)=>{let i=Vv(s.origin);return(i&&Pp(i)?e:t).dispatch(s,r)},n.close=(()=>Promise.all([e.close(),t.close()]).then(()=>{})),n.destroy=(s=>Promise.all([e.destroy(s??null),t.destroy(s??null)]).then(()=>{})),Kv(n)}function Vv(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function Pp(t){for(let e of xr.keys())if(_p(e)?.host===t)return!0;return!1}function Mp(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=ml(e.raw);for(let[s,r]of xr.entries()){let i=_p(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${Ja(n)})`)}function _p(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}function $o(t){return Pp(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>Mp(e,n)}:{autoSelectFamily:!0}}function Yv(){xr.clear(),ul=!1}var xr,ul,Oo=J(()=>{"use strict";cl();xr=new Map,ul=!1});import*as Bp from"os";async function Ot(t){let e=await To(),n=await ms();if(n&&Mn(n.pid))return{baseUrl:`http://127.0.0.1:${n.loopbackPort}`,wsUrl:`ws://127.0.0.1:${n.loopbackPort}/acp`,token:e,display:`${n.host}:${n.port}`,isLocal:!0};let s=t.daemon.host,r=s==="0.0.0.0"||s==="::"||s==="0.0.0.0/0"?"127.0.0.1":s,i=t.daemon.port;return{baseUrl:`http://${r}:${i}`,wsUrl:`ws://${r}:${i}/acp`,token:e,display:`${s}:${i}`,isLocal:kr(r)}}function Op(t,e){let{httpScheme:n,wsScheme:s}=ol(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:Dp(t),isLocal:t.isLoopback}}async function Np(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??hi,r=e.confirmImpl??Zv,i=e.tlsHandshakeImpl??Qv,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let b=await fi();if(b)return Xv(t,b)}let c=e.store??await za.load();pl(c),gl();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&_o(t.host,t.port,d.pinnedFingerprint),Op(t,d.token);if(!a)throw new yl(t.host,t.port);let l=Dp(t),{httpScheme:u}=ol(t.host),f;if(u==="https"&&fl(t.host,t.port)===void 0){let b=await i(t.host,t.port);if(b.kind==="untrusted"){let v=b.subject||b.issuer?`
10
10
  subject: ${b.subject??"(unknown)"}
11
11
  issuer: ${b.issuer??"(unknown)"}`:"";if(process.stderr.write(`The certificate presented by ${l} is not signed by a trusted CA.
12
- sha256: ${Ka(b.fingerprint)}${v}
13
- `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);Mo(t.host,t.port,b.fingerprint),f=b.fingerprint}else if(b.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${b.message}`)}let p=await s(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let h=`${u}://${t.host}:${t.port}`,m=await n(`${h}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:Op()})});if(m.status===401)throw new Error(`Wrong password for ${l}.`);if(m.status===403)throw new Error(`No password is configured on ${l}. Run \`hydra-acp auth password\` on the daemon host first.`);if(m.status===429)throw new Error(`Too many failed login attempts on ${l}; try again later.`);if(!m.ok)throw new Error(`Login to ${l} failed: HTTP ${m.status}`);let y=await m.json();if(!y.session_token||!y.expires_at)throw new Error(`Login to ${l} returned a malformed response.`);return await c.set(t.host,t.port,{token:y.session_token,expiresAt:y.expires_at,label:Op(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),$p(t,y.session_token)}async function Jv(t,e){let n=await Yv(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await pl(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function Yv(t,e,n=1e4){let s=await import("tls");return new Promise(r=>{let i=!1,o=d=>{if(!i){i=!0,clearTimeout(c);try{a.destroy()}catch{}r(d)}},a=s.connect({host:t,port:e,servername:t,autoSelectFamily:!0}),c=setTimeout(()=>o({kind:"error",message:`TLS connect timed out after ${n}ms`}),n);a.once("secureConnect",()=>o({kind:"trusted"})),a.once("error",d=>{let l=d.code??"";if(l==="DEPTH_ZERO_SELF_SIGNED_CERT"||l==="SELF_SIGNED_CERT_IN_CHAIN"||l==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||l==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||l==="UNABLE_TO_GET_ISSUER_CERT"||l==="CERT_HAS_EXPIRED"||l==="ERR_TLS_CERT_ALTNAME_INVALID"){let p=a.getPeerCertificate(!1);o({kind:"untrusted",subject:p?.subject?Fp(p.subject):void 0,issuer:p?.issuer?Fp(p.issuer):void 0});return}let f=[l,d.message].filter(p=>p&&p.length>0);o({kind:"error",message:f.join(": ")||"unknown TLS error"})}),a.once("close",()=>{o({kind:"error",message:"connection closed before TLS handshake completed"})})})}function Fp(t){if(!t)return"";let e=[];for(let[n,s]of Object.entries(t)){let r=Array.isArray(s)?s.join(", "):s;e.push(`${n}=${r}`)}return e.join(", ")}async function Vv(t,e){let n=await hs(),r=n&&Mn(n.pid)?n.loopbackPort:t.port,i=t.port===Pn?t.host:`${t.host}:${t.port}`;return{baseUrl:`http://127.0.0.1:${r}`,wsUrl:`ws://127.0.0.1:${r}/acp`,token:e,display:i,isLocal:!0}}async function Qv(t){return process.stdout.write(t),new Promise(e=>{let n="",s=r=>{n+=r.toString("utf8");let i=n.indexOf(`
14
- `);if(i===-1)return;process.stdin.removeListener("data",s),process.stdin.pause();let o=n.slice(0,i).trim().toLowerCase();e(o==="y"||o==="yes")};process.stdin.resume(),process.stdin.on("data",s)})}function Op(){try{let t=Lp.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function Np(t){return t.port===Pn?t.host:`${t.host}:${t.port}`}var gl,Ar=J(()=>{"use strict";Ve();fs();Eo();dl();cl();Po();mi();$o();Eo();gl=class extends Error{host;port;constructor(e,n){let s=n===Pn?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Dn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{appendFileSync as Gv,renameSync as Xv,statSync as Zv}from"fs";function Up(t){Hp=t}function se(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?_.tuiLogFile():e;if(n.length!==0)try{eS(n);let s=JSON.stringify({t:new Date().toISOString(),...t});Gv(n,`${s}
15
- `)}catch{}}function eS(t){try{if(Zv(t).size<Hp)return;Xv(t,`${t}.0`)}catch{}}var Hp,Cr=J(()=>{"use strict";he();Hp=5*1024*1024});var z,Xa=J(()=>{"use strict";z={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014}});import{z as Oe}from"zod";var lh,RS,uh,fh,ph,El=J(()=>{"use strict";lh=Oe.object({protocolVersion:Oe.number().optional(),clientCapabilities:Oe.record(Oe.unknown()).optional(),clientInfo:Oe.object({name:Oe.string(),version:Oe.string().optional()}).optional()}),RS=Oe.enum(["full","pending_only","none","after_message"]),uh=Oe.object({cwd:Oe.string(),mcpServers:Oe.array(Oe.unknown()).optional(),_meta:Oe.record(Oe.unknown()).optional()}),fh=Oe.object({upstreamSessionId:Oe.string(),agentId:Oe.string(),cwd:Oe.string(),title:Oe.string().optional(),agentArgs:Oe.array(Oe.string()).optional()}),ph=Oe.object({sessionId:Oe.string(),historyPolicy:RS.default("full"),afterMessageId:Oe.string().optional(),clientId:Oe.string().optional(),clientInfo:Oe.object({name:Oe.string(),version:Oe.string().optional()}).optional(),_meta:Oe.record(Oe.unknown()).optional()})});import{z as de}from"zod";function Za(t,e){let n={attachedClients:t.attachedClients,status:t.status,busy:t.busy,awaitingInput:t.awaitingInput};return t.cwd!==void 0&&(n.cwd=t.cwd),t.title!==void 0&&(n.title=t.title),t.agentId!==void 0&&(n.agentId=t.agentId),t.upstreamSessionId!==void 0&&(n.upstreamSessionId=t.upstreamSessionId),t.currentModel!==void 0&&(n.currentModel=t.currentModel),t.currentUsage!==void 0&&(n.currentUsage=t.currentUsage),t.importedFromMachine!==void 0&&(n.importedFromMachine=t.importedFromMachine),t.importedFromUpstreamSessionId!==void 0&&(n.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),t.parentSessionId!==void 0&&(n.parentSessionId=t.parentSessionId),t.forkedFromSessionId!==void 0&&(n.forkedFromSessionId=t.forkedFromSessionId),t.forkedFromMessageId!==void 0&&(n.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient!==void 0&&(n.originatingClient=t.originatingClient),t.interactive!==void 0&&(n.interactive=t.interactive),t.priority!==void 0&&t.priority>0&&(n.priority=t.priority),t.compactionState!==void 0&&(n.compactionState=t.compactionState),t.forkSynthesisState!==void 0&&(n.forkSynthesisState=t.forkSynthesisState),e&&(e.clientId!==void 0&&(n.clientId=e.clientId),e.currentMode!==void 0&&(n.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(n.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(n.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(n.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(n.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(n.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(n.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(n.queue=e.queue),e.resurrected===!0&&(n.resurrected=!0)),n}function gh(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:Fo(t._meta,Za(t))};return t.title!==void 0&&(e.title=t.title),e}var hh,mh,Pl,VE,TS,QE,Ml=J(()=>{"use strict";ed();hh=de.object({sessionId:de.string()}),mh=de.object({cwd:de.string().optional(),cursor:de.string().optional()}),Pl=de.object({used:de.number().optional(),size:de.number().optional(),costAmount:de.number().optional(),costCurrency:de.string().optional()}),VE=de.object({sessionId:de.string(),upstreamSessionId:de.string().optional(),cwd:de.string(),title:de.string().optional(),agentId:de.string().optional(),currentModel:de.string().optional(),currentUsage:Pl.optional(),importedFromMachine:de.string().optional(),importedFromUpstreamSessionId:de.string().optional(),parentSessionId:de.string().optional(),forkedFromSessionId:de.string().optional(),forkedFromMessageId:de.string().optional(),originatingClient:de.object({name:de.string(),version:de.string().optional()}).optional(),interactive:de.boolean().optional(),priority:de.number().int().nonnegative().optional(),updatedAt:de.string(),attachedClients:de.number().int().nonnegative(),status:de.enum(["warm","cold"]).default("warm"),busy:de.boolean().default(!1),awaitingInput:de.boolean().default(!1),compactionState:de.any().optional(),forkSynthesisState:de.enum(["running","failed"]).optional(),_meta:de.record(de.unknown()).optional()}),TS=de.object({sessionId:de.string(),cwd:de.string(),title:de.string().optional(),updatedAt:de.string().optional(),_meta:de.record(de.unknown()).optional()}),QE=de.object({sessions:de.array(TS),nextCursor:de.string().optional()})});function ES(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,s]of Object.entries(t)){if(typeof n!="string"||n.length===0||typeof s!="string")return;e[n]=s}return e}function en(t){if(!t)return{};let e=t[Tt];if(!e||typeof e!="object"||Array.isArray(e))return{};let n=e,s={};if(typeof n.upstreamSessionId=="string"&&(s.upstreamSessionId=n.upstreamSessionId),typeof n.agentId=="string"&&(s.agentId=n.agentId),typeof n.cwd=="string"&&(s.cwd=n.cwd),typeof n.clientId=="string"&&(s.clientId=n.clientId),typeof n.readonly=="boolean"&&(s.readonly=n.readonly),(n.replayMode==="instant"||n.replayMode==="drip")&&(s.replayMode=n.replayMode),typeof n.dripSpeed=="number"&&n.dripSpeed>0&&(s.dripSpeed=n.dripSpeed),(n.toolContent==="inline"||n.toolContent==="references")&&(s.toolContent=n.toolContent),n.detachStatus==="detached"&&(s.detachStatus=n.detachStatus),typeof n.title=="string"&&(s.title=n.title),Array.isArray(n.agentArgs)&&n.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=n.agentArgs),Array.isArray(n.transformers)&&n.transformers.every(r=>typeof r=="string")&&(s.transformers=n.transformers),n.resume){let r=fh.safeParse(n.resume);r.success&&(s.resume=r.data)}if(typeof n.model=="string"&&(s.model=n.model),typeof n.currentModel=="string"&&(s.currentModel=n.currentModel),typeof n.currentMode=="string"&&(s.currentMode=n.currentMode),n.currentUsage){let r=Pl.safeParse(n.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof n.turnStartedAt=="number"&&n.turnStartedAt>0&&(s.turnStartedAt=n.turnStartedAt),Array.isArray(n.availableCommands)){let r=[];for(let i of n.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(n.prompt&&typeof n.prompt=="object"&&!Array.isArray(n.prompt)){let r=n.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(n.agents&&typeof n.agents=="object"&&!Array.isArray(n.agents)){let r=n.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof n.mcpStdin=="boolean"&&(s.mcpStdin=n.mcpStdin),typeof n.interactive=="boolean"&&(s.interactive=n.interactive),typeof n.ancillary=="boolean"&&(s.ancillary=n.ancillary),Array.isArray(n.queue)){let r=[];for(let i of n.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let c={clientId:a.clientId};typeof a.name=="string"&&(c.name=a.name),typeof a.version=="string"&&(c.version=a.version),r.push({messageId:o.messageId,originator:c,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(n.availableModes)){let r=[];for(let i of n.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(n.availableModels)){let r=[];for(let i of n.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((n.status==="warm"||n.status==="cold")&&(s.status=n.status),typeof n.busy=="boolean"&&(s.busy=n.busy),typeof n.awaitingInput=="boolean"&&(s.awaitingInput=n.awaitingInput),typeof n.attachedClients=="number"&&(s.attachedClients=n.attachedClients),typeof n.resurrected=="boolean"&&(s.resurrected=n.resurrected),typeof n.importedFromMachine=="string"&&(s.importedFromMachine=n.importedFromMachine),typeof n.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),typeof n.parentSessionId=="string"&&(s.parentSessionId=n.parentSessionId),typeof n.forkedFromSessionId=="string"&&(s.forkedFromSessionId=n.forkedFromSessionId),typeof n.forkedFromMessageId=="string"&&(s.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient&&typeof n.originatingClient=="object"&&!Array.isArray(n.originatingClient)&&typeof n.originatingClient.name=="string"){let r=n.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(n.agentCapabilities!==void 0&&(s.agentCapabilities=n.agentCapabilities),n.env!==void 0){let r=ES(n.env);r!==void 0&&(s.env=r)}return s}function Fo(t,e){return{...t??{},[Tt]:e}}var Tt,ed=J(()=>{"use strict";El();Ml();Tt="hydra-acp"});import{z as ee}from"zod";var yh,td,wh,nP,sP,rP,bh,iP,vh,oP,Sh,aP,dP,kh=J(()=>{"use strict";yh=ee.object({sessionId:ee.string(),prompt:ee.array(ee.unknown()),_meta:ee.record(ee.unknown()).optional()}),td=ee.object({sessionId:ee.string()}),wh=ee.object({clientId:ee.string(),name:ee.string().optional(),version:ee.string().optional()}),nP=ee.object({sessionId:ee.string(),messageId:ee.string(),originator:wh,prompt:ee.array(ee.unknown()),position:ee.number().int().nonnegative(),queueDepth:ee.number().int().positive(),enqueuedAt:ee.number()}),sP=ee.object({sessionId:ee.string(),messageId:ee.string(),prompt:ee.array(ee.unknown())}),rP=ee.object({sessionId:ee.string(),messageId:ee.string(),reason:ee.enum(["started","cancelled","abandoned"])}),bh=ee.object({sessionId:ee.string(),messageId:ee.string()}),iP=ee.object({cancelled:ee.boolean(),reason:ee.enum(["ok","not_found","already_running"])}),vh=ee.object({sessionId:ee.string(),messageId:ee.string(),prompt:ee.array(ee.unknown())}),oP=ee.object({updated:ee.boolean(),reason:ee.enum(["ok","not_found","already_running"])}),Sh=ee.object({sessionId:ee.string(),targetMessageId:ee.string(),prompt:ee.array(ee.unknown()),replaceQueue:ee.boolean().optional(),onTargetCompleted:ee.enum(["reject","send_anyway"]).optional()}),aP=ee.object({amended:ee.boolean(),reason:ee.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:ee.string().optional()}),dP=ee.object({sessionId:ee.string(),cancelledMessageId:ee.string(),newMessageId:ee.string(),prompt:ee.array(ee.unknown()),originator:wh,amendedAt:ee.number()})});import{z as Ns}from"zod";var Ih,nd,vi,xh=J(()=>{"use strict";Ih=Ns.object({agentId:Ns.string(),version:Ns.string(),source:Ns.enum(["binary","npm"]),phase:Ns.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:Ns.number().optional(),totalBytes:Ns.number().optional(),packageSpec:Ns.string().optional()}),nd="hydra-acp/agents/install_progress",vi={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Et=J(()=>{"use strict";Xa();El();ed();Ml();kh();xh()});import{nanoid as PS}from"nanoid";var _l,zt,Tr=J(()=>{"use strict";Et();_l=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},zt=class t{constructor(e){this.stream=e;this.stream.onMessage(n=>this.handleIncoming(n)),this.stream.onClose(n=>this.handleClose(n))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;static MAX_BUFFERED_METHODS=256;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,n){this.requestHandlers.set(e,n)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,n){this.notificationHandlers.set(e,n);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{n(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,n){return this.requestWithId(e,n).response}requestWithId(e,n){if(this.closed)throw new _l;let s=PS(),r={jsonrpc:"2.0",id:s,method:e,params:n},i=new Promise((o,a)=>{this.pending.set(s,{resolve:c=>o(c),reject:a}),this.stream.send(r).catch(c=>{this.pending.delete(s),a(c)})});return{id:s,response:i}}notify(e,n){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:n};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let n=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!n){await this.sendError(e.id,{code:z.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await n(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??z.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let n=this.notificationHandlers.get(e.method);if(n){n(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=t.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>t.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let n=e.id===null?void 0:this.pending.get(e.id);if(!n){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,n.reject(s)}else n.resolve(e.result)}async sendError(e,n){let s={jsonrpc:"2.0",id:e,error:n};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let n of this.pending.values())n.reject(e??new Error("connection closed"));this.pending.clear();for(let n of this.closeHandlers)n(e)}}}});async function Si(t){let{agent:e,upstreamSessionId:n,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=t;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(c=>c.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:n,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function ki(t){let{agent:e,upstreamSessionId:n,persistedModel:s,agentReportedModel:r,logger:i}=t;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:n,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}var $l=J(()=>{"use strict"});import*as Rh from"fs/promises";function jS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var OS,LS,Ii,BS,NS,DS,HS,US,Ch,id,Th=J(()=>{"use strict";OS=64*1024*1024,LS=1*1024*1024,Ii=64*1024,BS=6e4,NS=100,DS=1e3,HS=64*1024,US=256*1024,Ch=20;id=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??OS,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(LS,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,n){let s=Math.max(0,Math.min(n,Ii));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let c=Math.min(a,s),l={bytes:this.sliceFromRing(r,c),nextCursor:r+c};return i>0&&(l.gap=i),this.closed&&r+c>=this.writeCursor&&(l.eof=!0),l}tail(e){let n=Math.max(0,Math.min(e,Ii)),s=this.oldestAvailable,r=this.writeCursor-n,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let n=Math.max(0,Math.min(e,Ii)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+n);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,n){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(n,BS));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let n=this.oldestAvailable,s=e.cursor,r=s??n,i=0;s!==void 0&&s<n&&(i=n-s,r=n),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,c=e.caseInsensitive===!0?"i":"",d=a?new RegExp(e.pattern,c):new RegExp(jS(e.pattern),c),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??NS,DS)),f=Math.max(1,Math.min(e.maxBytes??HS,US)),p=Math.max(0,Math.min(e.contextBefore??0,Ch)),h=Math.max(0,Math.min(e.contextAfter??0,Ch)),m=[],y=[],b=[],v=0,S=!1,k=0,T=0,F=(K,U)=>{for(let G of b)G.remaining>0&&(G.match.after===void 0&&(G.match.after=[]),G.match.after.push({cursor:K,line:U}),G.remaining--,v+=U.length);for(;b.length>0&&b[0].remaining===0;)b.shift();if(d.test(U)!==l&&m.length<u){let G={cursor:K,line:U};if(p>0&&y.length>0){G.before=y.slice();for(let Se of G.before)v+=Se.line.length}v+=U.length,m.push(G),h>0&&b.push({match:G,remaining:h})}if(p>0)for(y.push({cursor:K,line:U});y.length>p;)y.shift();let N=m.length>=u&&b.length===0,Z=v>=f;return N||Z};for(let K=0;K<o.length;K++){if(o[K]!==10)continue;let U=o.subarray(k,K).toString("utf8"),L=r+k;if(k=K+1,T=k,F(L,U)){S=!0;break}}if(!S&&k<o.length&&this.closed){let K=o.subarray(k).toString("utf8"),U=r+k;F(U,K)&&(S=!0),T=o.length}let $=Math.min(r+T,this.writeCursor),B={matches:m,truncated:S,nextCursor:$,scannedBytes:T};return i>0&&(B.gap=i),this.closed&&$>=this.writeCursor&&(B.eof=!0),B}wakeWaiters(e){if(this.waiters.length===0)return;let n=this.waiters;this.waiters=[];for(let s of n)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let n=this.writeCursor+e;if(n<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<n&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let n=e.length;if(this.growIfNeeded(n),n>=this.currentCapacityBytes){let i=n-this.currentCapacityBytes;e.copy(this.storage,0,i,n);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;n<=r?e.copy(this.storage,s,0,n):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,n))}sliceFromRing(e,n){if(n<=0)return Buffer.alloc(0);let s=Buffer.alloc(n),r=e%this.currentCapacityBytes,i=Math.min(n,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<n&&this.storage.copy(s,i,0,n-i),s}scheduleFileWrite(e){let n=this.filePath;if(n===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>Rh.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var od,MP,Eh=J(()=>{"use strict";od=[{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:"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:"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."}],MP=new Map(od.map(t=>[t.verb,t]))});function Ph(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function xi(t,e){return Fl(t,e.map(n=>n.modelId))}function Fl(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=Ph(t),s=e.filter(i=>Ph(i)===n);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:t};if(s.length>1)return{kind:"ambiguous",requested:t,candidates:s};let r=t.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:t};if(i.length>1)return{kind:"ambiguous",requested:t,candidates:i}}return{kind:"unknown",requested:t}}var ad=J(()=>{"use strict"});function Mh(t){if(t.length===0)return t;let e=new Map,n=new Map,s=new Map;for(let a=0;a<t.length;a++){let c=t[a];if(c===void 0)continue;let d=Ol(c);if(d?.sessionUpdate!=="tool_call_update")continue;let l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),d.rawInput&&typeof d.rawInput=="object"&&!Array.isArray(d.rawInput)&&Object.keys(d.rawInput).length>0&&s.set(l,d.rawInput),Array.isArray(d.content)&&d.content.length>0)){let u=n.get(l);u?u.push(...d.content):n.set(l,[...d.content])}}let r=[],i=null,o=null;for(let a=0;a<t.length;a++){let c=t[a];if(c===void 0)continue;let d=Ol(c);if(!d||typeof d.sessionUpdate!="string"){r.push(c),i=null;continue}let l=d.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?WS(r,i.outIndex,qS(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let u=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let f=u!==void 0&&n.has(u)?zS(c,n.get(u)??[]):c;u!==void 0&&s.has(u)&&!KS(f)&&(f=JS(f,s.get(u))),r.push(f);continue}if(l==="plan"){o!==null?r[o]=c:(r.push(c),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(c)}return r}function Ol(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function qS(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function WS(t,e,n){if(n.length===0)return;let s=t[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";t[e]={...s,params:{...r,update:{...i,content:{...o,text:a+n}}}}}function zS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function KS(t){let n=Ol(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function JS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var _h=J(()=>{"use strict"});function Ai(t,e={}){let n=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of t){if(o.method!=="session/update")continue;let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate;if(d==="prompt_received"){i();let l=Bl(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=Nl(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(Ll(c))):d==="turn_complete"&&i()}return i(),XS(s.join(`
16
- `),n)}function Ll(t){let e=VS(t),n=QS(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function VS(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function QS(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of YS){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${GS(r,200)}`)}return n}function Bl(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{if(e&&typeof e=="object"){let n=e.text;if(typeof n=="string")return n}return""}).join(""):""}function Nl(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function GS(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function XS(t,e){if(t.length<=e)return t;let n=t.split(`
17
- `);for(;n.length>0;){let s=$h+n.join(`
18
- `);if(s.length<=e)return s;n.shift()}return $h}var $h,YS,dd=J(()=>{"use strict";$h=`[older history truncated]
19
- `,YS=["file_path","filePath","path","command","pattern","query"]});function Dl(t){let e=[];e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??ZS}`),t.synopsis.goal!==void 0&&t.synopsis.goal.trim().length>0&&e.push(`[Goal] ${t.synopsis.goal}`),t.synopsis.outcome!==void 0&&t.synopsis.outcome.trim().length>0&&e.push(`[Outcome] ${t.synopsis.outcome}`);let n=Oo("Open threads",t.synopsis.open_threads);n.length>0&&e.push(n);let s=Oo("Decisions",t.synopsis.decisions);s.length>0&&e.push(s);let r=Oo("File edit intentions",t.synopsis.file_edit_intentions);r.length>0&&e.push(r);let i=Oo("Unresolved errors",t.synopsis.unresolved_errors);i.length>0&&e.push(i);let o=Oo("Tool state",t.synopsis.tool_state);o.length>0&&e.push(o);let a=Fh(t.synopsis.files_touched);a.length>0&&e.push(`[Files previously touched] ${a}`);let c=Fh(t.synopsis.tools_used);c.length>0&&e.push(`[Tools previously used] ${c}`),e.push("--- end prior session compaction ---");let d=ek(t.tail,t.tailK);return e.push("--- begin recent turns (verbatim, last "+t.tailK+") ---"),d.length>0&&e.push(d),e.push("--- end recent turns ---"),e.push(""),e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"),e.join(`
20
- `)}function Oo(t,e){if(!e||!Array.isArray(e))return"";let n=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(n.length===0)return"";let s=n.map(r=>"- "+r.trim());return`[${t}] ${s.join(`
21
- `)}`}function Fh(t){if(!t||!Array.isArray(t))return"";let e=t.filter(n=>typeof n=="string"&&n.trim().length>0);return e.length===0?"":e.map(n=>n.trim()).join(", ")}function ek(t,e){if(t.length===0||e<=0)return"";let n=tk(t);if(n.length===0)return"";let s=n.slice(-e),r=[];for(let i of s)if(i.user.length>0&&r.push("User: "+i.user),i.agent.length>0&&r.push("Assistant: "+i.agent),i.tools.length>0)for(let o of i.tools)r.push(o);return r.join(`
22
- `)}function tk(t){let e=[],n=null;for(let s of t){if(s.method!=="session/update")continue;let i=s.params?.update;if(!i||typeof i.sessionUpdate!="string")continue;let o=i.sessionUpdate;if(o==="prompt_received")n!==null&&n.user.length>0&&e.push(n),n={user:Bl(i.prompt).trim(),agent:"",tools:[]};else if(o==="agent_message_chunk"&&n!==null){let a=Nl(i.content);a.length>0&&(n.agent+=a)}else o==="tool_call"&&n!==null?n.tools.push(Ll(i)):o==="turn_complete"&&n!==null&&(e.push(n),n=null)}return n!==null&&n.user.length>0&&e.push(n),e}var ZS,Oh=J(()=>{"use strict";dd();ZS="(untitled)"});import*as jn from"fs/promises";async function Lo(t,e){let n=_.queueFile(t);if(e.length===0){await jn.unlink(n).catch(()=>{});return}await jn.mkdir(_.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
12
+ sha256: ${Ja(b.fingerprint)}${v}
13
+ `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);_o(t.host,t.port,b.fingerprint),f=b.fingerprint}else if(b.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${b.message}`)}let p=await s(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let h=`${u}://${t.host}:${t.port}`,m=await n(`${h}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:Lp()})});if(m.status===401)throw new Error(`Wrong password for ${l}.`);if(m.status===403)throw new Error(`No password is configured on ${l}. Run \`hydra-acp auth password\` on the daemon host first.`);if(m.status===429)throw new Error(`Too many failed login attempts on ${l}; try again later.`);if(!m.ok)throw new Error(`Login to ${l} failed: HTTP ${m.status}`);let y=await m.json();if(!y.session_token||!y.expires_at)throw new Error(`Login to ${l} returned a malformed response.`);return await c.set(t.host,t.port,{token:y.session_token,expiresAt:y.expires_at,label:Lp(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),Op(t,y.session_token)}async function Qv(t,e){let n=await Gv(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await hl(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function Gv(t,e,n=1e4){let s=await import("tls");return new Promise(r=>{let i=!1,o=d=>{if(!i){i=!0,clearTimeout(c);try{a.destroy()}catch{}r(d)}},a=s.connect({host:t,port:e,servername:t,autoSelectFamily:!0}),c=setTimeout(()=>o({kind:"error",message:`TLS connect timed out after ${n}ms`}),n);a.once("secureConnect",()=>o({kind:"trusted"})),a.once("error",d=>{let l=d.code??"";if(l==="DEPTH_ZERO_SELF_SIGNED_CERT"||l==="SELF_SIGNED_CERT_IN_CHAIN"||l==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||l==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||l==="UNABLE_TO_GET_ISSUER_CERT"||l==="CERT_HAS_EXPIRED"||l==="ERR_TLS_CERT_ALTNAME_INVALID"){let p=a.getPeerCertificate(!1);o({kind:"untrusted",subject:p?.subject?Fp(p.subject):void 0,issuer:p?.issuer?Fp(p.issuer):void 0});return}let f=[l,d.message].filter(p=>p&&p.length>0);o({kind:"error",message:f.join(": ")||"unknown TLS error"})}),a.once("close",()=>{o({kind:"error",message:"connection closed before TLS handshake completed"})})})}function Fp(t){if(!t)return"";let e=[];for(let[n,s]of Object.entries(t)){let r=Array.isArray(s)?s.join(", "):s;e.push(`${n}=${r}`)}return e.join(", ")}async function Xv(t,e){let n=await ms(),r=n&&Mn(n.pid)?n.loopbackPort:t.port,i=t.port===Pn?t.host:`${t.host}:${t.port}`;return{baseUrl:`http://127.0.0.1:${r}`,wsUrl:`ws://127.0.0.1:${r}/acp`,token:e,display:i,isLocal:!0}}async function Zv(t){return process.stdout.write(t),new Promise(e=>{let n="",s=r=>{n+=r.toString("utf8");let i=n.indexOf(`
14
+ `);if(i===-1)return;process.stdin.removeListener("data",s),process.stdin.pause();let o=n.slice(0,i).trim().toLowerCase();e(o==="y"||o==="yes")};process.stdin.resume(),process.stdin.on("data",s)})}function Lp(){try{let t=Bp.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function Dp(t){return t.port===Pn?t.host:`${t.host}:${t.port}`}var yl,Ar=J(()=>{"use strict";Ge();ps();Po();cl();ll();Mo();mi();Oo();Po();yl=class extends Error{host;port;constructor(e,n){let s=n===Pn?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Dn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{appendFileSync as eS,renameSync as tS,statSync as nS}from"fs";function jp(t){Up=t}function se(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?_.tuiLogFile():e;if(n.length!==0)try{sS(n);let s=JSON.stringify({t:new Date().toISOString(),...t});eS(n,`${s}
15
+ `)}catch{}}function sS(t){try{if(nS(t).size<Up)return;tS(t,`${t}.0`)}catch{}}var Up,Cr=J(()=>{"use strict";he();Up=5*1024*1024});var z,Za=J(()=>{"use strict";z={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014}});import{z as Fe}from"zod";var uh,PS,fh,ph,hh,Pl=J(()=>{"use strict";uh=Fe.object({protocolVersion:Fe.number().optional(),clientCapabilities:Fe.record(Fe.unknown()).optional(),clientInfo:Fe.object({name:Fe.string(),version:Fe.string().optional()}).optional()}),PS=Fe.enum(["full","pending_only","none","after_message"]),fh=Fe.object({cwd:Fe.string(),mcpServers:Fe.array(Fe.unknown()).optional(),_meta:Fe.record(Fe.unknown()).optional()}),ph=Fe.object({upstreamSessionId:Fe.string(),agentId:Fe.string(),cwd:Fe.string(),title:Fe.string().optional(),agentArgs:Fe.array(Fe.string()).optional()}),hh=Fe.object({sessionId:Fe.string(),historyPolicy:PS.default("full"),afterMessageId:Fe.string().optional(),clientId:Fe.string().optional(),clientInfo:Fe.object({name:Fe.string(),version:Fe.string().optional()}).optional(),_meta:Fe.record(Fe.unknown()).optional()})});import{z as de}from"zod";function ed(t,e){let n={attachedClients:t.attachedClients,status:t.status,busy:t.busy,awaitingInput:t.awaitingInput};return t.cwd!==void 0&&(n.cwd=t.cwd),t.title!==void 0&&(n.title=t.title),t.agentId!==void 0&&(n.agentId=t.agentId),t.upstreamSessionId!==void 0&&(n.upstreamSessionId=t.upstreamSessionId),t.currentModel!==void 0&&(n.currentModel=t.currentModel),t.currentUsage!==void 0&&(n.currentUsage=t.currentUsage),t.importedFromMachine!==void 0&&(n.importedFromMachine=t.importedFromMachine),t.importedFromUpstreamSessionId!==void 0&&(n.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),t.parentSessionId!==void 0&&(n.parentSessionId=t.parentSessionId),t.forkedFromSessionId!==void 0&&(n.forkedFromSessionId=t.forkedFromSessionId),t.forkedFromMessageId!==void 0&&(n.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient!==void 0&&(n.originatingClient=t.originatingClient),t.interactive!==void 0&&(n.interactive=t.interactive),t.priority!==void 0&&t.priority>0&&(n.priority=t.priority),t.compactionState!==void 0&&(n.compactionState=t.compactionState),t.forkSynthesisState!==void 0&&(n.forkSynthesisState=t.forkSynthesisState),e&&(e.clientId!==void 0&&(n.clientId=e.clientId),e.currentMode!==void 0&&(n.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(n.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(n.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(n.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(n.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(n.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(n.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(n.queue=e.queue),e.resurrected===!0&&(n.resurrected=!0)),n}function yh(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:Fo(t._meta,ed(t))};return t.title!==void 0&&(e.title=t.title),e}var mh,gh,Ml,tP,MS,nP,_l=J(()=>{"use strict";td();mh=de.object({sessionId:de.string()}),gh=de.object({cwd:de.string().optional(),cursor:de.string().optional()}),Ml=de.object({used:de.number().optional(),size:de.number().optional(),costAmount:de.number().optional(),costCurrency:de.string().optional()}),tP=de.object({sessionId:de.string(),upstreamSessionId:de.string().optional(),cwd:de.string(),title:de.string().optional(),agentId:de.string().optional(),currentModel:de.string().optional(),currentUsage:Ml.optional(),importedFromMachine:de.string().optional(),importedFromUpstreamSessionId:de.string().optional(),parentSessionId:de.string().optional(),forkedFromSessionId:de.string().optional(),forkedFromMessageId:de.string().optional(),originatingClient:de.object({name:de.string(),version:de.string().optional()}).optional(),interactive:de.boolean().optional(),priority:de.number().int().nonnegative().optional(),updatedAt:de.string(),attachedClients:de.number().int().nonnegative(),status:de.enum(["warm","cold"]).default("warm"),busy:de.boolean().default(!1),awaitingInput:de.boolean().default(!1),compactionState:de.any().optional(),forkSynthesisState:de.enum(["running","failed"]).optional(),_meta:de.record(de.unknown()).optional()}),MS=de.object({sessionId:de.string(),cwd:de.string(),title:de.string().optional(),updatedAt:de.string().optional(),_meta:de.record(de.unknown()).optional()}),nP=de.object({sessions:de.array(MS),nextCursor:de.string().optional()})});function _S(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,s]of Object.entries(t)){if(typeof n!="string"||n.length===0||typeof s!="string")return;e[n]=s}return e}function en(t){if(!t)return{};let e=t[Tt];if(!e||typeof e!="object"||Array.isArray(e))return{};let n=e,s={};if(typeof n.upstreamSessionId=="string"&&(s.upstreamSessionId=n.upstreamSessionId),typeof n.agentId=="string"&&(s.agentId=n.agentId),typeof n.cwd=="string"&&(s.cwd=n.cwd),typeof n.clientId=="string"&&(s.clientId=n.clientId),typeof n.readonly=="boolean"&&(s.readonly=n.readonly),(n.replayMode==="instant"||n.replayMode==="drip")&&(s.replayMode=n.replayMode),typeof n.dripSpeed=="number"&&n.dripSpeed>0&&(s.dripSpeed=n.dripSpeed),(n.toolContent==="inline"||n.toolContent==="references")&&(s.toolContent=n.toolContent),n.detachStatus==="detached"&&(s.detachStatus=n.detachStatus),typeof n.title=="string"&&(s.title=n.title),Array.isArray(n.agentArgs)&&n.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=n.agentArgs),Array.isArray(n.transformers)&&n.transformers.every(r=>typeof r=="string")&&(s.transformers=n.transformers),n.resume){let r=ph.safeParse(n.resume);r.success&&(s.resume=r.data)}if(typeof n.model=="string"&&(s.model=n.model),typeof n.currentModel=="string"&&(s.currentModel=n.currentModel),typeof n.currentMode=="string"&&(s.currentMode=n.currentMode),n.currentUsage){let r=Ml.safeParse(n.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof n.turnStartedAt=="number"&&n.turnStartedAt>0&&(s.turnStartedAt=n.turnStartedAt),Array.isArray(n.availableCommands)){let r=[];for(let i of n.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(n.prompt&&typeof n.prompt=="object"&&!Array.isArray(n.prompt)){let r=n.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(n.agents&&typeof n.agents=="object"&&!Array.isArray(n.agents)){let r=n.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof n.mcpStdin=="boolean"&&(s.mcpStdin=n.mcpStdin),typeof n.interactive=="boolean"&&(s.interactive=n.interactive),typeof n.ancillary=="boolean"&&(s.ancillary=n.ancillary),Array.isArray(n.queue)){let r=[];for(let i of n.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let c={clientId:a.clientId};typeof a.name=="string"&&(c.name=a.name),typeof a.version=="string"&&(c.version=a.version),r.push({messageId:o.messageId,originator:c,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(n.availableModes)){let r=[];for(let i of n.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(n.availableModels)){let r=[];for(let i of n.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((n.status==="warm"||n.status==="cold")&&(s.status=n.status),typeof n.busy=="boolean"&&(s.busy=n.busy),typeof n.awaitingInput=="boolean"&&(s.awaitingInput=n.awaitingInput),typeof n.attachedClients=="number"&&(s.attachedClients=n.attachedClients),typeof n.resurrected=="boolean"&&(s.resurrected=n.resurrected),typeof n.importedFromMachine=="string"&&(s.importedFromMachine=n.importedFromMachine),typeof n.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),typeof n.parentSessionId=="string"&&(s.parentSessionId=n.parentSessionId),typeof n.forkedFromSessionId=="string"&&(s.forkedFromSessionId=n.forkedFromSessionId),typeof n.forkedFromMessageId=="string"&&(s.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient&&typeof n.originatingClient=="object"&&!Array.isArray(n.originatingClient)&&typeof n.originatingClient.name=="string"){let r=n.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(n.agentCapabilities!==void 0&&(s.agentCapabilities=n.agentCapabilities),n.env!==void 0){let r=_S(n.env);r!==void 0&&(s.env=r)}return s}function Fo(t,e){return{...t??{},[Tt]:e}}var Tt,td=J(()=>{"use strict";Pl();_l();Tt="hydra-acp"});import{z as ee}from"zod";var wh,nd,bh,dP,cP,lP,vh,uP,Sh,fP,kh,pP,hP,Ih=J(()=>{"use strict";wh=ee.object({sessionId:ee.string(),prompt:ee.array(ee.unknown()),_meta:ee.record(ee.unknown()).optional()}),nd=ee.object({sessionId:ee.string()}),bh=ee.object({clientId:ee.string(),name:ee.string().optional(),version:ee.string().optional()}),dP=ee.object({sessionId:ee.string(),messageId:ee.string(),originator:bh,prompt:ee.array(ee.unknown()),position:ee.number().int().nonnegative(),queueDepth:ee.number().int().positive(),enqueuedAt:ee.number()}),cP=ee.object({sessionId:ee.string(),messageId:ee.string(),prompt:ee.array(ee.unknown())}),lP=ee.object({sessionId:ee.string(),messageId:ee.string(),reason:ee.enum(["started","cancelled","abandoned"])}),vh=ee.object({sessionId:ee.string(),messageId:ee.string()}),uP=ee.object({cancelled:ee.boolean(),reason:ee.enum(["ok","not_found","already_running"])}),Sh=ee.object({sessionId:ee.string(),messageId:ee.string(),prompt:ee.array(ee.unknown())}),fP=ee.object({updated:ee.boolean(),reason:ee.enum(["ok","not_found","already_running"])}),kh=ee.object({sessionId:ee.string(),targetMessageId:ee.string(),prompt:ee.array(ee.unknown()),replaceQueue:ee.boolean().optional(),onTargetCompleted:ee.enum(["reject","send_anyway"]).optional()}),pP=ee.object({amended:ee.boolean(),reason:ee.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:ee.string().optional()}),hP=ee.object({sessionId:ee.string(),cancelledMessageId:ee.string(),newMessageId:ee.string(),prompt:ee.array(ee.unknown()),originator:bh,amendedAt:ee.number()})});import{z as Ns}from"zod";var xh,sd,vi,Ah=J(()=>{"use strict";xh=Ns.object({agentId:Ns.string(),version:Ns.string(),source:Ns.enum(["binary","npm"]),phase:Ns.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:Ns.number().optional(),totalBytes:Ns.number().optional(),packageSpec:Ns.string().optional()}),sd="hydra-acp/agents/install_progress",vi={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Et=J(()=>{"use strict";Za();Pl();td();_l();Ih();Ah()});import{nanoid as $S}from"nanoid";var $l,zt,Tr=J(()=>{"use strict";Et();$l=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},zt=class t{constructor(e){this.stream=e;this.stream.onMessage(n=>this.handleIncoming(n)),this.stream.onClose(n=>this.handleClose(n))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;static MAX_BUFFERED_METHODS=256;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,n){this.requestHandlers.set(e,n)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,n){this.notificationHandlers.set(e,n);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{n(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,n){return this.requestWithId(e,n).response}requestWithId(e,n){if(this.closed)throw new $l;let s=$S(),r={jsonrpc:"2.0",id:s,method:e,params:n},i=new Promise((o,a)=>{this.pending.set(s,{resolve:c=>o(c),reject:a}),this.stream.send(r).catch(c=>{this.pending.delete(s),a(c)})});return{id:s,response:i}}notify(e,n){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:n};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let n=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!n){await this.sendError(e.id,{code:z.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await n(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??z.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let n=this.notificationHandlers.get(e.method);if(n){n(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=t.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>t.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let n=e.id===null?void 0:this.pending.get(e.id);if(!n){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,n.reject(s)}else n.resolve(e.result)}async sendError(e,n){let s={jsonrpc:"2.0",id:e,error:n};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let n of this.pending.values())n.reject(e??new Error("connection closed"));this.pending.clear();for(let n of this.closeHandlers)n(e)}}}});async function Si(t){let{agent:e,upstreamSessionId:n,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=t;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(c=>c.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:n,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function ki(t){let{agent:e,upstreamSessionId:n,persistedModel:s,agentReportedModel:r,logger:i}=t;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:n,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}var Ol=J(()=>{"use strict"});import*as Th from"fs/promises";function zS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var NS,DS,Ii,HS,US,jS,qS,WS,Rh,od,Eh=J(()=>{"use strict";NS=64*1024*1024,DS=1*1024*1024,Ii=64*1024,HS=6e4,US=100,jS=1e3,qS=64*1024,WS=256*1024,Rh=20;od=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??NS,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(DS,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,n){let s=Math.max(0,Math.min(n,Ii));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let c=Math.min(a,s),l={bytes:this.sliceFromRing(r,c),nextCursor:r+c};return i>0&&(l.gap=i),this.closed&&r+c>=this.writeCursor&&(l.eof=!0),l}tail(e){let n=Math.max(0,Math.min(e,Ii)),s=this.oldestAvailable,r=this.writeCursor-n,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let n=Math.max(0,Math.min(e,Ii)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+n);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,n){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(n,HS));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let n=this.oldestAvailable,s=e.cursor,r=s??n,i=0;s!==void 0&&s<n&&(i=n-s,r=n),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,c=e.caseInsensitive===!0?"i":"",d=a?new RegExp(e.pattern,c):new RegExp(zS(e.pattern),c),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??US,jS)),f=Math.max(1,Math.min(e.maxBytes??qS,WS)),p=Math.max(0,Math.min(e.contextBefore??0,Rh)),h=Math.max(0,Math.min(e.contextAfter??0,Rh)),m=[],y=[],b=[],v=0,S=!1,k=0,T=0,O=(K,U)=>{for(let G of b)G.remaining>0&&(G.match.after===void 0&&(G.match.after=[]),G.match.after.push({cursor:K,line:U}),G.remaining--,v+=U.length);for(;b.length>0&&b[0].remaining===0;)b.shift();if(d.test(U)!==l&&m.length<u){let G={cursor:K,line:U};if(p>0&&y.length>0){G.before=y.slice();for(let Se of G.before)v+=Se.line.length}v+=U.length,m.push(G),h>0&&b.push({match:G,remaining:h})}if(p>0)for(y.push({cursor:K,line:U});y.length>p;)y.shift();let N=m.length>=u&&b.length===0,Z=v>=f;return N||Z};for(let K=0;K<o.length;K++){if(o[K]!==10)continue;let U=o.subarray(k,K).toString("utf8"),L=r+k;if(k=K+1,T=k,O(L,U)){S=!0;break}}if(!S&&k<o.length&&this.closed){let K=o.subarray(k).toString("utf8"),U=r+k;O(U,K)&&(S=!0),T=o.length}let $=Math.min(r+T,this.writeCursor),B={matches:m,truncated:S,nextCursor:$,scannedBytes:T};return i>0&&(B.gap=i),this.closed&&$>=this.writeCursor&&(B.eof=!0),B}wakeWaiters(e){if(this.waiters.length===0)return;let n=this.waiters;this.waiters=[];for(let s of n)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let n=this.writeCursor+e;if(n<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<n&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let n=e.length;if(this.growIfNeeded(n),n>=this.currentCapacityBytes){let i=n-this.currentCapacityBytes;e.copy(this.storage,0,i,n);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;n<=r?e.copy(this.storage,s,0,n):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,n))}sliceFromRing(e,n){if(n<=0)return Buffer.alloc(0);let s=Buffer.alloc(n),r=e%this.currentCapacityBytes,i=Math.min(n,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<n&&this.storage.copy(s,i,0,n-i),s}scheduleFileWrite(e){let n=this.filePath;if(n===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>Th.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var xi,BP,Ph=J(()=>{"use strict";xi=[{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:"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:"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."}],BP=new Map(xi.map(t=>[t.verb,t]))});function Mh(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function Ai(t,e){return Fl(t,e.map(n=>n.modelId))}function Fl(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=Mh(t),s=e.filter(i=>Mh(i)===n);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:t};if(s.length>1)return{kind:"ambiguous",requested:t,candidates:s};let r=t.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:t};if(i.length>1)return{kind:"ambiguous",requested:t,candidates:i}}return{kind:"unknown",requested:t}}var ad=J(()=>{"use strict"});function _h(t){if(t.length===0)return t;let e=new Map,n=new Map,s=new Map;for(let a=0;a<t.length;a++){let c=t[a];if(c===void 0)continue;let d=Ll(c);if(d?.sessionUpdate!=="tool_call_update")continue;let l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),d.rawInput&&typeof d.rawInput=="object"&&!Array.isArray(d.rawInput)&&Object.keys(d.rawInput).length>0&&s.set(l,d.rawInput),Array.isArray(d.content)&&d.content.length>0)){let u=n.get(l);u?u.push(...d.content):n.set(l,[...d.content])}}let r=[],i=null,o=null;for(let a=0;a<t.length;a++){let c=t[a];if(c===void 0)continue;let d=Ll(c);if(!d||typeof d.sessionUpdate!="string"){r.push(c),i=null;continue}let l=d.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?JS(r,i.outIndex,KS(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let u=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let f=u!==void 0&&n.has(u)?VS(c,n.get(u)??[]):c;u!==void 0&&s.has(u)&&!YS(f)&&(f=QS(f,s.get(u))),r.push(f);continue}if(l==="plan"){o!==null?r[o]=c:(r.push(c),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(c)}return r}function Ll(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function KS(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function JS(t,e,n){if(n.length===0)return;let s=t[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";t[e]={...s,params:{...r,update:{...i,content:{...o,text:a+n}}}}}function VS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function YS(t){let n=Ll(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function QS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var $h=J(()=>{"use strict"});function Ci(t,e={}){let n=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of t){if(o.method!=="session/update")continue;let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate;if(d==="prompt_received"){i();let l=Nl(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=Dl(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(Bl(c))):d==="turn_complete"&&i()}return i(),tk(s.join(`
16
+ `),n)}function Bl(t){let e=XS(t),n=ZS(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function XS(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function ZS(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of GS){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${ek(r,200)}`)}return n}function Nl(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{if(e&&typeof e=="object"){let n=e.text;if(typeof n=="string")return n}return""}).join(""):""}function Dl(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function ek(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function tk(t,e){if(t.length<=e)return t;let n=t.split(`
17
+ `);for(;n.length>0;){let s=Oh+n.join(`
18
+ `);if(s.length<=e)return s;n.shift()}return Oh}var Oh,GS,dd=J(()=>{"use strict";Oh=`[older history truncated]
19
+ `,GS=["file_path","filePath","path","command","pattern","query"]});function Hl(t){let e=[],n=t.synopsis;if(n!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??Fh}`),n.goal!==void 0&&n.goal.trim().length>0&&e.push(`[Goal] ${n.goal}`),n.outcome!==void 0&&n.outcome.trim().length>0&&e.push(`[Outcome] ${n.outcome}`);let o=Lo("Open threads",n.open_threads);o.length>0&&e.push(o);let a=Lo("Decisions",n.decisions);a.length>0&&e.push(a);let c=Lo("File edit intentions",n.file_edit_intentions);c.length>0&&e.push(c);let d=Lo("Unresolved errors",n.unresolved_errors);d.length>0&&e.push(d);let l=Lo("Tool state",n.tool_state);l.length>0&&e.push(l);let u=Lh(n.files_touched);u.length>0&&e.push(`[Files previously touched] ${u}`);let f=Lh(n.tools_used);f.length>0&&e.push(`[Tools previously used] ${f}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${t.title??Fh}`);let{closedText:s,openText:r,keptCount:i}=nk(t.tail,t.tailK,t.watermark??0,t.tailFloor??0);return e.push("--- begin recent turns (verbatim, last "+i+") ---"),s.length>0&&e.push(s),e.push("--- end recent turns ---"),r.length>0&&(e.push("--- begin current in-flight turn (no completion yet) ---"),e.push(r),e.push("--- end current in-flight turn ---")),e.push(""),n!==void 0?e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"):e.push("(This is a side conversation forked from another session. The turns above are the most recent; earlier history is available on demand via the hydra-recall tools. Do NOT call any tools yet. Do NOT read any files or run any commands. Reply with the single word 'OK' and wait for the next user message.)"),e.join(`
20
+ `)}function Lo(t,e){if(!e||!Array.isArray(e))return"";let n=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(n.length===0)return"";let s=n.map(r=>"- "+r.trim());return`[${t}] ${s.join(`
21
+ `)}`}function Lh(t){if(!t||!Array.isArray(t))return"";let e=t.filter(n=>typeof n=="string"&&n.trim().length>0);return e.length===0?"":e.map(n=>n.trim()).join(", ")}function nk(t,e,n,s){if(t.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:i}=sk(t),o=0,a=[];if(e>0&&r.length>0){let l=r.filter(p=>p.startEntryIndex>=n).length,u=Math.max(l,s),f=Math.min(u,e,r.length);o=f,a=f>0?r.slice(-f):[]}let c=a.length>0?Bh(a):"",d=i?Bh([i]):"";return{closedText:c,openText:d,keptCount:o}}function Bh(t){let e=[];for(let n of t){n.user.length>0&&e.push("User: "+n.user),n.agent.length>0&&e.push("Assistant: "+n.agent);for(let s of n.tools)e.push(s)}return e.join(`
22
+ `)}function sk(t){let e=[],n=null;for(let r=0;r<t.length;r++){let i=t[r];if(i.method!=="session/update")continue;let a=i.params?.update;if(!a||typeof a.sessionUpdate!="string")continue;let c=a.sessionUpdate;if(c==="prompt_received")n!==null&&n.user.length>0&&e.push(n),n={user:Nl(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(c==="agent_message_chunk"&&n!==null){let d=Dl(a.content);d.length>0&&(n.agent+=d)}else c==="tool_call"&&n!==null?n.tools.push(Bl(a)):c==="turn_complete"&&n!==null&&(e.push(n),n=null)}let s=n!==null&&n.user.length>0?n:null;return{closed:e,open:s}}var Fh,Nh=J(()=>{"use strict";dd();Fh="(untitled)"});import*as jn from"fs/promises";async function Bo(t,e){let n=_.queueFile(t);if(e.length===0){await jn.unlink(n).catch(()=>{});return}await jn.mkdir(_.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
23
23
  `)+`
24
- `;await jn.writeFile(n,s,"utf8")}async function Lh(t){let e=_.queueFile(t),n;try{n=await jn.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n.split(`
25
- `))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function Bh(t){let e=_.queueFile(t);await jn.unlink(e).catch(()=>{})}var Hl=J(()=>{"use strict";he()});import{customAlphabet as jh}from"nanoid";import*as zh from"fs/promises";function Hs(){return`m_${Wh()}`}function rt(t){return t.startsWith(bn)?t.slice(bn.length):t}function tn(t,e){return t.code=e,t}function Dh(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&ik.has(s)}function ok(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function ak(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.id!==e[n]?.id||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function dk(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.modelId!==e[n]?.modelId||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function Ri(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={modelId:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function Bo(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={id:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function ck(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_modes_update")return null;let s=n.availableModes;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.id!="string"||o.id.length===0)continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function lk(t,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let i=s.content??{};typeof i.text=="string"&&(t.chunks.push(i.text),t.messageChars+=i.text.length);return}if(r==="agent_thought_chunk"){let i=s.content??{};typeof i.text=="string"&&(t.thinkingChars+=i.text.length);return}if(r==="tool_call"){t.toolCalls++;return}if(r==="usage_update"){typeof s.used=="number"&&(t.lastUsed=s.used),typeof s.size=="number"&&(t.lastSize=s.size);return}}function uk(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_commands_update")return null;let s=n.availableCommands??n.commands;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.name!="string"||o.name.length===0)continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function fk(t,e){if(t!=="session/update"||!e||typeof e!="object")return e;let n=e;return!n.update||typeof n.update!="object"||Array.isArray(n.update)||typeof n.update.messageId=="string"?e:{...e,update:{...n.update,messageId:Hs()}}}function ql(t,e){for(let n=0;n<t.length;n++){let s=t[n];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return n}return-1}function Hh(t){if(!t||typeof t!="object")return;let e=t.toolCall;if(!e||typeof e!="object")return;let n=e.toolCallId;return typeof n=="string"?n:void 0}function pk(t){let e=hk(t.result),n={sessionUpdate:"permission_resolved"};return t.toolCallId!==void 0&&(n.toolCallId=t.toolCallId),e&&(n.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(n.chosenOptionId=e.optionId)),n.resolvedBy=mk(t.resolver),n}function hk(t){if(!t||typeof t!="object")return;let e=t.outcome;if(!e||typeof e!="object")return;let n=e.kind;if(typeof n!="string")return;let s={kind:n},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function mk(t){let e={clientId:t.clientId};return t.clientInfo?.name&&(e.name=t.clientInfo.name),t.clientInfo?.version&&(e.version=t.clientInfo.version),e}function Ci(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function jl(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function gk(t){return t==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function Uh(t){let e=t.name&&t.name!==t.id?`${t.id} (${t.name}) \u2014 \u25B6 ${t.currentValue}`:`${t.id} \u2014 \u25B6 ${t.currentValue}`;if(t.options.length===0)return e;let n=Math.max(...t.options.map(r=>r.value.length)),s=t.options.map(r=>{let i=r.value===t.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(n):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
24
+ `;await jn.writeFile(n,s,"utf8")}async function Dh(t){let e=_.queueFile(t),n;try{n=await jn.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n.split(`
25
+ `))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function Hh(t){let e=_.queueFile(t);await jn.unlink(e).catch(()=>{})}var Ul=J(()=>{"use strict";he()});import{customAlphabet as Wh}from"nanoid";import*as Jh from"fs/promises";function Hs(){return`m_${Kh()}`}function rt(t){return t.startsWith(bn)?t.slice(bn.length):t}function tn(t,e){return t.code=e,t}function Uh(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&ck.has(s)}function lk(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function uk(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.id!==e[n]?.id||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function fk(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.modelId!==e[n]?.modelId||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function Ti(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={modelId:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function No(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={id:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function pk(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_modes_update")return null;let s=n.availableModes;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.id!="string"||o.id.length===0)continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function hk(t,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let i=s.content??{};typeof i.text=="string"&&(t.chunks.push(i.text),t.messageChars+=i.text.length);return}if(r==="agent_thought_chunk"){let i=s.content??{};typeof i.text=="string"&&(t.thinkingChars+=i.text.length);return}if(r==="tool_call"){t.toolCalls++;return}if(r==="usage_update"){typeof s.used=="number"&&(t.lastUsed=s.used),typeof s.size=="number"&&(t.lastSize=s.size);return}}function mk(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_commands_update")return null;let s=n.availableCommands??n.commands;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.name!="string"||o.name.length===0)continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function gk(t,e){if(t!=="session/update"||!e||typeof e!="object")return e;let n=e;return!n.update||typeof n.update!="object"||Array.isArray(n.update)||typeof n.update.messageId=="string"?e:{...e,update:{...n.update,messageId:Hs()}}}function Wl(t,e){for(let n=0;n<t.length;n++){let s=t[n];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return n}return-1}function jh(t){if(!t||typeof t!="object")return;let e=t.toolCall;if(!e||typeof e!="object")return;let n=e.toolCallId;return typeof n=="string"?n:void 0}function yk(t){let e=wk(t.result),n={sessionUpdate:"permission_resolved"};return t.toolCallId!==void 0&&(n.toolCallId=t.toolCallId),e&&(n.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(n.chosenOptionId=e.optionId)),n.resolvedBy=bk(t.resolver),n}function wk(t){if(!t||typeof t!="object")return;let e=t.outcome;if(!e||typeof e!="object")return;let n=e.kind;if(typeof n!="string")return;let s={kind:n},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function bk(t){let e={clientId:t.clientId};return t.clientInfo?.name&&(e.name=t.clientInfo.name),t.clientInfo?.version&&(e.version=t.clientInfo.version),e}function Ri(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function ql(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function vk(t){return t==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function qh(t){let e=t.name&&t.name!==t.id?`${t.id} (${t.name}) \u2014 \u25B6 ${t.currentValue}`:`${t.id} \u2014 \u25B6 ${t.currentValue}`;if(t.options.length===0)return e;let n=Math.max(...t.options.map(r=>r.value.length)),s=t.options.map(r=>{let i=r.value===t.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(n):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
26
26
  ${s.join(`
27
- `)}`}function Wl(t,e){for(let n of t.split(/\r?\n/)){let s=n.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}var qh,Wh,Ul,nk,Nh,bn,sk,cd,rk,Ti,ik,qn=J(()=>{"use strict";$l();Th();Eh();ad();_h();Oh();Hl();Et();qh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Wh=jh(qh,16),Ul=jh(qh,16),nk=20,Nh=20,bn="hydra_session_";sk=1e3,cd=300*1e3,rk=64,Ti=class t{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;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;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;getCompactionStateHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;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;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Map;filesEditedSeen=new Set;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},n=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:n||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${bn}${Wh()}`,this.cwd=e.cwd,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.forkSynthesisState=e.forkSynthesisState,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.getCompactionStateHook=e.getCompactionState,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,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]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.idleEventTimeoutMs>0&&this.onIdle(n=>n.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.uncompactHook=e.uncompactHook,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._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let n=e.compactionState;(n.status==="requested"||n.status==="running"||n.status==="swap_pending"||n.status==="swap_deferred")&&(n.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:n.attempts}:this._liveCompactionPhase={phase:n.status==="requested"?"started":"iteration",iter:n.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let n of e.attentionFlags)this.attentionFlags.set(`${n.source}::${n.reason}`,n);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??sk,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.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:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"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){e.connection.onNotification("session/update",n=>{if(this.internalPromptCapture){lk(this.internalPromptCapture,n);return}this.maybeEmitToolEdges(n),this.runResponseChain(n)}),e.connection.onRequest("session/request_permission",async n=>{let s=await this.runAgentRequestChain("session/request_permission",n),r=Hh(s.shortCircuit?n:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let i=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:i,sourceWasTransformer:!1}),i}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(n=>{this.handleOrphanError(n)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let n=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||n>t.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,n=new Set,s=0,r="session/update"){let i=e,o=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let l=s;l<this.transformChain.length;l++){let u=this.transformChain[l];if(n.has(u.name)||!u.intercepts.has(a))continue;let f=`t_${Ul()}`,p;try{p=await u.connection.request("hydra-acp/transformer/message",{token:f,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(m){this.logger?.warn(`transformer ${u.name} error on ${a}: ${m.message}`);continue}let h=p?.action??"continue";if(h==="stop")return;if(h==="processing"){let m=l,y=o,b=new Set(n),v=r;await new Promise(S=>{let k=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:u.name}),this.runResponseChain(y,new Set([...b,u.name]),m+1,v).then(()=>S()).catch(()=>S()))},cd);typeof k.unref=="function"&&k.unref(),this.pendingClaims.set(f,{resolve:()=>S(),timer:k,transformerName:u.name,method:v,envelope:y,chainIdx:m,originatedBy:b,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(o=p.payload),n.add(u.name)}if(r!=="session/update")return;let c=uk(o);if(c!==null){this.setAgentAdvertisedCommands(c);return}let d=ck(o);if(d!==null){this.setAgentAdvertisedModes(d);return}if(this.maybeApplyAgentModel(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentMode(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentConfigOption(o)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(o));return}if(this.maybeApplyAgentUsage(i)){this.recordAndBroadcast("session/update",o);return}this.maybeApplyAgentSessionInfo(o),this.recordAndBroadcast("session/update",o)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let n=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),n.push(r)}return n}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}isQuiescedSync(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight)}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let s=this.agentId,r=e.newAgentId??this.agentId,i=r!==this.agentId,o=this.cwd,a=this.agentArgs,c=this.forwardedEnv,d=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:o,agentArgs:a,...c?{forwardedEnv:c}:{},mcpServers:f});this.accumulateAndResetCost(),this.wireAgent(p.agent),i||(await ki({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:d,agentReportedModel:p.initialModel,logger:this.logger}),await Si({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:l,agentReportedMode:p.initialMode,logger:this.logger})),p.agent.connection.drainBuffered("session/update");let h=[];if(this.historyStore)try{h=await this.historyStore.load(this.sessionId)}catch(T){this.logger?.warn(`swapUpstream: historyStore.load failed: ${T.message}`)}let m=Dl({synopsis:e.artifact,title:e.title,tail:h,tailK:e.tailK});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:m}]});let T=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${m.length} toolCalls=${T.toolCalls} thinkingChars=${T.thinkingChars} messageChars=${T.messageChars} used=${T.lastUsed??"?"} size=${T.lastSize??"?"} reply=${JSON.stringify(T.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let y=this.upstreamSessionId,b=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let v=this.agent;this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,i&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let T of this.agentChangeHandlers)try{T({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(F){this.logger?.warn(`swapUpstream: agentChange handler failed: ${F.message}`)}if(!i&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:y,...b!==void 0?{previousSummarizedThroughEntry:b}:{}})}catch(T){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${T.message}`)}await v.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:y,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),i||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),i&&this.broadcastAgentSwitch(s,r);let S=i?`
27
+ `)}`}function zl(t,e){for(let n of t.split(/\r?\n/)){let s=n.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}var zh,Kh,jl,rk,ik,ok,bn,ak,cd,dk,Ei,ck,qn=J(()=>{"use strict";Ol();Eh();Ph();ad();$h();Nh();Ul();Et();zh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Kh=Wh(zh,16),jl=Wh(zh,16),rk=20,ik=20,ok=5,bn="hydra_session_";ak=1e3,cd=300*1e3,dk=64,Ei=class t{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;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;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;getCompactionStateHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;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;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Map;filesEditedSeen=new Set;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},n=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:n||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${bn}${Kh()}`,this.cwd=e.cwd,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.forkSynthesisState=e.forkSynthesisState,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.getCompactionStateHook=e.getCompactionState,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,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]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.idleEventTimeoutMs>0&&this.onIdle(n=>n.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.uncompactHook=e.uncompactHook,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._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let n=e.compactionState;(n.status==="requested"||n.status==="running"||n.status==="swap_pending"||n.status==="swap_deferred")&&(n.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:n.attempts}:this._liveCompactionPhase={phase:n.status==="requested"?"started":"iteration",iter:n.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let n of e.attentionFlags)this.attentionFlags.set(`${n.source}::${n.reason}`,n);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??ak,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.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:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"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){e.connection.onNotification("session/update",n=>{if(this.internalPromptCapture){hk(this.internalPromptCapture,n);return}this.maybeEmitToolEdges(n),this.runResponseChain(n)}),e.connection.onRequest("session/request_permission",async n=>{let s=await this.runAgentRequestChain("session/request_permission",n),r=jh(s.shortCircuit?n:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let i=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:i,sourceWasTransformer:!1}),i}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(n=>{this.handleOrphanError(n)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let n=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||n>t.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,n=new Set,s=0,r="session/update"){let i=e,o=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let l=s;l<this.transformChain.length;l++){let u=this.transformChain[l];if(n.has(u.name)||!u.intercepts.has(a))continue;let f=`t_${jl()}`,p;try{p=await u.connection.request("hydra-acp/transformer/message",{token:f,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(m){this.logger?.warn(`transformer ${u.name} error on ${a}: ${m.message}`);continue}let h=p?.action??"continue";if(h==="stop")return;if(h==="processing"){let m=l,y=o,b=new Set(n),v=r;await new Promise(S=>{let k=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:u.name}),this.runResponseChain(y,new Set([...b,u.name]),m+1,v).then(()=>S()).catch(()=>S()))},cd);typeof k.unref=="function"&&k.unref(),this.pendingClaims.set(f,{resolve:()=>S(),timer:k,transformerName:u.name,method:v,envelope:y,chainIdx:m,originatedBy:b,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(o=p.payload),n.add(u.name)}if(r!=="session/update")return;let c=mk(o);if(c!==null){this.setAgentAdvertisedCommands(c);return}let d=pk(o);if(d!==null){this.setAgentAdvertisedModes(d);return}if(this.maybeApplyAgentModel(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentMode(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentConfigOption(o)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(o));return}if(this.maybeApplyAgentUsage(i)){this.recordAndBroadcast("session/update",o);return}this.maybeApplyAgentSessionInfo(o),this.recordAndBroadcast("session/update",o)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let n=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),n.push(r)}return n}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}isQuiescedSync(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight)}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let s=this.agentId,r=e.newAgentId??this.agentId,i=r!==this.agentId,o=this.cwd,a=this.agentArgs,c=this.forwardedEnv,d=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:o,agentArgs:a,...c?{forwardedEnv:c}:{},mcpServers:f});this.accumulateAndResetCost(),this.wireAgent(p.agent),i||(await ki({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:d,agentReportedModel:p.initialModel,logger:this.logger}),await Si({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:l,agentReportedMode:p.initialMode,logger:this.logger})),p.agent.connection.drainBuffered("session/update");let h=[];if(this.historyStore)try{h=await this.historyStore.load(this.sessionId)}catch(T){this.logger?.warn(`swapUpstream: historyStore.load failed: ${T.message}`)}let m=Hl({synopsis:e.artifact,title:e.title,tail:h,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{}});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:m}]});let T=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${m.length} toolCalls=${T.toolCalls} thinkingChars=${T.thinkingChars} messageChars=${T.messageChars} used=${T.lastUsed??"?"} size=${T.lastSize??"?"} reply=${JSON.stringify(T.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let y=this.upstreamSessionId,b=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let v=this.agent;this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,i&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let T of this.agentChangeHandlers)try{T({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(O){this.logger?.warn(`swapUpstream: agentChange handler failed: ${O.message}`)}if(!i&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:y,...b!==void 0?{previousSummarizedThroughEntry:b}:{}})}catch(T){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${T.message}`)}await v.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:y,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),i||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),i&&this.broadcastAgentSwitch(s,r);let S=i?`
28
28
  Switched to ${r}.
29
29
  `:`
30
30
  Compaction completed.
31
- `,k=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:S},_meta:{"hydra-acp":{synthetic:!0}}}});for(let T of this.clients.values())T.connection.notify("session/update",k).catch(()=>{});this.updatedAt=Date.now()}async rollbackToUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");let s=this.loadExistingAgentSession;if(!s)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,i=this.cwd,o=this.agentArgs,a=this.forwardedEnv,c=this.currentModel,d=this.currentMode,l=await s(e.previousUpstreamSessionId,{agentId:r,cwd:i,agentArgs:o,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(l.agent),await ki({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await Si({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let u=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await u.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let f of this.agentChangeHandlers)try{f({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(p){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${p.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=nk){if(!this.historyStore)return!1;let n=await this.historyStore.load(this.sessionId),s=n.length>e?n.slice(-e):n,r=new Set,i=new Set;for(let o of s){let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate,l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l){if(d==="tool_call")r.add(l);else if(d==="tool_call_update"){let u=c.status;(u==="completed"||u==="failed")&&i.add(l)}}}for(let o of r)if(!i.has(o))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let n=this.broadcastHandlers.indexOf(e);n>=0&&this.broadcastHandlers.splice(n,1)}}broadcastClientUpdate(e){let n=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",n).catch(()=>{})}broadcastCompactionPhase(e){let n=e.phase;n==="swapped"||n==="failed"||n==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{});this.notifyChain("compaction",{...e})}attach(e,n,s={}){if(this.closed)throw tn(new Error("session is closed"),z.SessionNotFound);if(this.clients.has(e.clientId))throw tn(new Error(`client ${e.clientId} is already attached`),z.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),n==="none"?Promise.resolve({entries:[],appliedPolicy:n}):n==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:n}):this.loadReplay(n,s)}async loadReplay(e,n){let s=a=>n.raw?a:Mh(a),i=(await this.getHistorySnapshot(n.toolContent??"inline")).filter(a=>!Dh(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=n.afterMessageId?ql(i,n.afterMessageId):-1;return a<0?{entries:[...o,...s(i)],appliedPolicy:"full"}:{entries:[...o,...s(i.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...o,...s(i)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],n=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let i={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(i.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(i.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:n,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let i=this.currentUsage,o={sessionUpdate:"usage_update"};if(typeof i.used=="number"&&(o.used=i.used),typeof i.size=="number"&&(o.size=i.size),typeof i.costAmount=="number"||typeof i.costCurrency=="string"){let a={};typeof i.costAmount=="number"&&(a.amount=i.costAmount),typeof i.costCurrency=="string"&&(a.currency=i.costCurrency),o.cost=a}Object.keys(o).length>1&&e.push({method:"session/update",params:{sessionId:n,update:o},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let n of this.attentionFlags.values()){if(n.source!=="daemon"||!n.reason.startsWith("permission:"))continue;let s=n.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(e)}}detach(e){let n=this.clients.get(e);n&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(n))}broadcastClientDisconnected(e){let n={clientId:e.clientId};e.clientInfo?.name&&(n.name=e.clientInfo.name),e.clientInfo?.version&&(n.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:n,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,n){let s=this.clients.get(e);if(!s)throw tn(new Error("client not attached"),z.SessionNotFound);if(this.closing)throw tn(new Error("session is closing; new prompts cannot be accepted"),z.SessionClosing);let r=Hs();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(en((n??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,n,r)}broadcastPromptReceived(e){let n={clientId:e.originator.clientId};e.originator.name&&(n.name=e.originator.name),e.originator.version&&(n.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:n}},e.clientId);let s=Ci(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let n={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(n.used=e.used),typeof e.size=="number"&&(n.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),n.cost=r}if(Object.keys(n).length<=1)return;let s={sessionId:this.sessionId,update:n};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,n,s,r){let i=n&&typeof n=="object"&&"stopReason"in n&&typeof n.stopReason=="string"?n.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:Hs()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:o},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,n){for(this.recentlyTerminal.set(e,{stopReason:n,terminatedAt:Date.now()});this.recentlyTerminal.size>rk;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let n=this.findUserEntry(e.newMessageId);if(!n)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:n.prompt,originator:n.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let n=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return n?.kind==="user"?n:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let n of this.promptQueue)n.kind==="user"&&!n.cancelled&&(e+=1);return e}broadcastQueueAdded(e,n){let s=this.visibleQueueDepth(),r=n?.position??Math.max(0,s-1),i={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};n?.amending!==void 0&&(i._meta={"hydra-acp":{amending:n.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:n})}broadcastQueueRemoved(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:n})}broadcastQueueNotification(e,n){for(let s of this.clients.values())s.connection.notify(e,n).catch(()=>{})}queueSnapshot(){let e=[],n=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:n++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:n++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let n of e){let s={clientId:`hydra-resurrected_${n.messageId}`};n.originator.clientInfo.name!==void 0&&(s.name=n.originator.clientInfo.name),n.originator.clientInfo.version!==void 0&&(s.version=n.originator.clientInfo.version);let r={kind:"user",messageId:n.messageId,originator:s,clientId:s.clientId,prompt:n.prompt,enqueuedAt:n.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let n=this.promptQueue.findIndex(r=>r.messageId===e);if(n<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[n];return s.cancelled=!0,this.promptQueue.splice(n,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,n){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=n,this.broadcastQueueUpdated(e,n),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,n){let s=this.clients.get(e);if(!s)throw tn(new Error("client not attached"),z.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=n;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let c=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(c&&c.kind==="user"&&!c.cancelled)return c.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let d=this.recentlyTerminal.get(r);return d?d.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,n,s,r){let i=Hs(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let c=[];for(let d of this.promptQueue){if(d.kind==="user"&&!d.cancelled){d.cancelled=!0,this.broadcastQueueRemoved(d.messageId,"cancelled"),d.resolve({stopReason:"cancelled"});continue}c.push(d)}this.promptQueue=c}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,n){let s=Hs(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw tn(new Error("client not attached"),z.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let n=this.transformChain.findIndex(s=>s.name===e.name);n>=0?this.transformChain[n]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,n,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(n);for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name))continue;let d=`request:${e}`;if(!c.intercepts.has(d))continue;let l=`t_${Ul()}`,u;try{u=await c.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${c.name} error on ${d}: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return i==="notification"?void 0:u?.payload??jl(e);if(f==="continue"){u?.payload&&typeof u.payload=="object"&&(o=u.payload),s.add(c.name);continue}if(f==="processing"){let p=a,h=o,m=new Set(s);return new Promise(y=>{let b=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.forwardRequest(e,h,new Set([...m,c.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:jl(e))))},cd);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:y,timer:b,transformerName:c.name,method:e,envelope:h,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(c.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}async runAgentRequestChain(e,n,s=new Set,r=0){let i=n,o=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name)||!c.intercepts.has(o))continue;let d=`t_${Ul()}`,l;try{l=await c.connection.request("hydra-acp/transformer/message",{token:d,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(f){this.logger?.warn(`transformer ${c.name} error on ${o}: ${f.message}`);continue}let u=l?.action??"continue";if(u==="stop")return{shortCircuit:!0,payload:l?.payload??gk(e)};if(u==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),s.add(c.name);continue}if(u==="processing"){let f=a,p=i,h=new Set(s),m=e;return new Promise(y=>{let b=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:c.name}),this.runAgentRequestChain(m,p,new Set([...h,c.name]),f+1).then(y).catch(()=>y({shortCircuit:!1,envelope:p})))},cd);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(d,{resolve:v=>y({shortCircuit:!0,payload:v}),timer:b,transformerName:c.name,method:m,envelope:p,chainIdx:f,originatedBy:h,side:"agent-request"})})}s.add(c.name)}return{shortCircuit:!1,envelope:i}}dischargeClaim(e,n){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(n),!0):!1}keepAliveClaim(e,n){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof n=="number"&&n>0?Math.min(n*1.5,1800*1e3):cd,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else if(s.side==="agent-request")this.runAgentRequestChain(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(s.resolve).catch(()=>s.resolve({shortCircuit:!1,envelope:s.envelope}));else{let o=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,o).then(s.resolve).catch(()=>s.resolve(o==="notification"?void 0:jl(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,n,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(n==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(n,s,o,i)}async emitToQueue(e,n){let s=this.transformChain.findIndex(d=>d.name===e),r=s>=0?s+1:0,i=(n??{}).prompt??[],o=Hs(),a=`transformer:${e}`,c={clientId:a,name:e};return new Promise((d,l)=>{let u={kind:"user",messageId:o,originator:c,clientId:a,prompt:i,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:d,reject:l},f=this.insertEntryAt(u,"tail");this.persistRewrite(),this.broadcastQueueAdded(u,{position:f}),this.drainQueue()})}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.sessionId)return{...n,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(e.deleteRecord&&(this.deleteRecordIntent=!0),!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let n of this.pendingClaims.values())clearTimeout(n.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let n=this.closeHandlers.indexOf(e);n>=0&&this.closeHandlers.splice(n,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let n=e.trim();if(!(!n||n===this.title)){this.title=n,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:n,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(n)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=Ci((e??{}).prompt),r=Wl(s,200);r&&(r.startsWith("/")||(this._firstPromptSeeded=!0,this.setTitle(r)))}maybeApplyAgentModel(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_model_update")return!1;let r=Ri(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let i=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(i===void 0)return!0;let o=i.trim();if(!o||o===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(o)}`),this.currentModel=o;for(let a of this.modelHandlers)try{a(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let i of r){if(!i||typeof i!="object")continue;let o=i;if(o.id==="model"){let a=Ri(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(d)}`),this.applyModelChange(d))}}else if(o.id==="mode"){let a=Bo(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(d)}`),this.applyModeChange(d))}}else if(typeof o.id=="string"&&o.id.trim()){let a=o.id.trim(),c=Ri(o.options);if(c.length>0){let d=Bo(o.options),l=d.length>0?d.map(y=>({value:y.id,name:y.name??y.id})):c.map(y=>({value:y.modelId,name:y.name??y.modelId})),u=o.name,f=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,h=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(y=>y.id===a);if(m>=0){let y={...this.agentAdvertisedConfigOptions[m]};y.options=l,typeof p=="string"&&p.trim()&&(y.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=y}else this.agentAdvertisedConfigOptions.push({id:a,name:f,category:"other",type:"select",currentValue:h,options:l})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e);let n={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=n;for(let r of this.usageHandlers)try{r(n)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let i={};typeof s.costAmount=="number"&&(i.amount=s.costAmount),typeof s.costCurrency=="string"&&(i.currency=s.costCurrency),r.cost=i}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r})}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...n,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(ok(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(ak(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let n of this.agentModesHandlers)try{n(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(n=>n.modelId).join(",")}]`),dk(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let n of this.agentModelsHandlers)try{n(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let n=e===void 0||e<=0?void 0:Math.floor(e);if(n!==this._priority){this._priority=n,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(n)}catch{}}}applyModelChange(e){let n=e.trim();if(n){this.modelChangeInFlight=!0;try{if(n!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(n)}`),this.currentModel=n;for(let r of this.modelHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:n};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let n=e.trim();if(n){this.modeChangeInFlight=!0;try{if(n!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(n)}`),this.currentMode=n;for(let r of this.modeHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:n};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(o=>({value:o.modelId,name:o.name??o.modelId,...o.description!==void 0?{description:o.description}:{}})),i=this.currentModel&&r.some(o=>o.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:i,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(o=>({value:o.id,name:o.name??o.id,...o.description!==void 0?{description:o.description}:{}})),i=this.currentMode&&r.some(o=>o.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:i,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let o=this.buildConfigOptions().find(a=>a.id==="agent");return o?{...n,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"compact",description:"Alias for '/hydra compact'"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}];if(this.extensionCommands)for(let{name:n,command:s}of this.extensionCommands.list()){let r=s.verb?`hydra ${n} ${s.verb}`:`hydra ${n}`,o={name:s.argsHint?`${r} ${s.argsHint}`:r};if(s.description&&(o.description=s.description),e.push(o),n.startsWith("hydra-acp-")){let a=n.slice(10);if(a.length>0){let c=s.verb?`hydra ${a} ${s.verb}`:`hydra ${a}`,l={name:s.argsHint?`${c} ${s.argsHint}`:c};s.description&&(l.description=s.description),e.push(l)}}}return e.push(...this.agentAdvertisedCommands),e}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,n){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),i=r?.[1]??"",o=(r?.[2]??"").trim();if(i==="")return{stopReason:"end_turn"};let a=n!==void 0;if(od.some(u=>u.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(o):this.runCompactCommand(o);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let u=new Error(`no dispatcher for /hydra verb ${i}`);throw u.code=z.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,n):this.runExtensionCommand(i,o);let c=`hydra-acp-${i}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,o,n):this.runExtensionCommand(c,o);let d=od.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:f}of this.extensionCommands.list())u.has(f)||(d.push(f),u.add(f))}let l=new Error(`unknown /hydra verb: ${i} (known: ${d.join(", ")})`);throw l.code=z.InvalidParams,l}runExtensionCommand(e,n){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,n,void 0))}async runExtensionCommandInline(e,n,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=n.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(h=>h.verb===o)){let h=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${h||"(none)"})`)}let c={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(c.messageId=s);let d=()=>{},l=new Promise(h=>{d=h});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:h=>d({stopReason:"cancelled",reason:h})});let u,f=!1;try{let h=r.connection.request("hydra-acp/commands/invoke",c),m=await Promise.race([h,l]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return f=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=m}catch(h){return this.emitExtensionReply(`${e} ${o}: ${h.message}`)}finally{s!==void 0&&!f&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,n){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:n})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(n),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
31
+ `,k=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:S},_meta:{"hydra-acp":{synthetic:!0}}}});for(let T of this.clients.values())T.connection.notify("session/update",k).catch(()=>{});this.updatedAt=Date.now()}async rollbackToUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");let s=this.loadExistingAgentSession;if(!s)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,i=this.cwd,o=this.agentArgs,a=this.forwardedEnv,c=this.currentModel,d=this.currentMode,l=await s(e.previousUpstreamSessionId,{agentId:r,cwd:i,agentArgs:o,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(l.agent),await ki({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await Si({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let u=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await u.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let f of this.agentChangeHandlers)try{f({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(p){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${p.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=rk){if(!this.historyStore)return!1;let n=await this.historyStore.load(this.sessionId),s=n.length>e?n.slice(-e):n,r=new Set,i=new Set;for(let o of s){let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate,l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l){if(d==="tool_call")r.add(l);else if(d==="tool_call_update"){let u=c.status;(u==="completed"||u==="failed")&&i.add(l)}}}for(let o of r)if(!i.has(o))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let n=this.broadcastHandlers.indexOf(e);n>=0&&this.broadcastHandlers.splice(n,1)}}broadcastClientUpdate(e){let n=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",n).catch(()=>{})}broadcastCompactionPhase(e){let n=e.phase;n==="swapped"||n==="failed"||n==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{});this.notifyChain("compaction",{...e})}attach(e,n,s={}){if(this.closed)throw tn(new Error("session is closed"),z.SessionNotFound);if(this.clients.has(e.clientId))throw tn(new Error(`client ${e.clientId} is already attached`),z.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),n==="none"?Promise.resolve({entries:[],appliedPolicy:n}):n==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:n}):this.loadReplay(n,s)}async loadReplay(e,n){let s=a=>n.raw?a:_h(a),i=(await this.getHistorySnapshot(n.toolContent??"inline")).filter(a=>!Uh(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=n.afterMessageId?Wl(i,n.afterMessageId):-1;return a<0?{entries:[...o,...s(i)],appliedPolicy:"full"}:{entries:[...o,...s(i.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...o,...s(i)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],n=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let i={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(i.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(i.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:n,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let i=this.currentUsage,o={sessionUpdate:"usage_update"};if(typeof i.used=="number"&&(o.used=i.used),typeof i.size=="number"&&(o.size=i.size),typeof i.costAmount=="number"||typeof i.costCurrency=="string"){let a={};typeof i.costAmount=="number"&&(a.amount=i.costAmount),typeof i.costCurrency=="string"&&(a.currency=i.costCurrency),o.cost=a}Object.keys(o).length>1&&e.push({method:"session/update",params:{sessionId:n,update:o},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let n of this.attentionFlags.values()){if(n.source!=="daemon"||!n.reason.startsWith("permission:"))continue;let s=n.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(e)}}detach(e){let n=this.clients.get(e);n&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(n))}broadcastClientDisconnected(e){let n={clientId:e.clientId};e.clientInfo?.name&&(n.name=e.clientInfo.name),e.clientInfo?.version&&(n.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:n,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,n){let s=this.clients.get(e);if(!s)throw tn(new Error("client not attached"),z.SessionNotFound);if(this.closing)throw tn(new Error("session is closing; new prompts cannot be accepted"),z.SessionClosing);let r=Hs();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(en((n??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,n,r)}broadcastPromptReceived(e){let n={clientId:e.originator.clientId};e.originator.name&&(n.name=e.originator.name),e.originator.version&&(n.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:n}},e.clientId);let s=Ri(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let n={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(n.used=e.used),typeof e.size=="number"&&(n.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),n.cost=r}if(Object.keys(n).length<=1)return;let s={sessionId:this.sessionId,update:n};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,n,s,r){let i=n&&typeof n=="object"&&"stopReason"in n&&typeof n.stopReason=="string"?n.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:Hs()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:o},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,n){for(this.recentlyTerminal.set(e,{stopReason:n,terminatedAt:Date.now()});this.recentlyTerminal.size>dk;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let n=this.findUserEntry(e.newMessageId);if(!n)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:n.prompt,originator:n.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let n=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return n?.kind==="user"?n:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let n of this.promptQueue)n.kind==="user"&&!n.cancelled&&(e+=1);return e}broadcastQueueAdded(e,n){let s=this.visibleQueueDepth(),r=n?.position??Math.max(0,s-1),i={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};n?.amending!==void 0&&(i._meta={"hydra-acp":{amending:n.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:n})}broadcastQueueRemoved(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:n})}broadcastQueueNotification(e,n){for(let s of this.clients.values())s.connection.notify(e,n).catch(()=>{})}queueSnapshot(){let e=[],n=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:n++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:n++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let n of e){let s={clientId:`hydra-resurrected_${n.messageId}`};n.originator.clientInfo.name!==void 0&&(s.name=n.originator.clientInfo.name),n.originator.clientInfo.version!==void 0&&(s.version=n.originator.clientInfo.version);let r={kind:"user",messageId:n.messageId,originator:s,clientId:s.clientId,prompt:n.prompt,enqueuedAt:n.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let n=this.promptQueue.findIndex(r=>r.messageId===e);if(n<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[n];return s.cancelled=!0,this.promptQueue.splice(n,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,n){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=n,this.broadcastQueueUpdated(e,n),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,n){let s=this.clients.get(e);if(!s)throw tn(new Error("client not attached"),z.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=n;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let c=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(c&&c.kind==="user"&&!c.cancelled)return c.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let d=this.recentlyTerminal.get(r);return d?d.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,n,s,r){let i=Hs(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let c=[];for(let d of this.promptQueue){if(d.kind==="user"&&!d.cancelled){d.cancelled=!0,this.broadcastQueueRemoved(d.messageId,"cancelled"),d.resolve({stopReason:"cancelled"});continue}c.push(d)}this.promptQueue=c}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,n){let s=Hs(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw tn(new Error("client not attached"),z.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let n=this.transformChain.findIndex(s=>s.name===e.name);n>=0?this.transformChain[n]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,n,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(n);for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name))continue;let d=`request:${e}`;if(!c.intercepts.has(d))continue;let l=`t_${jl()}`,u;try{u=await c.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${c.name} error on ${d}: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return i==="notification"?void 0:u?.payload??ql(e);if(f==="continue"){u?.payload&&typeof u.payload=="object"&&(o=u.payload),s.add(c.name);continue}if(f==="processing"){let p=a,h=o,m=new Set(s);return new Promise(y=>{let b=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.forwardRequest(e,h,new Set([...m,c.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:ql(e))))},cd);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:y,timer:b,transformerName:c.name,method:e,envelope:h,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(c.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}async runAgentRequestChain(e,n,s=new Set,r=0){let i=n,o=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name)||!c.intercepts.has(o))continue;let d=`t_${jl()}`,l;try{l=await c.connection.request("hydra-acp/transformer/message",{token:d,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(f){this.logger?.warn(`transformer ${c.name} error on ${o}: ${f.message}`);continue}let u=l?.action??"continue";if(u==="stop")return{shortCircuit:!0,payload:l?.payload??vk(e)};if(u==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),s.add(c.name);continue}if(u==="processing"){let f=a,p=i,h=new Set(s),m=e;return new Promise(y=>{let b=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:c.name}),this.runAgentRequestChain(m,p,new Set([...h,c.name]),f+1).then(y).catch(()=>y({shortCircuit:!1,envelope:p})))},cd);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(d,{resolve:v=>y({shortCircuit:!0,payload:v}),timer:b,transformerName:c.name,method:m,envelope:p,chainIdx:f,originatedBy:h,side:"agent-request"})})}s.add(c.name)}return{shortCircuit:!1,envelope:i}}dischargeClaim(e,n){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(n),!0):!1}keepAliveClaim(e,n){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof n=="number"&&n>0?Math.min(n*1.5,1800*1e3):cd,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else if(s.side==="agent-request")this.runAgentRequestChain(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(s.resolve).catch(()=>s.resolve({shortCircuit:!1,envelope:s.envelope}));else{let o=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,o).then(s.resolve).catch(()=>s.resolve(o==="notification"?void 0:ql(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,n,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(n==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(n,s,o,i)}async emitToQueue(e,n){let s=this.transformChain.findIndex(d=>d.name===e),r=s>=0?s+1:0,i=(n??{}).prompt??[],o=Hs(),a=`transformer:${e}`,c={clientId:a,name:e};return new Promise((d,l)=>{let u={kind:"user",messageId:o,originator:c,clientId:a,prompt:i,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:d,reject:l},f=this.insertEntryAt(u,"tail");this.persistRewrite(),this.broadcastQueueAdded(u,{position:f}),this.drainQueue()})}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.sessionId)return{...n,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(e.deleteRecord&&(this.deleteRecordIntent=!0),!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let n of this.pendingClaims.values())clearTimeout(n.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let n=this.closeHandlers.indexOf(e);n>=0&&this.closeHandlers.splice(n,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let n=e.trim();if(!(!n||n===this.title)){this.title=n,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:n,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(n)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=Ri((e??{}).prompt),r=zl(s,200);r&&(r.startsWith("/")||(this._firstPromptSeeded=!0,this.setTitle(r)))}maybeApplyAgentModel(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_model_update")return!1;let r=Ti(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let i=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(i===void 0)return!0;let o=i.trim();if(!o||o===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(o)}`),this.currentModel=o;for(let a of this.modelHandlers)try{a(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let i of r){if(!i||typeof i!="object")continue;let o=i;if(o.id==="model"){let a=Ti(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(d)}`),this.applyModelChange(d))}}else if(o.id==="mode"){let a=No(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(d)}`),this.applyModeChange(d))}}else if(typeof o.id=="string"&&o.id.trim()){let a=o.id.trim(),c=Ti(o.options);if(c.length>0){let d=No(o.options),l=d.length>0?d.map(y=>({value:y.id,name:y.name??y.id})):c.map(y=>({value:y.modelId,name:y.name??y.modelId})),u=o.name,f=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,h=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(y=>y.id===a);if(m>=0){let y={...this.agentAdvertisedConfigOptions[m]};y.options=l,typeof p=="string"&&p.trim()&&(y.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=y}else this.agentAdvertisedConfigOptions.push({id:a,name:f,category:"other",type:"select",currentValue:h,options:l})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e);let n={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=n;for(let r of this.usageHandlers)try{r(n)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let i={};typeof s.costAmount=="number"&&(i.amount=s.costAmount),typeof s.costCurrency=="string"&&(i.currency=s.costCurrency),r.cost=i}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r})}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...n,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(lk(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(uk(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let n of this.agentModesHandlers)try{n(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(n=>n.modelId).join(",")}]`),fk(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let n of this.agentModelsHandlers)try{n(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let n=e===void 0||e<=0?void 0:Math.floor(e);if(n!==this._priority){this._priority=n,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(n)}catch{}}}applyModelChange(e){let n=e.trim();if(n){this.modelChangeInFlight=!0;try{if(n!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(n)}`),this.currentModel=n;for(let r of this.modelHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:n};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let n=e.trim();if(n){this.modeChangeInFlight=!0;try{if(n!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(n)}`),this.currentMode=n;for(let r of this.modeHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:n};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(o=>({value:o.modelId,name:o.name??o.modelId,...o.description!==void 0?{description:o.description}:{}})),i=this.currentModel&&r.some(o=>o.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:i,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(o=>({value:o.id,name:o.name??o.id,...o.description!==void 0?{description:o.description}:{}})),i=this.currentMode&&r.some(o=>o.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:i,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let o=this.buildConfigOptions().find(a=>a.id==="agent");return o?{...n,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),n=this.aliasableBareVerbs();for(let s of xi){if(n.get(s.verb)!=="__hydra__")continue;let r=s.argsHint?`${s.verb} ${s.argsHint}`:s.verb;e.push({name:r,description:`Alias for '/hydra ${s.verb}': ${s.description}`})}if(this.extensionCommands)for(let{name:s,command:r}of this.extensionCommands.list()){let i=r.verb?`hydra ${s} ${r.verb}`:`hydra ${s}`,a={name:r.argsHint?`${i} ${r.argsHint}`:i};r.description&&(a.description=r.description),e.push(a);let c=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&c.length>0){let d=r.verb?`hydra ${c} ${r.verb}`:`hydra ${c}`,u={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(u.description=r.description),e.push(u)}if(c.length>0&&n.get(c)===s){let d=r.verb?`${c} ${r.verb}`:c,u={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(u.description=r.description),e.push(u)}}return e.push(...this.agentAdvertisedCommands),e}daemonTopLevelCommands(){return[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}]}aliasableBareVerbs(){let e=new Set,n=o=>o.split(/\s+/)[0]??"";for(let o of this.daemonTopLevelCommands()){let a=n(o.name);a&&e.add(a)}for(let o of this.agentAdvertisedCommands){let a=n(o.name);a&&e.add(a)}let s=new Map;for(let o of xi)e.has(o.verb)||s.set(o.verb,"__hydra__");if(!this.extensionCommands)return s;let r=new Map,i=new Set;for(let{name:o}of this.extensionCommands.list()){if(i.has(o))continue;i.add(o);let a=o.startsWith("hydra-acp-")?o.slice(10):o;if(!a||e.has(a)||s.has(a))continue;let c=r.get(a);c===void 0?r.set(a,o):c!==o&&r.set(a,"__conflict__")}for(let[o,a]of r)a!=="__conflict__"&&s.set(o,a);return s}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,n){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),i=r?.[1]??"",o=(r?.[2]??"").trim();if(i==="")return{stopReason:"end_turn"};let a=n!==void 0;if(xi.some(u=>u.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(o):this.runCompactCommand(o);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let u=new Error(`no dispatcher for /hydra verb ${i}`);throw u.code=z.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,n):this.runExtensionCommand(i,o);let c=`hydra-acp-${i}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,o,n):this.runExtensionCommand(c,o);let d=xi.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:f}of this.extensionCommands.list())u.has(f)||(d.push(f),u.add(f))}let l=new Error(`unknown /hydra verb: ${i} (known: ${d.join(", ")})`);throw l.code=z.InvalidParams,l}runExtensionCommand(e,n){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,n,void 0))}async runExtensionCommandInline(e,n,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=n.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(h=>h.verb===o)){let h=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${h||"(none)"})`)}let c={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(c.messageId=s);let d=()=>{},l=new Promise(h=>{d=h});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:h=>d({stopReason:"cancelled",reason:h})});let u,f=!1;try{let h=r.connection.request("hydra-acp/commands/invoke",c),m=await Promise.race([h,l]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return f=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=m}catch(h){return this.emitExtensionReply(`${e} ${o}: ${h.message}`)}finally{s!==void 0&&!f&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,n){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:n})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(n),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
32
32
  ${e}
33
33
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let n=await this.listSessions();if(n.length===0)e="_(no sessions)_";else{let s=n.map(r=>{let i=r.sessionId.replace(/^hydra_session_/,"").slice(0,12),o=r.currentModel?` \xB7 ${r.currentModel}`:"",a=r.sessionId===this.sessionId?" \u25C0":"",c=r.title?` ${r.title}`:"";return`\`${i}\` ${r.cwd}${o}${a}${c}`});e=`Sessions (${n.length}):
34
34
  ${s.join(`
@@ -41,7 +41,7 @@ ${s}
41
41
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let n=e.slice(6).trim();if(n===""){let i=this.agentAdvertisedModels,o=this.currentModel,a;if(i.length===0)a=o?`Current model: ${o}`:"_(no models advertised yet)_";else{let c=o?i.some(l=>l.modelId===o):!0,d=i.map(l=>{let u=l.modelId===o?"\u25B6 ":" ",f=l.name&&l.name!==l.modelId?` ${l.name}`:"";return`${u}${l.modelId}${f}`});!c&&o&&d.unshift(`\u25B6 ${o}`),a=d.join(`
42
42
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
43
43
  ${a}
44
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=xi(n,this.agentAdvertisedModels),r=n;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(u=>u.modelId),o=n.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:i.filter(u=>u.toLowerCase().includes(o)),c=a.length>0?a:i,d=s.kind==="ambiguous"?`"${n}" matches multiple models: ${s.candidates.join(", ")}`:a.length>0?`"${n}" is not an available model. Did you mean`:`"${n}" is not an available model`,l=s.kind==="ambiguous"||a.length===0?"Available models":"Matching models";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
44
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=Ai(n,this.agentAdvertisedModels),r=n;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(u=>u.modelId),o=n.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:i.filter(u=>u.toLowerCase().includes(o)),c=a.length>0?a:i,d=s.kind==="ambiguous"?`"${n}" matches multiple models: ${s.candidates.join(", ")}`:a.length>0?`"${n}" is not an available model. Did you mean`:`"${n}" is not an available model`,l=s.kind==="ambiguous"||a.length===0?"Available models":"Matching models";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
45
45
  ${d}.
46
46
  ${l}:
47
47
  ${c.join(`
@@ -51,7 +51,7 @@ ${l}:
51
51
  ${o}
52
52
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===n)){let r=s.map(i=>i.id).join(", ");throw tn(new Error(`unknown mode: ${n} (known: ${r})`),z.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:n}),this.applyModeChange(n),{stopReason:"end_turn"}}async handleConfigCommand(e){let n=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=n?.[1],r=n?.[2]??"";if(!s){let l=this.buildConfigOptions();if(l.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
53
53
  _(no config options advertised yet)_
54
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let u=l.map(f=>Uh(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
54
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let u=l.map(f=>qh(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
55
55
  ${u.join(`
56
56
 
57
57
  `)}
@@ -61,16 +61,16 @@ ${u.join(`
61
61
  Available options:
62
62
  ${l}
63
63
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}if(!r)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
64
- ${Uh(o)}
64
+ ${qh(o)}
65
65
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),c=Fl(r,a),d=r;if(c.kind==="resolved")d=c.modelId;else if(c.kind==="ambiguous"||c.kind==="unknown"){let l=r.toLowerCase(),u=c.kind==="ambiguous"?c.candidates:a.filter(m=>m.toLowerCase().includes(l)),f=u.length>0?u:a,p=c.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${c.candidates.join(", ")}`:u.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,h=c.kind==="ambiguous"||u.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
66
66
  ${p}.
67
67
  ${h}:
68
68
  ${f.join(`
69
69
  `)}
70
70
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(d!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:d}),this.applyModelChange(d),{stopReason:"end_turn"}):s==="mode"?(d!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:d}),this.applyModeChange(d),{stopReason:"end_turn"}):s==="agent"?(d!==this.agentId&&await this.runAgentCommandInline(d),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:d}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let n={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};this.internalPromptCapture=n;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),n.chunks.join("")}finally{this.internalPromptCapture=void 0}}setAgent(e){return this.runAgentCommand(e)}runAgentCommand(e){return this.enqueuePrompt(()=>this.runAgentCommandInline(e))}async runAgentCommandInline(e){if(e==="status")return this.runAgentStatusCommandInline();let n=e;if(!n)throw tn(new Error("/hydra agent requires an agent id"),z.InvalidParams);if(n===this.agentId)throw tn(new Error(`already on agent ${n}`),z.InvalidParams);return this.scheduleCompactionHook?(this.scheduleCompactionHook({targetAgentId:n}),this.emitExtensionReply(`Agent switch to ${n} scheduled. The session will rotate to ${n} once synthesis completes.`),{stopReason:"end_turn"}):(this.emitExtensionReply("agent switching not configured for this session"),{stopReason:"end_turn"})}async runAgentStatusCommandInline(){let e=await this.getPendingAgentSwapHook?.();return e?(this.emitExtensionReply(`Agent switch to ${e} pending \u2014 will rotate on the next idle edge.`),{stopReason:"end_turn"}):(this.emitExtensionReply("No agent switch pending."),{stopReason:"end_turn"})}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw tn(new Error("agent restart not configured for this session"),z.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}runCompactCommand(e){return this.enqueuePrompt(()=>this.runCompactCommandInline(e))}async runCompactCommandInline(e){return e==="status"?this.runCompactStatusCommandInline():this.scheduleCompactionHook?(this.scheduleCompactionHook(),this.emitExtensionReply("Compaction scheduled. The session will rotate to a fresh upstream once summarization completes."),{stopReason:"end_turn"}):(this.emitExtensionReply("compaction scheduling not configured for this session"),{stopReason:"end_turn"})}async runCompactStatusCommandInline(){let e=await this.getCompactionStateHook?.(),n=this._summarizedThroughEntry;if(e==null&&n==null)return this.emitExtensionReply("This session has never been compacted."),{stopReason:"end_turn"};if(e==null)return this.emitExtensionReply(`No compaction in progress. Last summarized through entry: ${n}`),{stopReason:"end_turn"};let s=[`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${n??0}`,`Pending attempts: ${e.attempts??0}`];return this.emitExtensionReply(s.join(`
71
- `)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw tn(new Error("session is closing"),z.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,n=this.agentId,s=await this.buildSwitchTranscript(n),r=await e({agentId:n,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(n,n);let o={agentId:n,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,n){let s=[],r=await this.getHistorySnapshot();for(let d of r){if(d.method!=="session/update")continue;let u=(d.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let h=Ci(u.prompt);h&&s.push({speaker:"user",text:h})}else if(p==="agent_message_chunk"){let m=u.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(p==="tool_call"||p==="tool_call_update"){let h=u.status,m=u.title;(h==="completed"||h==="failed")&&s.push({speaker:"tool",text:`${m??"?"} ${h}`})}}if(s.length===0)return"";let i=[],o;for(let d of s)o&&o.speaker===d.speaker?o.text+=d.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:d.speaker,text:d.text});o&&i.push(`<${o.speaker}>: ${o.text.trim()}`);let a=n?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,c=n?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,c,"","--- begin transcript ---",...i,"--- end transcript ---"].join(`
72
- `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}async seedFromFork(e){e&&await this.enqueuePrompt(async()=>{let n=this.title??"(untitled)",s=[];if(this.historyStore)try{s=await this.historyStore.load(this.sessionId)}catch(o){this.logger?.warn(`seedFromFork: historyStore.load failed: ${o.message}`)}let r=s.slice(-Nh),i=Dl({synopsis:e,title:n,tail:r,tailK:Nh});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:i}]});let o=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${i.length} toolCalls=${o.toolCalls} thinkingChars=${o.thinkingChars} messageChars=${o.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,n){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:n,pendingAgentSwap:null}}}}),this.broadcastConfigOptions()}broadcastPendingAgentSwap(e){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,pendingAgentSwap:e}}}})}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let i=new id(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,n){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return n===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,n,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(n??Ii,Ii)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let c=await r.waitForData(o.nextCursor,s);(c==="data"||c==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,n){return this.requireStreamBuffer().waitForData(e,n)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=z.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let i of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(i,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let s=this.promptQueue;this.promptQueue=[];for(let i of s){i.cancelled=!0,i.kind==="user"&&this.broadcastQueueRemoved(i.messageId,"abandoned");try{i.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Bh(r).catch(()=>{}));for(let i of this.clients.values())i.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let i=this.streamBuffer,o=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,i.close(),o!==void 0&&i.drainFileWrites().then(()=>zh.unlink(o).catch(()=>{}))}for(let i of this.closeHandlers)i(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,n,s){this._setAttentionFlag(e,n,s,!0)}_setAttentionFlag(e,n,s,r){let i=`${e}::${n}`,o=this.attentionFlags.get(i);if(o){if(JSON.stringify(o.payload)===JSON.stringify(s))return;this.attentionFlags.set(i,{...o,payload:s,raisedAt:o.raisedAt})}else this.attentionFlags.set(i,{source:e,reason:n,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,n){this._clearAttentionFlag(e,n,!0)}_clearAttentionFlag(e,n,s){let r=`${e}::${n}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,n)=>e.raisedAt-n.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(n=>n.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let n of this.attentionFlagsChangeHandlers)try{n(e)}catch{}}broadcastAttentionUpdated(){for(let e of this.clients.values())e.connection.notify("hydra-acp/session/attention_updated",{sessionId:this.sessionId,flags:this.listAttentionFlags()}).catch(()=>{})}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let n=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(n).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.disposeIdleHandlers()}onIdle(e,n){let s={fn:e,once:!!n?.once,debounceMs:n?.debounceMs??0};return this.idleHandlers.push(s),()=>{let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1),s.timer&&(clearTimeout(s.timer),s.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let s of this.idleHandlers)s.timer&&(clearTimeout(s.timer),s.timer=void 0);return}let n=[...this.idleHandlers];for(let s of n){if(s.debounceMs===0){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}continue}s.timer&&(clearTimeout(s.timer),s.timer=void 0),s.timer=setTimeout(()=>{if(s.timer=void 0,!this.closed&&this.isQuiescedSync()){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}}},s.debounceMs),typeof s.timer.unref=="function"&&s.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let n=e.update;if(!n||typeof n!="object")return;let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:"";if(r!=="tool_call"&&r!=="tool_call_update")return;let i=typeof s.toolCallId=="string"&&s.toolCallId.length>0?s.toolCallId:void 0;if(!i)return;let o=typeof s.kind=="string"?s.kind:void 0;o&&!this.toolCallKind.has(i)&&this.toolCallKind.set(i,o);let a=o??this.toolCallKind.get(i);if(a==="edit"&&Array.isArray(s.locations))for(let l of s.locations){if(!l||typeof l!="object")continue;let u=l.path;if(typeof u!="string"||u.length===0||this.filesEditedSeen.has(u))continue;this.filesEditedSeen.add(u);let f=l.line,p={path:u,toolCallId:i};typeof f=="number"&&(p.line=f),this.notifyChain("file.edited",p)}if(r!=="tool_call_update")return;let c=typeof s.status=="string"?s.status:void 0;if(c!=="completed"&&c!=="failed"||this.toolCompletionSeen.has(i))return;this.toolCompletionSeen.set(i,c);let d={toolCallId:i,status:c};a&&(d.kind=a),s.content!==void 0&&(d.content=s.content),Array.isArray(s.locations)&&(d.locations=s.locations),this.notifyChain("tool.completed",d)}notifyChain(e,n){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:n}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(typeof n.sessionId=="string"&&n.sessionId!==this.sessionId)return{...n,sessionId:this.sessionId}}return e}recordAndBroadcast(e,n,s){let r=this.rewriteForClient(n),i=!Dh(e,r),o=i?fk(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let c=this.historyStore;c.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,c.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let c of this.broadcastHandlers)try{c(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let n=[...this.clients.values()];if(n.length===0)throw tn(new Error("no clients attached to handle permission request"),z.PermissionDenied);let s=this.rewriteForClient(e),r=Hh(s),i=Hs(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,u=[],f=0,p,h=this.sessionId,m=v=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),v())},y=v=>v?.code===z.MethodNotFound;function b(v){if(l)return;let S=v.connection.request("session/request_permission",s);u.push({client:v}),f++,S.then(k=>{f--,m(()=>{let T=pk({toolCallId:r,result:k,resolver:v});for(let F of u)F.client.clientId!==v.clientId&&F.client.connection.notify("session/update",{sessionId:h,update:T}).catch(()=>{});c(k)})}).catch(k=>{if(f--,y(k)||(p=k),f===0&&!l){let T=p??tn(new Error("no client handled permission request"),z.PermissionDenied);m(()=>d(T))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,b);for(let v of n)b(v)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:Hs(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:n,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,n,s){let r=(n??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(n);return new Promise((a,c)=>{let d={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:c},l=this.insertEntryAt(d,o);this.persistRewrite(),this.broadcastQueueAdded(d,{position:l}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let n=e._meta;if(!n||typeof n!="object"||Array.isArray(n))return"tail";let s=n["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,n){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(n==="head")return this.promptQueue.unshift(e),s;if(typeof n=="object"){let r=n.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let n=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Lo(n,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let n=await this.runQueueEntry(e);e.resolve(n),await new Promise(s=>setImmediate(s))}catch(n){e.reject(n)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let n=Ci(e.prompt).replace(/\s+$/,""),s=!n.includes(`
73
- `)&&n.startsWith("/")?n.split(/\s+/)[0]:"";if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"||s==="/compact"){let i;if(s==="/sessions")i=await this.handleSessionsCommand();else if(s==="/help")i=await this.handleHelpCommand();else if(s==="/mode")i=await this.handleModeCommand(n);else if(s==="/model")i=await this.handleModelCommand(n);else if(s==="/compact"){let o=n.slice(8).trim(),a=o?`/hydra compact ${o}`:"/hydra compact";i=await this.handleSlashCommand(a,e.messageId)}else i=await this.handleSlashCommand(n,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,i,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let r;try{r=await this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:e.prompt},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0)}catch(i){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}return this.closed||this.broadcastTurnComplete(e.clientId,r,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),r}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};ik=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction"])});import{z as Ei}from"zod";var yk,Kh,Jh=J(()=>{"use strict";yk=Ei.object({source:Ei.string(),reason:Ei.string(),raisedAt:Ei.number(),payload:Ei.unknown()}),Kh=Ei.array(yk)});import{z as Le}from"zod";function Qh(t){let e=t.trim();if(e.length===0)return;let n=Pi(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=Pi(e.slice(i,o+1)))}if(n===void 0){let i=Xh(e);i!==void 0&&(n=Pi(i))}if(n===void 0||n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,Vh))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=No.safeParse(s.synopsis);i.success&&wk(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Gh(t){let e=t.trim();if(e.length===0)return;let n=Pi(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=Pi(e.slice(d,l+1)))}if(n===void 0){let d=Xh(e);d!==void 0&&(n=Pi(d))}if(n===void 0||n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let d=s.title.trim();d.length>0&&(r.title=d.slice(0,Vh))}let i={},o=!1,a=["goal","outcome"];for(let d of a)if(typeof s[d]=="string"){let l=s[d].trim();l.length>0&&(i[d]=l,o=!0)}let c=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let d of c)if(Array.isArray(s[d])){let l=s[d],u=Le.array(Le.string()).safeParse(l);u.success&&l.length>0&&(i[d]=u.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function Pi(t){try{return JSON.parse(t)}catch{return}}function Xh(t){let e=t.indexOf("{");if(e<0)return;let n=0,s=!1,r=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){r?r=!1:o==="\\"?r=!0:o==='"'&&(s=!1);continue}if(o==='"'){s=!0;continue}if(o==="{")n++;else if(o==="}"&&(n--,n===0))return t.slice(e,i+1)}}function wk(t){return t.goal!==void 0&&t.goal.trim().length>0||t.outcome!==void 0&&t.outcome.trim().length>0||t.files_touched!==void 0&&t.files_touched.length>0||t.tools_used!==void 0&&t.tools_used.length>0||t.rejected_approaches!==void 0&&t.rejected_approaches.length>0||t.open_threads!==void 0&&t.open_threads.length>0||t.decisions!==void 0&&t.decisions.length>0||t.file_edit_intentions!==void 0&&t.file_edit_intentions.length>0||t.unresolved_errors!==void 0&&t.unresolved_errors.length>0||t.tool_state!==void 0&&t.tool_state.length>0}var Yh,No,Vh,zl,Kl,ld=J(()=>{"use strict";Yh=Le.object({status:Le.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:Le.number(),iter:Le.number().int().nonnegative().optional(),attempts:Le.number().int().nonnegative().optional(),lastError:Le.string().optional(),worker:Le.object({upstreamSessionId:Le.string(),pid:Le.number().int().nonnegative()}).optional()}),No=Le.object({goal:Le.string().optional(),outcome:Le.string().optional(),files_touched:Le.array(Le.string()).optional(),tools_used:Le.array(Le.string()).optional(),rejected_approaches:Le.array(Le.string()).optional(),open_threads:Le.array(Le.string()).optional(),decisions:Le.array(Le.string()).optional(),file_edit_intentions:Le.array(Le.string()).optional(),unresolved_errors:Le.array(Le.string()).optional(),tool_state:Le.array(Le.string()).optional()}),Vh=200,zl=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
71
+ `)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw tn(new Error("session is closing"),z.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,n=this.agentId,s=await this.buildSwitchTranscript(n),r=await e({agentId:n,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(n,n);let o={agentId:n,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,n){let s=[],r=await this.getHistorySnapshot();for(let d of r){if(d.method!=="session/update")continue;let u=(d.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let h=Ri(u.prompt);h&&s.push({speaker:"user",text:h})}else if(p==="agent_message_chunk"){let m=u.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(p==="tool_call"||p==="tool_call_update"){let h=u.status,m=u.title;(h==="completed"||h==="failed")&&s.push({speaker:"tool",text:`${m??"?"} ${h}`})}}if(s.length===0)return"";let i=[],o;for(let d of s)o&&o.speaker===d.speaker?o.text+=d.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:d.speaker,text:d.text});o&&i.push(`<${o.speaker}>: ${o.text.trim()}`);let a=n?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,c=n?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,c,"","--- begin transcript ---",...i,"--- end transcript ---"].join(`
72
+ `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}async seedFromFork(e){await this.enqueuePrompt(async()=>{let n=this.title??"(untitled)",s=[];if(this.historyStore)try{s=await this.historyStore.load(this.sessionId)}catch(i){this.logger?.warn(`seedFromFork: historyStore.load failed: ${i.message}`)}let r=Hl({synopsis:e,title:n,tail:s,tailK:ik,tailFloor:ok,watermark:this._summarizedThroughEntry});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:r}]});let i=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${i.toolCalls} thinkingChars=${i.thinkingChars} messageChars=${i.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,n){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:n,pendingAgentSwap:null}}}}),this.broadcastConfigOptions()}broadcastPendingAgentSwap(e){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,pendingAgentSwap:e}}}})}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let i=new od(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,n){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return n===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,n,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(n??Ii,Ii)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let c=await r.waitForData(o.nextCursor,s);(c==="data"||c==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,n){return this.requireStreamBuffer().waitForData(e,n)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=z.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let i of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(i,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let s=this.promptQueue;this.promptQueue=[];for(let i of s){i.cancelled=!0,i.kind==="user"&&this.broadcastQueueRemoved(i.messageId,"abandoned");try{i.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Hh(r).catch(()=>{}));for(let i of this.clients.values())i.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let i=this.streamBuffer,o=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,i.close(),o!==void 0&&i.drainFileWrites().then(()=>Jh.unlink(o).catch(()=>{}))}for(let i of this.closeHandlers)i(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,n,s){this._setAttentionFlag(e,n,s,!0)}_setAttentionFlag(e,n,s,r){let i=`${e}::${n}`,o=this.attentionFlags.get(i);if(o){if(JSON.stringify(o.payload)===JSON.stringify(s))return;this.attentionFlags.set(i,{...o,payload:s,raisedAt:o.raisedAt})}else this.attentionFlags.set(i,{source:e,reason:n,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,n){this._clearAttentionFlag(e,n,!0)}_clearAttentionFlag(e,n,s){let r=`${e}::${n}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,n)=>e.raisedAt-n.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(n=>n.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let n of this.attentionFlagsChangeHandlers)try{n(e)}catch{}}broadcastAttentionUpdated(){for(let e of this.clients.values())e.connection.notify("hydra-acp/session/attention_updated",{sessionId:this.sessionId,flags:this.listAttentionFlags()}).catch(()=>{})}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let n=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(n).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.disposeIdleHandlers()}onIdle(e,n){let s={fn:e,once:!!n?.once,debounceMs:n?.debounceMs??0};return this.idleHandlers.push(s),()=>{let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1),s.timer&&(clearTimeout(s.timer),s.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let s of this.idleHandlers)s.timer&&(clearTimeout(s.timer),s.timer=void 0);return}let n=[...this.idleHandlers];for(let s of n){if(s.debounceMs===0){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}continue}s.timer&&(clearTimeout(s.timer),s.timer=void 0),s.timer=setTimeout(()=>{if(s.timer=void 0,!this.closed&&this.isQuiescedSync()){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}}},s.debounceMs),typeof s.timer.unref=="function"&&s.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let n=e.update;if(!n||typeof n!="object")return;let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:"";if(r!=="tool_call"&&r!=="tool_call_update")return;let i=typeof s.toolCallId=="string"&&s.toolCallId.length>0?s.toolCallId:void 0;if(!i)return;let o=typeof s.kind=="string"?s.kind:void 0;o&&!this.toolCallKind.has(i)&&this.toolCallKind.set(i,o);let a=o??this.toolCallKind.get(i);if(a==="edit"&&Array.isArray(s.locations))for(let l of s.locations){if(!l||typeof l!="object")continue;let u=l.path;if(typeof u!="string"||u.length===0||this.filesEditedSeen.has(u))continue;this.filesEditedSeen.add(u);let f=l.line,p={path:u,toolCallId:i};typeof f=="number"&&(p.line=f),this.notifyChain("file.edited",p)}if(r!=="tool_call_update")return;let c=typeof s.status=="string"?s.status:void 0;if(c!=="completed"&&c!=="failed"||this.toolCompletionSeen.has(i))return;this.toolCompletionSeen.set(i,c);let d={toolCallId:i,status:c};a&&(d.kind=a),s.content!==void 0&&(d.content=s.content),Array.isArray(s.locations)&&(d.locations=s.locations),this.notifyChain("tool.completed",d)}notifyChain(e,n){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:n}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(typeof n.sessionId=="string"&&n.sessionId!==this.sessionId)return{...n,sessionId:this.sessionId}}return e}recordAndBroadcast(e,n,s){let r=this.rewriteForClient(n),i=!Uh(e,r),o=i?gk(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let c=this.historyStore;c.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,c.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let c of this.broadcastHandlers)try{c(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let n=[...this.clients.values()];if(n.length===0)throw tn(new Error("no clients attached to handle permission request"),z.PermissionDenied);let s=this.rewriteForClient(e),r=jh(s),i=Hs(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,u=[],f=0,p,h=this.sessionId,m=v=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),v())},y=v=>v?.code===z.MethodNotFound;function b(v){if(l)return;let S=v.connection.request("session/request_permission",s);u.push({client:v}),f++,S.then(k=>{f--,m(()=>{let T=yk({toolCallId:r,result:k,resolver:v});for(let O of u)O.client.clientId!==v.clientId&&O.client.connection.notify("session/update",{sessionId:h,update:T}).catch(()=>{});c(k)})}).catch(k=>{if(f--,y(k)||(p=k),f===0&&!l){let T=p??tn(new Error("no client handled permission request"),z.PermissionDenied);m(()=>d(T))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,b);for(let v of n)b(v)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:Hs(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:n,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,n,s){let r=(n??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(n);return new Promise((a,c)=>{let d={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:c},l=this.insertEntryAt(d,o);this.persistRewrite(),this.broadcastQueueAdded(d,{position:l}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let n=e._meta;if(!n||typeof n!="object"||Array.isArray(n))return"tail";let s=n["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,n){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(n==="head")return this.promptQueue.unshift(e),s;if(typeof n=="object"){let r=n.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let n=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Bo(n,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let n=await this.runQueueEntry(e);e.resolve(n),await new Promise(s=>setImmediate(s))}catch(n){e.reject(n)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let n=Ri(e.prompt).replace(/\s+$/,""),s=!n.includes(`
73
+ `)&&n.startsWith("/")?n.split(/\s+/)[0]??"":"",r=s.startsWith("/")?s.slice(1):"",i=r.length>0&&this.aliasableBareVerbs().has(r);if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"||i){let a;if(s==="/sessions")a=await this.handleSessionsCommand();else if(s==="/help")a=await this.handleHelpCommand();else if(s==="/mode")a=await this.handleModeCommand(n);else if(s==="/model")a=await this.handleModelCommand(n);else if(i){let c=n.slice(s.length).trim(),d=c?`/hydra ${r} ${c}`:`/hydra ${r}`;a=await this.handleSlashCommand(d,e.messageId)}else a=await this.handleSlashCommand(n,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let o;try{o=await this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:e.prompt},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0)}catch(a){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}return this.closed||this.broadcastTurnComplete(e.clientId,o,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),o}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};ck=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction"])});import{z as Pi}from"zod";var Sk,Vh,Yh=J(()=>{"use strict";Sk=Pi.object({source:Pi.string(),reason:Pi.string(),raisedAt:Pi.number(),payload:Pi.unknown()}),Vh=Pi.array(Sk)});import{z as Le}from"zod";function Xh(t){let e=t.trim();if(e.length===0)return;let n=Mi(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=Mi(e.slice(i,o+1)))}if(n===void 0){let i=em(e);i!==void 0&&(n=Mi(i))}if(n===void 0||n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,Gh))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=Do.safeParse(s.synopsis);i.success&&kk(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Zh(t){let e=t.trim();if(e.length===0)return;let n=Mi(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=Mi(e.slice(d,l+1)))}if(n===void 0){let d=em(e);d!==void 0&&(n=Mi(d))}if(n===void 0||n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let d=s.title.trim();d.length>0&&(r.title=d.slice(0,Gh))}let i={},o=!1,a=["goal","outcome"];for(let d of a)if(typeof s[d]=="string"){let l=s[d].trim();l.length>0&&(i[d]=l,o=!0)}let c=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let d of c)if(Array.isArray(s[d])){let l=s[d],u=Le.array(Le.string()).safeParse(l);u.success&&l.length>0&&(i[d]=u.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function Mi(t){try{return JSON.parse(t)}catch{return}}function em(t){let e=t.indexOf("{");if(e<0)return;let n=0,s=!1,r=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){r?r=!1:o==="\\"?r=!0:o==='"'&&(s=!1);continue}if(o==='"'){s=!0;continue}if(o==="{")n++;else if(o==="}"&&(n--,n===0))return t.slice(e,i+1)}}function kk(t){return t.goal!==void 0&&t.goal.trim().length>0||t.outcome!==void 0&&t.outcome.trim().length>0||t.files_touched!==void 0&&t.files_touched.length>0||t.tools_used!==void 0&&t.tools_used.length>0||t.rejected_approaches!==void 0&&t.rejected_approaches.length>0||t.open_threads!==void 0&&t.open_threads.length>0||t.decisions!==void 0&&t.decisions.length>0||t.file_edit_intentions!==void 0&&t.file_edit_intentions.length>0||t.unresolved_errors!==void 0&&t.unresolved_errors.length>0||t.tool_state!==void 0&&t.tool_state.length>0}var Qh,Do,Gh,Kl,Jl,ld=J(()=>{"use strict";Qh=Le.object({status:Le.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:Le.number(),iter:Le.number().int().nonnegative().optional(),attempts:Le.number().int().nonnegative().optional(),lastError:Le.string().optional(),worker:Le.object({upstreamSessionId:Le.string(),pid:Le.number().int().nonnegative()}).optional()}),Do=Le.object({goal:Le.string().optional(),outcome:Le.string().optional(),files_touched:Le.array(Le.string()).optional(),tools_used:Le.array(Le.string()).optional(),rejected_approaches:Le.array(Le.string()).optional(),open_threads:Le.array(Le.string()).optional(),decisions:Le.array(Le.string()).optional(),file_edit_intentions:Le.array(Le.string()).optional(),unresolved_errors:Le.array(Le.string()).optional(),tool_state:Le.array(Le.string()).optional()}),Gh=200,Kl=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
74
74
  {
75
75
  "title": "short summary, max 80 chars",
76
76
  "synopsis": {
@@ -80,7 +80,7 @@ ${h}:
80
80
  "open_threads": ["work started but not finished"]
81
81
  }
82
82
  }
83
- Use empty arrays/strings where a field doesn't apply.`;Kl=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
83
+ Use empty arrays/strings where a field doesn't apply.`;Jl=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
84
84
  {
85
85
  "title": "short summary, max 80 chars",
86
86
  "goal": "the user's original ask",
@@ -92,293 +92,293 @@ Use empty arrays/strings where a field doesn't apply.`;Kl=`Reply with ONLY a JSO
92
92
  "unresolved_errors": ["errors left open at session end"],
93
93
  "tool_state": ["runtime state relevant for recall"]
94
94
  }
95
- Use empty arrays/strings where a field doesn't apply.`});import*as Mi from"fs/promises";import*as eM from"path";import{customAlphabet as bk}from"nanoid";import{z as ne}from"zod";function Do(){return`${kk}${Sk()}`}function Ck(t){if(!Jl.test(t))throw new Error(`unsafe session id: ${t}`)}function Xl(t){let e=new Date().toISOString();return{sessionId:t.sessionId,lineageId:t.lineageId,upstreamSessionId:t.upstreamSessionId,importedFromSessionId:t.importedFromSessionId,importedFromUpstreamSessionId:t.importedFromUpstreamSessionId,importedFromMachine:t.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,compactionState:t.compactionState,rollbackBreadcrumb:t.rollbackBreadcrumb,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:t.currentUsage,agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,pendingHistorySync:t.pendingHistorySync,pendingAgentSwap:t.pendingAgentSwap,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forwardedEnv:t.forwardedEnv,attentionFlags:t.attentionFlags??[],createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var vk,Sk,kk,Yl,Vl,Ik,Ql,Gl,xk,Ak,Jl,ud,Zl=J(()=>{"use strict";he();Sr();Jh();ld();vk="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Sk=bk(vk,16),kk="hydra_lineage_";Yl=ne.object({name:ne.string(),description:ne.string().optional()}),Vl=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),Ik=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),Ql=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),Gl=ne.object({name:ne.string(),version:ne.string().optional()}),xk=ne.object({previousUpstreamSessionId:ne.string(),previousSummarizedThroughEntry:ne.number().int().nonnegative().optional()}),Ak=ne.object({version:ne.literal(1),sessionId:ne.string(),lineageId:ne.string().optional(),upstreamSessionId:ne.string(),importedFromSessionId:ne.string().optional(),importedFromUpstreamSessionId:ne.string().optional(),importedFromMachine:ne.string().optional(),agentId:ne.string(),cwd:ne.string(),title:ne.string().optional(),synopsis:No.optional(),compactionState:Yh.optional(),rollbackBreadcrumb:xk.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:Ql.optional(),agentCommands:ne.array(Yl).optional(),agentModes:ne.array(Vl).optional(),agentModels:ne.array(Ik).optional(),pendingHistorySync:ne.boolean().optional(),pendingAgentSwap:ne.string().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),forkSynthesisState:ne.enum(["running","failed"]).optional(),originatingClient:Gl.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),forwardedEnv:ne.record(ne.string(),ne.string()).optional(),attentionFlags:Kh.default([]).optional(),createdAt:ne.string(),updatedAt:ne.string()}),Jl=/^[A-Za-z0-9_-]+$/;ud=class{async write(e){Ck(e.sessionId);let n={version:1,...e};await Xt(_.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!Jl.test(e))return;let n=await yn(_.sessionFile(e));if(n!==void 0)try{return Ak.parse(n)}catch{return}}async delete(e){if(Jl.test(e)){try{await Mi.unlink(_.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await Mi.rmdir(_.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}}}async findByLineageId(e){if(e.length===0)return;let n=await this.list().catch(()=>[]);for(let s of n)if(s.lineageId===e)return s}async list(){let e;try{e=await Mi.readdir(_.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let n=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of n)r&&s.push(r);return s}}});import{fileURLToPath as Tk}from"url";import*as Ho from"path";import*as pd from"fs";function Ek(){try{let t=Ho.dirname(Tk(import.meta.url));for(let e=0;e<8;e+=1){let n=Ho.join(t,"package.json");if(pd.existsSync(n)){let r=JSON.parse(pd.readFileSync(n,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=Ho.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var fe,Er,nn=J(()=>{"use strict";fe=Ek(),Er="hydra-acp-cat"});function eu(t){let e=new Map;for(let n of dm(t).values())e.set(n.toolName,(e.get(n.toolName)??0)+1);return[...e.entries()].map(([n,s])=>({name:n,count:s})).sort((n,s)=>s.count-n.count||n.name.localeCompare(s.name))}function im(t){return eu(t).map(e=>e.name)}function tu(t){let e=new Map;for(let n of dm(t).values())for(let s of n.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(n.toolName,(r.get(n.toolName)??0)+1)}return[...e.entries()].map(([n,s])=>{let r=[...s.entries()].map(([o,a])=>({name:o,count:a})).sort((o,a)=>a.count-o.count||o.name.localeCompare(a.name)),i=r.reduce((o,a)=>o+a.count,0);return{path:n,count:i,byTool:r}}).sort((n,s)=>s.count-n.count||n.path.localeCompare(s.path))}function om(t){return tu(t).map(e=>e.path)}function am(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function dm(t){let e=new Map,n=0;for(let s of t){let i=s.params?.update;if(!i)continue;let o=i.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;if(o==="tool_call"){let c=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${n++}`,d=e.get(c);d===void 0?(d={toolName:sm(i),paths:new Set},e.set(c,d)):d.toolName=sm(i);for(let l of rm(i.rawInput,i.locations))d.paths.add(l);continue}if(typeof i.toolCallId!="string"||i.toolCallId.length===0)continue;let a=e.get(i.toolCallId);if(a!==void 0)for(let c of rm(i.rawInput,i.locations))a.paths.add(c)}return e}function sm(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function rm(t,e){let n=new Set;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t;typeof s.file_path=="string"?n.add(s.file_path):typeof s.path=="string"&&n.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let i of r)if(i&&typeof i=="object"){let o=i.file_path;typeof o=="string"&&n.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&n.add(r)}}return n}var nu=J(()=>{"use strict"});import{promises as jo}from"fs";import*as du from"path";async function qo(t){let e;try{e=await jo.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return Dk(e)}function Dk(t){let e=[];for(let n of t.split(`
96
- `))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function Wo(t,e,n=bm){let s=e.replace(/\n+$/,"");if(s.length===0||t.length>0&&t[t.length-1]===s)return t;let r=t.concat(s);return r.length>n?r.slice(r.length-n):r}async function Pr(t,e){await jo.mkdir(du.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await jo.writeFile(t,n.length>0?n.join(`
95
+ Use empty arrays/strings where a field doesn't apply.`});import*as _i from"fs/promises";import*as oM from"path";import{customAlphabet as Ik}from"nanoid";import{z as ne}from"zod";function Ho(){return`${Ck}${Ak()}`}function Pk(t){if(!Vl.test(t))throw new Error(`unsafe session id: ${t}`)}function Zl(t){let e=new Date().toISOString();return{sessionId:t.sessionId,lineageId:t.lineageId,upstreamSessionId:t.upstreamSessionId,importedFromSessionId:t.importedFromSessionId,importedFromUpstreamSessionId:t.importedFromUpstreamSessionId,importedFromMachine:t.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,compactionState:t.compactionState,rollbackBreadcrumb:t.rollbackBreadcrumb,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:t.currentUsage,agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,pendingHistorySync:t.pendingHistorySync,pendingAgentSwap:t.pendingAgentSwap,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forwardedEnv:t.forwardedEnv,attentionFlags:t.attentionFlags??[],createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var xk,Ak,Ck,Yl,Ql,Rk,Gl,Xl,Tk,Ek,Vl,ud,eu=J(()=>{"use strict";he();Sr();Yh();ld();xk="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ak=Ik(xk,16),Ck="hydra_lineage_";Yl=ne.object({name:ne.string(),description:ne.string().optional()}),Ql=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),Rk=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),Gl=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),Xl=ne.object({name:ne.string(),version:ne.string().optional()}),Tk=ne.object({previousUpstreamSessionId:ne.string(),previousSummarizedThroughEntry:ne.number().int().nonnegative().optional()}),Ek=ne.object({version:ne.literal(1),sessionId:ne.string(),lineageId:ne.string().optional(),upstreamSessionId:ne.string(),importedFromSessionId:ne.string().optional(),importedFromUpstreamSessionId:ne.string().optional(),importedFromMachine:ne.string().optional(),agentId:ne.string(),cwd:ne.string(),title:ne.string().optional(),synopsis:Do.optional(),compactionState:Qh.optional(),rollbackBreadcrumb:Tk.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:Gl.optional(),agentCommands:ne.array(Yl).optional(),agentModes:ne.array(Ql).optional(),agentModels:ne.array(Rk).optional(),pendingHistorySync:ne.boolean().optional(),pendingAgentSwap:ne.string().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),forkSynthesisState:ne.enum(["running","failed"]).optional(),originatingClient:Xl.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),forwardedEnv:ne.record(ne.string(),ne.string()).optional(),attentionFlags:Vh.default([]).optional(),createdAt:ne.string(),updatedAt:ne.string()}),Vl=/^[A-Za-z0-9_-]+$/;ud=class{async write(e){Pk(e.sessionId);let n={version:1,...e};await Xt(_.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!Vl.test(e))return;let n=await yn(_.sessionFile(e));if(n!==void 0)try{return Ek.parse(n)}catch{return}}async delete(e){if(Vl.test(e)){try{await _i.unlink(_.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await _i.rmdir(_.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}}}async findByLineageId(e){if(e.length===0)return;let n=await this.list().catch(()=>[]);for(let s of n)if(s.lineageId===e)return s}async list(){let e;try{e=await _i.readdir(_.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let n=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of n)r&&s.push(r);return s}}});import{fileURLToPath as _k}from"url";import*as Uo from"path";import*as pd from"fs";function $k(){try{let t=Uo.dirname(_k(import.meta.url));for(let e=0;e<8;e+=1){let n=Uo.join(t,"package.json");if(pd.existsSync(n)){let r=JSON.parse(pd.readFileSync(n,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=Uo.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var fe,Er,nn=J(()=>{"use strict";fe=$k(),Er="hydra-acp-cat"});function tu(t){let e=new Map;for(let n of lm(t).values())e.set(n.toolName,(e.get(n.toolName)??0)+1);return[...e.entries()].map(([n,s])=>({name:n,count:s})).sort((n,s)=>s.count-n.count||n.name.localeCompare(s.name))}function am(t){return tu(t).map(e=>e.name)}function nu(t){let e=new Map;for(let n of lm(t).values())for(let s of n.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(n.toolName,(r.get(n.toolName)??0)+1)}return[...e.entries()].map(([n,s])=>{let r=[...s.entries()].map(([o,a])=>({name:o,count:a})).sort((o,a)=>a.count-o.count||o.name.localeCompare(a.name)),i=r.reduce((o,a)=>o+a.count,0);return{path:n,count:i,byTool:r}}).sort((n,s)=>s.count-n.count||n.path.localeCompare(s.path))}function dm(t){return nu(t).map(e=>e.path)}function cm(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function lm(t){let e=new Map,n=0;for(let s of t){let i=s.params?.update;if(!i)continue;let o=i.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;if(o==="tool_call"){let c=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${n++}`,d=e.get(c);d===void 0?(d={toolName:im(i),paths:new Set},e.set(c,d)):d.toolName=im(i);for(let l of om(i.rawInput,i.locations))d.paths.add(l);continue}if(typeof i.toolCallId!="string"||i.toolCallId.length===0)continue;let a=e.get(i.toolCallId);if(a!==void 0)for(let c of om(i.rawInput,i.locations))a.paths.add(c)}return e}function im(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function om(t,e){let n=new Set;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t;typeof s.file_path=="string"?n.add(s.file_path):typeof s.path=="string"&&n.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let i of r)if(i&&typeof i=="object"){let o=i.file_path;typeof o=="string"&&n.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&n.add(r)}}return n}var su=J(()=>{"use strict"});import{promises as qo}from"fs";import*as cu from"path";async function Wo(t){let e;try{e=await qo.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return qk(e)}function qk(t){let e=[];for(let n of t.split(`
96
+ `))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function zo(t,e,n=Sm){let s=e.replace(/\n+$/,"");if(s.length===0||t.length>0&&t[t.length-1]===s)return t;let r=t.concat(s);return r.length>n?r.slice(r.length-n):r}async function Pr(t,e){await qo.mkdir(cu.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await qo.writeFile(t,n.length>0?n.join(`
97
97
  `)+`
98
- `:"")}async function vm(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await jo.mkdir(du.dirname(t),{recursive:!0}),await jo.appendFile(t,JSON.stringify(n)+`
99
- `,{encoding:"utf8"}))}function yd(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function cu(t,e,n=bm){if(e.length===0)return t;let s=new Set(t),r=t;for(let i of e){let o=i.replace(/\n+$/,"");o.length!==0&&(s.has(o)||(s.add(o),r=Wo(r,o,n)))}return r}var bm,wd=J(()=>{"use strict";bm=500});import{z as Me}from"zod";function zo(t){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:t.hydraVersion,machine:t.machine,...t.hydraHost!==void 0&&t.hydraHost.length>0?{hydraHost:t.hydraHost}:{}},session:{sessionId:t.record.sessionId,lineageId:t.record.lineageId,...t.record.upstreamSessionId?{upstreamSessionId:t.record.upstreamSessionId}:{},agentId:t.record.agentId,cwd:t.record.cwd,...t.record.title!==void 0?{title:t.record.title}:{},...t.record.synopsis!==void 0?{synopsis:t.record.synopsis}:{},...t.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:t.record.summarizedThroughEntry}:{},...t.record.currentModel!==void 0?{currentModel:t.record.currentModel}:{},...t.record.currentMode!==void 0?{currentMode:t.record.currentMode}:{},...t.record.currentUsage!==void 0?{currentUsage:t.record.currentUsage}:{},...t.record.agentCommands!==void 0?{agentCommands:t.record.agentCommands}:{},...t.record.agentModes!==void 0?{agentModes:t.record.agentModes}:{},...t.record.interactive!==void 0?{interactive:t.record.interactive}:{},...t.record.originatingClient!==void 0?{originatingClient:t.record.originatingClient}:{},...t.record.priority!==void 0&&t.record.priority>0?{priority:t.record.priority}:{},createdAt:t.record.createdAt,updatedAt:t.record.updatedAt},history:t.history};return t.promptHistory!==void 0&&(e.promptHistory=t.promptHistory),t.toolBlobs!==void 0&&Object.keys(t.toolBlobs).length>0&&(e.toolBlobs=t.toolBlobs),e}function _n(t){return jk.parse(t)}var Hk,Uk,jk,Mr=J(()=>{"use strict";Zl();ld();Hk=Me.object({method:Me.string(),params:Me.unknown(),recordedAt:Me.number()}),Uk=Me.object({sessionId:Me.string(),lineageId:Me.string(),upstreamSessionId:Me.string().optional(),agentId:Me.string(),cwd:Me.string(),title:Me.string().optional(),synopsis:No.optional(),summarizedThroughEntry:Me.number().int().nonnegative().optional(),currentModel:Me.string().optional(),currentMode:Me.string().optional(),currentUsage:Ql.optional(),agentCommands:Me.array(Yl).optional(),agentModes:Me.array(Vl).optional(),interactive:Me.boolean().optional(),originatingClient:Gl.optional(),priority:Me.number().int().nonnegative().optional(),createdAt:Me.string(),updatedAt:Me.string()}),jk=Me.object({version:Me.literal(1),exportedAt:Me.string(),exportedFrom:Me.object({hydraVersion:Me.string(),machine:Me.string(),hydraHost:Me.string().optional()}),session:Uk,history:Me.array(Hk),promptHistory:Me.array(Me.string()).optional(),toolBlobs:Me.record(Me.string()).optional()})});import{createHash as nI}from"crypto";function bu(t){if(Array.isArray(t))return t.map(bu);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=bu(t[n]);return e}return t}function qs(t){let{tui:e,...n}=t,s=JSON.stringify(bu(n));return nI("sha256").update(s).digest("hex").slice(0,16)}var Xo=J(()=>{"use strict";Ve()});function vu(t){return Math.floor(t/4)}function Dm(t){if(t.compactionInFlight||t.totalEntries===0)return!1;let e;if(typeof t.agentReportedUsed=="number"&&typeof t.agentReportedSize=="number"&&t.agentReportedSize>0)e=t.agentReportedUsed/t.agentReportedSize;else{let s=vu(t.unsummarizedChars),r=t.currentModel!==void 0?t.config.modelContextWindows[t.currentModel]??t.config.absoluteFallback:t.config.absoluteFallback;e=s/r}if(e>=t.config.hardCeilingFraction)return!0;let n=t.nowMs-t.lastActivityMs;return e>=t.config.contextFraction&&n>=t.config.idleBeforePromptMs}function Hm(t){return t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}var Su=J(()=>{"use strict"});function Zo(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Um=J(()=>{"use strict"});import{posix as hI}from"path";import mI from"strip-ansi";function lt(t){return mI(t).replace(gI,"")}function Ee(t){return lt(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Kn(t,e={}){if(!t||typeof t!="object")return null;let n=t,s=n.sessionUpdate??n.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return kI(n);case"agent_thought_chunk":case"agent_thought":return II(n);case"user_message_chunk":return xI(n);case"prompt_received":return AI(n);case"tool_call":return CI(n,e);case"tool_call_update":return MI(n,e);case"plan":return FI(n);case"current_mode_update":return OI(n);case"current_model_update":return LI(n);case"turn_complete":return BI(n);case"usage_update":return SI(n);case"available_commands_update":return bI(n);case"available_modes_update":return vI(n);case"session_info_update":return wI(n);case"config_option_update":return yI(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function yI(t){let e=t.configOptions;if(!Array.isArray(e))return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}n.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:n}}function wI(t){let e=tt(t,"title"),n=e!==void 0?Ee(e):void 0,s=t._meta,r,i;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a.agentId;if(typeof c=="string"&&(r=c),"pendingAgentSwap"in a){let d=a.pendingAgentSwap;typeof d=="string"?i=d:d===null&&(i=null)}}}if(n===void 0&&r===void 0&&i===void 0)return null;let o={kind:"session-info"};return n!==void 0&&(o.title=n),r!==void 0&&(o.agentId=r),i!==void 0&&(o.pendingAgentSwap=i),o}function Fd(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:Ee(r)};typeof s.description=="string"&&(i.description=Ee(s.description)),e.push(i)}return e}function bI(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:Fd(e)}:null}function vI(t){let e=t.availableModes;if(!Array.isArray(e))return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:Ee(r.id)};typeof r.name=="string"&&(i.name=Ee(r.name)),typeof r.description=="string"&&(i.description=Ee(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function SI(t){let e={kind:"usage-update"};if(typeof t.used=="number"&&(e.used=t.used),typeof t.size=="number"&&(e.size=t.size),t.cost&&typeof t.cost=="object"){let n=t.cost;typeof n.amount=="number"&&(e.costAmount=n.amount),typeof n.currency=="string"&&(e.costCurrency=n.currency)}return e}function kI(t){let e=ea(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Zo(t)}}function II(t){let e=typeof t.text=="string"?lt(t.text):ea(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Zo(t)}}function xI(t){let e=t._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let n=ea(t.content);return n===null?null:{kind:"user-text",text:n}}function AI(t){let e=NI(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Wm(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function jm(t){if(typeof t=="string")return{text:t};if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function Od(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=jm(r.oldText),o=jm(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function zm(t){let e=t.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e.plan;return typeof n!="string"||n.length===0?null:lt(n)}function CI(t,e={}){let n=tt(t,"toolCallId")??tt(t,"id");if(!n)return null;let s=tt(t,"title")??tt(t,"name")??tt(t,"label")??"tool call",r=tt(t,"name")??tt(t,"title");if(Wm(r)){let h=zm(t);if(h!==null){let m=tt(t,"status"),y={kind:"exit-plan-mode",toolCallId:n,plan:h};return m!==void 0&&(y.status=m),y}}let i=Ym(Ee(s),t,e),o=tt(t,"status"),a=tt(t,"kind"),c={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=Od(t);d!==null&&(c.editDiff=d);let l=Jm(t);l!==void 0&&(c.detail=l);let u=ku(t);u!==void 0&&(c.detailFull=u);let f=Km(t);f!==void 0&&(c.locations=f);let p=Zo(t);return p!==void 0&&(c.workerTaskId=p),c}function Km(t){let e=t.locations;if(!Array.isArray(e))return;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),n.push(i)}return n.length>0?n:void 0}function Jm(t){let e=ku(t);if(e===void 0)return;let n=Ee(e),s=t.rawInput;return s&&typeof s.command=="string"?EI(n,qm):PI(n,qm)}function ku(t){let e=t.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(typeof n.command=="string"&&n.command.trim().length>0)return lt(n.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof n.file_path=="string"?n.file_path:typeof n.filePath=="string"?n.filePath:typeof n.path=="string"?n.path:void 0;if(s!==void 0&&s.length>0)return Ze(Ee(s))}if(Array.isArray(t.locations)){for(let n of t.locations)if(n&&typeof n=="object"){let s=n.path;if(typeof s=="string"&&s.length>0)return Ze(Ee(s))}}}function TI(t){for(let e of RI)if(t.startsWith(e))return!0;return!1}function Ym(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return Ze(t);if(t.startsWith("~")||!t.includes("/")||/\s/.test(t))return t;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${t}`||o.endsWith(`/${t}`)||o===t))return Ze(o)}return TI(t)?Ze(`/${t}`):n.cwd&&n.cwd.length>0?Ze(hI.resolve(n.cwd,t)):t}function EI(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function PI(t,e){if(t.length<=e)return t;let n=t.slice(-(e-1)),s=n.indexOf("/");return s>=0&&s<e/2?`\u2026${n.slice(s)}`:`\u2026${n}`}function MI(t,e={}){let n=tt(t,"toolCallId")??tt(t,"id");if(!n)return null;let s=tt(t,"title"),r=s!==void 0?Ym(Ee(s),t,e):void 0,i=tt(t,"status"),o=Od(t),a=Jm(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=tt(t,"name")??s;if(Wm(d)){let h={kind:"exit-plan-mode",toolCallId:n},m=zm(t);return m!==null&&(h.plan=m),i!==void 0&&(h.status=i),h}let l={kind:"tool-call-update",toolCallId:n};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let u=ku(t);u!==void 0&&(l.detailFull=u);let f=Km(t);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=_I(t);h!==null&&(l.errorText=h),$I(t,h)&&(l.upstreamInterrupted=!0)}let p=Zo(t);return p!==void 0&&(l.workerTaskId=p),l}function _I(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=ea(s.content);if(i!==null&&i.length>0)return i}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"&&s.length>0)return lt(s)}return null}function $I(t,e){let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function FI(t){let e=t.entries;if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?Ee(r.content):void 0;if(!i)continue;let o={content:i};typeof r.status=="string"&&(o.status=r.status),typeof r.priority=="string"&&(o.priority=r.priority),n.push(o)}return{kind:"plan",entries:n}}function OI(t){let e=tt(t,"currentModeId")??tt(t,"currentMode")??tt(t,"mode");return e?{kind:"mode-changed",mode:Ee(e)}:null}function LI(t){let e=tt(t,"currentModel")??tt(t,"model");if(!e)return null;let n=t.availableModels,s=Array.isArray(n)?n.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:Ee(e),...s&&s.length>0?{availableModels:s}:{}}}function BI(t){let e=tt(t,"stopReason"),n=t._meta,s=n?.["hydra-acp"]?.amended!==void 0&&n["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function ea(t){if(typeof t=="string")return lt(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?lt(e.text):null}function NI(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=ea(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function tt(t,e){let n=t[e];return typeof n=="string"?n:void 0}var gI,qm,RI,Ws=J(()=>{"use strict";he();Um();gI=/[\x00-\x08\x0b-\x1f\x7f]/g;qm=64;RI=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function Oi(t){let e=new Map,n=new Map;for(let r of t){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let c=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,d=HI(o);if(d.length===0)continue;let l=d;if(c!==void 0){let u=e.get(c)??[],f=[];for(let p of d)u.some(h=>h.path===p.path&&h.oldText===p.oldText&&h.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(c,[...u,...f]),l=f}for(let u of l)DI(n,u)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function Li(t){let e=[];for(let n of t){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===n.oldText){s=i;break}if(s===-1){e.push(n);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:n.newText})}return e}function DI(t,e){let n={oldText:e.oldText,newText:e.newText},s=t.get(e.path);if(s===void 0){t.set(e.path,{hunks:[n],created:e.oldText.length===0});return}s.hunks.push(n)}function HI(t){let e=[],n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let c of a){if(!c||typeof c!="object")continue;let d=c,l=typeof d.old_string=="string"?d.old_string:void 0,u=typeof d.new_string=="string"?d.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=t.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let c=typeof o.oldText=="string"?o.oldText:"",d=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:c,newText:d})}if(e.length>0)return e}let r=Od(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var Ld=J(()=>{"use strict";Ws()});function Jn(t){let e=[],n=[],s=!1,r=i=>{if(!s){s=!0;for(let o of n)o(i)}};return t.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let c=JSON.parse(a);for(let d of e)d(c)}catch(c){for(let d of e)d({jsonrpc:"2.0",id:null,error:{code:z.ParseError,message:`Failed to parse WS frame: ${c.message}`}})}}),t.on("close",()=>r()),t.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,c)=>{t.send(o,d=>{if(d){c(d);return}a()})})},onMessage(i){e.push(i)},onClose(i){n.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(c),i())},c=setTimeout(a,5e3);t.once("close",a);try{t.close()}catch{a()}}),r())}}}var Di=J(()=>{"use strict";Et()});import{spawn as iA}from"child_process";import{setTimeout as oA}from"timers/promises";async function $g(){let t=await hs();if(t&&Mn(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function aA(t){let e=await Fr(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===qs(t)?"match":"mismatch":"missing"}async function Js(t){let e=await aA(t);if(e!=="match"){if(e==="mismatch"){let n=Dn();throw new Error(`config changed since daemon started \u2014 run \`${n} daemon restart\` to apply.`)}process.stderr.write(`hydra-acp: daemon not running; starting it...
100
- `),Yd(),await Vd(t)}}async function Jd(t){let e=await $g();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Fr(t,e=1e3){let n=await $g();if(n)try{let s=await fetch(n,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}});if(!s.ok)return;let r=await s.json();return{version:typeof r.version=="string"?r.version:void 0,configDigest:typeof r.configDigest=="string"?r.configDigest:void 0}}catch{return}}function Yd(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");iA(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function Vd(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await Jd(t))return;await oA(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Or=J(()=>{"use strict";Po();Xo();mi()});import*as Fg from"fs";import*as ji from"fs/promises";async function qi(t,e,n){let s=cA(e),r;try{r=await ji.stat(t)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${n} (${t})
101
- `),process.exit(1);return}throw c}let i=await dA(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
102
- `);let o=!1,a=Fg.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await ji.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await ji.open(t,"r");try{let l=Buffer.alloc(c.size-i);await d.read(l,0,l.length,i),process.stdout.write(l),i=c.size}finally{await d.close()}}catch{}}))});await new Promise(c=>{let d=()=>{a.close(),c()};process.once("SIGINT",d),process.once("SIGTERM",d)})}async function dA(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await ji.open(t,"r");try{let i=e,o="",a=0;for(;i>0&&a<=n;){let l=Math.min(s,i);i-=l;let u=Buffer.alloc(l);await r.read(u,0,l,i),o=u.toString("utf8")+o,a=(o.match(/\n/g)??[]).length}let d=o.split(`
98
+ `:"")}async function km(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await qo.mkdir(cu.dirname(t),{recursive:!0}),await qo.appendFile(t,JSON.stringify(n)+`
99
+ `,{encoding:"utf8"}))}function yd(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function lu(t,e,n=Sm){if(e.length===0)return t;let s=new Set(t),r=t;for(let i of e){let o=i.replace(/\n+$/,"");o.length!==0&&(s.has(o)||(s.add(o),r=zo(r,o,n)))}return r}var Sm,wd=J(()=>{"use strict";Sm=500});import{z as Me}from"zod";function Ko(t){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:t.hydraVersion,machine:t.machine,...t.hydraHost!==void 0&&t.hydraHost.length>0?{hydraHost:t.hydraHost}:{}},session:{sessionId:t.record.sessionId,lineageId:t.record.lineageId,...t.record.upstreamSessionId?{upstreamSessionId:t.record.upstreamSessionId}:{},agentId:t.record.agentId,cwd:t.record.cwd,...t.record.title!==void 0?{title:t.record.title}:{},...t.record.synopsis!==void 0?{synopsis:t.record.synopsis}:{},...t.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:t.record.summarizedThroughEntry}:{},...t.record.currentModel!==void 0?{currentModel:t.record.currentModel}:{},...t.record.currentMode!==void 0?{currentMode:t.record.currentMode}:{},...t.record.currentUsage!==void 0?{currentUsage:t.record.currentUsage}:{},...t.record.agentCommands!==void 0?{agentCommands:t.record.agentCommands}:{},...t.record.agentModes!==void 0?{agentModes:t.record.agentModes}:{},...t.record.interactive!==void 0?{interactive:t.record.interactive}:{},...t.record.originatingClient!==void 0?{originatingClient:t.record.originatingClient}:{},...t.record.priority!==void 0&&t.record.priority>0?{priority:t.record.priority}:{},createdAt:t.record.createdAt,updatedAt:t.record.updatedAt},history:t.history};return t.promptHistory!==void 0&&(e.promptHistory=t.promptHistory),t.toolBlobs!==void 0&&Object.keys(t.toolBlobs).length>0&&(e.toolBlobs=t.toolBlobs),e}function _n(t){return Kk.parse(t)}var Wk,zk,Kk,Mr=J(()=>{"use strict";eu();ld();Wk=Me.object({method:Me.string(),params:Me.unknown(),recordedAt:Me.number()}),zk=Me.object({sessionId:Me.string(),lineageId:Me.string(),upstreamSessionId:Me.string().optional(),agentId:Me.string(),cwd:Me.string(),title:Me.string().optional(),synopsis:Do.optional(),summarizedThroughEntry:Me.number().int().nonnegative().optional(),currentModel:Me.string().optional(),currentMode:Me.string().optional(),currentUsage:Gl.optional(),agentCommands:Me.array(Yl).optional(),agentModes:Me.array(Ql).optional(),interactive:Me.boolean().optional(),originatingClient:Xl.optional(),priority:Me.number().int().nonnegative().optional(),createdAt:Me.string(),updatedAt:Me.string()}),Kk=Me.object({version:Me.literal(1),exportedAt:Me.string(),exportedFrom:Me.object({hydraVersion:Me.string(),machine:Me.string(),hydraHost:Me.string().optional()}),session:zk,history:Me.array(Wk),promptHistory:Me.array(Me.string()).optional(),toolBlobs:Me.record(Me.string()).optional()})});import{createHash as oI}from"crypto";function vu(t){if(Array.isArray(t))return t.map(vu);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=vu(t[n]);return e}return t}function qs(t){let{tui:e,...n}=t,s=JSON.stringify(vu(n));return oI("sha256").update(s).digest("hex").slice(0,16)}var Zo=J(()=>{"use strict";Ge()});function Su(t){return Math.floor(t/4)}function Um(t){if(t.compactionInFlight||t.totalEntries===0)return!1;let e;if(typeof t.agentReportedUsed=="number"&&typeof t.agentReportedSize=="number"&&t.agentReportedSize>0)e=t.agentReportedUsed/t.agentReportedSize;else{let s=Su(t.unsummarizedChars),r=t.currentModel!==void 0?t.config.modelContextWindows[t.currentModel]??t.config.absoluteFallback:t.config.absoluteFallback;e=s/r}if(e>=t.config.hardCeilingFraction)return!0;let n=t.nowMs-t.lastActivityMs;return e>=t.config.contextFraction&&n>=t.config.idleBeforePromptMs}function jm(t){return t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}var ku=J(()=>{"use strict"});function ea(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var qm=J(()=>{"use strict"});import{posix as wI}from"path";import bI from"strip-ansi";function lt(t){return bI(t).replace(vI,"")}function Ee(t){return lt(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Kn(t,e={}){if(!t||typeof t!="object")return null;let n=t,s=n.sessionUpdate??n.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return CI(n);case"agent_thought_chunk":case"agent_thought":return RI(n);case"user_message_chunk":return TI(n);case"prompt_received":return EI(n);case"tool_call":return PI(n,e);case"tool_call_update":return FI(n,e);case"plan":return NI(n);case"current_mode_update":return DI(n);case"current_model_update":return HI(n);case"turn_complete":return UI(n);case"usage_update":return AI(n);case"available_commands_update":return II(n);case"available_modes_update":return xI(n);case"session_info_update":return kI(n);case"config_option_update":return SI(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function SI(t){let e=t.configOptions;if(!Array.isArray(e))return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}n.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:n}}function kI(t){let e=tt(t,"title"),n=e!==void 0?Ee(e):void 0,s=t._meta,r,i;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a.agentId;if(typeof c=="string"&&(r=c),"pendingAgentSwap"in a){let d=a.pendingAgentSwap;typeof d=="string"?i=d:d===null&&(i=null)}}}if(n===void 0&&r===void 0&&i===void 0)return null;let o={kind:"session-info"};return n!==void 0&&(o.title=n),r!==void 0&&(o.agentId=r),i!==void 0&&(o.pendingAgentSwap=i),o}function Od(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:Ee(r)};typeof s.description=="string"&&(i.description=Ee(s.description)),e.push(i)}return e}function II(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:Od(e)}:null}function xI(t){let e=t.availableModes;if(!Array.isArray(e))return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:Ee(r.id)};typeof r.name=="string"&&(i.name=Ee(r.name)),typeof r.description=="string"&&(i.description=Ee(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function AI(t){let e={kind:"usage-update"};if(typeof t.used=="number"&&(e.used=t.used),typeof t.size=="number"&&(e.size=t.size),t.cost&&typeof t.cost=="object"){let n=t.cost;typeof n.amount=="number"&&(e.costAmount=n.amount),typeof n.currency=="string"&&(e.costCurrency=n.currency)}return e}function CI(t){let e=ta(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:ea(t)}}function RI(t){let e=typeof t.text=="string"?lt(t.text):ta(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:ea(t)}}function TI(t){let e=t._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let n=ta(t.content);return n===null?null:{kind:"user-text",text:n}}function EI(t){let e=jI(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Km(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Wm(t){if(typeof t=="string")return{text:t};if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function Fd(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=Wm(r.oldText),o=Wm(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Jm(t){let e=t.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e.plan;return typeof n!="string"||n.length===0?null:lt(n)}function PI(t,e={}){let n=tt(t,"toolCallId")??tt(t,"id");if(!n)return null;let s=tt(t,"title")??tt(t,"name")??tt(t,"label")??"tool call",r=tt(t,"name")??tt(t,"title");if(Km(r)){let h=Jm(t);if(h!==null){let m=tt(t,"status"),y={kind:"exit-plan-mode",toolCallId:n,plan:h};return m!==void 0&&(y.status=m),y}}let i=Qm(Ee(s),t,e),o=tt(t,"status"),a=tt(t,"kind"),c={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=Fd(t);d!==null&&(c.editDiff=d);let l=Ym(t);l!==void 0&&(c.detail=l);let u=Iu(t);u!==void 0&&(c.detailFull=u);let f=Vm(t);f!==void 0&&(c.locations=f);let p=ea(t);return p!==void 0&&(c.workerTaskId=p),c}function Vm(t){let e=t.locations;if(!Array.isArray(e))return;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),n.push(i)}return n.length>0?n:void 0}function Ym(t){let e=Iu(t);if(e===void 0)return;let n=Ee(e),s=t.rawInput;return s&&typeof s.command=="string"?$I(n,zm):OI(n,zm)}function Iu(t){let e=t.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(typeof n.command=="string"&&n.command.trim().length>0)return lt(n.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof n.file_path=="string"?n.file_path:typeof n.filePath=="string"?n.filePath:typeof n.path=="string"?n.path:void 0;if(s!==void 0&&s.length>0)return Ze(Ee(s))}if(Array.isArray(t.locations)){for(let n of t.locations)if(n&&typeof n=="object"){let s=n.path;if(typeof s=="string"&&s.length>0)return Ze(Ee(s))}}}function _I(t){for(let e of MI)if(t.startsWith(e))return!0;return!1}function Qm(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return Ze(t);if(t.startsWith("~")||!t.includes("/")||/\s/.test(t))return t;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${t}`||o.endsWith(`/${t}`)||o===t))return Ze(o)}return _I(t)?Ze(`/${t}`):n.cwd&&n.cwd.length>0?Ze(wI.resolve(n.cwd,t)):t}function $I(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function OI(t,e){if(t.length<=e)return t;let n=t.slice(-(e-1)),s=n.indexOf("/");return s>=0&&s<e/2?`\u2026${n.slice(s)}`:`\u2026${n}`}function FI(t,e={}){let n=tt(t,"toolCallId")??tt(t,"id");if(!n)return null;let s=tt(t,"title"),r=s!==void 0?Qm(Ee(s),t,e):void 0,i=tt(t,"status"),o=Fd(t),a=Ym(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=tt(t,"name")??s;if(Km(d)){let h={kind:"exit-plan-mode",toolCallId:n},m=Jm(t);return m!==null&&(h.plan=m),i!==void 0&&(h.status=i),h}let l={kind:"tool-call-update",toolCallId:n};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let u=Iu(t);u!==void 0&&(l.detailFull=u);let f=Vm(t);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=LI(t);h!==null&&(l.errorText=h),BI(t,h)&&(l.upstreamInterrupted=!0)}let p=ea(t);return p!==void 0&&(l.workerTaskId=p),l}function LI(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=ta(s.content);if(i!==null&&i.length>0)return i}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"&&s.length>0)return lt(s)}return null}function BI(t,e){let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function NI(t){let e=t.entries;if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?Ee(r.content):void 0;if(!i)continue;let o={content:i};typeof r.status=="string"&&(o.status=r.status),typeof r.priority=="string"&&(o.priority=r.priority),n.push(o)}return{kind:"plan",entries:n}}function DI(t){let e=tt(t,"currentModeId")??tt(t,"currentMode")??tt(t,"mode");return e?{kind:"mode-changed",mode:Ee(e)}:null}function HI(t){let e=tt(t,"currentModel")??tt(t,"model");if(!e)return null;let n=t.availableModels,s=Array.isArray(n)?n.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:Ee(e),...s&&s.length>0?{availableModels:s}:{}}}function UI(t){let e=tt(t,"stopReason"),n=t._meta,s=n?.["hydra-acp"]?.amended!==void 0&&n["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function ta(t){if(typeof t=="string")return lt(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?lt(e.text):null}function jI(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=ta(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function tt(t,e){let n=t[e];return typeof n=="string"?n:void 0}var vI,zm,MI,Ws=J(()=>{"use strict";he();qm();vI=/[\x00-\x08\x0b-\x1f\x7f]/g;zm=64;MI=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function Li(t){let e=new Map,n=new Map;for(let r of t){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let c=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,d=WI(o);if(d.length===0)continue;let l=d;if(c!==void 0){let u=e.get(c)??[],f=[];for(let p of d)u.some(h=>h.path===p.path&&h.oldText===p.oldText&&h.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(c,[...u,...f]),l=f}for(let u of l)qI(n,u)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function Bi(t){let e=[];for(let n of t){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===n.oldText){s=i;break}if(s===-1){e.push(n);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:n.newText})}return e}function qI(t,e){let n={oldText:e.oldText,newText:e.newText},s=t.get(e.path);if(s===void 0){t.set(e.path,{hunks:[n],created:e.oldText.length===0});return}s.hunks.push(n)}function WI(t){let e=[],n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let c of a){if(!c||typeof c!="object")continue;let d=c,l=typeof d.old_string=="string"?d.old_string:void 0,u=typeof d.new_string=="string"?d.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=t.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let c=typeof o.oldText=="string"?o.oldText:"",d=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:c,newText:d})}if(e.length>0)return e}let r=Fd(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var Ld=J(()=>{"use strict";Ws()});function Jn(t){let e=[],n=[],s=!1,r=i=>{if(!s){s=!0;for(let o of n)o(i)}};return t.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let c=JSON.parse(a);for(let d of e)d(c)}catch(c){for(let d of e)d({jsonrpc:"2.0",id:null,error:{code:z.ParseError,message:`Failed to parse WS frame: ${c.message}`}})}}),t.on("close",()=>r()),t.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,c)=>{t.send(o,d=>{if(d){c(d);return}a()})})},onMessage(i){e.push(i)},onClose(i){n.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(c),i())},c=setTimeout(a,5e3);t.once("close",a);try{t.close()}catch{a()}}),r())}}}var Hi=J(()=>{"use strict";Et()});import{spawn as cA}from"child_process";import{setTimeout as lA}from"timers/promises";async function Fg(){let t=await ms();if(t&&Mn(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function uA(t){let e=await Or(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===qs(t)?"match":"mismatch":"missing"}async function Js(t){let e=await uA(t);if(e!=="match"){if(e==="mismatch"){let n=Dn();throw new Error(`config changed since daemon started \u2014 run \`${n} daemon restart\` to apply.`)}process.stderr.write(`hydra-acp: daemon not running; starting it...
100
+ `),Vd(),await Yd(t)}}async function Jd(t){let e=await Fg();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Or(t,e=1e3){let n=await Fg();if(n)try{let s=await fetch(n,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}});if(!s.ok)return;let r=await s.json();return{version:typeof r.version=="string"?r.version:void 0,configDigest:typeof r.configDigest=="string"?r.configDigest:void 0}}catch{return}}function Vd(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");cA(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function Yd(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await Jd(t))return;await lA(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Fr=J(()=>{"use strict";Mo();Zo();mi()});import*as Lg from"fs";import*as qi from"fs/promises";async function Wi(t,e,n){let s=pA(e),r;try{r=await qi.stat(t)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${n} (${t})
101
+ `),process.exit(1);return}throw c}let i=await fA(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
102
+ `);let o=!1,a=Lg.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await qi.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await qi.open(t,"r");try{let l=Buffer.alloc(c.size-i);await d.read(l,0,l.length,i),process.stdout.write(l),i=c.size}finally{await d.close()}}catch{}}))});await new Promise(c=>{let d=()=>{a.close(),c()};process.once("SIGINT",d),process.once("SIGTERM",d)})}async function fA(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await qi.open(t,"r");try{let i=e,o="",a=0;for(;i>0&&a<=n;){let l=Math.min(s,i);i-=l;let u=Buffer.alloc(l);await r.read(u,0,l,i),o=u.toString("utf8")+o,a=(o.match(/\n/g)??[]).length}let d=o.split(`
103
103
  `).slice(-n-1);process.stdout.write(d.join(`
104
104
  `)),o.endsWith(`
105
105
  `)||process.stdout.write(`
106
- `)}finally{await r.close()}return e}function Qd(t){let e=new Set(["--tail","-n"]),n,s=[],r=0;for(;r<t.length;){let i=t[r];if(i===void 0)break;if(i.startsWith("-")){if(s.push(i),e.has(i)&&r+1<t.length){let o=t[r+1];o!==void 0&&s.push(o),r+=2;continue}r+=1;continue}if(n===void 0){n=i,r+=1;continue}s.push(i),r+=1}return{name:n,rest:s}}function cA(t){let e=50,n=!1,s=0;for(;s<t.length;){let r=t[s];if(r==="--tail"||r==="-n"){let i=t[s+1],o=Number.parseInt(i??"",10);(!Number.isInteger(o)||o<0)&&(process.stderr.write(`Invalid --tail value: ${i}
106
+ `)}finally{await r.close()}return e}function Qd(t){let e=new Set(["--tail","-n"]),n,s=[],r=0;for(;r<t.length;){let i=t[r];if(i===void 0)break;if(i.startsWith("-")){if(s.push(i),e.has(i)&&r+1<t.length){let o=t[r+1];o!==void 0&&s.push(o),r+=2;continue}r+=1;continue}if(n===void 0){n=i,r+=1;continue}s.push(i),r+=1}return{name:n,rest:s}}function pA(t){let e=50,n=!1,s=0;for(;s<t.length;){let r=t[s];if(r==="--tail"||r==="-n"){let i=t[s+1],o=Number.parseInt(i??"",10);(!Number.isInteger(o)||o<0)&&(process.stderr.write(`Invalid --tail value: ${i}
107
107
  `),process.exit(2)),e=o,s+=2;continue}if(r==="--follow"||r==="-f"){n=!0,s+=1;continue}return process.stderr.write(`Unknown flag: ${r}
108
- `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}var sa=J(()=>{"use strict"});import{WebSocket as fA}from"ws";async function Lr(t,e,n=pA){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=_o(r.hostname);i.rejectUnauthorized!==void 0&&(s.rejectUnauthorized=i.rejectUnauthorized),i.autoSelectFamily!==void 0&&(s.autoSelectFamily=i.autoSelectFamily),i.checkServerIdentity!==void 0&&(s.checkServerIdentity=i.checkServerIdentity)}}catch{}return new Promise((r,i)=>{let o=new fA(t,e,s),a=Date.now(),c=setTimeout(()=>{o.off("open",d),o.off("error",l),o.on("error",()=>{});try{o.terminate()}catch{}i(new Fu(t,Date.now()-a))},n),d=()=>{clearTimeout(c),o.off("error",l),r(o)},l=u=>{clearTimeout(c),o.off("open",d),i(u)};o.once("open",d),o.once("error",l)})}var pA,Fu,ra=J(()=>{"use strict";$o();pA=1e4,Fu=class extends Error{url;elapsedMs;constructor(e,n){super(`hydra-acp: websocket connect to ${e} timed out after ${n}ms`),this.name="WsConnectTimeoutError",this.url=e,this.elapsedMs=n}}});import*as Gd from"fs/promises";function hA(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"?"127.0.0.1":t}async function zi(){let t=await hs();if(t&&Mn(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await be();return Ug(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function Ug(t,e,n){return`${n?"https":"http"}://${hA(t)}:${e}`}async function Fe(t,e={}){let n=await vr(),s=await zi(),r=t.startsWith("http")?t:`${s}${t}`,i={Authorization:`Bearer ${n}`},o;e.body!==void 0&&(i["Content-Type"]="application/json",o=JSON.stringify(e.body));let a;try{a=await fetch(r,{method:e.method,headers:i,...o!==void 0?{body:o}:{}})}catch(u){if(e.rethrowNetworkError)throw u;process.stderr.write(`Could not reach daemon at ${s}: ${u.message}
108
+ `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}var ra=J(()=>{"use strict"});import{WebSocket as gA}from"ws";async function Lr(t,e,n=yA){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=$o(r.hostname);i.rejectUnauthorized!==void 0&&(s.rejectUnauthorized=i.rejectUnauthorized),i.autoSelectFamily!==void 0&&(s.autoSelectFamily=i.autoSelectFamily),i.checkServerIdentity!==void 0&&(s.checkServerIdentity=i.checkServerIdentity)}}catch{}return new Promise((r,i)=>{let o=new gA(t,e,s),a=Date.now(),c=setTimeout(()=>{o.off("open",d),o.off("error",l),o.on("error",()=>{});try{o.terminate()}catch{}i(new Fu(t,Date.now()-a))},n),d=()=>{clearTimeout(c),o.off("error",l),r(o)},l=u=>{clearTimeout(c),o.off("open",d),i(u)};o.once("open",d),o.once("error",l)})}var yA,Fu,ia=J(()=>{"use strict";Oo();yA=1e4,Fu=class extends Error{url;elapsedMs;constructor(e,n){super(`hydra-acp: websocket connect to ${e} timed out after ${n}ms`),this.name="WsConnectTimeoutError",this.url=e,this.elapsedMs=n}}});import*as Gd from"fs/promises";function wA(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"?"127.0.0.1":t}async function Ki(){let t=await ms();if(t&&Mn(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await be();return qg(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function qg(t,e,n){return`${n?"https":"http"}://${wA(t)}:${e}`}async function Oe(t,e={}){let n=await vr(),s=await Ki(),r=t.startsWith("http")?t:`${s}${t}`,i={Authorization:`Bearer ${n}`},o;e.body!==void 0&&(i["Content-Type"]="application/json",o=JSON.stringify(e.body));let a;try{a=await fetch(r,{method:e.method,headers:i,...o!==void 0?{body:o}:{}})}catch(u){if(e.rethrowNetworkError)throw u;process.stderr.write(`Could not reach daemon at ${s}: ${u.message}
109
109
  `),process.exit(1)}let c=null;if(a.status!==204)try{c=await a.json()}catch{c=null}let d=e.expectStatus,l=d===void 0?a.ok:Array.isArray(d)?d.includes(a.status):d===a.status;if(d!==void 0&&!l){let u=`HTTP ${a.status}`;if(c&&typeof c=="object"&&"error"in c){let p=c.error;typeof p=="string"&&p.length>0&&(u=p)}let f=e.errorPrefix??"Daemon returned";process.stderr.write(`${f} ${u}
110
- `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function Ki(t){let e;t instanceof Date?e=t.getTime():typeof t=="string"?e=Date.parse(t):e=t;let n=Math.max(0,Date.now()-e),s=Math.floor(n/1e3);if(s<60)return`${s}s ago`;let r=Math.floor(s/60);if(r<60)return`${r}m ago`;let i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function Xd(t,e){let n=e!=="agent",s=n?[]:void 0,r=[],i={},o=!0,a=0;for(;a<t.length;){let c=t[a];if(c==="--command"){let d=t[a+1];d===void 0&&(process.stderr.write(`--command requires a value
111
- `),process.exit(2)),s=n?mA(d):d,a+=2;continue}if(c==="--args"){let d=t[a+1];d===void 0&&(process.stderr.write(`--args requires a value
110
+ `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function Ji(t){let e;t instanceof Date?e=t.getTime():typeof t=="string"?e=Date.parse(t):e=t;let n=Math.max(0,Date.now()-e),s=Math.floor(n/1e3);if(s<60)return`${s}s ago`;let r=Math.floor(s/60);if(r<60)return`${r}m ago`;let i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function Xd(t,e){let n=e!=="agent",s=n?[]:void 0,r=[],i={},o=!0,a=0;for(;a<t.length;){let c=t[a];if(c==="--command"){let d=t[a+1];d===void 0&&(process.stderr.write(`--command requires a value
111
+ `),process.exit(2)),s=n?bA(d):d,a+=2;continue}if(c==="--args"){let d=t[a+1];d===void 0&&(process.stderr.write(`--args requires a value
112
112
  `),process.exit(2)),r=d.split(",").filter(l=>l.length>0),a+=2;continue}if(c==="--env"){let d=t[a+1];d===void 0&&(process.stderr.write(`--env requires KEY=VALUE
113
113
  `),process.exit(2));let l=d.indexOf("=");l<=0&&(process.stderr.write(`Invalid --env value '${d}': expected KEY=VALUE
114
114
  `),process.exit(2)),i[d.slice(0,l)]=d.slice(l+1),a+=2;continue}if(c==="--disabled"&&e!=="agent"){o=!1,a+=1;continue}process.stderr.write(`Unknown flag: ${c}
115
- `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function mA(t){return t.split(/\s+/).filter(e=>e.length>0)}async function Ji(){let t=await Gd.readFile(_.config(),"utf8");return JSON.parse(t)}async function Ou(t){await Gd.writeFile(_.config(),JSON.stringify(t,null,2)+`
116
- `,{encoding:"utf8",mode:384})}var Ys=J(()=>{"use strict";Ve();fs();he();mi();ra()});async function on(t,e={},n=8e3,s=fetch){let r=new AbortController,i=e.signal??void 0;i&&(i.aborted?r.abort(i.reason):i.addEventListener("abort",()=>r.abort(i.reason),{once:!0}));let o=!1,a=setTimeout(()=>{o=!0,r.abort()},n);try{return await s(t,{...e,signal:r.signal})}catch(c){throw o?new Lu(t,n):c}finally{clearTimeout(a)}}async function Yn(t,e={},n=fetch){let s=new URL(`${t.baseUrl}/v1/sessions`);e.cwd&&s.searchParams.set("cwd",e.cwd),e.all&&s.searchParams.set("all","true"),e.includeNonInteractive&&s.searchParams.set("includeNonInteractive","true");let r=await on(s.toString(),{headers:{Authorization:`Bearer ${t.token}`},signal:e.signal},8e3,n);if(!r.ok)throw new Error(`daemon returned HTTP ${r.status}`);let i=await r.json();return Array.isArray(i.sessions)?i.sessions.map(o=>({sessionId:o.sessionId,cwd:o.cwd,updatedAt:o.updatedAt,attachedClients:o.attachedClients??0,status:o.status??"warm",upstreamSessionId:o.upstreamSessionId,agentId:o.agentId,currentModel:o.currentModel,currentUsage:o.currentUsage,title:o.title,importedFromMachine:o.importedFromMachine,importedFromUpstreamSessionId:o.importedFromUpstreamSessionId,forkedFromSessionId:o.forkedFromSessionId,forkedFromMessageId:o.forkedFromMessageId,busy:o.busy,awaitingInput:o.awaitingInput,originatingClient:o.originatingClient,interactive:o.interactive,priority:o.priority,compactionState:o.compactionState,forkSynthesisState:o.forkSynthesisState})):[]}async function jg(t,e=fetch){let n=await on(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json(),r=Array.isArray(s.agents)?s.agents.filter(c=>c.installed==="yes"):[],i=0,o=0,a=0;for(let c of r)try{let d=await on(`${t.baseUrl}/v1/agents/${c.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}},3e4,e);if(!d.ok)continue;let l=await d.json();i+=Array.isArray(l.synced)?l.synced.length:0,o+=typeof l.skipped=="number"?l.skipped:0,a+=1}catch{}return{synced:i,skipped:o,agents:a}}async function Zd(t,e=fetch){let n=await on(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json();return Array.isArray(s.agents)?s.agents.map(r=>({id:r.id,name:r.name,description:r.description,...r.onboarding?{onboarding:r.onboarding}:{}})):[]}async function ec(t,e,n={},s=fetch){let r=await on(`${t.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(n)},18e4,s);if(!r.ok){let i="";try{let o=await r.json();typeof o.error=="string"&&(i=`: ${o.error}`)}catch{}throw new Error(`fork failed (HTTP ${r.status})${i}`)}return await r.json()}async function Vn(t,e,n=fetch){let s=await on(`${t.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}},8e3,n);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function qg(t,e,n,s=fetch){let r=await on(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:n})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Wg(t,e,n,s=fetch){let r=await on(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:n})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function zg(t,e,n=fetch){let s=await on(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})},8e3,n);if(!s.ok&&s.status!==202&&s.status!==204&&s.status!==404&&s.status!==409)throw new Error(`daemon returned HTTP ${s.status}`)}async function Kg(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await on(`${t.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(r)},2e4,s);if(!i.ok)throw new Error(`daemon returned HTTP ${i.status}`);return await i.json()}async function Jg(t,e,n=fetch){let s=await on(`${t.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}},8e3,n);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function tc(t,e){let n=t.filter(i=>i.cwd===e);if(n.length===0)return null;let s=i=>i.status==="warm"?1:0;return[...n].sort((i,o)=>{let a=s(o)-s(i);return a!==0?a:o.updatedAt.localeCompare(i.updatedAt)})[0]??null}var Lu,ia=J(()=>{"use strict";Lu=class extends Error{constructor(n,s){super(`daemon did not respond within ${s}ms (${n})`);this.url=n;this.timeoutMs=s;this.name="DaemonTimeoutError"}url;timeoutMs}});function Bu(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Yg(t,e){let n=t??"?",s=Bu(e);return s?`${n}${gA}${s}`:n}function Vg(t){return t??"?"}function Qg(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:Nu(e,n)}function Nu(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var gA,Du=J(()=>{"use strict";gA="\u2022"});function Gg(t){let e=t.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)throw new Error("--columns: no column names given");let n=new Set,s=[];for(let r of e){if(!sc.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${sc.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function Qi(t,e=Date.now()){return{session:rt(t.sessionId),upstream:bA(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:vA(t.status,t.busy,t.awaitingInput,wA(t.compactionState),t.forkSynthesisState),agent:Vg(t.agentId),model:Bu(t.currentModel)??"-",age:SA(t.updatedAt,e),title:t.title??"-",cwd:Ze(t.cwd),cost:Qg(t.currentUsage)}}function wA(t){if(t==null||typeof t!="object")return!1;let e=t.status;return e==="requested"||e==="running"||e==="swap_pending"||e==="swap_deferred"}function bA(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function vA(t,e,n,s,r){return t==="cold"?"COLD":n?r==="failed"?"WARM\u25E6\u26A0":"WARM\u25E6":e?r==="failed"?"WARM\u2022\u26A0":"WARM\u2022":r==="running"?"WARM\u2728":r==="failed"?"WARM\u26A0":s?"WARM\u27F3":"WARM"}function Gi(t,e={}){let n=e.columns??Yi,s={session:0,upstream:0,host:0,state:0,agent:0,model:0,age:0,cwd:0,title:0,cost:0};for(let r of n)s[r]=kA(Vi[r],t.map(i=>i[r]));return s}function SA(t,e){if(!t)return"?";let n=Date.parse(t);if(Number.isNaN(n))return"?";let s=Math.max(0,e-n),r=Math.floor(s/1e3);if(r<60)return"<1m";let i=Math.floor(r/60);if(i<60)return`${i}m`;let o=Math.floor(i/60);if(o<24)return`${o}h`;let a=Math.floor(o/24);if(a<14)return`${a}d`;let c=Math.floor(a/7);if(c<9)return`${c}w`;let d=Math.floor(a/30);return d<12?`${d}mo`:`${Math.floor(a/365)}y`}function kA(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Vs(t,e,n,s={}){let r=s.columns??Yi,i=s.cwdMaxWidth??yA,o=v=>v==="age"?t[v].padStart(e[v]):t[v].padEnd(e[v]);if(n===void 0)return r.map((S,k)=>k===r.length-1?t[S]:o(S)).join(nc);let a=r.map((v,S)=>({col:v,i:S})).filter(({col:v})=>Hu.has(v)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let v=r.map(o).join(nc);return v.length>n?v.slice(0,n):v}let d=r.filter(v=>!Hu.has(v)).reduce((v,S)=>v+e[S],0),l=Math.max(0,r.length-1),u=n-d-l*nc.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:v,i:S}of a){if(S===c)continue;let k=v==="cwd"?Math.min(e[v],i):e[v],T=Math.min(k,Math.max(0,p-1));f.set(S,T),p=Math.max(0,p-T)}f.set(c,Math.max(0,p));let h=r.length-1,m=(v,S,k)=>{if(v==="cwd")return oa(t[v],S).padEnd(S);let T=IA(t[v],S);return k?T:T.padEnd(S)},b=r.map((v,S)=>Hu.has(v)?m(v,f.get(S)??0,S===h):o(v)).join(nc);return b.length>n?b.slice(0,n):b}function IA(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function oa(t,e){if(e<=0)return"";if(t.length<=e)return t;if(e===1)return"\u2026";let n=Math.ceil((e-1)/2),s=e-1-n;return t.slice(0,n)+"\u2026"+t.slice(t.length-s)}var sc,Yi,Hu,Vi,nc,yA,rc=J(()=>{"use strict";Du();he();qn();sc=["session","upstream","host","state","agent","model","age","cwd","title","cost"],Yi=["session","state","age","cwd","title","agent","cost"],Hu=new Set(["cwd","title"]),Vi={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},nc=" ",yA=32});import{spawn as $A}from"child_process";import{Writable as FA}from"stream";function ic(t={}){let e=t.isTTY??process.stdout.isTTY===!0;if(t.disabled===!0||!e)return{stream:process.stdout,flush:async()=>{}};let n=t.env??process.env,s=OA(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??$A,i={...n};i.LESS===void 0&&(i.LESS="FRX");let o=r(s,[],{shell:!0,stdio:["pipe","inherit","inherit"],env:i}),a=o.stdin;if(a===null)return{stream:process.stdout,flush:async()=>{}};a.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
117
- `)});let c=new FA({write(l,u,f){if(!a.writable){f();return}a.write(l,h=>{if(h&&h.code!=="EPIPE"){f(h);return}f()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});c.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
118
- `)});let d=new Promise(l=>{o.once("exit",()=>l()),o.once("error",()=>l())});return{stream:c,flush:async()=>{a.writable&&await new Promise(l=>{c.end(()=>l())}),await d}}}function OA(t){let e=t.HYDRA_ACP_PAGER;if(e!==void 0)return e.length===0?null:e;let n=t.PAGER;return n!==void 0?n.length===0?null:n:"less"}var Uu=J(()=>{"use strict"});import LA from"chalk";import{highlight as BA,supportsLanguage as oc}from"cli-highlight";import dc from"string-width";function Qs(t,e={}){switch(t.kind){case"user-text":{let n=ju(t.text,"\u258E ","user",void 0,t.sentBy,!0);if(t.attachments&&t.attachments.length>0)for(let s of t.attachments)n.push({prefix:"\u258E ",prefixStyle:"user",body:`\u{1F4CE} ${s.name??"image"}`,bodyStyle:"user",fillRow:!0,iterm2Image:{data:s.data,heightCells:5}});return n}case"agent-text":return ju(t.text," ","agent");case"agent-thought":return ju(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return iC(t,e.maxPlanItems??sC);case"mode-changed":return[{prefix:"\xBB ",prefixStyle:"info",body:`mode: ${t.mode}`,bodyStyle:"info"}];case"model-changed":return[];case"turn-complete":return[];case"usage-update":return[];case"available-commands":case"available-modes":case"config-options":return[];case"session-info":return[];case"unknown":return[]}}function qu(t,e){return Xi(t,e).styled}function Xi(t,e){let n=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.linkOpen??"^C^_",o=e?.linkReset??"^:",a="",c=0,d=!1,l=[],u=0;for(;u<t.length;){let f=t[u];if(f==="^"){a+="^^",c+=1,u+=1;continue}if(f==="*"&&t[u+1]==="*"){let p=t.indexOf("**",u+2);if(p!==-1&&p>u+2){let h=t.slice(u+2,p),m=Xi(h,e),y=c;a+=`^+${m.styled}${r}`;for(let b of m.links)l.push({start:y+b.start,end:y+b.end,url:b.url});c+=m.cleanLength,m.ansi&&(d=!0),u=p+2;continue}}if(f==="`"){let p=t.indexOf("`",u+1);if(p!==-1&&p>u+1){let h=t.slice(u+1,p),m=h.replace(/\^/g,"^^");a+=`${n}${m}${s}`,c+=h.length,u=p+1;continue}}if(f==="["){let p=t.indexOf("]",u+1);if(p!==-1&&t[p+1]==="("&&p>u+1){let h=-1;{let m=1,y=p+2;for(;y<t.length;){let b=t[y];if(b==="\\"&&y+1<t.length){y+=2;continue}if(b==="(")m+=1;else if(b===")"&&(m-=1,m===0)){h=y;break}y+=1}}if(h!==-1&&h>p+2){let m=t.slice(u+1,p),y=t.slice(p+2,h),b=Xi(m,e),v=c,S=y.startsWith("file://");S?a+=`${i}${b.styled}${o}`:(a+=`\x1B]8;;${y}\x1B\\${i}${b.styled}${o}\x1B]8;;\x1B\\`,d=!0);for(let k of b.links)l.push({start:v+k.start,end:v+k.end,url:k.url});c+=b.cleanLength,S&&l.push({start:v,end:c,url:y}),u=h+1;continue}}}a+=f,c+=1,u+=1}return{styled:a,links:l,cleanLength:c,ansi:d}}function NA(t){switch(t){case"plan-done":return{codeOpen:"^C",boldReset:"^:^g",codeReset:"^:^g"};case"plan-pending":return{codeOpen:"^C",boldReset:"^:^-",codeReset:"^:^-"};default:return{codeOpen:"^C",boldReset:"^:^Y",codeReset:"^:^Y"}}}function cy(t){switch(t){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",codeReset:"^:^+"}}}function ly(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=t.replace(/^\s+/,"").split(`
119
- `),l=!1,u="",f=[],p=i!==" ",h=(b,v,S=" ",k,T)=>{let F={prefix:S,body:b,bodyStyle:v};r!==void 0&&(F.prefixStyle=r),k&&k.length>0&&(F.links=k),T&&(F.ansi=!0),c.push(F)},m=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let b=fy(u,f);for(let v of b){let S={prefix:" ",body:v.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(S.prefixStyle=r),v.ansi&&(S.ansi=!0),c.push(S)}}else for(let b of f)h(b.replace(/\^/g,"^^"),n);f=[],u=""}};for(let b=0;b<d.length;b++){let v=d[b],S=v.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,u=S[1]??"");continue}if(l){f.push(v);continue}let k=v.match(/^(#{1,6})\s+(.*)$/);if(k){let U=k[1].length,L=k[2]??"",N=s?U===1?"heading-1":U===2?"heading-2":"heading-3":n,Z=s?cy(N):o;h(qu(L,Z),N,m());continue}let T=d[b+1];if(v.includes("|")&&T!==void 0&&DA(T)&&aa(v).length===aa(T).length){let U=aa(v),L=[],N=b+2;for(;N<d.length&&d[N].includes("|");)L.push(aa(d[N])),N++;let Z=KA(U,L,a);for(let G of Z)r!==void 0&&(G.prefixStyle=r),c.push(G);b=N-1;continue}let F=v.match(/^(\s*)[-*+]\s+(.*)$/);if(F){let U=F[1]??"",L=F[2]??"",N=Xi(L,o),Z=U.length+2,G=N.links.map(Se=>({start:Se.start+Z,end:Se.end+Z,url:Se.url}));h(`${U}\u2022 ${N.styled}`,n,m(),G,N.ansi);continue}let $=v.match(/^(\s*)(\d+)\.\s+(.*)$/);if($){let U=$[1]??"",L=$[2]??"",N=$[3]??"",Z=Xi(N,o),G=U.length+L.length+2,Se=Z.links.map(X=>({start:X.start+G,end:X.end+G,url:X.url}));h(`${U}${L}. ${Z.styled}`,n,m(),Se,Z.ansi);continue}let B=v.trim()==="",K=Xi(v,o);h(K.styled,n,B?" ":m(),K.links,K.ansi)}for(l&&y();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function Gs(t,e){return ly(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function Zi(t){return ly(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function aa(t){let e=t.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let n=[],s="",r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(o==="\\"&&i+1<e.length&&e[i+1]==="|"){s+="|",i+=1;continue}if(o==="`"){r=!r,s+=o;continue}if(o==="|"&&!r){n.push(s.trim()),s="";continue}s+=o}return n.push(s.trim()),n}function DA(t){if(!t.includes("|"))return!1;let e=aa(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function ac(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return dc(e)}function jA(t){let e=[],n=0;for(;n<t.length;){let s=t[n];if(s===" "||s===" "){let o=n;for(;o<t.length&&(t[o]===" "||t[o]===" ");)o++;let a=t.slice(n,o);e.push({text:a,isWS:!0,width:dc(a)}),n=o;continue}let r="",i=n;for(;i<t.length;){let o=t[i];if(o===" "||o===" ")break;if(t[i]==="*"&&t[i+1]==="*"){let a=t.indexOf("**",i+2);a===-1?(r+="**",i+=2):(r+=t.slice(i,a+2),i=a+2);continue}if(o==="`"){let a=t.indexOf("`",i+1);a===-1?(r+="`",i+=1):(r+=t.slice(i,a+1),i=a+1);continue}r+=o,i+=1}e.push({text:r,isWS:!1,width:ac(r)}),n=i}return e}function qA(t,e){let n=[],s="",r=0;for(let i of t){let o=dc(i);r>0&&r+o>e?(n.push(s),s=i,r=o):(s+=i,r+=o)}return s.length>0&&n.push(s),n}function WA(t,e){if(e<=0)return t.length===0?[""]:[t.map(o=>o.text).join("")];let n=[],s="",r=0,i=()=>{n.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let o of t){if(o.isWS){if(r===0)continue;s+=o.text,r+=o.width;continue}if(o.width>e){if(r>0&&i(),o.text.includes("**")||o.text.includes("`"))n.push(o.text);else{let c=qA(o.text,e);for(let l=0;l<c.length-1;l++)n.push(c[l]);let d=c[c.length-1]??"";s=d,r=dc(d)}continue}if(r===0){s=o.text,r=o.width;continue}r+o.width>e?(i(),s=o.text,r=o.width):(s+=o.text,r+=o.width)}return(s.length>0||n.length===0)&&i(),n}function zA(t,e){let n=t.length;if(t.reduce((l,u)=>l+u,0)<=e)return t.slice();let r=t.map(l=>Math.min(l,uy)),i=r.reduce((l,u)=>l+u,0);if(i>=e)return r;let o=e-i,a=t.map((l,u)=>({i:u,slack:Math.max(0,l-r[u])})).filter(l=>l.slack>0),c=a.reduce((l,u)=>l+u.slack,0);if(c===0)return r;for(let l of a){let u=Math.floor(o*l.slack/c);r[l.i]=r[l.i]+Math.min(u,l.slack)}i=r.reduce((l,u)=>l+u,0);let d=e-i;for(;d>0;){let l=-1,u=0;for(let f=0;f<n;f++){let p=t[f]-r[f];p>u&&(u=p,l=f)}if(l<0)break;r[l]=r[l]+1,d--}return r}function KA(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=ac(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let u=d[l]??"",f=ac(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(n!==void 0){let d=Math.max(s*uy,n-HA-(s-1)*UA);i=zA(r,d)}let o=(d,l,u)=>{let f=[],p=1;for(let m=0;m<s;m++){let y=d[m]??"",b=i[m],v=WA(jA(y),b);f.push(v),v.length>p&&(p=v.length)}let h=[];for(let m=0;m<p;m++){let y=[];for(let b=0;b<s;b++){let v=f[b][m]??"",S=i[b],k=ac(v),T=qu(v,u);y.push(T+" ".repeat(Math.max(0,S-k)))}h.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return h},a=[];a.push(...o(t,"heading-3",cy("heading-3")));let c=[];for(let d=0;d<s;d++)c.push("\u2500".repeat(i[d]));a.push({prefix:" ",body:c.join("\u2500\u253C\u2500"),bodyStyle:"dim"});for(let d of e)a.push(...o(d,"agent"));return a}function fy(t,e){if(t.length===0||!oc(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=BA(e.join(`
120
- `),{language:t,theme:JA,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
121
- `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function VA(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return oc("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return oc("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=YA[s];return r&&oc(r)?r:""}function ju(t,e,n,s,r,i){let o=t.replace(/^\s+/,"").split(`
122
- `),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let c of o){let d={prefix:e,prefixStyle:s??n,body:c,bodyStyle:n};i&&(d.fillRow=!0),a.push(d)}return a}function QA(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Qn(t){let e=Math.floor(t/1e3);if(e<60)return`${e}s`;let n=Math.floor(e/60),s=e%60;if(n<60)return s===0?`${n}m`:`${n}m ${s}s`;let r=Math.floor(n/60),i=n%60;return i===0?`${r}h`:`${r}h ${i}m`}function py(t){if(t.length<=4096&&t.split(`
115
+ `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function bA(t){return t.split(/\s+/).filter(e=>e.length>0)}async function Vi(){let t=await Gd.readFile(_.config(),"utf8");return JSON.parse(t)}async function Lu(t){await Gd.writeFile(_.config(),JSON.stringify(t,null,2)+`
116
+ `,{encoding:"utf8",mode:384})}var Vs=J(()=>{"use strict";Ge();ps();he();mi();ia()});async function on(t,e={},n=8e3,s=fetch){let r=new AbortController,i=e.signal??void 0;i&&(i.aborted?r.abort(i.reason):i.addEventListener("abort",()=>r.abort(i.reason),{once:!0}));let o=!1,a=setTimeout(()=>{o=!0,r.abort()},n);try{return await s(t,{...e,signal:r.signal})}catch(c){throw o?new Bu(t,n):c}finally{clearTimeout(a)}}async function Vn(t,e={},n=fetch){let s=new URL(`${t.baseUrl}/v1/sessions`);e.cwd&&s.searchParams.set("cwd",e.cwd),e.all&&s.searchParams.set("all","true"),e.includeNonInteractive&&s.searchParams.set("includeNonInteractive","true");let r=await on(s.toString(),{headers:{Authorization:`Bearer ${t.token}`},signal:e.signal},8e3,n);if(!r.ok)throw new Error(`daemon returned HTTP ${r.status}`);let i=await r.json();return Array.isArray(i.sessions)?i.sessions.map(o=>({sessionId:o.sessionId,cwd:o.cwd,updatedAt:o.updatedAt,attachedClients:o.attachedClients??0,status:o.status??"warm",upstreamSessionId:o.upstreamSessionId,agentId:o.agentId,currentModel:o.currentModel,currentUsage:o.currentUsage,title:o.title,importedFromMachine:o.importedFromMachine,importedFromUpstreamSessionId:o.importedFromUpstreamSessionId,forkedFromSessionId:o.forkedFromSessionId,forkedFromMessageId:o.forkedFromMessageId,busy:o.busy,awaitingInput:o.awaitingInput,originatingClient:o.originatingClient,interactive:o.interactive,priority:o.priority,compactionState:o.compactionState,forkSynthesisState:o.forkSynthesisState})):[]}async function Wg(t,e=fetch){let n=await on(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json(),r=Array.isArray(s.agents)?s.agents.filter(c=>c.installed==="yes"):[],i=0,o=0,a=0;for(let c of r)try{let d=await on(`${t.baseUrl}/v1/agents/${c.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}},3e4,e);if(!d.ok)continue;let l=await d.json();i+=Array.isArray(l.synced)?l.synced.length:0,o+=typeof l.skipped=="number"?l.skipped:0,a+=1}catch{}return{synced:i,skipped:o,agents:a}}async function Zd(t,e=fetch){let n=await on(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json();return Array.isArray(s.agents)?s.agents.map(r=>({id:r.id,name:r.name,description:r.description,...r.onboarding?{onboarding:r.onboarding}:{}})):[]}async function ec(t,e,n={},s=fetch){let r=await on(`${t.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(n)},18e4,s);if(!r.ok){let i="";try{let o=await r.json();typeof o.error=="string"&&(i=`: ${o.error}`)}catch{}throw new Error(`fork failed (HTTP ${r.status})${i}`)}return await r.json()}async function Yn(t,e,n=fetch){let s=await on(`${t.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}},8e3,n);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function zg(t,e,n,s=fetch){let r=await on(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:n})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Kg(t,e,n,s=fetch){let r=await on(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:n})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Jg(t,e,n=fetch){let s=await on(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})},8e3,n);if(!s.ok&&s.status!==202&&s.status!==204&&s.status!==404&&s.status!==409)throw new Error(`daemon returned HTTP ${s.status}`)}async function Vg(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await on(`${t.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(r)},2e4,s);if(!i.ok)throw new Error(`daemon returned HTTP ${i.status}`);return await i.json()}async function Yg(t,e,n=fetch){let s=await on(`${t.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}},8e3,n);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function tc(t,e){let n=t.filter(i=>i.cwd===e);if(n.length===0)return null;let s=i=>i.status==="warm"?1:0;return[...n].sort((i,o)=>{let a=s(o)-s(i);return a!==0?a:o.updatedAt.localeCompare(i.updatedAt)})[0]??null}var Bu,oa=J(()=>{"use strict";Bu=class extends Error{constructor(n,s){super(`daemon did not respond within ${s}ms (${n})`);this.url=n;this.timeoutMs=s;this.name="DaemonTimeoutError"}url;timeoutMs}});function Nu(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Qg(t,e){let n=t??"?",s=Nu(e);return s?`${n}${vA}${s}`:n}function Gg(t){return t??"?"}function Xg(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:Du(e,n)}function Du(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var vA,Hu=J(()=>{"use strict";vA="\u2022"});function Zg(t){let e=t.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)throw new Error("--columns: no column names given");let n=new Set,s=[];for(let r of e){if(!sc.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${sc.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function Gi(t,e=Date.now()){return{session:rt(t.sessionId),upstream:IA(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:xA(t.status,t.busy,t.awaitingInput,kA(t.compactionState),t.forkSynthesisState),agent:Gg(t.agentId),model:Nu(t.currentModel)??"-",age:AA(t.updatedAt,e),title:t.title??"-",cwd:Ze(t.cwd),cost:Xg(t.currentUsage)}}function kA(t){if(t==null||typeof t!="object")return!1;let e=t.status;return e==="requested"||e==="running"||e==="swap_pending"||e==="swap_deferred"}function IA(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function xA(t,e,n,s,r){return t==="cold"?"COLD":n?r==="failed"?"WARM\u25E6\u26A0":"WARM\u25E6":e?r==="failed"?"WARM\u2022\u26A0":"WARM\u2022":r==="running"?"WARM\u2728":r==="failed"?"WARM\u26A0":s?"WARM\u27F3":"WARM"}function Xi(t,e={}){let n=e.columns??Yi,s={session:0,upstream:0,host:0,state:0,agent:0,model:0,age:0,cwd:0,title:0,cost:0};for(let r of n)s[r]=CA(Qi[r],t.map(i=>i[r]));return s}function AA(t,e){if(!t)return"?";let n=Date.parse(t);if(Number.isNaN(n))return"?";let s=Math.max(0,e-n),r=Math.floor(s/1e3);if(r<60)return"<1m";let i=Math.floor(r/60);if(i<60)return`${i}m`;let o=Math.floor(i/60);if(o<24)return`${o}h`;let a=Math.floor(o/24);if(a<14)return`${a}d`;let c=Math.floor(a/7);if(c<9)return`${c}w`;let d=Math.floor(a/30);return d<12?`${d}mo`:`${Math.floor(a/365)}y`}function CA(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Ys(t,e,n,s={}){let r=s.columns??Yi,i=s.cwdMaxWidth??SA,o=v=>v==="age"?t[v].padStart(e[v]):t[v].padEnd(e[v]);if(n===void 0)return r.map((S,k)=>k===r.length-1?t[S]:o(S)).join(nc);let a=r.map((v,S)=>({col:v,i:S})).filter(({col:v})=>Uu.has(v)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let v=r.map(o).join(nc);return v.length>n?v.slice(0,n):v}let d=r.filter(v=>!Uu.has(v)).reduce((v,S)=>v+e[S],0),l=Math.max(0,r.length-1),u=n-d-l*nc.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:v,i:S}of a){if(S===c)continue;let k=v==="cwd"?Math.min(e[v],i):e[v],T=Math.min(k,Math.max(0,p-1));f.set(S,T),p=Math.max(0,p-T)}f.set(c,Math.max(0,p));let h=r.length-1,m=(v,S,k)=>{if(v==="cwd")return aa(t[v],S).padEnd(S);let T=RA(t[v],S);return k?T:T.padEnd(S)},b=r.map((v,S)=>Uu.has(v)?m(v,f.get(S)??0,S===h):o(v)).join(nc);return b.length>n?b.slice(0,n):b}function RA(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function aa(t,e){if(e<=0)return"";if(t.length<=e)return t;if(e===1)return"\u2026";let n=Math.ceil((e-1)/2),s=e-1-n;return t.slice(0,n)+"\u2026"+t.slice(t.length-s)}var sc,Yi,Uu,Qi,nc,SA,rc=J(()=>{"use strict";Hu();he();qn();sc=["session","upstream","host","state","agent","model","age","cwd","title","cost"],Yi=["session","state","age","cwd","title","agent","cost"],Uu=new Set(["cwd","title"]),Qi={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},nc=" ",SA=32});import{spawn as BA}from"child_process";import{Writable as NA}from"stream";function ic(t={}){let e=t.isTTY??process.stdout.isTTY===!0;if(t.disabled===!0||!e)return{stream:process.stdout,flush:async()=>{}};let n=t.env??process.env,s=DA(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??BA,i={...n};i.LESS===void 0&&(i.LESS="FRX");let o=r(s,[],{shell:!0,stdio:["pipe","inherit","inherit"],env:i}),a=o.stdin;if(a===null)return{stream:process.stdout,flush:async()=>{}};a.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
117
+ `)});let c=new NA({write(l,u,f){if(!a.writable){f();return}a.write(l,h=>{if(h&&h.code!=="EPIPE"){f(h);return}f()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});c.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
118
+ `)});let d=new Promise(l=>{o.once("exit",()=>l()),o.once("error",()=>l())});return{stream:c,flush:async()=>{a.writable&&await new Promise(l=>{c.end(()=>l())}),await d}}}function DA(t){let e=t.HYDRA_ACP_PAGER;if(e!==void 0)return e.length===0?null:e;let n=t.PAGER;return n!==void 0?n.length===0?null:n:"less"}var ju=J(()=>{"use strict"});import HA from"chalk";import{highlight as UA,supportsLanguage as oc}from"cli-highlight";import dc from"string-width";function Qs(t,e={}){switch(t.kind){case"user-text":{let n=qu(t.text,"\u258E ","user",void 0,t.sentBy,!0);if(t.attachments&&t.attachments.length>0)for(let s of t.attachments)n.push({prefix:"\u258E ",prefixStyle:"user",body:`\u{1F4CE} ${s.name??"image"}`,bodyStyle:"user",fillRow:!0,iterm2Image:{data:s.data,heightCells:5}});return n}case"agent-text":return qu(t.text," ","agent");case"agent-thought":return qu(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return lC(t,e.maxPlanItems??dC);case"mode-changed":return[{prefix:"\xBB ",prefixStyle:"info",body:`mode: ${t.mode}`,bodyStyle:"info"}];case"model-changed":return[];case"turn-complete":return[];case"usage-update":return[];case"available-commands":case"available-modes":case"config-options":return[];case"session-info":return[];case"unknown":return[]}}function Wu(t,e){return Zi(t,e).styled}function Zi(t,e){let n=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.linkOpen??"^C^_",o=e?.linkReset??"^:",a="",c=0,d=!1,l=[],u=0;for(;u<t.length;){let f=t[u];if(f==="^"){a+="^^",c+=1,u+=1;continue}if(f==="*"&&t[u+1]==="*"){let p=t.indexOf("**",u+2);if(p!==-1&&p>u+2){let h=t.slice(u+2,p),m=Zi(h,e),y=c;a+=`^+${m.styled}${r}`;for(let b of m.links)l.push({start:y+b.start,end:y+b.end,url:b.url});c+=m.cleanLength,m.ansi&&(d=!0),u=p+2;continue}}if(f==="`"){let p=t.indexOf("`",u+1);if(p!==-1&&p>u+1){let h=t.slice(u+1,p),m=h.replace(/\^/g,"^^");a+=`${n}${m}${s}`,c+=h.length,u=p+1;continue}}if(f==="["){let p=t.indexOf("]",u+1);if(p!==-1&&t[p+1]==="("&&p>u+1){let h=-1;{let m=1,y=p+2;for(;y<t.length;){let b=t[y];if(b==="\\"&&y+1<t.length){y+=2;continue}if(b==="(")m+=1;else if(b===")"&&(m-=1,m===0)){h=y;break}y+=1}}if(h!==-1&&h>p+2){let m=t.slice(u+1,p),y=t.slice(p+2,h),b=Zi(m,e),v=c,S=y.startsWith("file://"),k=jA.test(y);S?a+=`${i}${b.styled}${o}`:(a+=`\x1B]8;;${y}\x1B\\${i}${b.styled}${o}\x1B]8;;\x1B\\`,d=!0);for(let T of b.links)l.push({start:v+T.start,end:v+T.end,url:T.url});c+=b.cleanLength,(S||k)&&l.push({start:v,end:c,url:y}),u=h+1;continue}}}a+=f,c+=1,u+=1}return{styled:a,links:l,cleanLength:c,ansi:d}}function qA(t){switch(t){case"plan-done":return{codeOpen:"^C",boldReset:"^:^g",codeReset:"^:^g"};case"plan-pending":return{codeOpen:"^C",boldReset:"^:^-",codeReset:"^:^-"};default:return{codeOpen:"^C",boldReset:"^:^Y",codeReset:"^:^Y"}}}function uy(t){switch(t){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",codeReset:"^:^+"}}}function fy(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=t.replace(/^\s+/,"").split(`
119
+ `),l=!1,u="",f=[],p=i!==" ",h=(b,v,S=" ",k,T)=>{let O={prefix:S,body:b,bodyStyle:v};r!==void 0&&(O.prefixStyle=r),k&&k.length>0&&(O.links=k),T&&(O.ansi=!0),c.push(O)},m=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let b=hy(u,f);for(let v of b){let S={prefix:" ",body:v.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(S.prefixStyle=r),v.ansi&&(S.ansi=!0),c.push(S)}}else for(let b of f)h(b.replace(/\^/g,"^^"),n);f=[],u=""}};for(let b=0;b<d.length;b++){let v=d[b],S=v.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,u=S[1]??"");continue}if(l){f.push(v);continue}let k=v.match(/^(#{1,6})\s+(.*)$/);if(k){let U=k[1].length,L=k[2]??"",N=s?U===1?"heading-1":U===2?"heading-2":"heading-3":n,Z=s?uy(N):o;h(Wu(L,Z),N,m());continue}let T=d[b+1];if(v.includes("|")&&T!==void 0&&WA(T)&&da(v).length===da(T).length){let U=da(v),L=[],N=b+2;for(;N<d.length&&d[N].includes("|");)L.push(da(d[N])),N++;let Z=GA(U,L,a);for(let G of Z)r!==void 0&&(G.prefixStyle=r),c.push(G);b=N-1;continue}let O=v.match(/^(\s*)[-*+]\s+(.*)$/);if(O){let U=O[1]??"",L=O[2]??"",N=Zi(L,o),Z=U.length+2,G=N.links.map(Se=>({start:Se.start+Z,end:Se.end+Z,url:Se.url}));h(`${U}\u2022 ${N.styled}`,n,m(),G,N.ansi);continue}let $=v.match(/^(\s*)(\d+)\.\s+(.*)$/);if($){let U=$[1]??"",L=$[2]??"",N=$[3]??"",Z=Zi(N,o),G=U.length+L.length+2,Se=Z.links.map(X=>({start:X.start+G,end:X.end+G,url:X.url}));h(`${U}${L}. ${Z.styled}`,n,m(),Se,Z.ansi);continue}let B=v.trim()==="",K=Zi(v,o);h(K.styled,n,B?" ":m(),K.links,K.ansi)}for(l&&y();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function Gs(t,e){return fy(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function eo(t){return fy(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function da(t){let e=t.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let n=[],s="",r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(o==="\\"&&i+1<e.length&&e[i+1]==="|"){s+="|",i+=1;continue}if(o==="`"){r=!r,s+=o;continue}if(o==="|"&&!r){n.push(s.trim()),s="";continue}s+=o}return n.push(s.trim()),n}function WA(t){if(!t.includes("|"))return!1;let e=da(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function ac(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return dc(e)}function JA(t){let e=[],n=0;for(;n<t.length;){let s=t[n];if(s===" "||s===" "){let o=n;for(;o<t.length&&(t[o]===" "||t[o]===" ");)o++;let a=t.slice(n,o);e.push({text:a,isWS:!0,width:dc(a)}),n=o;continue}let r="",i=n;for(;i<t.length;){let o=t[i];if(o===" "||o===" ")break;if(t[i]==="*"&&t[i+1]==="*"){let a=t.indexOf("**",i+2);a===-1?(r+="**",i+=2):(r+=t.slice(i,a+2),i=a+2);continue}if(o==="`"){let a=t.indexOf("`",i+1);a===-1?(r+="`",i+=1):(r+=t.slice(i,a+1),i=a+1);continue}r+=o,i+=1}e.push({text:r,isWS:!1,width:ac(r)}),n=i}return e}function VA(t,e){let n=[],s="",r=0;for(let i of t){let o=dc(i);r>0&&r+o>e?(n.push(s),s=i,r=o):(s+=i,r+=o)}return s.length>0&&n.push(s),n}function YA(t,e){if(e<=0)return t.length===0?[""]:[t.map(o=>o.text).join("")];let n=[],s="",r=0,i=()=>{n.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let o of t){if(o.isWS){if(r===0)continue;s+=o.text,r+=o.width;continue}if(o.width>e){if(r>0&&i(),o.text.includes("**")||o.text.includes("`"))n.push(o.text);else{let c=VA(o.text,e);for(let l=0;l<c.length-1;l++)n.push(c[l]);let d=c[c.length-1]??"";s=d,r=dc(d)}continue}if(r===0){s=o.text,r=o.width;continue}r+o.width>e?(i(),s=o.text,r=o.width):(s+=o.text,r+=o.width)}return(s.length>0||n.length===0)&&i(),n}function QA(t,e){let n=t.length;if(t.reduce((l,u)=>l+u,0)<=e)return t.slice();let r=t.map(l=>Math.min(l,py)),i=r.reduce((l,u)=>l+u,0);if(i>=e)return r;let o=e-i,a=t.map((l,u)=>({i:u,slack:Math.max(0,l-r[u])})).filter(l=>l.slack>0),c=a.reduce((l,u)=>l+u.slack,0);if(c===0)return r;for(let l of a){let u=Math.floor(o*l.slack/c);r[l.i]=r[l.i]+Math.min(u,l.slack)}i=r.reduce((l,u)=>l+u,0);let d=e-i;for(;d>0;){let l=-1,u=0;for(let f=0;f<n;f++){let p=t[f]-r[f];p>u&&(u=p,l=f)}if(l<0)break;r[l]=r[l]+1,d--}return r}function GA(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=ac(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let u=d[l]??"",f=ac(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(n!==void 0){let d=Math.max(s*py,n-zA-(s-1)*KA);i=QA(r,d)}let o=(d,l,u)=>{let f=[],p=1;for(let m=0;m<s;m++){let y=d[m]??"",b=i[m],v=YA(JA(y),b);f.push(v),v.length>p&&(p=v.length)}let h=[];for(let m=0;m<p;m++){let y=[];for(let b=0;b<s;b++){let v=f[b][m]??"",S=i[b],k=ac(v),T=Wu(v,u);y.push(T+" ".repeat(Math.max(0,S-k)))}h.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return h},a=[];a.push(...o(t,"heading-3",uy("heading-3")));let c=[];for(let d=0;d<s;d++)c.push("\u2500".repeat(i[d]));a.push({prefix:" ",body:c.join("\u2500\u253C\u2500"),bodyStyle:"dim"});for(let d of e)a.push(...o(d,"agent"));return a}function hy(t,e){if(t.length===0||!oc(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=UA(e.join(`
120
+ `),{language:t,theme:XA,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
121
+ `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function eC(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return oc("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return oc("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=ZA[s];return r&&oc(r)?r:""}function qu(t,e,n,s,r,i){let o=t.replace(/^\s+/,"").split(`
122
+ `),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let c of o){let d={prefix:e,prefixStyle:s??n,body:c,bodyStyle:n};i&&(d.fillRow=!0),a.push(d)}return a}function tC(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Qn(t){let e=Math.floor(t/1e3);if(e<60)return`${e}s`;let n=Math.floor(e/60),s=e%60;if(n<60)return s===0?`${n}m`:`${n}m ${s}s`;let r=Math.floor(n/60),i=n%60;return i===0?`${r}h`:`${r}h ${i}m`}function my(t){if(t.length<=4096&&t.split(`
123
123
  `).length<=40)return{text:t,truncated:!1};let s=t.slice(0,4096),r=t.length>4096,i=s.split(`
124
124
  `);return i.length>40&&(s=i.slice(0,40).join(`
125
- `),r=!0),{text:s,truncated:r}}function da(t,e=Date.now()){let n=t.initialTitle,s=t.latestTitle,r=n.toLowerCase(),i=s.toLowerCase(),o;s===n||i.includes(r)?o=s:r.includes(i)?o=n:o=`${n} \xB7 ${s}`;let a=[];if(t.detail){let l=t.detail,u=o.toLowerCase(),f=l.toLowerCase();(f.startsWith(`${u} `)||f.startsWith(`${u} `))&&(l=l.slice(o.length).trimStart());let p=o.includes(l)||t.detailFull!==void 0&&o.includes(t.detailFull);if(l.length>0&&!p){let h=o.length+3;if(o=`${o} \xB7 ${l}`,l.startsWith("\u2026")){let m=t.locations?.[0]?.path??t.detailFull??"";(m.startsWith("/")||m.startsWith("~"))&&a.push({start:h,end:h+l.length,url:m})}}}if(t.startedAt!==void 0){let l=t.endedAt??e;o=`${o} \xB7 ${Qn(l-t.startedAt)}`}let c={prefix:` ${eC(t.status)} `,prefixStyle:tC(t.status),body:o,bodyStyle:oC(t.status)};a.length>0&&(c.links=a);let d=[c];return t.status==="failed"&&t.errorText&&d.push({prefix:" ",body:Ee(t.errorText),bodyStyle:"tool-status-fail"}),d}function hy(t){if(t.editDiff!==void 0)return[];let e=[],n=t.detailFull??t.detail;if(n)for(let s of n.split(`
125
+ `),r=!0),{text:s,truncated:r}}function ca(t,e=Date.now()){let n=t.initialTitle,s=t.latestTitle,r=n.toLowerCase(),i=s.toLowerCase(),o;s===n||i.includes(r)?o=s:r.includes(i)?o=n:o=`${n} \xB7 ${s}`;let a=[];if(t.detail){let l=t.detail,u=o.toLowerCase(),f=l.toLowerCase();(f.startsWith(`${u} `)||f.startsWith(`${u} `))&&(l=l.slice(o.length).trimStart());let p=o.includes(l)||t.detailFull!==void 0&&o.includes(t.detailFull);if(l.length>0&&!p){let h=o.length+3;if(o=`${o} \xB7 ${l}`,l.startsWith("\u2026")){let m=t.locations?.[0]?.path??t.detailFull??"";(m.startsWith("/")||m.startsWith("~"))&&a.push({start:h,end:h+l.length,url:m})}}}if(t.startedAt!==void 0){let l=t.endedAt??e;o=`${o} \xB7 ${Qn(l-t.startedAt)}`}let c={prefix:` ${iC(t.status)} `,prefixStyle:oC(t.status),body:o,bodyStyle:uC(t.status)};a.length>0&&(c.links=a);let d=[c];return t.status==="failed"&&t.errorText&&d.push({prefix:" ",body:Ee(t.errorText),bodyStyle:"tool-status-fail"}),d}function gy(t){if(t.editDiff!==void 0)return[];let e=[],n=t.detailFull??t.detail;if(n)for(let s of n.split(`
126
126
  `))e.push({prefix:" ",body:Ee(s),bodyStyle:"dim"});if(t.status==="failed"&&t.errorText&&e.push({prefix:" ",body:Ee(t.errorText),bodyStyle:"tool-status-fail"}),t.resultText){let s=t.resultText.split(`
127
- `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=VA(r);if(i.length>0){let o=fy(i,s.map(a=>Ee(a)));for(let a of o){let c={prefix:" ",body:a.body,bodyStyle:"code",fillRow:!0};a.ansi&&(c.ansi=!0),e.push(c)}}else for(let o of s)e.push({prefix:" ",body:Ee(o),bodyStyle:"dim"});t.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function gy(t){my=t>=0?t:0}function Wu(t,e,n={}){let s=[],r=t.oldRef!==void 0||t.newRef!==void 0,i;if(r){let d=(t.oldRef?.bytes??0)+(t.newRef?.bytes??0);i=` (~${QA(d)})`}else{let d=XA(t),l=[];d.added>0&&l.push(`+${d.added}`),d.removed>0&&l.push(`-${d.removed}`),i=l.length>0?` (${l.join(" ")})`:""}let o=d=>({prefix:" ",body:`${d?"\u25BE":"\u25B8"} Edited ${Ee(Ze(t.path))}${i}`,bodyStyle:"dim"});if(e==="edit")return t.path&&s.push(o(!1)),s;if(r)return t.path&&(s.push(o(!0)),s.push(n.deferredStatus==="error"?{prefix:" ",body:"\u26A0 failed to load diff",bodyStyle:"tool-status-fail"}:{prefix:" ",body:"\u22EF fetching diff\u2026",bodyStyle:"dim"}),s.unshift({body:""})),s;let a=zu(t,{maxLines:1/0});if(a.length===0)return t.path&&s.push(o(!1)),s;t.path&&s.push(o(!0));let c="```diff\n"+a+"\n```";return s.push(...Gs(c)),s.length>0&&s.unshift({body:""}),s}function yy(t){let e=lt(t.oldText).split(`
127
+ `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=eC(r);if(i.length>0){let o=hy(i,s.map(a=>Ee(a)));for(let a of o){let c={prefix:" ",body:a.body,bodyStyle:"code",fillRow:!0};a.ansi&&(c.ansi=!0),e.push(c)}}else for(let o of s)e.push({prefix:" ",body:Ee(o),bodyStyle:"dim"});t.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function wy(t){yy=t>=0?t:0}function zu(t,e,n={}){let s=[],r=t.oldRef!==void 0||t.newRef!==void 0,i;if(r){let d=(t.oldRef?.bytes??0)+(t.newRef?.bytes??0);i=` (~${tC(d)})`}else{let d=sC(t),l=[];d.added>0&&l.push(`+${d.added}`),d.removed>0&&l.push(`-${d.removed}`),i=l.length>0?` (${l.join(" ")})`:""}let o=d=>({prefix:" ",body:`${d?"\u25BE":"\u25B8"} Edited ${Ee(Ze(t.path))}${i}`,bodyStyle:"dim"});if(e==="edit")return t.path&&s.push(o(!1)),s;if(r)return t.path&&(s.push(o(!0)),s.push(n.deferredStatus==="error"?{prefix:" ",body:"\u26A0 failed to load diff",bodyStyle:"tool-status-fail"}:{prefix:" ",body:"\u22EF fetching diff\u2026",bodyStyle:"dim"}),s.unshift({body:""})),s;let a=Ku(t,{maxLines:1/0});if(a.length===0)return t.path&&s.push(o(!1)),s;t.path&&s.push(o(!0));let c="```diff\n"+a+"\n```";return s.push(...Gs(c)),s.length>0&&s.unshift({body:""}),s}function by(t){let e=lt(t.oldText).split(`
128
128
  `),n=lt(t.newText).split(`
129
- `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function XA(t){let{oldLines:e,newLines:n}=yy(t),s=0,r=0;for(let i of wy(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function dy(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function zu(t,e={}){let n=e.maxLines??GA,s=e.contextLines??my,{oldLines:r,newLines:i}=yy(t),o=wy(r,i),a=[];if(Number.isFinite(s)){if(!o.some(f=>f.op!=="="))return"";let l=new Array(o.length).fill(!1);for(let f=0;f<o.length;f++)if(o[f].op!=="="){let p=Math.max(0,f-s),h=Math.min(o.length-1,f+s);for(let m=p;m<=h;m++)l[m]=!0}let u=0;for(;u<o.length;){if(l[u]){a.push(dy(o[u])),u++;continue}let f=u;for(;f<o.length&&!l[f];)f++;let p=f-u;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),u=f}}else for(let d of o)a.push(dy(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=n-1&&d<a.length-1){let u=a.length-d;c.push(`\u2026 ${u} more line${u===1?"":"s"}`);break}c.push(a[d])}return c.join(`
130
- `)}function wy(t,e){let n=0,s=Math.min(t.length,e.length);for(;n<s&&t[n]===e[n];)n++;let r=t.length,i=e.length;for(;r>n&&i>n&&t[r-1]===e[i-1];)r--,i--;let o=[];for(let a=0;a<n;a++)o.push({op:"=",text:t[a]});o.push(...ZA(t.slice(n,r),e.slice(n,i)));for(let a=r;a<t.length;a++)o.push({op:"=",text:t[a]});return o}function ZA(t,e){let n=t.length,s=e.length;if(n===0||s===0){let c=[];for(let d of t)c.push({op:"-",text:d});for(let d of e)c.push({op:"+",text:d});return c}let r=Array.from({length:n+1},()=>new Array(s+1).fill(0));for(let c=n-1;c>=0;c--)for(let d=s-1;d>=0;d--)t[c]===e[d]?r[c][d]=r[c+1][d+1]+1:r[c][d]=Math.max(r[c+1][d],r[c][d+1]);let i=[],o=0,a=0;for(;o<n&&a<s;)t[o]===e[a]?(i.push({op:"=",text:t[o]}),o++,a++):r[o+1][a]>=r[o][a+1]?(i.push({op:"-",text:t[o]}),o++):(i.push({op:"+",text:e[a]}),a++);for(;o<n;)i.push({op:"-",text:t[o]}),o++;for(;a<s;)i.push({op:"+",text:e[a]}),a++;return i}function Ku(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function eC(t){switch(t){case"completed":case"succeeded":case"ok":return"\u2713";case"failed":case"error":return"\u2717";case"rejected":return"\u2298";case"cancelled":return"\u229D";default:return"\u25D0"}}function tC(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"cancelled":return"tool-status-cancelled";default:return"tool-status-running"}}function by(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...Gs(t.plan));let n=t.status;if(n!==void 0){let s=nC(n);s!==null&&e.push(s)}return e}function nC(t){switch(t){case"completed":case"succeeded":case"ok":return{prefix:" ",body:"\u2713 Approved",bodyStyle:"tool-status-ok"};case"failed":case"error":case"rejected":return{prefix:" ",body:"\u2717 Rejected",bodyStyle:"tool-status-fail"};case"cancelled":return{prefix:" ",body:"\u229D Cancelled",bodyStyle:"tool-status-cancelled"};case"pending":case"in_progress":case"running":case"updated":return{prefix:" ",body:"awaiting approval\u2026",bodyStyle:"dim"};default:return null}}function rC(t,e){let n=t.length;if(e<=0||n<=e)return{start:0,end:n};let s=t.findIndex(d=>(d.status??"pending")==="in_progress"),r=t.findIndex(d=>(d.status??"pending")==="pending"),i=s>=0?s:r>=0?r:n-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),c=Math.min(n,a+e);return c-a<e&&(a=Math.max(0,c-e)),{start:a,end:c}}function iC(t,e){let n=t.stopped===!0,r=t.amended===!0?"tool-status-cancelled":"tool-status-fail",o=t.entries.every(p=>(p.status??"pending")==="completed")?"plan-done":n?r:"plan",a=t.entries.length,{start:c,end:d}=rC(t.entries,e),l=d-c<a,u="Plan";if(l){let p=0;for(let m of t.entries)(m.status??"pending")==="completed"&&(p+=1);let h=a-p;u=h===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${h} left`}let f=[{prefix:"\u25A3 ",prefixStyle:o,body:u,bodyStyle:o}];for(let p=c;p<d;p++){let h=t.entries[p];if(!h)continue;let m=h.status??"pending",y=m==="completed"?"[x]":m==="in_progress"?"[~]":"[ ]",b=m==="completed"?"plan-done":m==="in_progress"?n?"plan-pending":"plan":"plan-pending",v=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=qu(v,NA(b));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:b})}return f}function oC(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"in_progress":case"running":case"updated":return"tool-status-running";case"cancelled":return"tool-status-cancelled";default:return"tool-status-pending"}}var uy,HA,UA,nt,JA,YA,GA,my,sC,eo=J(()=>{"use strict";he();Ws();uy=6,HA=2,UA=3;nt=new LA.Instance({level:3}),JA={keyword:nt.blueBright,built_in:nt.cyan,type:nt.cyanBright,literal:nt.blue,number:nt.greenBright,string:nt.yellow,regexp:nt.red,comment:nt.gray,function:nt.yellow,title:nt.yellow,class:nt.yellowBright,attr:nt.cyan,attribute:nt.cyan,variable:nt.white,params:nt.white,meta:nt.magenta,symbol:nt.magenta,addition:nt.greenBright,deletion:nt.redBright,section:nt.cyan,tag:nt.cyan,name:nt.cyanBright};YA={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".jsonc":"json",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".kts":"kotlin",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"csharp",".swift":"swift",".m":"objectivec",".mm":"objectivec",".php":"php",".scala":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".fish":"bash",".ps1":"powershell",".sql":"sql",".html":"xml",".htm":"xml",".xml":"xml",".svg":"xml",".css":"css",".scss":"scss",".sass":"scss",".less":"less",".yaml":"yaml",".yml":"yaml",".toml":"ini",".ini":"ini",".md":"markdown",".markdown":"markdown",".lua":"lua",".pl":"perl",".pm":"perl",".r":"r",".dart":"dart",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".clj":"clojure",".cljs":"clojure",".vim":"vim",".dockerfile":"dockerfile",".diff":"diff",".patch":"diff",".tf":"terraform",".proto":"protobuf",".graphql":"graphql",".gql":"graphql",".el":"lisp"};GA=40,my=Number.POSITIVE_INFINITY;sC=5});import{highlight as aC,supportsLanguage as dC}from"cli-highlight";async function Sy(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
131
- `),process.exit(2));let n=e.fold===!0?"?fold=true":"",s=await Fe(`/v1/sessions/${encodeURIComponent(t)}/diff${n}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await Fe(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,l;try{l=_n(d)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
132
- `),process.exit(1)}let u=Oi(l.history);r=e.fold===!0?u.map(f=>({...f,hunks:Li(f.hunks)})):u}else process.stderr.write(`Daemon returned HTTP ${s.status}
129
+ `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function sC(t){let{oldLines:e,newLines:n}=by(t),s=0,r=0;for(let i of vy(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function ly(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function Ku(t,e={}){let n=e.maxLines??nC,s=e.contextLines??yy,{oldLines:r,newLines:i}=by(t),o=vy(r,i),a=[];if(Number.isFinite(s)){if(!o.some(f=>f.op!=="="))return"";let l=new Array(o.length).fill(!1);for(let f=0;f<o.length;f++)if(o[f].op!=="="){let p=Math.max(0,f-s),h=Math.min(o.length-1,f+s);for(let m=p;m<=h;m++)l[m]=!0}let u=0;for(;u<o.length;){if(l[u]){a.push(ly(o[u])),u++;continue}let f=u;for(;f<o.length&&!l[f];)f++;let p=f-u;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),u=f}}else for(let d of o)a.push(ly(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=n-1&&d<a.length-1){let u=a.length-d;c.push(`\u2026 ${u} more line${u===1?"":"s"}`);break}c.push(a[d])}return c.join(`
130
+ `)}function vy(t,e){let n=0,s=Math.min(t.length,e.length);for(;n<s&&t[n]===e[n];)n++;let r=t.length,i=e.length;for(;r>n&&i>n&&t[r-1]===e[i-1];)r--,i--;let o=[];for(let a=0;a<n;a++)o.push({op:"=",text:t[a]});o.push(...rC(t.slice(n,r),e.slice(n,i)));for(let a=r;a<t.length;a++)o.push({op:"=",text:t[a]});return o}function rC(t,e){let n=t.length,s=e.length;if(n===0||s===0){let c=[];for(let d of t)c.push({op:"-",text:d});for(let d of e)c.push({op:"+",text:d});return c}let r=Array.from({length:n+1},()=>new Array(s+1).fill(0));for(let c=n-1;c>=0;c--)for(let d=s-1;d>=0;d--)t[c]===e[d]?r[c][d]=r[c+1][d+1]+1:r[c][d]=Math.max(r[c+1][d],r[c][d+1]);let i=[],o=0,a=0;for(;o<n&&a<s;)t[o]===e[a]?(i.push({op:"=",text:t[o]}),o++,a++):r[o+1][a]>=r[o][a+1]?(i.push({op:"-",text:t[o]}),o++):(i.push({op:"+",text:e[a]}),a++);for(;o<n;)i.push({op:"-",text:t[o]}),o++;for(;a<s;)i.push({op:"+",text:e[a]}),a++;return i}function Ju(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function iC(t){switch(t){case"completed":case"succeeded":case"ok":return"\u2713";case"failed":case"error":return"\u2717";case"rejected":return"\u2298";case"cancelled":return"\u229D";default:return"\u25D0"}}function oC(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"cancelled":return"tool-status-cancelled";default:return"tool-status-running"}}function Sy(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...Gs(t.plan));let n=t.status;if(n!==void 0){let s=aC(n);s!==null&&e.push(s)}return e}function aC(t){switch(t){case"completed":case"succeeded":case"ok":return{prefix:" ",body:"\u2713 Approved",bodyStyle:"tool-status-ok"};case"failed":case"error":case"rejected":return{prefix:" ",body:"\u2717 Rejected",bodyStyle:"tool-status-fail"};case"cancelled":return{prefix:" ",body:"\u229D Cancelled",bodyStyle:"tool-status-cancelled"};case"pending":case"in_progress":case"running":case"updated":return{prefix:" ",body:"awaiting approval\u2026",bodyStyle:"dim"};default:return null}}function cC(t,e){let n=t.length;if(e<=0||n<=e)return{start:0,end:n};let s=t.findIndex(d=>(d.status??"pending")==="in_progress"),r=t.findIndex(d=>(d.status??"pending")==="pending"),i=s>=0?s:r>=0?r:n-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),c=Math.min(n,a+e);return c-a<e&&(a=Math.max(0,c-e)),{start:a,end:c}}function lC(t,e){let n=t.stopped===!0,r=t.amended===!0?"tool-status-cancelled":"tool-status-fail",o=t.entries.every(p=>(p.status??"pending")==="completed")?"plan-done":n?r:"plan",a=t.entries.length,{start:c,end:d}=cC(t.entries,e),l=d-c<a,u="Plan";if(l){let p=0;for(let m of t.entries)(m.status??"pending")==="completed"&&(p+=1);let h=a-p;u=h===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${h} left`}let f=[{prefix:"\u25A3 ",prefixStyle:o,body:u,bodyStyle:o}];for(let p=c;p<d;p++){let h=t.entries[p];if(!h)continue;let m=h.status??"pending",y=m==="completed"?"[x]":m==="in_progress"?"[~]":"[ ]",b=m==="completed"?"plan-done":m==="in_progress"?n?"plan-pending":"plan":"plan-pending",v=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=Wu(v,qA(b));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:b})}return f}function uC(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"in_progress":case"running":case"updated":return"tool-status-running";case"cancelled":return"tool-status-cancelled";default:return"tool-status-pending"}}var jA,py,zA,KA,nt,XA,ZA,nC,yy,dC,to=J(()=>{"use strict";he();Ws();jA=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/;py=6,zA=2,KA=3;nt=new HA.Instance({level:3}),XA={keyword:nt.blueBright,built_in:nt.cyan,type:nt.cyanBright,literal:nt.blue,number:nt.greenBright,string:nt.yellow,regexp:nt.red,comment:nt.gray,function:nt.yellow,title:nt.yellow,class:nt.yellowBright,attr:nt.cyan,attribute:nt.cyan,variable:nt.white,params:nt.white,meta:nt.magenta,symbol:nt.magenta,addition:nt.greenBright,deletion:nt.redBright,section:nt.cyan,tag:nt.cyan,name:nt.cyanBright};ZA={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".jsonc":"json",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".kts":"kotlin",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"csharp",".swift":"swift",".m":"objectivec",".mm":"objectivec",".php":"php",".scala":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".fish":"bash",".ps1":"powershell",".sql":"sql",".html":"xml",".htm":"xml",".xml":"xml",".svg":"xml",".css":"css",".scss":"scss",".sass":"scss",".less":"less",".yaml":"yaml",".yml":"yaml",".toml":"ini",".ini":"ini",".md":"markdown",".markdown":"markdown",".lua":"lua",".pl":"perl",".pm":"perl",".r":"r",".dart":"dart",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".clj":"clojure",".cljs":"clojure",".vim":"vim",".dockerfile":"dockerfile",".diff":"diff",".patch":"diff",".tf":"terraform",".proto":"protobuf",".graphql":"graphql",".gql":"graphql",".el":"lisp"};nC=40,yy=Number.POSITIVE_INFINITY;dC=5});import{highlight as fC,supportsLanguage as pC}from"cli-highlight";async function Iy(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
131
+ `),process.exit(2));let n=e.fold===!0?"?fold=true":"",s=await Oe(`/v1/sessions/${encodeURIComponent(t)}/diff${n}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await Oe(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,l;try{l=_n(d)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
132
+ `),process.exit(1)}let u=Li(l.history);r=e.fold===!0?u.map(f=>({...f,hunks:Bi(f.hunks)})):u}else process.stderr.write(`Daemon returned HTTP ${s.status}
133
133
  `),process.exit(1);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
134
- `);return}let i=ic({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(Ju(r,a)),await i.flush()}function Ju(t,e){if(t.length===0)return`No file edits found in this session.
135
- `;let n=[],s=[...t].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=uC(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
136
- `:n.join("")}function cC(t){let e=[];for(let n of t.hunks){let s=zu(n,{maxLines:1/0});lC(s)&&e.push({body:s,oldCount:vy(n.oldText),newCount:vy(n.newText)})}return e}function lC(t){if(t.length===0)return!1;for(let e of t.split(`
137
- `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function uC(t,e){let n=cC(t);if(n.length===0)return null;let s=[];s.push(`diff --hydra a/${t.path} b/${t.path}`),t.created?(s.push("new file"),s.push("--- /dev/null"),s.push(`+++ b/${t.path}`)):(s.push(`--- a/${t.path}`),s.push(`+++ b/${t.path}`));let r=n.length;n.forEach((o,a)=>{let c=o.oldCount===0?0:1,d=o.newCount===0?0:1,l=r>1?` edit ${a+1} of ${r}`:"";s.push(`@@ -${c},${o.oldCount} +${d},${o.newCount} @@${l}`),s.push(o.body)});let i=s.join(`
134
+ `);return}let i=ic({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(Vu(r,a)),await i.flush()}function Vu(t,e){if(t.length===0)return`No file edits found in this session.
135
+ `;let n=[],s=[...t].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=gC(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
136
+ `:n.join("")}function hC(t){let e=[];for(let n of t.hunks){let s=Ku(n,{maxLines:1/0});mC(s)&&e.push({body:s,oldCount:ky(n.oldText),newCount:ky(n.newText)})}return e}function mC(t){if(t.length===0)return!1;for(let e of t.split(`
137
+ `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function gC(t,e){let n=hC(t);if(n.length===0)return null;let s=[];s.push(`diff --hydra a/${t.path} b/${t.path}`),t.created?(s.push("new file"),s.push("--- /dev/null"),s.push(`+++ b/${t.path}`)):(s.push(`--- a/${t.path}`),s.push(`+++ b/${t.path}`));let r=n.length;n.forEach((o,a)=>{let c=o.oldCount===0?0:1,d=o.newCount===0?0:1,l=r>1?` edit ${a+1} of ${r}`:"";s.push(`@@ -${c},${o.oldCount} +${d},${o.newCount} @@${l}`),s.push(o.body)});let i=s.join(`
138
138
  `)+`
139
139
 
140
- `;return!e||!dC("diff")?i:aC(i,{language:"diff"})}function vy(t){if(t.length===0)return 0;let e=t.split(`
141
- `);return e[e.length-1]===""&&e.pop(),e.length}var Yu=J(()=>{"use strict";Ys();Mr();Ld();eo();Uu()});async function ky(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
142
- `),process.exit(2));let n=await Fe(`/v1/sessions/${encodeURIComponent(t)}`,{expectStatus:[200,404]}),s=n.status===200?n.body.status:void 0,i=(await Fe(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,o;try{o=_n(i)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
143
- `),process.exit(1)}let a=Gu(o,s??"cold"),c=e.diff===!0,d=null;if(c){let f=Oi(o.history);d=e.fold===!0?f.map(p=>({...p,hunks:Li(p.hunks)})):f}if(e.json){let f={...a};d!==null&&(f.diff=d),process.stdout.write(JSON.stringify(f,null,2)+`
140
+ `;return!e||!pC("diff")?i:fC(i,{language:"diff"})}function ky(t){if(t.length===0)return 0;let e=t.split(`
141
+ `);return e[e.length-1]===""&&e.pop(),e.length}var Yu=J(()=>{"use strict";Vs();Mr();Ld();to();ju()});async function xy(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
142
+ `),process.exit(2));let n=await Oe(`/v1/sessions/${encodeURIComponent(t)}`,{expectStatus:[200,404]}),s=n.status===200?n.body.status:void 0,i=(await Oe(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,o;try{o=_n(i)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
143
+ `),process.exit(1)}let a=Xu(o,s??"cold"),c=e.diff===!0,d=null;if(c){let f=Li(o.history);d=e.fold===!0?f.map(p=>({...p,hunks:Bi(p.hunks)})):f}if(e.json){let f={...a};d!==null&&(f.diff=d),process.stdout.write(JSON.stringify(f,null,2)+`
144
144
  `);return}let l=process.stdout.isTTY===!0,u=!e.noColor&&l;if(c){let f=ic({disabled:e.noPager===!0});f.stream.write(cc(a,e.verbose===!0)),f.stream.write(`
145
- `),f.stream.write(Ju(d??[],u)),await f.flush();return}process.stdout.write(cc(a,e.verbose===!0))}function Gu(t,e){let n=t.session,s=t.history,r=am(s),i=eu(s),o=tu(s),a=n.currentUsage,c=Date.parse(n.createdAt),d=Date.parse(n.updatedAt),l=Number.isFinite(c)&&Number.isFinite(d)?d-c:null;return{sessionId:n.sessionId,...n.upstreamSessionId!==void 0?{upstreamSessionId:n.upstreamSessionId}:{},...n.title!==void 0?{title:n.title}:{},cwd:n.cwd,agentId:n.agentId,...n.currentModel!==void 0?{currentModel:n.currentModel}:{},status:e,createdAt:n.createdAt,updatedAt:n.updatedAt,synopsis:n.synopsis??null,summarizedThroughEntry:n.summarizedThroughEntry??null,turns:r,tools:i,files:o,cost:{amount:a?.costAmount??null,currency:a?.costCurrency??null,cumulative:a?.cumulativeCost??null,inputTokens:a?.used??null,outputTokens:a?.size??null},duration:{totalMs:l},historyEntries:s.length}}function cc(t,e){let n=[],s=a=>a.padEnd(14);n.push(`${s("Session:")}${t.sessionId}`),t.upstreamSessionId&&n.push(`${s("Upstream:")}${t.upstreamSessionId}`),t.title&&n.push(`${s("Title:")}${t.title}`),n.push(`${s("Cwd:")}${t.cwd}`);let r=t.currentModel?` \xB7 ${t.currentModel}`:"";n.push(`${s("Agent:")}${t.agentId}${r}`),n.push(`${s("Status:")}${t.status}`),n.push(`${s("Created:")}${t.createdAt}`),n.push(`${s("Last active:")}${t.updatedAt}`),t.duration.totalMs!==null&&n.push(`${s("Duration:")}${pC(t.duration.totalMs)}`),n.push(`${s("Turns:")}${t.turns}`);let i=[];if(t.cost.amount!==null){let a=t.cost.currency??"USD";i.push(`${a} ${t.cost.amount.toFixed(4)}`)}else if(t.cost.cumulative!==null){let a=t.cost.currency??"USD";i.push(`${a} ${t.cost.cumulative.toFixed(4)} (cumulative)`)}if(t.cost.inputTokens!==null||t.cost.outputTokens!==null){let a=[];t.cost.inputTokens!==null&&a.push(`${t.cost.inputTokens.toLocaleString()} in`),t.cost.outputTokens!==null&&a.push(`${t.cost.outputTokens.toLocaleString()} out`),i.push(a.join(" / "))}if(i.length>0&&n.push(`${s("Cost:")}${i.join(" | ")}`),t.synopsis){n.push(""),n.push("Synopsis:");let a=" ",c=d=>d.padEnd(22);if(t.synopsis.goal&&n.push(`${a}${c("Goal:")}${t.synopsis.goal}`),t.synopsis.outcome&&n.push(`${a}${c("Outcome:")}${t.synopsis.outcome}`),t.synopsis.rejected_approaches&&t.synopsis.rejected_approaches.length>0){n.push(`${a}${c("Rejected approaches:")}`);for(let d of t.synopsis.rejected_approaches)n.push(`${a} - ${d}`)}if(t.synopsis.open_threads&&t.synopsis.open_threads.length>0){n.push(`${a}${c("Open threads:")}`);for(let d of t.synopsis.open_threads)n.push(`${a} - ${d}`)}if(t.synopsis.files_touched&&t.synopsis.files_touched.length>0){n.push(`${a}${c("Files touched:")}`);for(let d of t.synopsis.files_touched)n.push(`${a} - ${d}`)}if(t.synopsis.tools_used&&t.synopsis.tools_used.length>0){n.push(`${a}${c("Tools used:")}`);for(let d of t.synopsis.tools_used)n.push(`${a} - ${d}`)}}else n.push(""),n.push("Synopsis: (none yet \u2014 generated on idle-close or daemon shutdown)");if(t.tools.length>0){n.push("");let a=t.tools.reduce((l,u)=>l+u.count,0);n.push(`Tools (${a} calls):`);let c=e?t.tools:t.tools.slice(0,Vu),d=Math.max(...c.map(l=>l.name.length),4);for(let l of c)n.push(` ${l.name.padEnd(d)} ${l.count}`);!e&&t.tools.length>Vu&&n.push(` ... ${t.tools.length-Vu} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>fC.has(l.name)),d=c.reduce((l,u)=>l+u.count,0);return{path:a.path,count:d,byTool:c}}).filter(a=>a.count>0);if(o.length>0){n.push("");let a=e?"Files touched":"Files edited";n.push(`${a} (${o.length}):`);let c=e?o:o.slice(0,Qu),d=Math.max(...c.map(l=>l.path.length),4);for(let l of c)if(e){let u=l.byTool.map(f=>`${f.name}\xD7${f.count}`).join(", ");n.push(` ${l.path.padEnd(d)} ${l.count} (${u})`)}else n.push(` ${l.path.padEnd(d)} ${l.count}`);!e&&o.length>Qu&&n.push(` ... ${o.length-Qu} more (use --verbose to see all)`)}return n.join(`
145
+ `),f.stream.write(Vu(d??[],u)),await f.flush();return}process.stdout.write(cc(a,e.verbose===!0))}function Xu(t,e){let n=t.session,s=t.history,r=cm(s),i=tu(s),o=nu(s),a=n.currentUsage,c=Date.parse(n.createdAt),d=Date.parse(n.updatedAt),l=Number.isFinite(c)&&Number.isFinite(d)?d-c:null;return{sessionId:n.sessionId,...n.upstreamSessionId!==void 0?{upstreamSessionId:n.upstreamSessionId}:{},...n.title!==void 0?{title:n.title}:{},cwd:n.cwd,agentId:n.agentId,...n.currentModel!==void 0?{currentModel:n.currentModel}:{},status:e,createdAt:n.createdAt,updatedAt:n.updatedAt,synopsis:n.synopsis??null,summarizedThroughEntry:n.summarizedThroughEntry??null,turns:r,tools:i,files:o,cost:{amount:a?.costAmount??null,currency:a?.costCurrency??null,cumulative:a?.cumulativeCost??null,inputTokens:a?.used??null,outputTokens:a?.size??null},duration:{totalMs:l},historyEntries:s.length}}function cc(t,e){let n=[],s=a=>a.padEnd(14);n.push(`${s("Session:")}${t.sessionId}`),t.upstreamSessionId&&n.push(`${s("Upstream:")}${t.upstreamSessionId}`),t.title&&n.push(`${s("Title:")}${t.title}`),n.push(`${s("Cwd:")}${t.cwd}`);let r=t.currentModel?` \xB7 ${t.currentModel}`:"";n.push(`${s("Agent:")}${t.agentId}${r}`),n.push(`${s("Status:")}${t.status}`),n.push(`${s("Created:")}${t.createdAt}`),n.push(`${s("Last active:")}${t.updatedAt}`),t.duration.totalMs!==null&&n.push(`${s("Duration:")}${wC(t.duration.totalMs)}`),n.push(`${s("Turns:")}${t.turns}`);let i=[];if(t.cost.amount!==null){let a=t.cost.currency??"USD";i.push(`${a} ${t.cost.amount.toFixed(4)}`)}else if(t.cost.cumulative!==null){let a=t.cost.currency??"USD";i.push(`${a} ${t.cost.cumulative.toFixed(4)} (cumulative)`)}if(t.cost.inputTokens!==null||t.cost.outputTokens!==null){let a=[];t.cost.inputTokens!==null&&a.push(`${t.cost.inputTokens.toLocaleString()} in`),t.cost.outputTokens!==null&&a.push(`${t.cost.outputTokens.toLocaleString()} out`),i.push(a.join(" / "))}if(i.length>0&&n.push(`${s("Cost:")}${i.join(" | ")}`),t.synopsis){n.push(""),n.push("Synopsis:");let a=" ",c=d=>d.padEnd(22);if(t.synopsis.goal&&n.push(`${a}${c("Goal:")}${t.synopsis.goal}`),t.synopsis.outcome&&n.push(`${a}${c("Outcome:")}${t.synopsis.outcome}`),t.synopsis.rejected_approaches&&t.synopsis.rejected_approaches.length>0){n.push(`${a}${c("Rejected approaches:")}`);for(let d of t.synopsis.rejected_approaches)n.push(`${a} - ${d}`)}if(t.synopsis.open_threads&&t.synopsis.open_threads.length>0){n.push(`${a}${c("Open threads:")}`);for(let d of t.synopsis.open_threads)n.push(`${a} - ${d}`)}if(t.synopsis.files_touched&&t.synopsis.files_touched.length>0){n.push(`${a}${c("Files touched:")}`);for(let d of t.synopsis.files_touched)n.push(`${a} - ${d}`)}if(t.synopsis.tools_used&&t.synopsis.tools_used.length>0){n.push(`${a}${c("Tools used:")}`);for(let d of t.synopsis.tools_used)n.push(`${a} - ${d}`)}}else n.push(""),n.push("Synopsis: (none yet \u2014 generated on idle-close or daemon shutdown)");if(t.tools.length>0){n.push("");let a=t.tools.reduce((l,u)=>l+u.count,0);n.push(`Tools (${a} calls):`);let c=e?t.tools:t.tools.slice(0,Qu),d=Math.max(...c.map(l=>l.name.length),4);for(let l of c)n.push(` ${l.name.padEnd(d)} ${l.count}`);!e&&t.tools.length>Qu&&n.push(` ... ${t.tools.length-Qu} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>yC.has(l.name)),d=c.reduce((l,u)=>l+u.count,0);return{path:a.path,count:d,byTool:c}}).filter(a=>a.count>0);if(o.length>0){n.push("");let a=e?"Files touched":"Files edited";n.push(`${a} (${o.length}):`);let c=e?o:o.slice(0,Gu),d=Math.max(...c.map(l=>l.path.length),4);for(let l of c)if(e){let u=l.byTool.map(f=>`${f.name}\xD7${f.count}`).join(", ");n.push(` ${l.path.padEnd(d)} ${l.count} (${u})`)}else n.push(` ${l.path.padEnd(d)} ${l.count}`);!e&&o.length>Gu&&n.push(` ... ${o.length-Gu} more (use --verbose to see all)`)}return n.join(`
146
146
  `)+`
147
- `}function pC(t){if(t<0)return"0s";let e=Math.floor(t/1e3),n=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,o=[];return n>0&&o.push(`${n}d`),s>0&&o.push(`${s}h`),r>0&&o.push(`${r}m`),(o.length===0||i>0)&&o.push(`${i}s`),o.join(" ")}var Vu,Qu,fC,Xu=J(()=>{"use strict";Ys();Mr();nu();Ld();Uu();Yu();Vu=10,Qu=15,fC=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var Uy={};Zc(Uy,{assertKnownAgent:()=>fc,resolveAgentIdOrExit:()=>tf,runAgentsAdd:()=>df,runAgentsInstall:()=>nf,runAgentsList:()=>ef,runAgentsLogs:()=>rf,runAgentsPin:()=>af,runAgentsRefresh:()=>pc,runAgentsRemove:()=>cf,runAgentsSet:()=>of,runAgentsSync:()=>sf,runRegistryPin:()=>hc});async function ef(){let e=(await Fe("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
148
- `);return}let n=e.agents.map(a=>({id:a.id,name:a.name,version:a.version,source:a.source??"registry",distributions:a.distributions.join(","),installed:a.installed,description:a.description??""})),s={id:"ID",name:"NAME",version:"VERSION",source:"SOURCE",distributions:"DIST",installed:"INSTALLED",description:"DESCRIPTION"},r={id:gs(s.id,n.map(a=>a.id)),name:gs(s.name,n.map(a=>a.name)),version:gs(s.version,n.map(a=>a.version)),source:gs(s.source,n.map(a=>a.source)),distributions:gs(s.distributions,n.map(a=>a.distributions)),installed:gs(s.installed,n.map(a=>a.installed))},i=a=>[a.id.padEnd(r.id),a.name.padEnd(r.name),a.version.padEnd(r.version),a.source.padEnd(r.source),a.distributions.padEnd(r.distributions),a.installed.padEnd(r.installed),a.description].join(" ");process.stdout.write(i(s)+`
147
+ `}function wC(t){if(t<0)return"0s";let e=Math.floor(t/1e3),n=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,o=[];return n>0&&o.push(`${n}d`),s>0&&o.push(`${s}h`),r>0&&o.push(`${r}m`),(o.length===0||i>0)&&o.push(`${i}s`),o.join(" ")}var Qu,Gu,yC,Zu=J(()=>{"use strict";Vs();Mr();su();Ld();ju();Yu();Qu=10,Gu=15,yC=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var qy={};el(qy,{assertKnownAgent:()=>fc,resolveAgentIdOrExit:()=>nf,runAgentsAdd:()=>cf,runAgentsInstall:()=>sf,runAgentsList:()=>tf,runAgentsLogs:()=>of,runAgentsPin:()=>df,runAgentsRefresh:()=>pc,runAgentsRemove:()=>lf,runAgentsSet:()=>af,runAgentsSync:()=>rf,runRegistryPin:()=>hc});async function tf(){let e=(await Oe("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
148
+ `);return}let n=e.agents.map(a=>({id:a.id,name:a.name,version:a.version,source:a.source??"registry",distributions:a.distributions.join(","),installed:a.installed,description:a.description??""})),s={id:"ID",name:"NAME",version:"VERSION",source:"SOURCE",distributions:"DIST",installed:"INSTALLED",description:"DESCRIPTION"},r={id:ys(s.id,n.map(a=>a.id)),name:ys(s.name,n.map(a=>a.name)),version:ys(s.version,n.map(a=>a.version)),source:ys(s.source,n.map(a=>a.source)),distributions:ys(s.distributions,n.map(a=>a.distributions)),installed:ys(s.installed,n.map(a=>a.installed))},i=a=>[a.id.padEnd(r.id),a.name.padEnd(r.name),a.version.padEnd(r.version),a.source.padEnd(r.source),a.distributions.padEnd(r.distributions),a.installed.padEnd(r.installed),a.description].join(" ");process.stdout.write(i(s)+`
149
149
  `);for(let a of n)process.stdout.write(i(a)+`
150
- `);let o=e.fetchedAt!==void 0?` (synced ${Ki(e.fetchedAt)})`:"";process.stdout.write(`
150
+ `);let o=e.fetchedAt!==void 0?` (synced ${Ji(e.fetchedAt)})`:"";process.stdout.write(`
151
151
  Registry version: ${e.version}${o}
152
- `)}async function fc(t){if((await be()).agents[t]!==void 0)return;let n;try{let r=await Fe("/v1/agents",{rethrowNetworkError:!0});if(!r.ok)return;n=r.body.agents.map(o=>o.id)}catch{return}if(n.includes(t))return;let s=t.toLowerCase();s.length>0&&n.filter(i=>i.toLowerCase().startsWith(s)).length===1||(process.stderr.write(`hydra-acp: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
153
- `),process.exit(2))}async function tf(t,e){let n;try{let r=await Fe("/v1/agents",{rethrowNetworkError:!0});if(!r.ok)return t;n=r.body.agents.map(o=>o.id)}catch{return t}if(n.includes(t))return t;let s=t.toLowerCase();if(s.length>0){let r=n.filter(i=>i.toLowerCase().startsWith(s));if(r.length===1)return r[0];r.length>1&&(process.stderr.write(`${e}: '${t}' is ambiguous (matches ${r.join(", ")}).
152
+ `)}async function fc(t){if((await be()).agents[t]!==void 0)return;let n;try{let r=await Oe("/v1/agents",{rethrowNetworkError:!0});if(!r.ok)return;n=r.body.agents.map(o=>o.id)}catch{return}if(n.includes(t))return;let s=t.toLowerCase();s.length>0&&n.filter(i=>i.toLowerCase().startsWith(s)).length===1||(process.stderr.write(`hydra-acp: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
153
+ `),process.exit(2))}async function nf(t,e){let n;try{let r=await Oe("/v1/agents",{rethrowNetworkError:!0});if(!r.ok)return t;n=r.body.agents.map(o=>o.id)}catch{return t}if(n.includes(t))return t;let s=t.toLowerCase();if(s.length>0){let r=n.filter(i=>i.toLowerCase().startsWith(s));if(r.length===1)return r[0];r.length>1&&(process.stderr.write(`${e}: '${t}' is ambiguous (matches ${r.join(", ")}).
154
154
  `),process.exit(2))}process.stderr.write(`${e}: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
155
- `),process.exit(2)}async function nf(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
156
- `),process.exit(2);return}let e=await tf(t,"hydra agent install");process.stdout.write(`Installing ${e}\u2026
157
- `);let s=(await Fe(`/v1/agents/${encodeURIComponent(e)}/install`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent install ${t}:`})).body;if(!s.installed){process.stdout.write(`${s.agentId} (${s.version}, ${s.distribution}): ${s.message??"nothing to install"}
155
+ `),process.exit(2)}async function sf(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
156
+ `),process.exit(2);return}let e=await nf(t,"hydra agent install");process.stdout.write(`Installing ${e}\u2026
157
+ `);let s=(await Oe(`/v1/agents/${encodeURIComponent(e)}/install`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent install ${t}:`})).body;if(!s.installed){process.stdout.write(`${s.agentId} (${s.version}, ${s.distribution}): ${s.message??"nothing to install"}
158
158
  `);return}process.stdout.write(`Installed ${s.agentId} (${s.version}, ${s.distribution})
159
159
  `),s.command&&process.stdout.write(` \u2192 ${s.command}
160
- `)}async function sf(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
161
- `),process.exit(2);return}let e=await tf(t,"hydra agent sync"),s=(await Fe(`/v1/agents/${encodeURIComponent(e)}/sync`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent sync ${t}:`})).body;if(s.synced.length===0){process.stdout.write(`Nothing new to sync (${s.skipped} already tracked).
162
- `);return}let r=s.synced.map(c=>({id:c.sessionId,upstream:c.upstreamSessionId,cwd:c.cwd,title:c.title??"-"})),i={id:"ID",upstream:"UPSTREAM",cwd:"CWD",title:"TITLE"},o={id:gs(i.id,r.map(c=>c.id)),upstream:gs(i.upstream,r.map(c=>c.upstream)),cwd:gs(i.cwd,r.map(c=>c.cwd))},a=c=>[c.id.padEnd(o.id),c.upstream.padEnd(o.upstream),c.cwd.padEnd(o.cwd),c.title].join(" ");process.stdout.write(a(i)+`
160
+ `)}async function rf(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
161
+ `),process.exit(2);return}let e=await nf(t,"hydra agent sync"),s=(await Oe(`/v1/agents/${encodeURIComponent(e)}/sync`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent sync ${t}:`})).body;if(s.synced.length===0){process.stdout.write(`Nothing new to sync (${s.skipped} already tracked).
162
+ `);return}let r=s.synced.map(c=>({id:c.sessionId,upstream:c.upstreamSessionId,cwd:c.cwd,title:c.title??"-"})),i={id:"ID",upstream:"UPSTREAM",cwd:"CWD",title:"TITLE"},o={id:ys(i.id,r.map(c=>c.id)),upstream:ys(i.upstream,r.map(c=>c.upstream)),cwd:ys(i.cwd,r.map(c=>c.cwd))},a=c=>[c.id.padEnd(o.id),c.upstream.padEnd(o.upstream),c.cwd.padEnd(o.cwd),c.title].join(" ");process.stdout.write(a(i)+`
163
163
  `);for(let c of r)process.stdout.write(a(c)+`
164
164
  `);process.stdout.write(`
165
165
  Synced ${s.synced.length} session(s); skipped ${s.skipped} already tracked.
166
- `)}async function rf(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
167
- `),process.exit(2);return}let n=_.agentLogFile(t);await qi(n,e,"No log file (agent never ran?)")}async function of(t,e){let n=await be();if(!t){let c=await Dy()??Zu(await Ji());process.stdout.write(`${Ny(c)}
168
- `);return}let s;try{let a=await Fe("/v1/agents",{rethrowNetworkError:!0});a.ok&&(s=a.body.agents.map(d=>d.id))}catch{}if(!(n.agents[t]!==void 0)&&s!==void 0&&!s.includes(t)){let a=t.toLowerCase(),c=a.length>0?s.filter(d=>d.toLowerCase().startsWith(a)):[];if(c.length===1)t=c[0];else if(c.length>1){process.stderr.write(`hydra agent set: '${t}' is ambiguous (matches ${c.join(", ")}).
166
+ `)}async function of(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
167
+ `),process.exit(2);return}let n=_.agentLogFile(t);await Wi(n,e,"No log file (agent never ran?)")}async function af(t,e){let n=await be();if(!t){let c=await Uy()??ef(await Vi());process.stdout.write(`${Hy(c)}
168
+ `);return}let s;try{let a=await Oe("/v1/agents",{rethrowNetworkError:!0});a.ok&&(s=a.body.agents.map(d=>d.id))}catch{}if(!(n.agents[t]!==void 0)&&s!==void 0&&!s.includes(t)){let a=t.toLowerCase(),c=a.length>0?s.filter(d=>d.toLowerCase().startsWith(a)):[];if(c.length===1)t=c[0];else if(c.length>1){process.stderr.write(`hydra agent set: '${t}' is ambiguous (matches ${c.join(", ")}).
169
169
  `),process.exit(1);return}else{process.stderr.write(`hydra agent set: '${t}' is not in the registry or config.agents. Known ids: ${s.join(", ")}
170
- `),process.exit(1);return}}e!==void 0?await bp(t,e):await ja(t);let i=Zu(await Ji());e!==void 0&&t!==i.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
171
- `),process.stdout.write(`${Ny(i)}
172
- `);let o=await Dy();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${Hy(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
173
- `))}function Ny(t){return`Default agent is ${Hy(t)}`}function Hy(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function Zu(t){let e=typeof t.defaultAgent=="string"?t.defaultAgent:"(unset)",s=(t.defaultModels&&typeof t.defaultModels=="object"?t.defaultModels:{})[e];return typeof s=="string"?{agent:e,model:s}:{agent:e}}async function Dy(){try{let t=await Fe("/v1/config",{rethrowNetworkError:!0});return t.ok?Zu(t.body):void 0}catch{return}}async function pc(){let e=(await Fe("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
174
- `)}async function af(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
175
- `),process.exit(2);return}await vp(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
170
+ `),process.exit(1);return}}e!==void 0?await vp(t,e):await qa(t);let i=ef(await Vi());e!==void 0&&t!==i.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
171
+ `),process.stdout.write(`${Hy(i)}
172
+ `);let o=await Uy();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${jy(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
173
+ `))}function Hy(t){return`Default agent is ${jy(t)}`}function jy(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function ef(t){let e=typeof t.defaultAgent=="string"?t.defaultAgent:"(unset)",s=(t.defaultModels&&typeof t.defaultModels=="object"?t.defaultModels:{})[e];return typeof s=="string"?{agent:e,model:s}:{agent:e}}async function Uy(){try{let t=await Oe("/v1/config",{rethrowNetworkError:!0});return t.ok?ef(t.body):void 0}catch{return}}async function pc(){let e=(await Oe("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
174
+ `)}async function df(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
175
+ `),process.exit(2);return}await Sp(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
176
176
  `):process.stdout.write(`Pinned ${t} to ${e}.
177
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function df(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
177
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function cf(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
178
178
  `),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(t)){process.stderr.write(`Invalid agent id '${t}': must match [A-Za-z0-9._-]+
179
- `),process.exit(2);return}let n=Xd(e,"agent"),s=n.command,r={};s!==void 0&&(r.command=s),n.args.length>0&&(r.args=n.args),Object.keys(n.env).length>0&&(r.env=n.env),await rl(t,r);let i=s??`${t} (default \u2014 resolved off PATH)`;process.stdout.write(`Local agent ${t} \u2192 ${i}${n.args.length>0?" "+n.args.join(" "):""}
180
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function cf(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
181
- `),process.exit(2);return}await rl(t,void 0),process.stdout.write(`Removed local agent ${t}.
182
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function hc(t){await Sp(t),process.stdout.write(t?"Registry pinned to the on-disk cache. `hydra-acp agent refresh` still forces a fetch.\n":`Registry unpinned \u2014 the daemon will re-fetch per registry.ttlHours.
183
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function gs(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}var lf=J(()=>{"use strict";Ve();he();sa();Ys()});var mc,ys,no,ca,jy,la,uf,gc,Dr,qy,Hr,Wy,Ur,zy,jr,so,ro,Ky,io,Jy,Yy,Vy,ff,Qy,yc,wc,ua,Gy,Xy,fa=J(()=>{"use strict";mc="\x1B[?2004h",ys="\x1B[?2004l",no="\x1B[200~",ca="\x1B[201~",jy="\x1B[?1049l",la="\x1B[?7h",uf="\x1B[?7l",gc="\x1B[?25h",Dr="\x1B[?1l",qy="\x1B[>1u",Hr="\x1B[<u",Wy="\x1B[>4;2m",Ur="\x1B[>4;0m",zy="\x1B[>5;1m",jr="\x1B[>5;0m",so="\x1B[?1000l",ro="\x1B[?1002l",Ky="\x1B[?1003l",io="\x1B[?1006l",Jy="\x1B[?1015l",Yy="\x1B[?w",Vy="\x1B[=24;1w",ff="\x1B[=0;0w",Qy="\x1B]22;pointer\x07",yc="\x1B]22;default\x07",wc="\x1B[?1004h",ua="\x1B[?1004l",Gy="\x1B[?2026h",Xy="\x1B[?2026l"});function $n(){process.stdout.write(Hr),process.stdout.write(ys),process.stdout.write(Ur),process.stdout.write(jr),process.stdout.write(so),process.stdout.write(ro),process.stdout.write(io),process.stdout.write(Dr),process.stdout.write("\x1B>")}function an(t){return t.width??80}function ws(t){return t.height??24}function Fn(t,e){let n=an(t),s=ws(t),r=e.contentWidth??mC,i=Math.max(10,n-4),o=Math.min(r,i),a=o+2,c=Math.max(1,Math.min(e.contentHeight,s-4)),d=c+2,l=Math.max(1,Math.floor((n-a)/2)+1),u=Math.max(1,Math.floor((s-d)/2)+1);t.moveTo(1,1).eraseDisplayBelow();let f=Zy.repeat(a-2),p=vC(f,e.title);t.moveTo(l,u),t.dim.noFormat(gC),SC(t,p),t.dim.noFormat(yC);for(let h=1;h<=c;h++)t.moveTo(l,u+h),t.dim.noFormat(ew),t.moveTo(l+a-1,u+h),t.dim.noFormat(ew);return t.moveTo(l,u+d-1),t.dim.noFormat(wC+Zy.repeat(a-2)+bC),{x:l,y:u,w:a,h:d,contentX:l+1,contentY:u+1,contentW:o,contentH:c}}function vC(t,e){if(!e)return{dashes:t};let n=` ${e} `;if(n.length+4>t.length)return{dashes:t};let s=2;return{dashes:t.slice(0,s)+" ".repeat(n.length)+t.slice(s+n.length),title:{offset:s,text:n}}}function SC(t,e){if(!e.title){t.dim.noFormat(e.dashes);return}t.dim.noFormat(e.dashes.slice(0,e.title.offset)),t.brightCyan.noFormat(e.title.text),t.dim.noFormat(e.dashes.slice(e.title.offset+e.title.text.length))}function ze(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function bc(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function Gn(t){let{term:e,render:n,onKey:s,onResize:r}=t,i=t.hideCursor!==!1;return n(),i&&e.hideCursor(),await new Promise(o=>{let a=!1,c=()=>{a||(r??n)()},d=(f,p,h)=>{a||s(f,p,h,u)},l=()=>{a||(a=!0,e.off("key",d),e.off("resize",c),e.grabInput(!1),se({src:"grab",site:"runModalPrompt.cleanup",on:!1}),e.hideCursor(!1),e.moveTo(1,1).eraseDisplayBelow())},u=f=>{l(),o(f)};e.grabInput({}),se({src:"grab",site:"runModalPrompt.install",on:!0}),e.on("key",d),e.on("resize",c)})}var mC,Zy,ew,gC,yC,wC,bC,qr=J(()=>{"use strict";Cr();fa();mC=64,Zy="\u2500",ew="\u2502",gC="\u250C",yC="\u2510",wC="\u2514",bC="\u2518"});function tw(t){let e=(t.name&&t.name.length>0?t.name:void 0)??(t.description&&t.description.length>0?t.description:void 0);return e?`${e} (${t.id})`:t.id}function xC(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??kC,footer:IC};if(e?.command&&(s.command=e.command),e?.url&&(s.url=e.url),n&&n.length>0){s.authMethods=n;let r=n.map((c,d)=>({index:d,label:`[${d+1}] ${tw(c)}`,method:c}));s.methodLines=r;let i=Math.min(n.length,9),o=i===1?"[1]":`[1\u2026${i}]`,a=n.length===1?" \xB7 [Enter] choose":"";s.footer=`${o} choose method${a} \xB7 [r] retry \xB7 [Esc] back`}return s}function AC(t,e,n=0){if(t==="CTRL_C"||t==="CTRL_D")return{kind:"cancel"};if(t==="ESCAPE")return{kind:"back"};if(t==="ENTER"||t==="KP_ENTER")return n===1?{kind:"selectMethod",index:0}:{kind:"retry"};if(e?.isCharacter&&/^[1-9]$/.test(t)){let s=Number(t)-1;return s<n?{kind:"selectMethod",index:s}:{kind:"ignore"}}return e?.isCharacter&&t.toLowerCase()==="r"?{kind:"retry"}:{kind:"ignore"}}function CC(t){return typeof t!="object"||t===null?!1:t.code===z.AuthRequired}function nw(t){if(typeof t!="object"||t===null)return;let e=t.data;if(typeof e!="object"||e===null)return;let n=e._meta;if(typeof n!="object"||n===null)return;let s=n[Tt];if(!(typeof s!="object"||s===null))return s}function RC(t){let e=nw(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function TC(t){let e=nw(t);if(!e)return;let n=e.authMethods;if(!Array.isArray(n))return;let s=[];for(let r of n){if(typeof r!="object"||r===null)continue;let i=r.id;if(typeof i!="string"||i.length===0)continue;let o=r.description,a=r.type,c=r.name,d=r._meta,l={id:i,description:typeof o=="string"?o:""};(a==="agent"||a==="terminal")&&(l.type=a),typeof c=="string"&&(l.name=c),d!==null&&typeof d=="object"&&!Array.isArray(d)&&(l._meta=d),s.push(l)}return s.length>0?s:void 0}async function sw(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!CC(e))throw e;let n=RC(e)??t.fallbackAgentId??"",s=TC(e),r=await t.resolveOnboarding(n),i=await t.showBanner(n,r,s);if(i==="back")return{kind:"back"};if(i==="cancel")return{kind:"cancel"}}}async function EC(t,e,n){t.grabInput(!1),se({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),$n(),t.moveTo(1,1).eraseDisplayBelow();let s=`\u2500 Running ${e.command} ${e.args.join(" ")} \u2014 finish setup, then return to hydra \u2500`;process.stdout.write(s+`
179
+ `),process.exit(2);return}let n=Xd(e,"agent"),s=n.command,r={};s!==void 0&&(r.command=s),n.args.length>0&&(r.args=n.args),Object.keys(n.env).length>0&&(r.env=n.env),await il(t,r);let i=s??`${t} (default \u2014 resolved off PATH)`;process.stdout.write(`Local agent ${t} \u2192 ${i}${n.args.length>0?" "+n.args.join(" "):""}
180
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function lf(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
181
+ `),process.exit(2);return}await il(t,void 0),process.stdout.write(`Removed local agent ${t}.
182
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function hc(t){await kp(t),process.stdout.write(t?"Registry pinned to the on-disk cache. `hydra-acp agent refresh` still forces a fetch.\n":`Registry unpinned \u2014 the daemon will re-fetch per registry.ttlHours.
183
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function ys(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}var uf=J(()=>{"use strict";Ge();he();ra();Vs()});var mc,ws,so,la,Wy,ua,ff,gc,Dr,zy,Hr,Ky,Ur,Jy,jr,ro,io,Vy,oo,Yy,Qy,Gy,pf,Xy,yc,wc,fa,Zy,ew,pa=J(()=>{"use strict";mc="\x1B[?2004h",ws="\x1B[?2004l",so="\x1B[200~",la="\x1B[201~",Wy="\x1B[?1049l",ua="\x1B[?7h",ff="\x1B[?7l",gc="\x1B[?25h",Dr="\x1B[?1l",zy="\x1B[>1u",Hr="\x1B[<u",Ky="\x1B[>4;2m",Ur="\x1B[>4;0m",Jy="\x1B[>5;1m",jr="\x1B[>5;0m",ro="\x1B[?1000l",io="\x1B[?1002l",Vy="\x1B[?1003l",oo="\x1B[?1006l",Yy="\x1B[?1015l",Qy="\x1B[?w",Gy="\x1B[=24;1w",pf="\x1B[=0;0w",Xy="\x1B]22;pointer\x07",yc="\x1B]22;default\x07",wc="\x1B[?1004h",fa="\x1B[?1004l",Zy="\x1B[?2026h",ew="\x1B[?2026l"});function $n(){process.stdout.write(Hr),process.stdout.write(ws),process.stdout.write(Ur),process.stdout.write(jr),process.stdout.write(ro),process.stdout.write(io),process.stdout.write(oo),process.stdout.write(Dr),process.stdout.write("\x1B>")}function an(t){return t.width??80}function bs(t){return t.height??24}function On(t,e){let n=an(t),s=bs(t),r=e.contentWidth??vC,i=Math.max(10,n-4),o=Math.min(r,i),a=o+2,c=Math.max(1,Math.min(e.contentHeight,s-4)),d=c+2,l=Math.max(1,Math.floor((n-a)/2)+1),u=Math.max(1,Math.floor((s-d)/2)+1);t.moveTo(1,1).eraseDisplayBelow();let f=tw.repeat(a-2),p=AC(f,e.title);t.moveTo(l,u),t.dim.noFormat(SC),CC(t,p),t.dim.noFormat(kC);for(let h=1;h<=c;h++)t.moveTo(l,u+h),t.dim.noFormat(nw),t.moveTo(l+a-1,u+h),t.dim.noFormat(nw);return t.moveTo(l,u+d-1),t.dim.noFormat(IC+tw.repeat(a-2)+xC),{x:l,y:u,w:a,h:d,contentX:l+1,contentY:u+1,contentW:o,contentH:c}}function AC(t,e){if(!e)return{dashes:t};let n=` ${e} `;if(n.length+4>t.length)return{dashes:t};let s=2;return{dashes:t.slice(0,s)+" ".repeat(n.length)+t.slice(s+n.length),title:{offset:s,text:n}}}function CC(t,e){if(!e.title){t.dim.noFormat(e.dashes);return}t.dim.noFormat(e.dashes.slice(0,e.title.offset)),t.brightCyan.noFormat(e.title.text),t.dim.noFormat(e.dashes.slice(e.title.offset+e.title.text.length))}function Ke(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function bc(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function Gn(t){let{term:e,render:n,onKey:s,onResize:r}=t,i=t.hideCursor!==!1;return n(),i&&e.hideCursor(),await new Promise(o=>{let a=!1,c=()=>{a||(r??n)()},d=(f,p,h)=>{a||s(f,p,h,u)},l=()=>{a||(a=!0,e.off("key",d),e.off("resize",c),e.grabInput(!1),se({src:"grab",site:"runModalPrompt.cleanup",on:!1}),e.hideCursor(!1),e.moveTo(1,1).eraseDisplayBelow())},u=f=>{l(),o(f)};e.grabInput({}),se({src:"grab",site:"runModalPrompt.install",on:!0}),e.on("key",d),e.on("resize",c)})}var vC,tw,nw,SC,kC,IC,xC,qr=J(()=>{"use strict";Cr();pa();vC=64,tw="\u2500",nw="\u2502",SC="\u250C",kC="\u2510",IC="\u2514",xC="\u2518"});function sw(t){let e=(t.name&&t.name.length>0?t.name:void 0)??(t.description&&t.description.length>0?t.description:void 0);return e?`${e} (${t.id})`:t.id}function EC(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??RC,footer:TC};if(e?.command&&(s.command=e.command),e?.url&&(s.url=e.url),n&&n.length>0){s.authMethods=n;let r=n.map((c,d)=>({index:d,label:`[${d+1}] ${sw(c)}`,method:c}));s.methodLines=r;let i=Math.min(n.length,9),o=i===1?"[1]":`[1\u2026${i}]`,a=n.length===1?" \xB7 [Enter] choose":"";s.footer=`${o} choose method${a} \xB7 [r] retry \xB7 [Esc] back`}return s}function PC(t,e,n=0){if(t==="CTRL_C"||t==="CTRL_D")return{kind:"cancel"};if(t==="ESCAPE")return{kind:"back"};if(t==="ENTER"||t==="KP_ENTER")return n===1?{kind:"selectMethod",index:0}:{kind:"retry"};if(e?.isCharacter&&/^[1-9]$/.test(t)){let s=Number(t)-1;return s<n?{kind:"selectMethod",index:s}:{kind:"ignore"}}return e?.isCharacter&&t.toLowerCase()==="r"?{kind:"retry"}:{kind:"ignore"}}function MC(t){return typeof t!="object"||t===null?!1:t.code===z.AuthRequired}function rw(t){if(typeof t!="object"||t===null)return;let e=t.data;if(typeof e!="object"||e===null)return;let n=e._meta;if(typeof n!="object"||n===null)return;let s=n[Tt];if(!(typeof s!="object"||s===null))return s}function _C(t){let e=rw(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function $C(t){let e=rw(t);if(!e)return;let n=e.authMethods;if(!Array.isArray(n))return;let s=[];for(let r of n){if(typeof r!="object"||r===null)continue;let i=r.id;if(typeof i!="string"||i.length===0)continue;let o=r.description,a=r.type,c=r.name,d=r._meta,l={id:i,description:typeof o=="string"?o:""};(a==="agent"||a==="terminal")&&(l.type=a),typeof c=="string"&&(l.name=c),d!==null&&typeof d=="object"&&!Array.isArray(d)&&(l._meta=d),s.push(l)}return s.length>0?s:void 0}async function iw(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!MC(e))throw e;let n=_C(e)??t.fallbackAgentId??"",s=$C(e),r=await t.resolveOnboarding(n),i=await t.showBanner(n,r,s);if(i==="back")return{kind:"back"};if(i==="cancel")return{kind:"cancel"}}}async function OC(t,e,n){t.grabInput(!1),se({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),$n(),t.moveTo(1,1).eraseDisplayBelow();let s=`\u2500 Running ${e.command} ${e.args.join(" ")} \u2014 finish setup, then return to hydra \u2500`;process.stdout.write(s+`
184
184
  `);let r=n?.spawn??(await import("child_process")).spawn;return await new Promise(i=>{let o=()=>{try{t.grabInput({}),se({src:"grab",site:"runTerminalAuthSpawn.reGrab",on:!0})}catch{}};try{let a=r(e.command,e.args,{stdio:"inherit",env:e.env,cwd:e.cwd});a.on("exit",c=>{o(),i({exitCode:c})}),a.on("error",c=>{o(),process.stdout.write(`
185
185
  failed to spawn ${e.command}: ${c.message}
186
186
  `),i({exitCode:-1})})}catch(a){o(),process.stdout.write(`
187
187
  failed to spawn ${e.command}: ${a.message}
188
- `),i({exitCode:-1})}})}function PC(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.kind==="terminal"&&typeof e.command=="string"&&Array.isArray(e.args)}async function pf(t,e){let n;try{n=await e.authenticate(t.id)}catch(s){return{kind:"error",message:s instanceof Error&&s.message.length>0?s.message:String(s)}}if(PC(n)){let s={command:n.command,args:n.args,env:n.env,cwd:n.cwd},r=await e.runTerminalAuth(s);return r.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:r.exitCode}}return{kind:"retry"}}async function rw(t,e,n,s,r){$n();let i=xC(e,n,s),o=!1,a,c,d=()=>{let u=4;i.command&&u++,i.url&&u++,i.methodLines&&(u+=1+i.methodLines.length),a&&u++,c&&u++;let f=Fn(t,{contentHeight:u,contentWidth:80,title:"Authentication required"}),p=f.contentW,h=0;if(a&&(t.moveTo(f.contentX,f.contentY+h),t.brightYellow.noFormat(ze(` ${a}`,p)),h++),c&&(t.moveTo(f.contentX,f.contentY+h),t.brightRed.noFormat(ze(` ${c}`,p)),h++),t.moveTo(f.contentX,f.contentY+h),t.brightWhite.bold.noFormat(ze(` ${i.title}`,p)),h+=2,t.moveTo(f.contentX,f.contentY+h),t.noFormat(ze(` ${i.description}`,p)),h++,i.command&&(t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Run: "),t.brightWhite.noFormat(ze(i.command,p-7)),h++),i.url&&(t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Docs: "),t.brightWhite.noFormat(ze(i.url,p-7)),h++),i.methodLines){t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Methods reported by the agent:"),h++;for(let m of i.methodLines)t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" "),t.noFormat(ze(m.label,p-3)),h++}return h++,t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(` ${i.footer}`),f},l=i.methodLines?.length??0;return Gn({term:t,render:()=>{d()},onKey:(u,f,p,h)=>{if(o)return;let m=AC(u,p,l);if(m.kind!=="ignore"){if(m.kind==="retry"||m.kind==="back"||m.kind==="cancel"){h(m.kind);return}if(m.kind==="selectMethod"){let y=i.methodLines?.[m.index]?.method;if(!y||!r?.authenticate)return;o=!0,c=void 0,a=`Authenticating with ${tw(y)}\u2026`,d();let b=r.runTerminalAuth??(v=>EC(t,v));(async()=>{let v=await pf(y,{authenticate:r.authenticate,runTerminalAuth:b});if(v.kind==="terminal-completed"){h("terminal-completed");return}if(v.kind==="retry"){h("retry");return}if(v.kind==="error"){c=v.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${v.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var kC,IC,hf=J(()=>{"use strict";Cr();Xa();ed();qr();kC="This agent requires authentication before use.",IC="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as cw}from"timers/promises";function DC(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var OC,LC,BC,NC,ao,mf=J(()=>{"use strict";ra();Di();OC=200,LC=5e3,BC=2,NC=60,ao=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 n=e.id,s=new Promise((r,i)=>{this.pendingRequests.set(n,{resolve:r,reject:i})});try{await this.current.send(e)}catch(r){throw this.pendingRequests.delete(n),r}return s}async close(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),cw(2e3)]),this.current&&await this.current.close().catch(()=>{}),this.pendingRequests.size>0){let e=new Error("resilient ws stream is destroyed");for(let{reject:n}of this.pendingRequests.values())n(e);this.pendingRequests.clear()}for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,n=OC;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await Lr(s,this.opts.subprotocols);this.bindStream(Jn(r));let i=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(o=>{this.releaseConnectGate=o});try{if(this.opts.onConnect)try{await this.opts.onConnect(i)}catch(o){this.log(`hydra-acp: post-connect handler failed: ${o.message}`)}}finally{this.releaseConnectGate?.(),this.releaseConnectGate=void 0,this.connectGate=void 0}await this.flushQueue();return}catch(s){if(e+=1,this.opts.onConnectFailure&&this.opts.onConnectFailure(s),e>=NC)throw new Error(`hydra-acp: gave up reconnecting after ${e} attempts: ${s.message}`);if(this.log(`hydra-acp: connect attempt ${e} failed (${s.message}); retrying in ${n}ms`),await cw(n),this.destroyed)return;n=Math.min(n*BC,LC)}}bindStream(e){this.current=e,e.onMessage(n=>{if(DC(n)&&n.id!==null){let s=this.pendingRequests.get(n.id);s&&(this.pendingRequests.delete(n.id),s.resolve(n))}for(let s of this.messageHandlers)s(n)}),e.onClose(n=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let s=n??new Error("ws closed before response");for(let{reject:r}of this.pendingRequests.values())r(s);this.pendingRequests.clear()}this.scheduleReconnect(n)}})}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(n){this.scheduleReconnect(n);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(n){this.log(`hydra-acp: onDisconnect handler threw: ${n.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(n){for(let s of this.closeHandlers)s(n);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
189
- `)}}});function lw(t,e){let n=t&&typeof t=="object"?t.options:void 0;if(Array.isArray(n)){for(let i of e){let o=n.find(a=>typeof a=="object"&&a!==null&&a.kind===i&&typeof a.optionId=="string");if(o?.optionId!==void 0)return o.optionId}let r=n.find(i=>typeof i=="object"&&i!==null&&typeof i.optionId=="string");if(r?.optionId!==void 0)return r.optionId}let s=e[0]??"allow";return console.warn(`[permission-pick] no optionId match for preferredKinds=${JSON.stringify(e)}; falling back to kind name ${JSON.stringify(s)} (agent will likely reject)`),s}function Wr(t){return{outcome:{outcome:"selected",optionId:lw(t,["allow_once","allow_always"])}}}function uw(t){return{outcome:{outcome:"selected",optionId:lw(t,["reject_once","reject_always"])}}}function kc(t){return t&&typeof t=="object"?t:void 0}function pa(t){return typeof t=="string"&&t.length>0?t:void 0}function fw(t){let e=kc(t),n=kc(e?.toolCall),s={paths:[]};if(!n)return s;let r=pa(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=pa(d);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=n.locations;if(Array.isArray(a))for(let d of a)o(kc(d)?.path);let c=kc(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=pa(c.command);d&&(s.command=d);let l=pa(c.url);l&&(s.url=l);let u=pa(c.description);u&&(s.description=u)}return s}function pw(t){let e=[];return t.command?e.push(`$ ${t.command}`):t.url?e.push(t.url):t.paths.length===1?e.push(t.paths[0]):t.paths.length>1?e.push(`${t.paths[0]} (+${t.paths.length-1} more)`):t.description&&e.push(t.description),e.join(" ").replace(/\s+/g," ").trim()}var Ic=J(()=>{"use strict"});function NR(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function _w(t){let n=(t.split("-",1)[0]??t).split("."),s=Number(n[0]),r=Number(n[1]),i=Number(n[2]);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i)?null:[s,r,i]}function DR(t,e){let n=_w(t),s=_w(e);if(!n||!s)return t!==e;for(let r=0;r<3;r++){let i=n[r],o=s[r];if(i>o)return!0;if(i<o)return!1}return!1}async function ha(){if(Zs!==void 0)return Zs;if(NR())return Zs=null,Zs;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:$w,version:fe}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&DR(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}Zs={current:s.current,latest:s.latest,type:typeof s.type=="string"?s.type:"unknown"}}else{if(s&&typeof s.latest=="string"&&typeof s.current=="string")try{n.config?.set?.("update",void 0)}catch{}Zs=null}}catch{Zs=null}return Zs}function ma(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${$w}`}var $w,Zs,wf=J(()=>{"use strict";nn();$w="@hydra-acp/cli"});import*as ga from"fs/promises";import*as bf from"path";async function ya(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=bf.resolve(et(e)),s;try{s=await ga.stat(n)}catch{return{ok:!1,reason:`${n} does not exist`}}return s.isDirectory()?{ok:!0,path:n}:{ok:!1,reason:`${n} is not a directory`}}async function Fw(t){let e=[],n=new Set,s=r=>{n.has(r)||(n.add(r),e.push(r))};s(t),t.startsWith("/Users/")?s("/home/"+t.slice(7)):t.startsWith("/home/")&&s("/Users/"+t.slice(6));for(let r of e)try{if((await ga.stat(r)).isDirectory())return r}catch{}return null}async function Ow(t){let e=t.lastIndexOf("/"),n,s,r;e===-1?(n="",s=t,r="."):(n=t.slice(0,e+1),s=t.slice(e+1),r=e===0?"/":n);let i=bf.resolve(et(r)),o;try{o=(await ga.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:n,basePrefix:s,matches:[]}}let a=s.startsWith("."),c=o.filter(d=>d.name.startsWith(s)).filter(d=>a||!d.name.startsWith(".")).map(d=>d.isDir?`${d.name}/`:d.name).sort();return{prefix:n,basePrefix:s,matches:c}}var vf=J(()=>{"use strict";Ve()});var Lw,Bw,Nw,Dw=J(()=>{"use strict";Lw="hydra-acp/question/list",Bw="hydra-acp/question/answer",Nw="hydra-acp/question/dismiss"});import{EventEmitter as HR}from"events";import{WebSocket as UR}from"ws";function jR(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=_o(s.hostname);r.rejectUnauthorized!==void 0&&(n.rejectUnauthorized=r.rejectUnauthorized),r.autoSelectFamily!==void 0&&(n.autoSelectFamily=r.autoSelectFamily),r.checkServerIdentity!==void 0&&(n.checkServerIdentity=r.checkServerIdentity)}}catch{}return new Promise((s,r)=>{let i=new UR(t,e,n),o=()=>{i.off("error",a),s(Jn(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function Hw(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??jR,c=["acp.v1",`hydra-acp-token.${t.token}`],d=await a(t.wsUrl,c),l=new zt(d),u;try{try{await l.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-sidechain"}})}catch{}if(s.reuseSessionId!==void 0)u=s.reuseSessionId;else{let m=n.replace(/\s+/g," ").trim().slice(0,60);u=(await ec(t,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${m}`,mode:"verbatim"},o)).sessionId}}catch(m){throw d.close().catch(()=>{}),m}let f=new Sf(l,d,u,t,o),p=!1,h=m=>{p||(p=!0,f.emit("event",m),d.close().catch(()=>{}))};l.onNotification("session/update",m=>{let y=m?.update;y!==void 0&&f.emit("event",{kind:"update",update:y})}),l.onClose(()=>{p||h({kind:"completed"})});try{await l.request("session/attach",{sessionId:u,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(m){throw d.close().catch(()=>{}),Vn(t,u,o).catch(()=>{}),m}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:n}],_meta:{[Tt]:{ancillary:!0}}}).then(m=>{let y=m&&typeof m=="object"?m.stopReason:void 0;h(y==="cancelled"?{kind:"cancelled"}:y==="error"||y==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(m=>{h({kind:"errored",error:m instanceof Error?m:new Error(String(m))})})})})().catch(i)})}var Sf,Uw=J(()=>{"use strict";$o();ia();Tr();Di();Et();Sf=class extends HR{_conn;_stream;_sessionId;_target;_fetchImpl;_cancelled=!1;constructor(e,n,s,r,i){super(),this._conn=e,this._stream=n,this._sessionId=s,this._target=r,this._fetchImpl=i}get sessionId(){return this._sessionId}cancel(){this._cancelled||(this._cancelled=!0,this._conn.notify("session/cancel",{sessionId:this._sessionId}).catch(()=>{}),this._stream.close().catch(()=>{}),Vn(this._target,this._sessionId,this._fetchImpl).catch(()=>{}))}once(e,n){return super.once(e,n)}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}}});var kf,Tc,jw=J(()=>{"use strict";eo();Ws();kf=class{_listeners=new Map;on(e,n){let s=this._listeners.get(e);s||(s=new Set,this._listeners.set(e,s)),s.add(n)}off(e,n){this._listeners.get(e)?.delete(n)}emit(e){this._listeners.get(e)?.forEach(s=>s())}},Tc=class extends kf{_lines=[];_toolStates=new Map;_toolRanges=new Map;_pendingAgentText=null;_pendingAgentRange=null;_pendingThoughtText=null;_pendingThoughtRange=null;_emitChanged;_getMaxWidth;constructor(e={}){super(),this._emitChanged=e.emitChanged??!0,this._getMaxWidth=e.getMaxWidth}append(e){let n=Kn(e);if(!n)return 0;switch(n.kind!=="agent-text"&&(this._pendingAgentText=null,this._pendingAgentRange=null),n.kind!=="agent-thought"&&(this._pendingThoughtText=null,this._pendingThoughtRange=null),n.kind){case"agent-text":{let s=n.text;if(this._pendingAgentText!==null&&this._pendingAgentRange!==null){this._pendingAgentText+=s;let o=this._parseAgent(this._pendingAgentText);return this._replaceAgentRange(this._pendingAgentRange,o),o.length}this._pendingAgentText=s;let r=this._parseAgent(s),i=this._lines.length;return this._pushLines(r),this._pendingAgentRange={start:i,length:r.length},r.length}case"agent-thought":{let s=n.text;if(this._pendingThoughtText!==null&&this._pendingThoughtRange!==null){this._pendingThoughtText+=s;let o=Zi(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=Zi(s),i=this._lines.length;return this._pushLines(r),this._pendingThoughtRange={start:i,length:r.length},r.length}case"tool-call":{let s={initialTitle:n.title,latestTitle:n.title,status:n.status??"pending"};n.detail!==void 0&&(s.detail=n.detail),this._toolStates.set(n.toolCallId,s);let r=da(s),i=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:i,length:r.length}),r.length}case"tool-call-update":{let s=this._toolStates.get(n.toolCallId);if(!s)return 0;n.title!==void 0&&(s.latestTitle=n.title),n.status!==void 0&&(s.status=n.status),n.detail!==void 0&&(s.detail=n.detail),n.errorText!==void 0&&(s.errorText=n.errorText);let r=da(s),i=this._toolRanges.get(n.toolCallId);if(!i){let o=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:o,length:r.length}),r.length}return this._replaceRange(n.toolCallId,i,r),r.length}default:{let s=Qs(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return Gs(e,n!==void 0&&n>0?{maxWidth:n}:void 0)}_replaceAgentRange(e,n){let s=n.length-e.length;if(this._lines.splice(e.start,e.length,...n),e.length=n.length,s!==0){for(let r of this._toolRanges.values())r.start>e.start&&(r.start+=s);this._pendingThoughtRange&&this._pendingThoughtRange.start>e.start&&(this._pendingThoughtRange.start+=s)}this._emitChanged&&this.emit("changed")}_replaceThoughtRange(e,n){let s=n.length-e.length;if(this._lines.splice(e.start,e.length,...n),e.length=n.length,s!==0){for(let r of this._toolRanges.values())r.start>e.start&&(r.start+=s);this._pendingAgentRange&&this._pendingAgentRange.start>e.start&&(this._pendingAgentRange.start+=s)}this._emitChanged&&this.emit("changed")}_replaceRange(e,n,s){let r=s.length-n.length;if(this._lines.splice(n.start,n.length,...s),n.length=s.length,r!==0){for(let[i,o]of this._toolRanges)i!==e&&o.start>n.start&&(o.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>n.start&&(this._pendingAgentRange.start+=r),this._pendingThoughtRange&&this._pendingThoughtRange.start>n.start&&(this._pendingThoughtRange.start+=r)}this._emitChanged&&this.emit("changed")}getLines(){return this._lines.slice()}clear(){(this._lines.length>0||this._toolStates.size>0)&&(this._lines.length=0,this._toolStates.clear(),this._toolRanges.clear(),this._pendingAgentText=null,this._pendingAgentRange=null,this._pendingThoughtText=null,this._pendingThoughtRange=null,this.emit("changed"))}get size(){return this._lines.length}_pushLines(e){let n=this._lines.length;for(let s of e)this._lines.push(s);this._emitChanged&&this._lines.length>n&&this.emit("changed")}}});function WR(t,e){return`[pasted #${t} +${e} lines]`}var qR,Ec,If,zR,bs,xf=J(()=>{"use strict";qR=/\[pasted #(\d+) \+\d+ lines\]/g,Ec=/\[pasted #(\d+) \+\d+ lines\]$/,If=/^\[pasted #(\d+) \+\d+ lines\]/;zR=500,bs=class{buffer=[""];row=0;col=0;planMode=!1;historyIndex=-1;queueIndex=-1;savedDraft=null;history=[];historySearch=null;queue=[];turnRunning=!1;killBuffer="";attachments=[];savedAttachments=null;pastes=new Map;nextPasteId=1;collapsePastes;lastTapKey=null;lastTapAt=null;undoStack=[];redoStack=[];constructor(e={}){this.history=[...e.history??[]],this.planMode=e.planMode??!1,this.collapsePastes=e.collapsePastes??!0}expandedText(){return this.expandPastes(this.bufferText())}state(){return Object.freeze({buffer:this.buffer,row:this.row,col:this.col,planMode:this.planMode,historyIndex:this.historyIndex,queueIndex:this.queueIndex,attachments:this.attachments,historySearchQuery:this.historySearch?.query??null})}addAttachment(e){this.recordEdit(),this.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||(this.recordEdit(),this.attachments.splice(e,1))}snapshotState(){return{buffer:[...this.buffer],row:this.row,col:this.col,planMode:this.planMode,attachments:[...this.attachments]}}restoreSnapshot(e){this.buffer=[...e.buffer],this.row=e.row,this.col=e.col,this.planMode=e.planMode,this.attachments=[...e.attachments]}recordEdit(){this.undoStack.push(this.snapshotState()),this.undoStack.length>zR&&this.undoStack.shift(),this.redoStack=[]}clearUndoHistory(){this.undoStack=[],this.redoStack=[]}undo(){let e=this.undoStack.pop();e!==void 0&&(this.redoStack.push(this.snapshotState()),this.restoreSnapshot(e))}redo(){let e=this.redoStack.pop();e!==void 0&&(this.undoStack.push(this.snapshotState()),this.restoreSnapshot(e))}setTurnRunning(e){this.turnRunning=e}setHistory(e){this.history=[...e],this.historyIndex=-1,this.savedDraft=null,this.historySearch=null,this.clearUndoHistory()}setQueue(e){this.queue=[...e],this.queueIndex>=this.queue.length&&(this.queueIndex=-1)}replaceFirstLine(e){this.recordEdit(),this.buffer[0]=e,this.row===0&&(this.col=e.length)}replaceRangeOnCurrentLine(e,n,s){this.recordEdit();let r=this.currentLine(),i=Math.max(0,Math.min(e,r.length)),o=Math.max(i,Math.min(n,r.length));this.setCurrentLine(r.slice(0,i)+s+r.slice(o)),this.col=i+s.length}setBuffer(e,n=[]){this.loadEntry(e),this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[...n],this.clearUndoHistory()}feed(e){if(this.historySearch!==null){if(e.type==="char")return this.mutateHistorySearchQuery(this.historySearch.query+e.ch.toLowerCase());if(e.type==="paste")return this.mutateHistorySearchQuery(this.historySearch.query+e.text.replace(/\n/g," ").toLowerCase());if(e.type==="key"){if(e.name==="ctrl-r")return this.advanceHistorySearch();if(e.name==="ctrl-s")return this.retreatHistorySearch(),[];if(e.name==="escape"||e.name==="ctrl-c")return this.cancelHistorySearch(),[];if(e.name==="backspace")return this.historySearch.query.length===0?(this.cancelHistorySearch(),[]):this.mutateHistorySearchQuery(this.historySearch.query.slice(0,-1));this.historySearch=null}}if(e.type==="char")return this.clearDoubleTap(),this.recordEdit(),this.insertChar(e.ch),[];if(e.type==="paste"){this.clearDoubleTap(),this.recordEdit();let n=e.text.split(`
190
- `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(WR(s,n))}else this.insertText(e.text);return[]}return e.type==="attachment-paths"?[]:this.handleKey(e.name)}handleKey(e){switch(this.lastTapKey!==null&&this.lastTapKey!==e&&this.clearDoubleTap(),e){case"enter":return this.send();case"shift-enter":case"ctrl-enter":return this.amend();case"alt-enter":return this.recordEdit(),this.insertNewline(),[];case"shift-tab":return this.recordEdit(),this.planMode=!this.planMode,[{type:"plan-toggle",on:this.planMode},{type:"redraw-banner"}];case"tab":return this.recordEdit(),this.insertText(" "),[];case"up":return this.handleUp();case"down":return this.handleDown();case"left":return this.bufferIsEmpty()?this.consumeDoubleTap("left")?[{type:"switch-session"}]:(this.armDoubleTap("left"),[]):(this.moveLeft(),[]);case"right":return this.moveRight(),[];case"ctrl-a":return this.col=0,[];case"ctrl-e":return this.col=this.currentLine().length,[];case"home":return this.handleHome();case"end":return this.handleEnd();case"ctrl-b":return this.moveLeft(),[];case"ctrl-f":return this.moveRight(),[];case"ctrl-g":return[{type:"show-help"}];case"alt-b":return this.moveWordBackward(),[];case"alt-f":return this.moveWordForward(),[];case"ctrl-k":return this.recordEdit(),this.killToEnd(),[];case"ctrl-n":return this.handleDown();case"ctrl-o":return[{type:"toggle-options"}];case"ctrl-q":return[{type:"toggle-questions"}];case"backspace":return this.recordEdit(),this.backspace(),[];case"delete":return this.recordEdit(),this.deleteForward(),[];case"ctrl-c":return this.handleCtrlC();case"ctrl-d":return this.bufferIsEmpty()?[{type:"exit"}]:(this.recordEdit(),this.deleteForward(),[]);case"ctrl-l":return[{type:"redraw"}];case"ctrl-p":return[{type:"switch-session"}];case"ctrl-t":return[{type:"toggle-thoughts"}];case"alt-n":case"alt-tab":return[{type:"next-live-session"}];case"ctrl-r":return this.startHistorySearch();case"ctrl-s":return this.amend();case"ctrl-u":return this.recordEdit(),this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.recordEdit(),this.killWord(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.recordEdit(),this.yank(),[];case"ctrl-underscore":return this.undo(),[];case"alt-underscore":return this.redo(),[];case"escape":return this.turnRunning?(this.clearDoubleTap(),[{type:"cancel",prefill:!0}]):this.consumeDoubleTap("escape")?[{type:"switch-session"}]:(this.armDoubleTap("escape"),[])}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
191
- `)}expandPastes(e){return e.replace(qR,(n,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:n})}armDoubleTap(e){this.lastTapKey=e,this.lastTapAt=Date.now()}consumeDoubleTap(e){return this.lastTapKey===e&&this.lastTapAt!==null&&Date.now()-this.lastTapAt<=500?(this.clearDoubleTap(),!0):!1}clearDoubleTap(){this.lastTapKey=null,this.lastTapAt=null}bufferIsEmpty(){return this.buffer.length===1&&this.buffer[0]===""}clearBuffer(){this.buffer=[""],this.row=0,this.col=0,this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[],this.clearUndoHistory()}insertChar(e){if(e.length===0)return;if(e.includes(`
188
+ `),i({exitCode:-1})}})}function FC(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.kind==="terminal"&&typeof e.command=="string"&&Array.isArray(e.args)}async function hf(t,e){let n;try{n=await e.authenticate(t.id)}catch(s){return{kind:"error",message:s instanceof Error&&s.message.length>0?s.message:String(s)}}if(FC(n)){let s={command:n.command,args:n.args,env:n.env,cwd:n.cwd},r=await e.runTerminalAuth(s);return r.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:r.exitCode}}return{kind:"retry"}}async function ow(t,e,n,s,r){$n();let i=EC(e,n,s),o=!1,a,c,d=()=>{let u=4;i.command&&u++,i.url&&u++,i.methodLines&&(u+=1+i.methodLines.length),a&&u++,c&&u++;let f=On(t,{contentHeight:u,contentWidth:80,title:"Authentication required"}),p=f.contentW,h=0;if(a&&(t.moveTo(f.contentX,f.contentY+h),t.brightYellow.noFormat(Ke(` ${a}`,p)),h++),c&&(t.moveTo(f.contentX,f.contentY+h),t.brightRed.noFormat(Ke(` ${c}`,p)),h++),t.moveTo(f.contentX,f.contentY+h),t.brightWhite.bold.noFormat(Ke(` ${i.title}`,p)),h+=2,t.moveTo(f.contentX,f.contentY+h),t.noFormat(Ke(` ${i.description}`,p)),h++,i.command&&(t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Run: "),t.brightWhite.noFormat(Ke(i.command,p-7)),h++),i.url&&(t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Docs: "),t.brightWhite.noFormat(Ke(i.url,p-7)),h++),i.methodLines){t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Methods reported by the agent:"),h++;for(let m of i.methodLines)t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" "),t.noFormat(Ke(m.label,p-3)),h++}return h++,t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(` ${i.footer}`),f},l=i.methodLines?.length??0;return Gn({term:t,render:()=>{d()},onKey:(u,f,p,h)=>{if(o)return;let m=PC(u,p,l);if(m.kind!=="ignore"){if(m.kind==="retry"||m.kind==="back"||m.kind==="cancel"){h(m.kind);return}if(m.kind==="selectMethod"){let y=i.methodLines?.[m.index]?.method;if(!y||!r?.authenticate)return;o=!0,c=void 0,a=`Authenticating with ${sw(y)}\u2026`,d();let b=r.runTerminalAuth??(v=>OC(t,v));(async()=>{let v=await hf(y,{authenticate:r.authenticate,runTerminalAuth:b});if(v.kind==="terminal-completed"){h("terminal-completed");return}if(v.kind==="retry"){h("retry");return}if(v.kind==="error"){c=v.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${v.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var RC,TC,mf=J(()=>{"use strict";Cr();Za();td();qr();RC="This agent requires authentication before use.",TC="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as uw}from"timers/promises";function WC(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var HC,UC,jC,qC,co,gf=J(()=>{"use strict";ia();Hi();HC=200,UC=5e3,jC=2,qC=60,co=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 n=e.id,s=new Promise((r,i)=>{this.pendingRequests.set(n,{resolve:r,reject:i})});try{await this.current.send(e)}catch(r){throw this.pendingRequests.delete(n),r}return s}async close(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),uw(2e3)]),this.current&&await this.current.close().catch(()=>{}),this.pendingRequests.size>0){let e=new Error("resilient ws stream is destroyed");for(let{reject:n}of this.pendingRequests.values())n(e);this.pendingRequests.clear()}for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,n=HC;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await Lr(s,this.opts.subprotocols);this.bindStream(Jn(r));let i=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(o=>{this.releaseConnectGate=o});try{if(this.opts.onConnect)try{await this.opts.onConnect(i)}catch(o){this.log(`hydra-acp: post-connect handler failed: ${o.message}`)}}finally{this.releaseConnectGate?.(),this.releaseConnectGate=void 0,this.connectGate=void 0}await this.flushQueue();return}catch(s){if(e+=1,this.opts.onConnectFailure&&this.opts.onConnectFailure(s),e>=qC)throw new Error(`hydra-acp: gave up reconnecting after ${e} attempts: ${s.message}`);if(this.log(`hydra-acp: connect attempt ${e} failed (${s.message}); retrying in ${n}ms`),await uw(n),this.destroyed)return;n=Math.min(n*jC,UC)}}bindStream(e){this.current=e,e.onMessage(n=>{if(WC(n)&&n.id!==null){let s=this.pendingRequests.get(n.id);s&&(this.pendingRequests.delete(n.id),s.resolve(n))}for(let s of this.messageHandlers)s(n)}),e.onClose(n=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let s=n??new Error("ws closed before response");for(let{reject:r}of this.pendingRequests.values())r(s);this.pendingRequests.clear()}this.scheduleReconnect(n)}})}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(n){this.scheduleReconnect(n);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(n){this.log(`hydra-acp: onDisconnect handler threw: ${n.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(n){for(let s of this.closeHandlers)s(n);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
189
+ `)}}});function fw(t,e){let n=t&&typeof t=="object"?t.options:void 0;if(Array.isArray(n)){for(let i of e){let o=n.find(a=>typeof a=="object"&&a!==null&&a.kind===i&&typeof a.optionId=="string");if(o?.optionId!==void 0)return o.optionId}let r=n.find(i=>typeof i=="object"&&i!==null&&typeof i.optionId=="string");if(r?.optionId!==void 0)return r.optionId}let s=e[0]??"allow";return console.warn(`[permission-pick] no optionId match for preferredKinds=${JSON.stringify(e)}; falling back to kind name ${JSON.stringify(s)} (agent will likely reject)`),s}function Wr(t){return{outcome:{outcome:"selected",optionId:fw(t,["allow_once","allow_always"])}}}function pw(t){return{outcome:{outcome:"selected",optionId:fw(t,["reject_once","reject_always"])}}}function kc(t){return t&&typeof t=="object"?t:void 0}function ha(t){return typeof t=="string"&&t.length>0?t:void 0}function hw(t){let e=kc(t),n=kc(e?.toolCall),s={paths:[]};if(!n)return s;let r=ha(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=ha(d);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=n.locations;if(Array.isArray(a))for(let d of a)o(kc(d)?.path);let c=kc(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=ha(c.command);d&&(s.command=d);let l=ha(c.url);l&&(s.url=l);let u=ha(c.description);u&&(s.description=u)}return s}function mw(t){let e=[];return t.command?e.push(`$ ${t.command}`):t.url?e.push(t.url):t.paths.length===1?e.push(t.paths[0]):t.paths.length>1?e.push(`${t.paths[0]} (+${t.paths.length-1} more)`):t.description&&e.push(t.description),e.join(" ").replace(/\s+/g," ").trim()}var Ic=J(()=>{"use strict"});function qR(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function Ow(t){let n=(t.split("-",1)[0]??t).split("."),s=Number(n[0]),r=Number(n[1]),i=Number(n[2]);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i)?null:[s,r,i]}function WR(t,e){let n=Ow(t),s=Ow(e);if(!n||!s)return t!==e;for(let r=0;r<3;r++){let i=n[r],o=s[r];if(i>o)return!0;if(i<o)return!1}return!1}async function ma(){if(Zs!==void 0)return Zs;if(qR())return Zs=null,Zs;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:Fw,version:fe}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&WR(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}Zs={current:s.current,latest:s.latest,type:typeof s.type=="string"?s.type:"unknown"}}else{if(s&&typeof s.latest=="string"&&typeof s.current=="string")try{n.config?.set?.("update",void 0)}catch{}Zs=null}}catch{Zs=null}return Zs}function ga(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${Fw}`}var Fw,Zs,bf=J(()=>{"use strict";nn();Fw="@hydra-acp/cli"});import*as ya from"fs/promises";import*as vf from"path";async function wa(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=vf.resolve(et(e)),s;try{s=await ya.stat(n)}catch{return{ok:!1,reason:`${n} does not exist`}}return s.isDirectory()?{ok:!0,path:n}:{ok:!1,reason:`${n} is not a directory`}}async function Lw(t){let e=[],n=new Set,s=r=>{n.has(r)||(n.add(r),e.push(r))};s(t),t.startsWith("/Users/")?s("/home/"+t.slice(7)):t.startsWith("/home/")&&s("/Users/"+t.slice(6));for(let r of e)try{if((await ya.stat(r)).isDirectory())return r}catch{}return null}async function Bw(t){let e=t.lastIndexOf("/"),n,s,r;e===-1?(n="",s=t,r="."):(n=t.slice(0,e+1),s=t.slice(e+1),r=e===0?"/":n);let i=vf.resolve(et(r)),o;try{o=(await ya.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:n,basePrefix:s,matches:[]}}let a=s.startsWith("."),c=o.filter(d=>d.name.startsWith(s)).filter(d=>a||!d.name.startsWith(".")).map(d=>d.isDir?`${d.name}/`:d.name).sort();return{prefix:n,basePrefix:s,matches:c}}var Sf=J(()=>{"use strict";Ge()});var Nw,Dw,Hw,Uw=J(()=>{"use strict";Nw="hydra-acp/question/list",Dw="hydra-acp/question/answer",Hw="hydra-acp/question/dismiss"});import{EventEmitter as zR}from"events";import{WebSocket as KR}from"ws";function JR(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=$o(s.hostname);r.rejectUnauthorized!==void 0&&(n.rejectUnauthorized=r.rejectUnauthorized),r.autoSelectFamily!==void 0&&(n.autoSelectFamily=r.autoSelectFamily),r.checkServerIdentity!==void 0&&(n.checkServerIdentity=r.checkServerIdentity)}}catch{}return new Promise((s,r)=>{let i=new KR(t,e,n),o=()=>{i.off("error",a),s(Jn(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function jw(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??JR,c=["acp.v1",`hydra-acp-token.${t.token}`],d=await a(t.wsUrl,c),l=new zt(d),u;try{try{await l.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-sidechain"}})}catch{}if(s.reuseSessionId!==void 0)u=s.reuseSessionId;else{let m=n.replace(/\s+/g," ").trim().slice(0,60);u=(await ec(t,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${m}`,mode:"verbatim"},o)).sessionId}}catch(m){throw d.close().catch(()=>{}),m}let f=new kf(l,d,u,t,o),p=!1,h=m=>{p||(p=!0,f.emit("event",m),d.close().catch(()=>{}))};l.onNotification("session/update",m=>{let y=m?.update;y!==void 0&&f.emit("event",{kind:"update",update:y})}),l.onClose(()=>{p||h({kind:"completed"})});try{await l.request("session/attach",{sessionId:u,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(m){throw d.close().catch(()=>{}),Yn(t,u,o).catch(()=>{}),m}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:n}],_meta:{[Tt]:{ancillary:!0}}}).then(m=>{let y=m&&typeof m=="object"?m.stopReason:void 0;h(y==="cancelled"?{kind:"cancelled"}:y==="error"||y==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(m=>{h({kind:"errored",error:m instanceof Error?m:new Error(String(m))})})})})().catch(i)})}var kf,qw=J(()=>{"use strict";Oo();oa();Tr();Hi();Et();kf=class extends zR{_conn;_stream;_sessionId;_target;_fetchImpl;_cancelled=!1;constructor(e,n,s,r,i){super(),this._conn=e,this._stream=n,this._sessionId=s,this._target=r,this._fetchImpl=i}get sessionId(){return this._sessionId}cancel(){this._cancelled||(this._cancelled=!0,this._conn.notify("session/cancel",{sessionId:this._sessionId}).catch(()=>{}),this._stream.close().catch(()=>{}),Yn(this._target,this._sessionId,this._fetchImpl).catch(()=>{}))}once(e,n){return super.once(e,n)}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}}});var If,Tc,Ww=J(()=>{"use strict";to();Ws();If=class{_listeners=new Map;on(e,n){let s=this._listeners.get(e);s||(s=new Set,this._listeners.set(e,s)),s.add(n)}off(e,n){this._listeners.get(e)?.delete(n)}emit(e){this._listeners.get(e)?.forEach(s=>s())}},Tc=class extends If{_lines=[];_toolStates=new Map;_toolRanges=new Map;_pendingAgentText=null;_pendingAgentRange=null;_pendingThoughtText=null;_pendingThoughtRange=null;_emitChanged;_getMaxWidth;constructor(e={}){super(),this._emitChanged=e.emitChanged??!0,this._getMaxWidth=e.getMaxWidth}append(e){let n=Kn(e);if(!n)return 0;switch(n.kind!=="agent-text"&&(this._pendingAgentText=null,this._pendingAgentRange=null),n.kind!=="agent-thought"&&(this._pendingThoughtText=null,this._pendingThoughtRange=null),n.kind){case"agent-text":{let s=n.text;if(this._pendingAgentText!==null&&this._pendingAgentRange!==null){this._pendingAgentText+=s;let o=this._parseAgent(this._pendingAgentText);return this._replaceAgentRange(this._pendingAgentRange,o),o.length}this._pendingAgentText=s;let r=this._parseAgent(s),i=this._lines.length;return this._pushLines(r),this._pendingAgentRange={start:i,length:r.length},r.length}case"agent-thought":{let s=n.text;if(this._pendingThoughtText!==null&&this._pendingThoughtRange!==null){this._pendingThoughtText+=s;let o=eo(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=eo(s),i=this._lines.length;return this._pushLines(r),this._pendingThoughtRange={start:i,length:r.length},r.length}case"tool-call":{let s={initialTitle:n.title,latestTitle:n.title,status:n.status??"pending"};n.detail!==void 0&&(s.detail=n.detail),this._toolStates.set(n.toolCallId,s);let r=ca(s),i=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:i,length:r.length}),r.length}case"tool-call-update":{let s=this._toolStates.get(n.toolCallId);if(!s)return 0;n.title!==void 0&&(s.latestTitle=n.title),n.status!==void 0&&(s.status=n.status),n.detail!==void 0&&(s.detail=n.detail),n.errorText!==void 0&&(s.errorText=n.errorText);let r=ca(s),i=this._toolRanges.get(n.toolCallId);if(!i){let o=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:o,length:r.length}),r.length}return this._replaceRange(n.toolCallId,i,r),r.length}default:{let s=Qs(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return Gs(e,n!==void 0&&n>0?{maxWidth:n}:void 0)}_replaceAgentRange(e,n){let s=n.length-e.length;if(this._lines.splice(e.start,e.length,...n),e.length=n.length,s!==0){for(let r of this._toolRanges.values())r.start>e.start&&(r.start+=s);this._pendingThoughtRange&&this._pendingThoughtRange.start>e.start&&(this._pendingThoughtRange.start+=s)}this._emitChanged&&this.emit("changed")}_replaceThoughtRange(e,n){let s=n.length-e.length;if(this._lines.splice(e.start,e.length,...n),e.length=n.length,s!==0){for(let r of this._toolRanges.values())r.start>e.start&&(r.start+=s);this._pendingAgentRange&&this._pendingAgentRange.start>e.start&&(this._pendingAgentRange.start+=s)}this._emitChanged&&this.emit("changed")}_replaceRange(e,n,s){let r=s.length-n.length;if(this._lines.splice(n.start,n.length,...s),n.length=s.length,r!==0){for(let[i,o]of this._toolRanges)i!==e&&o.start>n.start&&(o.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>n.start&&(this._pendingAgentRange.start+=r),this._pendingThoughtRange&&this._pendingThoughtRange.start>n.start&&(this._pendingThoughtRange.start+=r)}this._emitChanged&&this.emit("changed")}getLines(){return this._lines.slice()}clear(){(this._lines.length>0||this._toolStates.size>0)&&(this._lines.length=0,this._toolStates.clear(),this._toolRanges.clear(),this._pendingAgentText=null,this._pendingAgentRange=null,this._pendingThoughtText=null,this._pendingThoughtRange=null,this.emit("changed"))}get size(){return this._lines.length}_pushLines(e){let n=this._lines.length;for(let s of e)this._lines.push(s);this._emitChanged&&this._lines.length>n&&this.emit("changed")}}});function YR(t,e){return`[pasted #${t} +${e} lines]`}var VR,Ec,xf,QR,vs,Af=J(()=>{"use strict";VR=/\[pasted #(\d+) \+\d+ lines\]/g,Ec=/\[pasted #(\d+) \+\d+ lines\]$/,xf=/^\[pasted #(\d+) \+\d+ lines\]/;QR=500,vs=class{buffer=[""];row=0;col=0;planMode=!1;historyIndex=-1;queueIndex=-1;savedDraft=null;history=[];historySearch=null;queue=[];turnRunning=!1;killBuffer="";attachments=[];savedAttachments=null;pastes=new Map;nextPasteId=1;collapsePastes;lastTapKey=null;lastTapAt=null;undoStack=[];redoStack=[];constructor(e={}){this.history=[...e.history??[]],this.planMode=e.planMode??!1,this.collapsePastes=e.collapsePastes??!0}expandedText(){return this.expandPastes(this.bufferText())}state(){return Object.freeze({buffer:this.buffer,row:this.row,col:this.col,planMode:this.planMode,historyIndex:this.historyIndex,queueIndex:this.queueIndex,attachments:this.attachments,historySearchQuery:this.historySearch?.query??null})}addAttachment(e){this.recordEdit(),this.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||(this.recordEdit(),this.attachments.splice(e,1))}snapshotState(){return{buffer:[...this.buffer],row:this.row,col:this.col,planMode:this.planMode,attachments:[...this.attachments]}}restoreSnapshot(e){this.buffer=[...e.buffer],this.row=e.row,this.col=e.col,this.planMode=e.planMode,this.attachments=[...e.attachments]}recordEdit(){this.undoStack.push(this.snapshotState()),this.undoStack.length>QR&&this.undoStack.shift(),this.redoStack=[]}clearUndoHistory(){this.undoStack=[],this.redoStack=[]}undo(){let e=this.undoStack.pop();e!==void 0&&(this.redoStack.push(this.snapshotState()),this.restoreSnapshot(e))}redo(){let e=this.redoStack.pop();e!==void 0&&(this.undoStack.push(this.snapshotState()),this.restoreSnapshot(e))}setTurnRunning(e){this.turnRunning=e}setHistory(e){this.history=[...e],this.historyIndex=-1,this.savedDraft=null,this.historySearch=null,this.clearUndoHistory()}setQueue(e){this.queue=[...e],this.queueIndex>=this.queue.length&&(this.queueIndex=-1)}replaceFirstLine(e){this.recordEdit(),this.buffer[0]=e,this.row===0&&(this.col=e.length)}replaceRangeOnCurrentLine(e,n,s){this.recordEdit();let r=this.currentLine(),i=Math.max(0,Math.min(e,r.length)),o=Math.max(i,Math.min(n,r.length));this.setCurrentLine(r.slice(0,i)+s+r.slice(o)),this.col=i+s.length}setBuffer(e,n=[]){this.loadEntry(e),this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[...n],this.clearUndoHistory()}feed(e){if(this.historySearch!==null){if(e.type==="char")return this.mutateHistorySearchQuery(this.historySearch.query+e.ch.toLowerCase());if(e.type==="paste")return this.mutateHistorySearchQuery(this.historySearch.query+e.text.replace(/\n/g," ").toLowerCase());if(e.type==="key"){if(e.name==="ctrl-r")return this.advanceHistorySearch();if(e.name==="ctrl-s")return this.retreatHistorySearch(),[];if(e.name==="escape"||e.name==="ctrl-c")return this.cancelHistorySearch(),[];if(e.name==="backspace")return this.historySearch.query.length===0?(this.cancelHistorySearch(),[]):this.mutateHistorySearchQuery(this.historySearch.query.slice(0,-1));this.historySearch=null}}if(e.type==="char")return this.clearDoubleTap(),this.recordEdit(),this.insertChar(e.ch),[];if(e.type==="paste"){this.clearDoubleTap(),this.recordEdit();let n=e.text.split(`
190
+ `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(YR(s,n))}else this.insertText(e.text);return[]}return e.type==="attachment-paths"?[]:this.handleKey(e.name)}handleKey(e){switch(this.lastTapKey!==null&&this.lastTapKey!==e&&this.clearDoubleTap(),e){case"enter":return this.send();case"shift-enter":case"ctrl-enter":return this.amend();case"alt-enter":return this.recordEdit(),this.insertNewline(),[];case"shift-tab":return this.recordEdit(),this.planMode=!this.planMode,[{type:"plan-toggle",on:this.planMode},{type:"redraw-banner"}];case"tab":return this.recordEdit(),this.insertText(" "),[];case"up":return this.handleUp();case"down":return this.handleDown();case"left":return this.bufferIsEmpty()?this.consumeDoubleTap("left")?[{type:"switch-session"}]:(this.armDoubleTap("left"),[]):(this.moveLeft(),[]);case"right":return this.moveRight(),[];case"ctrl-a":return this.col=0,[];case"ctrl-e":return this.col=this.currentLine().length,[];case"home":return this.handleHome();case"end":return this.handleEnd();case"ctrl-b":return this.moveLeft(),[];case"ctrl-f":return this.moveRight(),[];case"ctrl-g":return[{type:"show-help"}];case"alt-b":return this.moveWordBackward(),[];case"alt-f":return this.moveWordForward(),[];case"ctrl-k":return this.recordEdit(),this.killToEnd(),[];case"ctrl-n":return this.handleDown();case"ctrl-o":return[{type:"toggle-options"}];case"ctrl-q":return[{type:"toggle-questions"}];case"backspace":return this.recordEdit(),this.backspace(),[];case"delete":return this.recordEdit(),this.deleteForward(),[];case"ctrl-c":return this.handleCtrlC();case"ctrl-d":return this.bufferIsEmpty()?[{type:"exit"}]:(this.recordEdit(),this.deleteForward(),[]);case"ctrl-l":return[{type:"redraw"}];case"ctrl-p":return[{type:"switch-session"}];case"ctrl-t":return[{type:"toggle-thoughts"}];case"alt-n":case"alt-tab":return[{type:"next-live-session"}];case"ctrl-r":return this.startHistorySearch();case"ctrl-s":return this.amend();case"ctrl-u":return this.recordEdit(),this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.recordEdit(),this.killWord(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.recordEdit(),this.yank(),[];case"ctrl-underscore":return this.undo(),[];case"alt-underscore":return this.redo(),[];case"escape":return this.turnRunning?(this.clearDoubleTap(),[{type:"cancel",prefill:!0}]):this.consumeDoubleTap("escape")?[{type:"switch-session"}]:(this.armDoubleTap("escape"),[])}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
191
+ `)}expandPastes(e){return e.replace(VR,(n,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:n})}armDoubleTap(e){this.lastTapKey=e,this.lastTapAt=Date.now()}consumeDoubleTap(e){return this.lastTapKey===e&&this.lastTapAt!==null&&Date.now()-this.lastTapAt<=500?(this.clearDoubleTap(),!0):!1}clearDoubleTap(){this.lastTapKey=null,this.lastTapAt=null}bufferIsEmpty(){return this.buffer.length===1&&this.buffer[0]===""}clearBuffer(){this.buffer=[""],this.row=0,this.col=0,this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[],this.clearUndoHistory()}insertChar(e){if(e.length===0)return;if(e.includes(`
192
192
  `)){this.insertText(e);return}let n=this.currentLine();this.setCurrentLine(n.slice(0,this.col)+e+n.slice(this.col)),this.col+=e.length}insertText(e){let n=e.split(`
193
- `);if(n.length===1){this.insertChar(n[0]??"");return}let s=this.currentLine(),r=s.slice(0,this.col),i=s.slice(this.col),o=n[0]??"",a=n[n.length-1]??"",c=n.slice(1,-1);this.setCurrentLine(r+o);let d=[...c,a+i];this.buffer.splice(this.row+1,0,...d),this.row+=n.length-1,this.col=a.length}insertNewline(){let e=this.currentLine(),n=e.slice(0,this.col),s=e.slice(this.col);this.setCurrentLine(n),this.buffer.splice(this.row+1,0,s),this.row+=1,this.col=0}backspace(){if(this.col>0){let s=this.currentLine(),i=s.slice(0,this.col).match(Ec);if(i!==null){this.pastes.delete(parseInt(i[1],10)),this.setCurrentLine(s.slice(0,this.col-i[0].length)+s.slice(this.col)),this.col-=i[0].length;return}this.setCurrentLine(s.slice(0,this.col-1)+s.slice(this.col)),this.col-=1;return}if(this.row===0)return;let e=this.buffer[this.row-1]??"",n=this.currentLine();this.buffer.splice(this.row,1),this.row-=1,this.col=e.length,this.buffer[this.row]=e+n}deleteForward(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(If);if(s!==null){this.pastes.delete(parseInt(s[1],10)),this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+s[0].length));return}this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+1));return}if(this.row<this.buffer.length-1){let n=this.buffer[this.row+1]??"";this.buffer.splice(this.row+1,1),this.setCurrentLine(e+n)}}killLine(){if(this.col>0){let n=this.currentLine();this.killBuffer=n.slice(0,this.col),this.setCurrentLine(n.slice(this.col)),this.col=0;return}if(this.row===0)return;if(this.currentLine().length===0){this.killBuffer=`
193
+ `);if(n.length===1){this.insertChar(n[0]??"");return}let s=this.currentLine(),r=s.slice(0,this.col),i=s.slice(this.col),o=n[0]??"",a=n[n.length-1]??"",c=n.slice(1,-1);this.setCurrentLine(r+o);let d=[...c,a+i];this.buffer.splice(this.row+1,0,...d),this.row+=n.length-1,this.col=a.length}insertNewline(){let e=this.currentLine(),n=e.slice(0,this.col),s=e.slice(this.col);this.setCurrentLine(n),this.buffer.splice(this.row+1,0,s),this.row+=1,this.col=0}backspace(){if(this.col>0){let s=this.currentLine(),i=s.slice(0,this.col).match(Ec);if(i!==null){this.pastes.delete(parseInt(i[1],10)),this.setCurrentLine(s.slice(0,this.col-i[0].length)+s.slice(this.col)),this.col-=i[0].length;return}this.setCurrentLine(s.slice(0,this.col-1)+s.slice(this.col)),this.col-=1;return}if(this.row===0)return;let e=this.buffer[this.row-1]??"",n=this.currentLine();this.buffer.splice(this.row,1),this.row-=1,this.col=e.length,this.buffer[this.row]=e+n}deleteForward(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(xf);if(s!==null){this.pastes.delete(parseInt(s[1],10)),this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+s[0].length));return}this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+1));return}if(this.row<this.buffer.length-1){let n=this.buffer[this.row+1]??"";this.buffer.splice(this.row+1,1),this.setCurrentLine(e+n)}}killLine(){if(this.col>0){let n=this.currentLine();this.killBuffer=n.slice(0,this.col),this.setCurrentLine(n.slice(this.col)),this.col=0;return}if(this.row===0)return;if(this.currentLine().length===0){this.killBuffer=`
194
194
  `,this.buffer.splice(this.row,1),this.row-=1,this.col=this.currentLine().length;return}let e=this.buffer[this.row-1]??"";this.killBuffer=e+`
195
195
  `,this.buffer.splice(this.row-1,1),this.row-=1}killToEnd(){let e=this.currentLine();if(this.col<e.length){this.killBuffer=e.slice(this.col),this.setCurrentLine(e.slice(0,this.col));return}if(this.row>=this.buffer.length-1)return;if(e.length===0){this.killBuffer=`
196
196
  `,this.buffer.splice(this.row,1);return}let n=this.buffer[this.row+1]??"";this.killBuffer=`
197
- `+n,this.buffer.splice(this.row+1,1)}killWord(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(Ec);if(s!==null){this.killBuffer=s[0];let o=this.col-s[0].length;this.setCurrentLine(e.slice(0,o)+e.slice(this.col)),this.col=o;return}let r=this.col;for(;r>0&&/\s/.test(e[r-1]??"");)r-=1;for(;r>0&&!/\s/.test(e[r-1]??"");)r-=1;let i=e.slice(r,this.col);i.length>0&&(this.killBuffer=i),this.setCurrentLine(e.slice(0,r)+e.slice(this.col)),this.col=r}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let n=this.currentLine().slice(0,this.col).match(Ec);if(n!==null){this.col-=n[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 s=e.slice(this.col).match(If);if(s!==null){this.col+=s[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(),n=this.col;for(;n>0&&/\s/.test(e[n-1]??"");)n-=1;let r=e.slice(0,n).match(Ec);if(r!==null){this.col=n-r[0].length;return}for(;n>0&&!/\s/.test(e[n-1]??"");)n-=1;this.col=n}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 n=this.col;for(;n<e.length&&/\s/.test(e[n]??"");)n+=1;let r=e.slice(n).match(If);if(r!==null){this.col=n+r[0].length;return}for(;n<e.length&&!/\s/.test(e[n]??"");)n+=1;this.col=n}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 n=this.findHistoryMatches(e);return n.length===0?[{type:"escalate-search",query:e}]:(this.historySearch={query:e,matchIndices:n,cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},this.loadEntry(this.history[n[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 r=e.query,i=e.savedDraft;return this.historySearch=null,this.buffer=[...i.buffer],this.row=i.row,this.col=i.col,[{type:"escalate-search",query:r}]}e.cursor+=1;let s=e.matchIndices[e.cursor];return this.loadEntry(this.history[s]??""),[]}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 s=this.historySearch.savedDraft;return this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[]}let n=this.findHistoryMatches(e);if(n.length===0){let s=this.historySearch.savedDraft;return this.historySearch=null,this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[{type:"escalate-search",query:e}]}return this.historySearch.query=e,this.historySearch.matchIndices=n,this.historySearch.cursor=0,this.loadEntry(this.history[n[0]]??""),[]}findHistoryMatches(e){let n=[];for(let s=this.history.length-1;s>=0;s--){let r=this.history[s]??"";(e.length===0||r.toLowerCase().includes(e))&&n.push(s)}return n}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(`
198
- `),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=[...this.attachments];return this.clearBuffer(),n.trim().length===0?[{type:"queue-remove",index:i}]:[{type:"queue-edit",index:i,text:n,displayText:e,attachments:o}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"send",text:n,displayText:e,planMode:s,attachments:r}]}amend(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=this.planMode,a=[...this.attachments],c=n.trim().length===0&&a.length===0;return this.clearBuffer(),c?[{type:"queue-remove",index:i}]:[{type:"queue-remove",index:i},{type:"amend",text:n,displayText:e,planMode:o,attachments:a}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:n,displayText:e,planMode:s,attachments:r}]}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,n=(this.buffer[e]??"").length;return this.row!==e||this.col!==n?(this.row=e,this.col=n,[]):[{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"}]}}});var uo,Pc,Af=J(()=>{"use strict";uo=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,n){return e!==this.lastFrameW||n!==this.lastFrameH?(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=n,!0):!1}paintRow(e,n,s){e<1||e>this.term.height||this.lastFrameRows.get(e)!==n&&(this.lastFrameRows.set(e,n),this.term.moveTo(1,e),s(),this.term.styleReset(),this.term.eraseLineAfter())}},Pc=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 s=Date.now()-this.lastRepaintAt;if(s>=e){this.cancel(),this.deps.doRepaint();return}this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.doRepaint()},e-s))}noteRepaintStart(){this.lastRepaintAt=Date.now(),this.cancel()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}}});import KR from"path";function wa(t){return qw[KR.extname(t).toLowerCase()]??null}function JR(t){return wa(t)!==null}function Cf(t){let e=t.match(/^data:(image\/[a-z0-9.+\-]+);base64,([A-Za-z0-9+/=]+)$/);if(!e)return null;let n=e[1].toLowerCase();if(!YR.has(n))return null;let s=e[2],r=s.endsWith("==")?2:s.endsWith("=")?1:0,i=Math.floor(s.length*3/4)-r;return{mimeType:n,data:s,sizeBytes:i}}function VR(t){return Cf(t)!==null}function kn(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function Ww(t){let e=t.trim();if(e.length===0)return null;let n=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]??"");)s++;if(s>=e.length)break;let r=e[s],i="";if(r==="'"||r==='"'){let a=r;for(s++;s<e.length&&e[s]!==a;)i+=e[s],s++;if(s>=e.length)return null;s++}else for(;s<e.length&&!/\s/.test(e[s]??"");)e[s]==="\\"&&s+1<e.length?(i+=e[s+1],s+=2):(i+=e[s],s++);if(i.startsWith("data:")){if(!VR(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!JR(o))return null;n.push(o)}return n.length>0?n:null}var Xn,qw,YR,Mc=J(()=>{"use strict";Xn=10*1024*1024,qw={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};YR=new Set(Object.values(qw))});import QR from"string-width";function zw(t,e){if(!t||e<=0)return 0;let n=0;for(let s of GR.segment(t)){let r=QR(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function Kw(t,e){if(e<=0)return 0;let n=0,s=0;for(let r of t)if(r.width>0&&e<n+r.width||(n+=r.width,s+=r.text.length,r.width>0&&e===n))return s;return s}var GR,Jw=J(()=>{"use strict";GR=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{spawn as XR}from"child_process";import Rf from"fs/promises";import ZR from"os";import e0 from"path";async function Qw(t={}){let e={...Tf,...t};return e.platform==="darwin"?r0(e):e.platform==="linux"?i0(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function Gw(t={}){let e={...Tf,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await fo(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await fo(e,"xclip"))n="xclip",s=["-selection","primary","-o"];else return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste the selection"};else return{ok:!1,reason:`selection paste is not supported on ${e.platform}`};try{let r=await ba(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Ef(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Xw(t,e={}){let{target:n="both",...s}=e,r={...Tf,...s},i=await t0(r,t,n);if(i.ok)return i;let o=n0(r,t,n);return o.ok||o.reason!==Zw?o:i}async function t0(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await _c(t.spawn,"pbcopy",[],s),{ok:!0,method:"pbcopy"}}catch{return{ok:!1,reason:"pbcopy failed"}}if(t.platform==="linux"){let r=n==="clipboard"||n==="both",i=n==="primary"||n==="both";return t.env.WAYLAND_DISPLAY&&await fo(t,"wl-copy")?Vw(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await fo(t,"xclip")?Vw(t,s,"xclip",["-selection","clipboard","-i"],["-selection","primary","-i"],r,i):{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to copy to the clipboard"}}return{ok:!1,reason:`clipboard copy is not supported on ${t.platform}`}}async function Vw(t,e,n,s,r,i,o){let a=n;if(i){try{await _c(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await _c(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await _c(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function n0(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>Yw)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${Yw} bytes)`};let i=`\x1B]52;${n==="both"?"cp":n==="primary"?"p":"c"};${s}\x07`;return t.env.TMUX&&(i=`\x1BPtmux;${i.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`),(t.ttyWrite??s0)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:Zw}}function s0(t){let e=[process.stderr,process.stdout];for(let n of e)if(n&&n.isTTY)try{return n.write(t),!0}catch{}return!1}async function r0(t){let e=e0.join(t.tmpdir(),`hydra-clipboard-${Date.now()}-${process.pid}.png`),n=["set png_data to the clipboard as \xABclass PNGf\xBB",`set out_file to (open for access (POSIX file "${e}") with write permission)`,"write png_data to out_file","close access out_file"],s=[];for(let r of n)s.push("-e",r);try{await eb(t.spawn,"osascript",s);let r=await l0(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await Rf.unlink(e).catch(()=>{})}try{let r=await ba(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Ef(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function i0(t){let e=await o0(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await c0(t,e),s=d0(n);if(s)try{let r=await ba(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>Xn?{ok:!1,reason:`clipboard image is ${kn(r.length)}, max ${kn(Xn)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await ba(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Ef(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function o0(t){return t.env.WAYLAND_DISPLAY&&await fo(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await fo(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function d0(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of a0)if(e.has(n))return n;return null}async function c0(t,e){try{return(await ba(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
199
- `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function Ef(t){return t.replace(/\r\n?/g,`
200
- `)}async function fo(t,e){try{return await eb(t.spawn,"which",[e]),!0}catch{return!1}}async function l0(t,e){try{let n=await Rf.readFile(t);return e&&await Rf.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>Xn?{ok:!1,reason:`clipboard image is ${kn(n.length)}, max ${kn(Xn)}`}:{ok:!0,kind:"image",attachment:{mimeType:wa(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function eb(t,e,n){return new Promise((s,r)=>{let i=t(e,n);i.stdout?.on("data",()=>{}),i.stderr?.on("data",()=>{}),i.on("error",r),i.on("close",o=>{o===0?s():r(new Error(`${e} exited ${o}`))})})}function _c(t,e,n,s){return new Promise((r,i)=>{let o=t(e,n,{stdio:["pipe","ignore","ignore"]});o.stdout?.on("data",()=>{}),o.stderr?.on("data",()=>{}),o.on("error",i),o.on("close",c=>{c===0?r():i(new Error(`${e} exited ${c}`))});let a=o.stdin;if(!a){i(new Error(`${e} has no stdin`));return}a.on("error",i),a.end(s)})}function ba(t,e,n){return new Promise((s,r)=>{let i=t(e,n),o=[],a=i.stdout===null,c=null,d=!1,l=()=>{d||!a||c===null||(d=!0,c===0?s(Buffer.concat(o)):r(new Error(`${e} exited ${c}`)))};i.stdout?.on("data",u=>{o.push(typeof u=="string"?Buffer.from(u):u)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",u=>{d||(d=!0,r(u))}),i.on("close",u=>{c=u??0,l()})})}var Tf,Yw,Zw,a0,Pf=J(()=>{"use strict";Mc();Tf={platform:process.platform,env:process.env,spawn:XR,tmpdir:ZR.tmpdir};Yw=74994;Zw="no TTY available for OSC 52 clipboard write";a0=["image/png","image/jpeg","image/gif","image/webp"]});function u0(){va===0&&process.stdout.write(Gy),va++}function f0(){va!==0&&(va--,va===0&&process.stdout.write(Xy))}function Ne(t){u0();try{t()}finally{f0()}}var va,Mf=J(()=>{"use strict";fa();va=0});import{spawn as p0}from"child_process";import{statSync as h0}from"fs";import{homedir as tb}from"os";import{isAbsolute as nb,resolve as m0}from"path";import Ke from"string-width";import g0 from"wrap-ansi";function A0(t){let e=t.replace(/\r\n?$|\n$/,"");return x0.test(e)?e:null}function C0(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function sb(t,e,n,s=null,r=null,i=null){let o=r===null?"":`a${r}`,a=i===null?"":`s${i.start}:${i.end}${i.toEndOfLine?"f":""}`;if(!n)return`${t}|${e}|empty|${s??""}|${o}|${a}`;let c=n.iterm2Image?`i${n.iterm2Image.heightCells}:${n.iterm2Image.data.length}`:"";return`${t}|${e}|${n.prefix??""}|${n.prefixStyle??""}|${n.body}|${n.bodyStyle??""}|${n.ansi?"1":"0"}|${n.fillRow?"1":"0"}|${s??""}|${o}|${a}|${c}`}function Ss(t,e){let n=[];for(let s=0;s<t.length;s++){let r=t[s]??"";if(r.length===0){n.push({bufferIdx:s,startCol:0,endCol:0});continue}let i=0;for(;i<r.length;){if(r.length-i<=e){n.push({bufferIdx:s,startCol:i,endCol:r.length}),i=r.length;break}let o=-1;for(let a=i+e-1;a>=i;a--){let c=r[a];if(c===" "||c===" "){o=a+1;break}}o===-1&&(o=i+e),n.push({bufferIdx:s,startCol:i,endCol:o}),i=o}}return n.length===0&&n.push({bufferIdx:0,startCol:0,endCol:0}),n}function tr(t,e,n){let s=0,r=0,i=-1;for(let c=0;c<t.length;c++){let d=t[c];if(!(!d||d.bufferIdx!==e.row)&&(i=c,e.col>=d.startCol&&e.col<d.endCol)){s=c,r=e.col-d.startCol,i=-1;break}}if(i!==-1){let c=t[i];c&&(s=i,r=e.col-c.startCol)}let o=Math.min(n,Math.max(1,t.length)),a=0;return t.length>o&&(a=Math.max(0,Math.min(t.length-o,s-(o-1))),s<a&&(a=s),s>=a+o&&(a=s-o+1)),{cursorVisualRow:s,cursorVisualCol:r,windowStart:a,rendered:o}}function rb(t,e,n,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){vs(t,e,n,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){vs(t,e.slice(c),n,o);return}d>c&&vs(t,e.slice(c,d),n,o);let l=r!==null&&d===r;vs(t,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function Sa(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function vs(t,e,n,s=!1){if(e.length!==0){if(s)switch(n){case"tool-status-ok":case"tool-status-pending":case"tool-status-cancelled":case"dim":t.noFormat(e);return;case"plan-pending":t(e);return;case"thought":{let r=e.replace(/\^\^|\^K/g,i=>i==="^K"?"\x1B[39m":i);t.bgColorGrayscale(25)(r);return}case"code":t.bgColorGrayscale.white.noFormat(60,e);return}switch(n){case"user":t.bgColorGrayscale.bold.noFormat(43,e);return;case"agent":t(e);return;case"thought":t.brightBlack(e);return;case"tool":t.brightBlue.noFormat(e);return;case"tool-status-ok":t.dim.noFormat(e);return;case"tool-status-fail":t.bold.red.noFormat(e);return;case"tool-status-pending":t.dim.noFormat(e);return;case"tool-status-running":t.brightYellow.noFormat(e);return;case"tool-status-cancelled":t.dim.noFormat(e);return;case"plan":t.brightYellow(e);return;case"plan-done":t.green(e);return;case"plan-pending":t.dim(e);return;case"system":t.brightYellow.noFormat(e);return;case"info":t.cyan.noFormat(e);return;case"dim":t.dim.noFormat(e);return;case"code":t.bgColorGrayscale.white.noFormat(28,e);return;case"heading-1":t.bold.brightYellow(e);return;case"heading-2":t.bold.brightCyan(e);return;case"heading-3":t.bold(e);return;case"search-highlight":t.bgBrightYellow.black.noFormat(e);return;case"selection-highlight":t.inverse.noFormat(e);return;case"search-highlight-active":t.bgRed.brightWhite.noFormat(e);return;default:t.noFormat(e)}}}function R0(t,e){return e<=0?[t]:t.length===0?[""]:g0(t,e,{hard:!0,trim:!1}).split(`
201
- `)}function pb(t){fb=t}function hb(t,e){if(t==="wide")return!0;if(t==="narrow")return!1;let n=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!(/^(ja|ko|zh)(_|\.|@|$)/i.test(n)||e.TERM_PROGRAM==="Apple_Terminal")}function er(t){return Ke(t,{ambiguousIsNarrow:!fb})}function po(t,e){if(t.charCodeAt(e)!==94)return null;let n=t[e+1];if(n===void 0)return null;if(n==="^")return{text:"^^",width:1};if(n==="["){let s=t.indexOf("]",e+2);if(s!==-1)return{text:t.slice(e,s+1),width:0}}return T0.test(n)?{text:t.slice(e,e+2),width:0}:null}function ib(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=po(t,s);if(r){r.width>0&&(n+="^");for(let i=1;i<r.text.length;i++)e[s+i]=n.length;s+=r.text.length;continue}n+=t[s],s+=1}return e[t.length]=n.length,{clean:n,rawToClean:e}}function ob(t){if(!t.includes("^"))return t;let e="",n=0;for(;n<t.length;){let s=po(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function E0(t){if(!t.includes("^"))return"";let e="",n=0;for(;n<t.length;){let s=po(t,n);if(s){s.width===0&&(e+=s.text),n+=s.text.length;continue}n+=1}return e}function mb(t){if(!t.includes("^"))return!1;for(let e=0;e<t.length;e++)if(po(t,e))return!0;return!1}function*jf(t){let e=0;for(;e<t.length;){let n=po(t,e);if(n){yield{text:n.text,width:n.width},e+=n.text.length;continue}let s=t.length,r=t.indexOf("^",e);for(;r!==-1&&r<t.length;){if(po(t,r)){s=r;break}r=t.indexOf("^",r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of Uf.segment(t.slice(e,s)))yield{text:i,width:er(i)};e=s}}function P0(t,e,n){let s=`\x1B]1337;File=inline=1;height=${e};preserveAspectRatio=1:${t}\x07`;return n?`\x1BPtmux;${s.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`:s}function M0(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&mb(t);return!s&&!ub.test(t)?_0(t,e):$0(t,e,s)}function _0(t,e){let n=[],s=t;for(;s.length>e;){let r=s.slice(0,e+1),i=-1;for(let o=Math.min(e,r.length-1);o>=0;o--)if(r[o]===" "){i=o;break}i<=0?(n.push(s.slice(0,e)),s=s.slice(e)):(n.push(s.slice(0,i)),s=s.slice(i+1))}return n.push(s),n}function $0(t,e,n){let s=[],r=n?[...jf(t)]:F0(t),i=0;for(;i<r.length;){let o="",a=0,c=-1,d="";for(;i<r.length;){let l=r[i];if(a+l.width>e){l.text===" "&&l.width===1&&(c=i,d=o);break}l.text===" "&&l.width===1&&(c=i,d=o),o+=l.text,a+=l.width,i+=1}if(i>=r.length){s.push(o);break}c>=0?(s.push(d),i=c+1):o.length===0?(s.push(r[i].text),i+=1):s.push(o)}return s}function F0(t){let e=[];for(let{segment:n}of Uf.segment(t))e.push({text:n,width:er(n)});return e}function kt(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&mb(t);if(!s&&t.length<=e&&!ub.test(t))return t;if(!s)return er(t)<=e?t:e<=1?ab(t,e):ab(t,e-1)+"\u2026";let r=[...jf(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?db(r,e):db(r,e-1)+"\u2026"}function ab(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of Uf.segment(t)){let i=er(r);if(s+i>e)break;n+=r,s+=i}return n}function db(t,e){if(e<=0)return"";let n="",s=0;for(let r of t){if(s+r.width>e)break;n+=r.text,s+=r.width}return n}function O0(t){let e=t.indexOf(`
202
- `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function cb(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${Fc(t.used)}/${Fc(t.size)}`):e.push(Fc(t.used)):typeof t.size=="number"&&e.push(`/${Fc(t.size)}`),typeof t.costAmount=="number"&&e.push(Nu(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Fc(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function Lc(t){switch(t){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_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"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_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function Kr(){let t=[so,ro,Ky,io,Jy,ff,ys,Ur,jr,Hr,Dr,"\x1B>",la,gc,yc,"\x1B]9;4;0\x07",jy].join("");try{process.stdout.write(t)}catch{}}function gb(t){let e=[["width",80],["height",24]];for(let[n,s]of e){let r=Object.getOwnPropertyDescriptor(t,n);if(r&&r.get)continue;let i=Symbol(`raw-${n}`),o=t;o[i]=r?r.value:void 0,Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){let a=this[i];return typeof a=="number"&&Number.isFinite(a)&&a>0?a:s},set(a){this[i]=a}})}}function lb(t,e){let n={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?n[t]??null:t===27?"escape":t===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:t===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:t===127&&e===1?"backspace":(t===95||t===47)&&e===5?"ctrl-underscore":(t===95||t===47)&&e===7?"alt-underscore":e===3?t===98||t===66?"alt-b":t===102||t===70?"alt-f":t===110||t===78?"alt-n":t===95?"alt-underscore":null:null}var _f,$c,$f,Ff,y0,Ue,Qe,w0,Ge,Of,Lf,b0,v0,S0,Bf,Nf,Df,k0,I0,x0,Oc,ub,Uf,fb,T0,Hf,qf=J(()=>{"use strict";Af();Du();he();qn();Mc();eo();Jw();Pf();Mf();Cr();fa();_f=500,$c=1,$f=/[A-Za-z0-9_]/,Ff=/[A-Za-z0-9_./\-~+@]/,y0=/\x1b\[[0-9;]*[A-Za-z]/g,Ue=1,Qe=0,w0=1,Ge=1,Of=8,Lf=5,b0=12,v0=12,S0=30,Bf=6,Nf=4,Df=2,k0=1e3,I0=1e4,x0=/^(https?|ftp):\/\/\S+$/;Oc=class{term;dispatcher;onKey;onBlockClick;onBlockDoubleClick;onMouse;onHoverRun;onBlockVisible;onSuspend;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;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;compactionPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};bannerHits=null;hoveredBannerHit=null;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;doubleClickPending=!1;lastLeftClick=null;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;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 n=e.onKey;this.onKey=i=>{this.selection!==null&&i.length>0&&this.clearSelection(),n(i)},this.onBlockClick=e.onBlockClick,this.onBlockDoubleClick=e.onBlockDoubleClick,this.onMouse=e.onMouse,this.onHoverRun=e.onHoverRun,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??k0,this.painter=new uo(this.term),this.scheduler=new Pc({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??I0,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both";let s=e.openFileCommand,r=typeof s=="string"?s.split(/\s+/).filter(i=>i.length>0):s;this.openFileCommand=r&&r.length>0?r:null,this.progressIndicatorEnabled=e.progressIndicator??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>this.repaint(),this.keyHandler=(i,o,a)=>this.handleKey(i,a),this.mouseHandler=(i,o)=>this.handleMouse(i,o),this.rawStdinHandler=i=>this.handleRawStdin(i)}start(e={}){this.started||(this.started=!0,e.skipFullscreen||this.term.fullscreen(!0),this.painter.clearCache(),this.lastWindowTitle=null,process.stdout.write(uf),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),se({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&&(this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.scheduler.cancel(),this.cancelPendingBlockClick(),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),se({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(yc),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(la),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(Kr(),this.term.fullscreen(!1),this.term(`
203
- `)))}installBracketedPaste(){process.stdout.write(mc),process.stdout.write(Wy),process.stdout.write(zy),process.stdout.write(qy),process.stdout.write(wc);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(){process.stdout.write(ys),process.stdout.write(Ur),process.stdout.write(jr),process.stdout.write(Hr),process.stdout.write(ua),process.stdout.write(Dr),process.stdout.write("\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,process.stdout.write(Yy),this.selectiveMouseProbeTimer=setTimeout(()=>{this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer=null},250))}uninstallSelectiveMouseReporting(){this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseProbing=!1,this.selectiveMouseSupported&&(process.stdout.write(ff),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>Kr(),this.onProcessSignal=e=>{Kr(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{Kr(),process.stderr.write(`
197
+ `+n,this.buffer.splice(this.row+1,1)}killWord(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(Ec);if(s!==null){this.killBuffer=s[0];let o=this.col-s[0].length;this.setCurrentLine(e.slice(0,o)+e.slice(this.col)),this.col=o;return}let r=this.col;for(;r>0&&/\s/.test(e[r-1]??"");)r-=1;for(;r>0&&!/\s/.test(e[r-1]??"");)r-=1;let i=e.slice(r,this.col);i.length>0&&(this.killBuffer=i),this.setCurrentLine(e.slice(0,r)+e.slice(this.col)),this.col=r}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let n=this.currentLine().slice(0,this.col).match(Ec);if(n!==null){this.col-=n[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 s=e.slice(this.col).match(xf);if(s!==null){this.col+=s[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(),n=this.col;for(;n>0&&/\s/.test(e[n-1]??"");)n-=1;let r=e.slice(0,n).match(Ec);if(r!==null){this.col=n-r[0].length;return}for(;n>0&&!/\s/.test(e[n-1]??"");)n-=1;this.col=n}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 n=this.col;for(;n<e.length&&/\s/.test(e[n]??"");)n+=1;let r=e.slice(n).match(xf);if(r!==null){this.col=n+r[0].length;return}for(;n<e.length&&!/\s/.test(e[n]??"");)n+=1;this.col=n}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 n=this.findHistoryMatches(e);return n.length===0?[{type:"escalate-search",query:e}]:(this.historySearch={query:e,matchIndices:n,cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},this.loadEntry(this.history[n[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 r=e.query,i=e.savedDraft;return this.historySearch=null,this.buffer=[...i.buffer],this.row=i.row,this.col=i.col,[{type:"escalate-search",query:r}]}e.cursor+=1;let s=e.matchIndices[e.cursor];return this.loadEntry(this.history[s]??""),[]}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 s=this.historySearch.savedDraft;return this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[]}let n=this.findHistoryMatches(e);if(n.length===0){let s=this.historySearch.savedDraft;return this.historySearch=null,this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[{type:"escalate-search",query:e}]}return this.historySearch.query=e,this.historySearch.matchIndices=n,this.historySearch.cursor=0,this.loadEntry(this.history[n[0]]??""),[]}findHistoryMatches(e){let n=[];for(let s=this.history.length-1;s>=0;s--){let r=this.history[s]??"";(e.length===0||r.toLowerCase().includes(e))&&n.push(s)}return n}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(`
198
+ `),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=[...this.attachments];return this.clearBuffer(),n.trim().length===0?[{type:"queue-remove",index:i}]:[{type:"queue-edit",index:i,text:n,displayText:e,attachments:o}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"send",text:n,displayText:e,planMode:s,attachments:r}]}amend(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=this.planMode,a=[...this.attachments],c=n.trim().length===0&&a.length===0;return this.clearBuffer(),c?[{type:"queue-remove",index:i}]:[{type:"queue-remove",index:i},{type:"amend",text:n,displayText:e,planMode:o,attachments:a}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:n,displayText:e,planMode:s,attachments:r}]}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,n=(this.buffer[e]??"").length;return this.row!==e||this.col!==n?(this.row=e,this.col=n,[]):[{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"}]}}});var fo,Pc,Cf=J(()=>{"use strict";fo=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,n){return e!==this.lastFrameW||n!==this.lastFrameH?(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=n,!0):!1}paintRow(e,n,s){e<1||e>this.term.height||this.lastFrameRows.get(e)!==n&&(this.lastFrameRows.set(e,n),this.term.moveTo(1,e),s(),this.term.styleReset(),this.term.eraseLineAfter())}},Pc=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 s=Date.now()-this.lastRepaintAt;if(s>=e){this.cancel(),this.deps.doRepaint();return}this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.doRepaint()},e-s))}noteRepaintStart(){this.lastRepaintAt=Date.now(),this.cancel()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}}});import GR from"path";function ba(t){return zw[GR.extname(t).toLowerCase()]??null}function XR(t){return ba(t)!==null}function Rf(t){let e=t.match(/^data:(image\/[a-z0-9.+\-]+);base64,([A-Za-z0-9+/=]+)$/);if(!e)return null;let n=e[1].toLowerCase();if(!ZR.has(n))return null;let s=e[2],r=s.endsWith("==")?2:s.endsWith("=")?1:0,i=Math.floor(s.length*3/4)-r;return{mimeType:n,data:s,sizeBytes:i}}function e0(t){return Rf(t)!==null}function kn(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function Kw(t){let e=t.trim();if(e.length===0)return null;let n=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]??"");)s++;if(s>=e.length)break;let r=e[s],i="";if(r==="'"||r==='"'){let a=r;for(s++;s<e.length&&e[s]!==a;)i+=e[s],s++;if(s>=e.length)return null;s++}else for(;s<e.length&&!/\s/.test(e[s]??"");)e[s]==="\\"&&s+1<e.length?(i+=e[s+1],s+=2):(i+=e[s],s++);if(i.startsWith("data:")){if(!e0(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!XR(o))return null;n.push(o)}return n.length>0?n:null}var Xn,zw,ZR,Mc=J(()=>{"use strict";Xn=10*1024*1024,zw={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};ZR=new Set(Object.values(zw))});import t0 from"string-width";function Jw(t,e){if(!t||e<=0)return 0;let n=0;for(let s of n0.segment(t)){let r=t0(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function Vw(t,e){if(e<=0)return 0;let n=0,s=0;for(let r of t)if(r.width>0&&e<n+r.width||(n+=r.width,s+=r.text.length,r.width>0&&e===n))return s;return s}var n0,Yw=J(()=>{"use strict";n0=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{spawn as s0}from"child_process";import Tf from"fs/promises";import r0 from"os";import i0 from"path";async function Xw(t={}){let e={...Ef,...t};return e.platform==="darwin"?c0(e):e.platform==="linux"?l0(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function Zw(t={}){let e={...Ef,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await po(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await po(e,"xclip"))n="xclip",s=["-selection","primary","-o"];else return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste the selection"};else return{ok:!1,reason:`selection paste is not supported on ${e.platform}`};try{let r=await va(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Pf(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function eb(t,e={}){let{target:n="both",...s}=e,r={...Ef,...s},i=await o0(r,t,n);if(i.ok)return i;let o=a0(r,t,n);return o.ok||o.reason!==tb?o:i}async function o0(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await _c(t.spawn,"pbcopy",[],s),{ok:!0,method:"pbcopy"}}catch{return{ok:!1,reason:"pbcopy failed"}}if(t.platform==="linux"){let r=n==="clipboard"||n==="both",i=n==="primary"||n==="both";return t.env.WAYLAND_DISPLAY&&await po(t,"wl-copy")?Gw(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await po(t,"xclip")?Gw(t,s,"xclip",["-selection","clipboard","-i"],["-selection","primary","-i"],r,i):{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to copy to the clipboard"}}return{ok:!1,reason:`clipboard copy is not supported on ${t.platform}`}}async function Gw(t,e,n,s,r,i,o){let a=n;if(i){try{await _c(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await _c(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await _c(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function a0(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>Qw)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${Qw} bytes)`};let i=`\x1B]52;${n==="both"?"cp":n==="primary"?"p":"c"};${s}\x07`;return t.env.TMUX&&(i=`\x1BPtmux;${i.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`),(t.ttyWrite??d0)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:tb}}function d0(t){let e=[process.stderr,process.stdout];for(let n of e)if(n&&n.isTTY)try{return n.write(t),!0}catch{}return!1}async function c0(t){let e=i0.join(t.tmpdir(),`hydra-clipboard-${Date.now()}-${process.pid}.png`),n=["set png_data to the clipboard as \xABclass PNGf\xBB",`set out_file to (open for access (POSIX file "${e}") with write permission)`,"write png_data to out_file","close access out_file"],s=[];for(let r of n)s.push("-e",r);try{await nb(t.spawn,"osascript",s);let r=await m0(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await Tf.unlink(e).catch(()=>{})}try{let r=await va(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Pf(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function l0(t){let e=await u0(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await h0(t,e),s=p0(n);if(s)try{let r=await va(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>Xn?{ok:!1,reason:`clipboard image is ${kn(r.length)}, max ${kn(Xn)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await va(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Pf(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function u0(t){return t.env.WAYLAND_DISPLAY&&await po(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await po(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function p0(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of f0)if(e.has(n))return n;return null}async function h0(t,e){try{return(await va(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
199
+ `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function Pf(t){return t.replace(/\r\n?/g,`
200
+ `)}async function po(t,e){try{return await nb(t.spawn,"which",[e]),!0}catch{return!1}}async function m0(t,e){try{let n=await Tf.readFile(t);return e&&await Tf.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>Xn?{ok:!1,reason:`clipboard image is ${kn(n.length)}, max ${kn(Xn)}`}:{ok:!0,kind:"image",attachment:{mimeType:ba(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function nb(t,e,n){return new Promise((s,r)=>{let i=t(e,n);i.stdout?.on("data",()=>{}),i.stderr?.on("data",()=>{}),i.on("error",r),i.on("close",o=>{o===0?s():r(new Error(`${e} exited ${o}`))})})}function _c(t,e,n,s){return new Promise((r,i)=>{let o=t(e,n,{stdio:["pipe","ignore","ignore"]});o.stdout?.on("data",()=>{}),o.stderr?.on("data",()=>{}),o.on("error",i),o.on("close",c=>{c===0?r():i(new Error(`${e} exited ${c}`))});let a=o.stdin;if(!a){i(new Error(`${e} has no stdin`));return}a.on("error",i),a.end(s)})}function va(t,e,n){return new Promise((s,r)=>{let i=t(e,n),o=[],a=i.stdout===null,c=null,d=!1,l=()=>{d||!a||c===null||(d=!0,c===0?s(Buffer.concat(o)):r(new Error(`${e} exited ${c}`)))};i.stdout?.on("data",u=>{o.push(typeof u=="string"?Buffer.from(u):u)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",u=>{d||(d=!0,r(u))}),i.on("close",u=>{c=u??0,l()})})}var Ef,Qw,tb,f0,Mf=J(()=>{"use strict";Mc();Ef={platform:process.platform,env:process.env,spawn:s0,tmpdir:r0.tmpdir};Qw=74994;tb="no TTY available for OSC 52 clipboard write";f0=["image/png","image/jpeg","image/gif","image/webp"]});function g0(){Sa===0&&process.stdout.write(Zy),Sa++}function y0(){Sa!==0&&(Sa--,Sa===0&&process.stdout.write(ew))}function Ne(t){g0();try{t()}finally{y0()}}var Sa,_f=J(()=>{"use strict";pa();Sa=0});import{spawn as w0}from"child_process";import{statSync as b0}from"fs";import{homedir as sb}from"os";import{isAbsolute as rb,resolve as v0}from"path";import je from"string-width";import S0 from"wrap-ansi";function E0(t){let e=t.replace(/\r\n?$|\n$/,"");return T0.test(e)?e:null}function P0(t,e){return!t||typeof t!="object"?!1:t[e]===!0}function M0(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function _0(t,e){if(t.body!==e.body||(t.prefix??"")!==(e.prefix??"")||(t.bodyStyle??"")!==(e.bodyStyle??"")||(t.prefixStyle??"")!==(e.prefixStyle??"")||!!t.ansi!=!!e.ansi||!!t.fillRow!=!!e.fillRow||!!t.collapsed!=!!e.collapsed||(t.blockKey??"")!==(e.blockKey??"")||(t.hoverSubKey??"")!==(e.hoverSubKey??""))return!1;let n=t.iterm2Image,s=e.iterm2Image;if(n===void 0!=(s===void 0)||n&&s&&(n.data!==s.data||n.heightCells!==s.heightCells))return!1;let r=t.links,i=e.links;if(r===void 0!=(i===void 0))return!1;if(r&&i){if(r.length!==i.length)return!1;for(let o=0;o<r.length;o++){let a=r[o],c=i[o];if(a.start!==c.start||a.end!==c.end||a.url!==c.url)return!1}}return!0}function ab(t,e,n,s=null,r=null,i=null){let o=r===null?"":`a${r}`,a=i===null?"":`s${i.start}:${i.end}${i.toEndOfLine?"f":""}`;if(!n)return`${t}|${e}|empty|${s??""}|${o}|${a}`;let c=n.iterm2Image?`i${n.iterm2Image.heightCells}:${n.iterm2Image.data.length}`:"";return`${t}|${e}|${n.prefix??""}|${n.prefixStyle??""}|${n.body}|${n.bodyStyle??""}|${n.ansi?"1":"0"}|${n.fillRow?"1":"0"}|${s??""}|${o}|${a}|${c}`}function Ss(t,e){let n=[];for(let s=0;s<t.length;s++){let r=t[s]??"";if(r.length===0){n.push({bufferIdx:s,startCol:0,endCol:0});continue}let i=0;for(;i<r.length;){if(r.length-i<=e){n.push({bufferIdx:s,startCol:i,endCol:r.length}),i=r.length;break}let o=-1;for(let a=i+e-1;a>=i;a--){let c=r[a];if(c===" "||c===" "){o=a+1;break}}o===-1&&(o=i+e),n.push({bufferIdx:s,startCol:i,endCol:o}),i=o}}return n.length===0&&n.push({bufferIdx:0,startCol:0,endCol:0}),n}function tr(t,e,n){let s=0,r=0,i=-1;for(let c=0;c<t.length;c++){let d=t[c];if(!(!d||d.bufferIdx!==e.row)&&(i=c,e.col>=d.startCol&&e.col<d.endCol)){s=c,r=e.col-d.startCol,i=-1;break}}if(i!==-1){let c=t[i];c&&(s=i,r=e.col-c.startCol)}let o=Math.min(n,Math.max(1,t.length)),a=0;return t.length>o&&(a=Math.max(0,Math.min(t.length-o,s-(o-1))),s<a&&(a=s),s>=a+o&&(a=s-o+1)),{cursorVisualRow:s,cursorVisualCol:r,windowStart:a,rendered:o}}function db(t,e,n,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){Zn(t,e,n,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){Zn(t,e.slice(c),n,o);return}d>c&&Zn(t,e.slice(c,d),n,o);let l=r!==null&&d===r;Zn(t,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function ka(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function Zn(t,e,n,s=!1){if(e.length!==0){if(s)switch(n){case"tool-status-ok":case"tool-status-pending":case"tool-status-cancelled":case"dim":t.noFormat(e);return;case"plan-pending":t(e);return;case"thought":{let r=e.replace(/\^\^|\^K/g,i=>i==="^K"?"\x1B[39m":i);t.bgColorGrayscale(25)(r);return}case"code":{t.noFormat(`\x1B[48;2;22;25;36m${e}\x1B[49m`);return}}switch(n){case"user":t.bgColorGrayscale.bold.noFormat(43,e);return;case"agent":t(e);return;case"thought":t.brightBlack(e);return;case"tool":t.brightBlue.noFormat(e);return;case"tool-status-ok":t.dim.noFormat(e);return;case"tool-status-fail":t.bold.red.noFormat(e);return;case"tool-status-pending":t.dim.noFormat(e);return;case"tool-status-running":t.brightYellow.noFormat(e);return;case"tool-status-cancelled":t.dim.noFormat(e);return;case"plan":t.brightYellow(e);return;case"plan-done":t.green(e);return;case"plan-pending":t.dim(e);return;case"system":t.brightYellow.noFormat(e);return;case"info":t.cyan.noFormat(e);return;case"dim":t.dim.noFormat(e);return;case"code":t.bgColorGrayscale.white.noFormat(28,e);return;case"heading-1":t.bold.brightYellow(e);return;case"heading-2":t.bold.brightCyan(e);return;case"heading-3":t.bold(e);return;case"search-highlight":t.bgBrightYellow.black.noFormat(e);return;case"selection-highlight":t.inverse.noFormat(e);return;case"search-highlight-active":t.bgRed.brightWhite.noFormat(e);return;default:t.noFormat(e)}}}function $0(t,e){return e<=0?[t]:t.length===0?[""]:S0(t,e,{hard:!0,trim:!1}).split(`
201
+ `)}function gb(t){mb=t}function yb(t,e){if(t==="wide")return!0;if(t==="narrow")return!1;let n=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!(/^(ja|ko|zh)(_|\.|@|$)/i.test(n)||e.TERM_PROGRAM==="Apple_Terminal")}function er(t){return je(t,{ambiguousIsNarrow:!mb})}function ho(t,e){if(t.charCodeAt(e)!==94)return null;let n=t[e+1];if(n===void 0)return null;if(n==="^")return{text:"^^",width:1};if(n==="["){let s=t.indexOf("]",e+2);if(s!==-1)return{text:t.slice(e,s+1),width:0}}return O0.test(n)?{text:t.slice(e,e+2),width:0}:null}function Uf(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=ho(t,s);if(r){r.width>0&&(n+="^");for(let i=1;i<r.text.length;i++)e[s+i]=n.length;s+=r.text.length;continue}n+=t[s],s+=1}return e[t.length]=n.length,{clean:n,rawToClean:e}}function cb(t){if(!t.includes("^"))return t;let e="",n=0;for(;n<t.length;){let s=ho(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function F0(t){if(!t.includes("^"))return"";let e="",n=0;for(;n<t.length;){let s=ho(t,n);if(s){s.width===0&&(e+=s.text),n+=s.text.length;continue}n+=1}return e}function wb(t){if(!t.includes("^"))return!1;for(let e=0;e<t.length;e++)if(ho(t,e))return!0;return!1}function*qf(t){let e=0;for(;e<t.length;){let n=ho(t,e);if(n){yield{text:n.text,width:n.width},e+=n.text.length;continue}let s=t.length,r=t.indexOf("^",e);for(;r!==-1&&r<t.length;){if(ho(t,r)){s=r;break}r=t.indexOf("^",r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of jf.segment(t.slice(e,s)))yield{text:i,width:er(i)};e=s}}function L0(t,e,n){let s=`\x1B]1337;File=inline=1;height=${e};preserveAspectRatio=1:${t}\x07`;return n?`\x1BPtmux;${s.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`:s}function B0(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&wb(t);return!s&&!hb.test(t)?N0(t,e):D0(t,e,s)}function N0(t,e){let n=[],s=t;for(;s.length>e;){let r=s.slice(0,e+1),i=-1;for(let o=Math.min(e,r.length-1);o>=0;o--)if(r[o]===" "){i=o;break}i<=0?(n.push(s.slice(0,e)),s=s.slice(e)):(n.push(s.slice(0,i)),s=s.slice(i+1))}return n.push(s),n}function D0(t,e,n){let s=[],r=n?[...qf(t)]:H0(t),i=0;for(;i<r.length;){let o="",a=0,c=-1,d="";for(;i<r.length;){let l=r[i];if(a+l.width>e){l.text===" "&&l.width===1&&(c=i,d=o);break}l.text===" "&&l.width===1&&(c=i,d=o),o+=l.text,a+=l.width,i+=1}if(i>=r.length){s.push(o);break}c>=0?(s.push(d),i=c+1):o.length===0?(s.push(r[i].text),i+=1):s.push(o)}return s}function H0(t){let e=[];for(let{segment:n}of jf.segment(t))e.push({text:n,width:er(n)});return e}function kt(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&wb(t);if(!s&&t.length<=e&&!hb.test(t))return t;if(!s)return er(t)<=e?t:e<=1?lb(t,e):lb(t,e-1)+"\u2026";let r=[...qf(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?ub(r,e):ub(r,e-1)+"\u2026"}function lb(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of jf.segment(t)){let i=er(r);if(s+i>e)break;n+=r,s+=i}return n}function ub(t,e){if(e<=0)return"";let n="",s=0;for(let r of t){if(s+r.width>e)break;n+=r.text,s+=r.width}return n}function U0(t){let e=t.indexOf(`
202
+ `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function fb(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${Fc(t.used)}/${Fc(t.size)}`):e.push(Fc(t.used)):typeof t.size=="number"&&e.push(`/${Fc(t.size)}`),typeof t.costAmount=="number"&&e.push(Du(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Fc(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function Bc(t){switch(t){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_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"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_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function Kr(){let t=[ro,io,Vy,oo,Yy,pf,ws,Ur,jr,Hr,Dr,"\x1B>",ua,gc,yc,"\x1B]9;4;0\x07",Wy].join("");try{process.stdout.write(t)}catch{}}function bb(t){let e=[["width",80],["height",24]];for(let[n,s]of e){let r=Object.getOwnPropertyDescriptor(t,n);if(r&&r.get)continue;let i=Symbol(`raw-${n}`),o=t;o[i]=r?r.value:void 0,Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){let a=this[i];return typeof a=="number"&&Number.isFinite(a)&&a>0?a:s},set(a){this[i]=a}})}}function pb(t,e){let n={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?n[t]??null:t===27?"escape":t===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:t===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:t===127&&e===1?"backspace":(t===95||t===47)&&e===5?"ctrl-underscore":(t===95||t===47)&&e===7?"alt-underscore":e===3?t===98||t===66?"alt-b":t===102||t===70?"alt-f":t===110||t===78?"alt-n":t===95?"alt-underscore":null:null}var $f,$c,Of,Ff,ib,ob,Ue,Je,k0,Ve,Lf,Bf,I0,x0,A0,Nf,Df,Hf,C0,R0,T0,Lc,hb,jf,mb,O0,Oc,Wf=J(()=>{"use strict";Cf();Hu();he();qn();Mc();to();Yw();Mf();_f();Cr();pa();$f=500,$c=1,Of=/[A-Za-z0-9_]/,Ff=/[A-Za-z0-9_./\-~+@]/,ib=/\x1b\[[0-9;]*[A-Za-z]/g,ob=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,Ue=1,Je=0,k0=1,Ve=1,Lf=8,Bf=5,I0=12,x0=12,A0=30,Nf=6,Df=4,Hf=2,C0=1e3,R0=1e4,T0=/^(https?|ftp):\/\/\S+$/;Lc=class t{term;dispatcher;onKey;onBlockClick;onBlockDoubleClick;onHydraLinkClick;onMouse;onHoverRun;onBlockVisible;onSuspend;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;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;compactionPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};bannerHits=null;hoveredBannerHit=null;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;doubleClickPending=!1;lastLeftClick=null;autoscrollTimer=null;autoscrollCell=null;autoscrollDir=1;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;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 n=e.onKey;this.onKey=i=>{this.selection!==null&&i.length>0&&this.clearSelection(),n(i)},this.onBlockClick=e.onBlockClick,this.onBlockDoubleClick=e.onBlockDoubleClick,this.onHydraLinkClick=e.onHydraLinkClick,this.onMouse=e.onMouse,this.onHoverRun=e.onHoverRun,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??C0,this.painter=new fo(this.term),this.scheduler=new Pc({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??R0,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both";let s=e.openFileCommand,r=typeof s=="string"?s.split(/\s+/).filter(i=>i.length>0):s;this.openFileCommand=r&&r.length>0?r:null,this.progressIndicatorEnabled=e.progressIndicator??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>this.repaint(),this.keyHandler=(i,o,a)=>this.handleKey(i,a),this.mouseHandler=(i,o)=>this.handleMouse(i,o),this.rawStdinHandler=i=>this.handleRawStdin(i)}start(e={}){this.started||(this.started=!0,e.skipFullscreen||this.term.fullscreen(!0),this.painter.clearCache(),this.lastWindowTitle=null,process.stdout.write(ff),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),se({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&&(this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),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),se({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(yc),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(ua),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(Kr(),this.term.fullscreen(!1),this.term(`
203
+ `)))}installBracketedPaste(){process.stdout.write(mc),process.stdout.write(Ky),process.stdout.write(Jy),process.stdout.write(zy),process.stdout.write(wc);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(){process.stdout.write(ws),process.stdout.write(Ur),process.stdout.write(jr),process.stdout.write(Hr),process.stdout.write(fa),process.stdout.write(Dr),process.stdout.write("\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,process.stdout.write(Qy),this.selectiveMouseProbeTimer=setTimeout(()=>{this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer=null},250))}uninstallSelectiveMouseReporting(){this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseProbing=!1,this.selectiveMouseSupported&&(process.stdout.write(pf),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>Kr(),this.onProcessSignal=e=>{Kr(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{Kr(),process.stderr.write(`
204
204
  uncaught: ${e.stack??e.message}
205
- `),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,process.stdout.write(Vy),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let n=/\x1b\[<(64|65);\d+;\d+M/g,s="",r=0,i;for(;(i=n.exec(e))!==null;)s+=e.slice(r,i.index),i[1]==="64"?this.scrollBy(3):this.scrollBy(-3),r=i.index+i[0].length;return s+=e.slice(r),s}handleRawStdin(e){let n=e.toString("binary");if(n=this.consumeSelectiveMouseSequences(n),n.includes("\x1B[I")||n.includes("\x1B[O"))for(;;){let s=n.indexOf("\x1B[I"),r=n.indexOf("\x1B[O"),i=s===-1?r:r===-1?s:Math.min(s,r);if(i===-1)break;let o=i===s;this.terminalFocused=o,o&&(this.lastFocusInAt=Date.now()),n=n.slice(0,i)+n.slice(i+"\x1B[I".length)}if(n.length!==0){if(this.pasteActive){this.handleRawStdinSegment(n);return}if(n===""&&this.onSuspend){this.onSuspend();return}if(this.onSuspend&&(n==="\x1B[27;5;122~"||n==="\x1B[122;5u")){this.onSuspend();return}if(n===""){this.onKey([{type:"key",name:"ctrl-underscore"}]);return}if(n==="\x1B"||n==="\x1B_"){this.onKey([{type:"key",name:"alt-underscore"}]);return}if(/\x1b\[27;\d+;\d+~/.test(n)){this.handleCsi27Stdin(n);return}if(n.includes(no)){this.handleRawStdinSegment(n);return}if(n.includes(`
205
+ `),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,process.stdout.write(Gy),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let n=/\x1b\[<(64|65);\d+;\d+M/g,s="",r=0,i;for(;(i=n.exec(e))!==null;)s+=e.slice(r,i.index),i[1]==="64"?this.scrollBy(3):this.scrollBy(-3),r=i.index+i[0].length;return s+=e.slice(r),s}handleRawStdin(e){let n=e.toString("binary");if(n=this.consumeSelectiveMouseSequences(n),n.includes("\x1B[I")||n.includes("\x1B[O"))for(;;){let s=n.indexOf("\x1B[I"),r=n.indexOf("\x1B[O"),i=s===-1?r:r===-1?s:Math.min(s,r);if(i===-1)break;let o=i===s;this.terminalFocused=o,o&&(this.lastFocusInAt=Date.now()),n=n.slice(0,i)+n.slice(i+"\x1B[I".length)}if(n.length!==0){if(this.pasteActive){this.handleRawStdinSegment(n);return}if(n===""&&this.onSuspend){this.onSuspend();return}if(this.onSuspend&&(n==="\x1B[27;5;122~"||n==="\x1B[122;5u")){this.onSuspend();return}if(n===""){this.onKey([{type:"key",name:"ctrl-underscore"}]);return}if(n==="\x1B"||n==="\x1B_"){this.onKey([{type:"key",name:"alt-underscore"}]);return}if(/\x1b\[27;\d+;\d+~/.test(n)){this.handleCsi27Stdin(n);return}if(n.includes(so)){this.handleRawStdinSegment(n);return}if(n.includes(`
206
206
  `)){let s=n.split(`
207
- `);if(s.filter(i=>i.length>0).length>1){this.onKey([{type:"paste",text:n.replace(/\r/g,"")}]);return}for(let i=0;i<s.length;i++)s[i].length>0&&this.handleRawStdin(Buffer.from(s[i],"binary")),i<s.length-1&&this.onKey([{type:"key",name:"ctrl-enter"}]);return}if(n.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(n)){this.handleCsiUStdin(n);return}this.handleRawStdinSegment(n)}}handleCsi27Stdin(e){let n=/\x1b\[27;(\d+);(\d+)~/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=parseInt(r[2],10),a=lb(o,i);a!==null?this.onKey([{type:"key",name:a}]):(i===1||i===2)&&o>=32&&o<127&&this.handleRawStdinSegment(String.fromCharCode(o)),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleCsiUStdin(e){let n=/\x1b\[(\d+)(?:;(\d+))?u/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=r[2]!==void 0?parseInt(r[2],10):1,a=lb(i,o);a!==null&&this.onKey([{type:"key",name:a}]),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleRawStdinSegment(e){let n=no,s=ca;for(;e.length>0;){if(this.pasteActive){let i=e.indexOf(s);if(i===-1){this.pasteBuffer+=e;return}this.pasteBuffer+=e.slice(0,i),e=e.slice(i+s.length),this.pasteActive=!1;let o=Buffer.from(this.pasteBuffer,"binary").toString("utf-8").replace(/\r\n?/g,`
208
- `);this.pasteBuffer="";let a=Ww(o);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:o}]);continue}let r=e.indexOf(n);if(r===-1){let i=A0(e);i!==null?this.onKey([{type:"paste",text:i}]):this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e,"binary"));return}r>0&&this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e.slice(0,r),"binary")),e=e.slice(r+n.length),this.pasteActive=!0}}width(){return this.term.width||0}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){this.scrollOffset>0&&e!==0&&(this.scrollOffset=Math.max(0,this.scrollOffset+e))}wrappedRowsOf(e){let n=this.term.width;return this.wrapCacheWidth!==n&&(this.wrapCache.clear(),this.wrapCacheWidth=n),this.wrapOne(e,n).length}wrappedRowsOfMany(e){let n=0;for(let s of e)n+=this.wrappedRowsOf(s);return n}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let n of e)this.trackLine(n)}forgetLine(e){let n=this.lineIds.get(e);n!==void 0&&this.wrapCache.delete(n)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let n=this.lines.splice(0,e);for(let s of n)this.forgetLine(s);this.invalidateSelectionIfTouches(n);for(let[s,r]of[...this.keyedBlocks.entries()])r.start-=e,r.start<0&&this.keyedBlocks.delete(s)}upsertLine(e,n){this.upsertLines(e,[n])}upsertLines(e,n){if(n.length===0)return;for(let o of n)o.blockKey=e;let s=this.keyedBlocks.get(e),r=!1,i=0;if(s){let o=s.start+s.count;r=o>=this.lines.length;let a=this.wrappedRowsOfMany(this.lines.slice(s.start,o)),c=n.length-s.count,d=this.lines.splice(s.start,s.count,...n);for(let l of d)this.forgetLine(l);if(this.trackLines(n),this.invalidateSelectionIfTouches(d),s.count=n.length,c!==0)for(let[l,u]of this.keyedBlocks)l!==e&&u.start>s.start&&(u.start+=c);i=this.wrappedRowsOfMany(n)-a}else r=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:n.length}),this.lines.push(...n),this.trackLines(n),i=this.wrappedRowsOfMany(n);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(i),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,n,s,r){if(e.length===0)return;let i=e.split(`
209
- `),[o,...a]=i,c=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+=o??"",c+=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),c+=this.wrappedRowsOf(p)}}let l={prefix:n,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),c+=this.wrappedRowsOf(l)}let d=" ".repeat(n.length);for(let l of a){let u={prefix:d,body:l,bodyStyle:s};this.lines.push(u),this.trackLine(u),c+=this.wrappedRowsOf(u)}this.streamingActive=!0,this.adjustScrollForRowChange(c),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),n=Hf(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:n,i=(this.readonly?`${s} [VIEW ONLY]`:s).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);i!==this.lastWindowTitle&&(this.lastWindowTitle=i,process.stdout.write(`\x1B]0;${i}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,process.stdout.write("\x1B]0;\x1B\\")}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&Ne(()=>{this.term.hideCursor(),e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,n=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},n),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()))}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)),se({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,n){let s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(n.sourceLineId),i=s<r||s===r&&e.offset<=n.offset,o=i?e:n,a=i?n:e;if(o.sourceLineId===a.sourceLineId&&o.offset===a.offset){this.clearSelection();return}let c={startLineId:o.sourceLineId,startOffset:o.offset,endLineId:a.sourceLineId,endOffset:a.offset},d=this.selection;d&&d.startLineId===c.startLineId&&d.startOffset===c.startOffset&&d.endLineId===c.endLineId&&d.endOffset===c.endOffset||(this.selection=c,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}}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let n=[];for(let s=e.loIdx;s<=e.hiIdx;s++){let r=this.lines[s];if(!r)continue;let i=this.lineIds.get(r),o=i===void 0?void 0:e.byId.get(i);if(!o)continue;let a=r.body??"",c;r.ansi?c=s===e.loIdx||s===e.hiIdx?"":a.replace(y0,""):(c=a.slice(o.start,o.end),Sa(r.bodyStyle)&&(c=ob(c))),n.push(c)}return n.join(`
210
- `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let n=this.lineIndexById(e.startLineId),s=this.lineIndexById(e.endLineId);if(n===-1||s===-1)return null;let r=n,i=s,o=e.startOffset,a=e.endOffset;n>s&&(r=s,i=n,o=e.endOffset,a=e.startOffset);let c=new Map;for(let d=r;d<=i;d++){let l=this.lines[d];if(!l)continue;let u=this.lineIds.get(l);if(u===void 0)continue;let f=(l.body??"").length,p=d===r?Math.max(0,Math.min(f,o)):0,h=d===i?Math.max(0,Math.min(f,a)):f;c.set(u,{start:p,end:h,toEnd:d<i})}return{loIdx:r,hiIdx:i,byId:c}}selectionRangeForChunk(e){if(this.selection===null||e.ansi)return null;let n=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(n===null)return null;let s=this.wrapOrigin.get(e);if(!s)return null;let r=n.get(s.sourceLineId);if(!r)return null;let i=s.sourceColOffset,o=i+e.body.length,a=Math.max(r.start,i),c=Math.min(r.end,o);return c<=a?null:{start:a-i,end:c-i,toEndOfLine:r.toEnd||r.end>o}}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,n=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${n}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}: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 n of e){let s=this.lineIds.get(n);if(s!==void 0&&(s===this.selection.startLineId||s===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 n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count,r=s>=this.lines.length,i=this.wrappedRowsOfMany(this.lines.slice(n.start,s)),o=this.lines.splice(n.start,n.count);for(let a of o)this.forgetLine(a);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[a,c]of this.keyedBlocks)a!==e&&c.start>n.start&&(c.start-=n.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-i),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 n=e.start+e.count;if(n>=this.lines.length)return;let s=this.lines.splice(e.start,e.count);for(let[r,i]of this.keyedBlocks)r!==this.stickyBottomKey&&i.start>=n&&(i.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(n.start,n.start+n.count)),i=this.lines.splice(n.start,n.count);for(let o of i)this.forgetLine(o);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[,o]of this.keyedBlocks)o.start>n.start&&(o.start-=n.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,n){if(!this.keyedBlocks.has(e))return[];let s=[...n].map(c=>{let d=this.keyedBlocks.get(c);return d?{key:c,start:d.start,count:d.count}:null}).filter(c=>c!==null).sort((c,d)=>c.start-d.start),r=s.findIndex(c=>c.key===e);if(r<0)return[];let i=(c,d)=>{for(let[l,u]of this.keyedBlocks)if(!n.has(l)&&u.start>=c&&u.start<d)return!0;return!1},o=r;for(;o>0&&!i(s[o-1].start+s[o-1].count,s[o].start);)o--;let a=r;for(;a<s.length-1&&!i(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(o,a+1).map(c=>c.key)}setRunCollapsed(e,n,s){if(e.length===0)return;let r=e[0];if(!this.keyedBlocks.has(r))return;this.upsertLines(r,s);let i=this.keyedBlocks.get(r),o=i.start+i.count;for(let a of e){let c=this.keyedBlocks.get(a);c&&(o=Math.max(o,c.start+c.count))}for(let a=i.start+i.count;a<o;a++){let c=this.lines[a];c&&(c.collapsed=n)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(uf),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.permissionPrompt=e?{...e}:null,this.repaint()}setOptionsPrompt(e){e!==null&&this.optionsPrompt===null&&this.clearSelection(),this.optionsPrompt=e?{...e,options:e.options.map(n=>({...n}))}:null,this.repaint()}isOptionsPromptActive(){return this.optionsPrompt!==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.compactionPrompt=e?{...e}:null,this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}openBtwOverlay(e){let n=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=n,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let n=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,n=!0),e.usage!==void 0){let s=this.btwOverlayUsage,r=e.usage;(!s||s.used!==r.used||s.size!==r.size||s.costAmount!==r.costAmount||s.costCurrency!==r.costCurrency)&&(this.btwOverlayUsage={...r},n=!0)}n&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let n=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){n=!1;break}if(n)return}this.btwOverlayLines=[...e],this.scheduleRepaint()}setBtwOverlayStatus(e){let n=this.btwOverlayLabel===e.label,s=this.btwOverlayStatus===e.style;n&&s||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,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((s,r)=>{let i=this.completions[r];return i!==void 0&&i.name===s.name&&i.description===s.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let n=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=n!==void 0&&n.start+n.count===this.lines.length,r=s?n.start-1:this.lines.length-1;if(r<0)return;let i=this.lines[r];if(i&&i.body===""&&(i.prefix===void 0||i.prefix===""))return;let o={body:""};e!==void 0&&(o.bodyStyle=e),s?(this.lines.splice(n.start,0,o),n.start+=1):this.lines.push(o),this.trackLine(o),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(o)),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,n){if(n.isCharacter){this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.scrollBy(-this.scrollPageSize());return}let s=Lc(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,n){if(e==="MOUSE_WHEEL_UP"){this.scrollBy(3);return}if(e==="MOUSE_WHEEL_DOWN"){this.scrollBy(-3);return}let r=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||r)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let o=this.mouseCell(n),a=C0(e),c=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?c="move":e.endsWith("_PRESSED")?c="press":e.endsWith("_RELEASED")&&(c="release"),c!==null&&o!==null&&this.onMouse&&this.onMouse({kind:c,button:a,x:o.x,y:o.y,name:e}),c==="move"){let d=o!==null?this.bannerHitAt(o.x,o.y):null;d!==this.hoveredBannerHit&&(this.hoveredBannerHit=d,this.syncedPartialRepaint(()=>this.drawBanner()))}if(o!==null&&c!=="release"){let d=this.keyAndSubAtRow(o.y),l=d!==null&&d.key.startsWith("agent:")?null:d;if(this.setPointerShape(l!==null?"pointer":"default"),c==="move"){let u=l?.key??null,f=l?.sub??null;(u!==this.hoveredBlockKey||f!==this.hoveredSubKey)&&(this.hoveredBlockKey=u,this.hoveredSubKey=f,this.hoveredRunKeys=u!==null&&this.onHoverRun?this.onHoverRun(u)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else o===null&&c==="move"&&(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 d=this.lastLeftClick;d!==null&&o!==null&&Math.abs(o.x-d.x)<=$c&&Math.abs(o.y-d.y)<=$c&&Date.now()-d.t<=_f||this.flushPendingBlockClick(),this.pressCell=o,this.handleSelectionPress(o);return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),e==="MOUSE_DRAG"&&o!==null){this.handleSelectionDrag(o);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let d=this.pressCell;this.pressCell=null;let l=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(this.onBlockClick&&d!==null&&o!==null&&o.x===d.x&&o.y===d.y&&!l){let u=this.keyAtRow(o.y);if(u!==null){let f=o.y;for(;f>1&&this.keyAtRow(f-1)===u;)f-=1;this.schedulePendingBlockClick(u,o.y-f)}}this.handleSelectionRelease(o)}}handleSelectionPress(e){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,!this.inAppSelectionEnabled||e===null)return;let n=this.resolveCellToSource(e.x,e.y);if(n===null){this.lastLeftClick=null;return}this.selectionAnchor=n;let s=Date.now(),r=this.lastLeftClick;if(r!==null&&s-r.t<=_f&&Math.abs(e.x-r.x)<=$c&&Math.abs(e.y-r.y)<=$c){if(this.cancelPendingBlockClick(),this.onBlockDoubleClick&&e!==null){let a=this.keyAtRow(e.y);if(a!==null){let c=e.y;for(;c>1&&this.keyAtRow(c-1)===a;)c-=1;let d=e.y-c;if(this.onBlockDoubleClick(a,d)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.tryOpenFileAt(n)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let o=this.wordBoundsAt(n);o!==null&&(this.setSelection({sourceLineId:n.sourceLineId,offset:o.start},{sourceLineId:n.sourceLineId,offset:o.end}),this.doubleClickPending=!0),this.lastLeftClick=null}}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;let n=this.resolveCellToSource(e.x,e.y);n!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,n))}handleSelectionRelease(e){let n=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null&&(this.lastLeftClick={x:e.x,y:e.y,t:Date.now()}),!!this.inAppSelectionEnabled){if(n||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=ib(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length,a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!$f.test(r[a]))return null;let c=a;for(;c>0&&$f.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&$f.test(r[d]);)d++;let l=s.length,u=s.length;for(let f=0;f<i.length;f++)if(i[f]===c&&l===s.length&&(l=f),i[f]===d&&u===s.length){u=f;break}return{start:l,end:u}}pathTokenAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=ib(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(n.links){for(let p of n.links)if(o>=p.start&&o<p.end){let h=p.url;return{raw:h.startsWith("file://")?h.slice(7):h,line:null}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!Ff.test(r[a]))return null;let c=a;for(;c>0&&Ff.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Ff.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0)return null;let u=null,f=r.slice(d).match(/^:(\d+)(?::\d+)?/);return f&&(u=Number.parseInt(f[1],10)),{raw:l,line:u}}resolvePathToken(e){let n=e;(n==="~"||n.startsWith("~/"))&&(n=n==="~"?tb():`${tb()}/${n.slice(2)}`);let s=nb(n)||e.startsWith("~"),r=n.includes("/");if(!s&&!r)return null;let i=nb(n)?n:m0(this.sessionbar.cwd,n);if(s)return i;try{if(h0(i).isFile())return i}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let n=this.pathTokenAt(e);if(n===null)return!1;let s=n.line===null?"":`:${n.line}`;return this.tryOpenPathString(n.raw+s)}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let n=e,s=null,r=e.match(/^(.*?):(\d+)(?::\d+)?$/);r&&(n=r[1],s=Number.parseInt(r[2],10));let i=this.resolvePathToken(n);if(i===null)return!1;let o=s===null?"":String(s),[a,...c]=this.openFileCommand;if(!a)return!1;let d=!1,l=[];for(let u of c)u.includes("%f")&&(d=!0),!(o===""&&u.includes("%n"))&&l.push(u.replaceAll("%f",i).replaceAll("%n",o));d||l.push(i);try{let u=p0(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});u.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),u.unref();let f=s===null?i:`${i}:${s}`;this.notify(`opening ${f}`)}catch(u){this.notify(`open file failed: ${u.message}`)}return!0}schedulePendingBlockClick(e,n){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,n);return}this.cancelPendingBlockClick();let s=this.onBlockClick,r=setTimeout(()=>{this.pendingBlockClick=null,s(e,n)},_f);typeof r.unref=="function"&&r.unref(),this.pendingBlockClick={timer:r,key:e,rowOffset:n}}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))}lineById(e){for(let n of this.lines)if(this.lineIds.get(n)===e)return n;return null}lineIndexById(e){for(let n=0;n<this.lines.length;n++){let s=this.lines[n];if(s&&this.lineIds.get(s)===e)return n}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&Xw(e,{target:this.selectionClipboard}).then(n=>{if(n.ok){let s=e.length;this.notify(`copied ${s} char${s===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${n.reason}`)},n=>{this.notify(`clipboard copy failed: ${n.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let n=e,s=Number(n.x),r=Number(n.y);return!Number.isFinite(s)||!Number.isFinite(r)?null:{x:s,y:r}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,process.stdout.write(e==="pointer"?Qy:yc))}keyAtRow(e){let n=this.term.width,s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let i=e-s;if(i<0||i>=r)return null;let{rows:o}=this.wrapTail(n,r+this.scrollOffset),a=o.length-this.scrollOffset,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),u=i-l;return u<0||u>=d.length?null:d[u]?.blockKey??null}keyAndSubAtRow(e){let n=this.term.width,s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let i=e-s;if(i<0||i>=r)return null;let{rows:o}=this.wrapTail(n,r+this.scrollOffset),a=o.length-this.scrollOffset,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),u=i-l;if(u<0||u>=d.length)return null;let f=d[u];return f?.blockKey?{key:f.blockKey,sub:f.hoverSubKey??null}:null}resolveCellToSource(e,n){if(!Number.isFinite(e)||!Number.isFinite(n))return null;let s=this.term.width,r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=n-r;if(o<0||o>=i||e<1||e>s)return null;let{rows:a}=this.wrapTail(s,i+this.scrollOffset),c=a.length-this.scrollOffset,d=Math.max(0,c-i),l=a.slice(d,c),u=Math.max(0,i-l.length),f=o-u;if(f<0||f>=l.length)return null;let p=l[f];if(!p)return null;let h=this.wrapOrigin.get(p);if(!h)return null;let m=er(p.prefix??""),y=e-1-m;if(y<0)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let b=Sa(p.bodyStyle)?Kw(jf(p.body),y):zw(p.body,y);return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+b}}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=this.maxScrollOffset(),s=Math.min(n,Math.max(0,this.scrollOffset+e));s!==this.scrollOffset&&(this.scrollOffset=s,this.repaint())}scrollToBottom(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,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 n=e.toLowerCase(),s=[];if(n.length>0)for(let r=this.lines.length-1;r>=0;r--){let i=this.lines[r];if(!i||i.body.length===0||i.ansi)continue;let o=i.body.toLowerCase(),a=[],c=0;for(;c<o.length;){let d=o.indexOf(n,c);if(d===-1)break;a.push(d),c=d+n.length}for(let d=a.length-1;d>=0;d--)s.push({lineIdx:r,col:a[d]})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=n.length>0?n:null,s.length>0&&this.scrollToMatch(s[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 n=this.lines[e.lineIdx];if(!n)return null;let s=this.lineIds.get(n);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,n){if(!e||n===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==n.lineId)return null;let r=n.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let n=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(r+=this.wrapOne(u,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let h=p.body.length;if(e.col<u+h){o=l.length-1-f;break}u+=h}}let a=r+o,c=Math.max(0,a-Math.floor(s/2)),d=this.maxScrollOffset();this.scrollOffset=Math.min(d,c)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-Ue-Ge-Qe-w0-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,n-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.term.width,Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){this.scheduler.schedule()}paintRow(e,n,s){this.started&&this.painter.paintRow(e,n,s)}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,n=this.term.height;e<20||n<8||(this.painter.ensureSize(e,n),Ne(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-Qe-Ge-Ue;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(n-Ue),this.drawSessionbar(),this.placeCursor(),(this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}drawSessionbar(){let e=Math.max(1,this.term.width-1),n=this.term.height,s=this.sessionbar.title?.trim(),r=Yg(this.sessionbar.agent,this.sessionbar.model),i=Ze(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(n,o,()=>{let a=Ke(r),c=1,d=Math.max(0,e-a-c),l=s?" \xB7 ":"",u=Ke(l),f,p;if(s){let v=Math.min(s.length,8);f=Math.min(i.length,Math.max(8,d-u-v)),p=Math.max(0,d-f-u)}else p=0,f=d;let h=kt(i,f),m=s?kt(s,p):"",y=Ke(h)+(s?u+Ke(m):0),b=Math.max(c,e-y-a);this.term.bold.noFormat(h),s&&this.term(l).bold.noFormat(m),this.term(" ".repeat(b)),this.term.noFormat(r)})}drawSeparator(e){let n=this.term.width,s=Hf(this.sessionbar.sessionId),r=this.banner.status,i=r==="busy"&&this.banner.stalled===!0,o;i?o="Stalled":r==="busy"?o="Busy":o=r.charAt(0).toUpperCase()+r.slice(1);let a=r==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?Qn(this.banner.elapsedMs):"",c=[];if(this.banner.queued>0){let T=`${this.banner.queued} queued`;c.push({text:T,paint:()=>{this.term.brightYellow(T)}})}if(this.scrollOffset>0){let T=`\u2191 ${this.scrollOffset}`;c.push({text:T,paint:()=>{this.term.brightCyan(T)}})}let d=cb(this.sessionbar.usage)??"",l="\u2500\u2500 ",u=a?` ${a}`:"",f=s?" \xB7 ":"",p=" ",h=d?" ":"",m=d?" \u2500\u2500":"\u2500\u2500",y=l.length+Ke(o)+Ke(u)+f.length+Ke(s);for(let T of c)y+=Ke(" \xB7 ")+Ke(T.text);y+=Ke(p);let b=Ke(h)+Ke(d)+Ke(m),v=Math.max(0,n-y-b),S="\u2500".repeat(v),k=`sep|${n}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${d}`;this.paintRow(e,k,()=>{this.term.bold(l),i||r==="disconnected"?this.term.brightRed(o):r==="busy"?this.term.brightYellow(o):r==="cold"?this.term.brightMagenta(o):this.term(o),u&&(i?this.term.brightRed.noFormat(u):r==="busy"?this.term.brightYellow.noFormat(u):this.term.dim.noFormat(u)),s&&(this.term.dim(f),this.term.dim(s));for(let T of c)this.term.dim(" \xB7 "),T.paint();this.term.dim(p),this.term.bold(S),d&&(this.term.dim(h),this.term.noFormat(d)),this.term.bold(m)})}drawBottomSeparator(e){let n=this.term.width,s=this.bannerRightContent(),r=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint,i=" ",o=" \u2500\u2500",a=s?s.text:r,c=Ke(i)+Ke(a)+Ke(o),d=Math.max(0,n-c),l="\u2500".repeat(d),u=s?`${s.kind}|${s.text}`:"",f=s?"":this.hoveredBannerHit??"",p=`bsep|${n}|${this.banner.currentMode??""}|${this.banner.hint}|${u}|${f}`;this.paintRow(e,p,()=>{if(this.term.bold(l),this.term.dim(i),s)s.kind==="search"?this.term.brightCyan.noFormat(s.text):this.term.brightYellow.noFormat(s.text);else{let m=r.split(" \xB7 "),y=this.hoveredBannerHit;for(let b=0;b<m.length;b++){b>0&&this.term.dim(" \xB7 ");let v=m[b];if(v===void 0)continue;let S=null;v.includes("mode")?S="mode":v.includes("pick")?S="pick":v.includes("guide")?S="guide":v.includes("detach")&&(S="detach"),S!==null&&S===y?this.term.noFormat(v):this.term.dim(v)}}this.term.bold(o);let h={mode:null,pick:null,guide:null,detach:null};if(!s){let m=d+Ke(i)+1,y=r.split(" \xB7 ");for(let b of y){let v=Ke(b),S=[m,m+v-1];b.includes("mode")&&h.mode===null?h.mode=S:b.includes("pick")&&h.pick===null?h.pick=S:b.includes("guide")&&h.guide===null?h.guide=S:b.includes("detach")&&h.detach===null&&(h.detach=S),m+=v+Ke(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?Hf(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=cb(this.btwOverlayUsage),c=a?` ${a} `:"",d=a?"\u2500\u2500":"",l=s.length+Ke(n)+i.length+Ke(r)+o.length+Ke(c)+d.length,u="\u2500".repeat(Math.max(0,e-l)),f=`${e}|${r}|${this.btwOverlayStatus}|${a??""}`;return{left:s,label:n,sidSep:i,sid:r,sidTrail:o,middle:u,usage:c,right:d,signature:f}}paintBtwHeader(e){switch(this.term.bold(e.left),this.btwOverlayStatus){case"busy":this.term.brightYellow(e.label);break;case"done":this.term(e.label);break;case"cancelled":case"errored":this.term.brightRed(e.label);break;default:this.term(e.label)}this.term.dim(e.sidSep),e.sid&&(this.term.dim(e.sid),this.term.dim(e.sidTrail)),this.term.bold(e.middle),e.usage&&this.term.noFormat(e.usage),this.term.bold(e.right)}drawScrollback(){let e=this.term.width,n=1,s=this.scrollbackVisibleRows();if(s<=0)return;let{rows:r,exhausted:i}=this.wrapTail(e,s+this.scrollOffset);if(i){let f=Math.max(0,r.length-s);this.scrollOffset>f&&(this.scrollOffset=f)}let o=r.length-this.scrollOffset,a=Math.max(0,o-s),c=r.slice(a,o),d=Math.max(0,s-c.length),l=this.currentMatchInfo(),u=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;for(let f=0;f<s;f++){let p=n+f,h=f-d,m=h>=0?c[h]:void 0,y=this.activeMatchCol(m,l),b=m?this.selectionRangeForChunk(m):null,S=m!==void 0&&m.blockKey!==void 0&&(m.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(m.blockKey))&&(this.hoveredSubKey===null||(m.hoverSubKey??null)===this.hoveredSubKey),k=sb("sb",e,m,this.scrollbackHighlight,y,b)+(S?"|H":"");this.paintRow(p,k,()=>{m&&this.writeFormattedLine(m,e,y,u,b,S)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let f=new Set;for(let h of c)h.blockKey!==void 0&&f.add(h.blockKey);let p=[];for(let h of this.pendingVisibleKeys)f.has(h)&&p.push(h);for(let h of p)this.pendingVisibleKeys.delete(h),this.onBlockVisible(h)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(Lf,this.queuedTexts.length)}chipRows(){return Math.min(Nf,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((n,s)=>n===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(Bf,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-Ue-Ge-Qe,i=this.queuedRows(),o=this.chipRows(),c=r-1-i-o-e+1,d=0;for(let l of this.completions.slice(0,e))l.name.length>d&&(d=l.name.length);for(let l=0;l<e;l++){let u=c+l,f=this.completions[l],p=l===e-1&&this.completions.length>Bf,h=this.completions.length-Bf+1,m=f?p?`comp|${n}|overflow|${h}`:`comp|${n}|${d}|${f.name}|${f.description??""}`:`comp|${n}|empty`;this.paintRow(u,m,()=>{if(!f)return;if(p){this.term.dim(` + ${h} more match(es)`);return}let y=f.name.padEnd(d),b=f.description??"",v=n-y.length-4,S=v>0?kt(b,v):"";this.term(" ").brightCyan(y),S.length>0&&this.term(" ").dim(S)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),o=this.term.height-s-Ue-Ge-Qe-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>Nf,u=this.attachments.length-Nf,f=this.attachments[c],p=f?`${f.name??"image"} \xB7 ${kn(f.sizeBytes)}`:"",h=l?`chip|${n}|overflow|${u}`:f?`chip|${n}|${a?"i":"t"}|${p}|${f.sizeBytes}`:`chip|${n}|empty`;this.paintRow(d,h,()=>{if(l){this.term.dim(` \u{1F4CE} + ${u+1} more attached`);return}f&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(f.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(P0(e,n,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-Ue-Ge-Qe,i=this.chipRows(),a=r-1-i-e+1,c=this.dispatcher.state().queueIndex;for(let d=0;d<e;d++){let l=a+d,u=this.queuedTexts[d],f=d===e-1&&this.queuedTexts.length>Lf,p=this.queuedTexts.length-Lf,h=u===void 0?"":f?`+ ${p+1} more queued`:kt(O0(u),n-4),m=!f&&d===c,y=u===void 0?`queued|${n}|empty`:`queued|${n}|${m?"edit":f?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(u===void 0)return;let b=`\u23F3 ${h}`,v=b+" ".repeat(Math.max(0,n-1-b.length));m?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(v)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();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,n=Math.max(1,e-2),s=this.dispatcher.state(),r=Ss(s.buffer,n),i=tr(r,s,Of),o=this.term.height-i.rendered-Qe-Ge-Ue+1,a=!1;for(let c=0;c<i.rendered;c++){let d=r[i.windowStart+c],l=o+c,u="wrap",f="";d&&(d.bufferIdx===0&&d.startCol===0?u="first":d.startCol===0&&(u="newline"),f=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let p=d?`prompt|${this.term.width}|${u}|${f}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{d&&(u==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):u==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(f):this.term.noFormat(f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-Df-Qe-Ge-Ue+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${kt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${kt(e.hint,n-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let n=this.term.width,s=this.compactionRows(),r=this.term.height-s-Qe-Ge-Ue+1,i=r,o=(a,c)=>{i>=r+s||(this.paintRow(i,a,c),i+=1)};o(`cpct|msg|${n}|${e.message}`,()=>{this.term.brightYellow(` ${kt(e.message,n-2)}`)}),o(`cpct|q|${n}`,()=>{this.term(" Compact now to reduce future per-turn token cost?")});for(let a=0;a<e.options.length&&!(i>=r+s-1);a++){let c=e.options[a];if(!c)continue;let d=a===e.selectedIndex,u=` ${d?"\u276F":" "} ${a+1}. ${kt(c.label,n-8)}`;o(`cpct|o|${n}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(u):this.term.dim(u)})}o(`cpct|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 y/n quick-pick")})}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let n=this.term.width,s=this.helpRows(),r=this.term.height-s-Qe-Ge-Ue+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`help|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${kt(e.title,n-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(c=>c===null?0:c[0].length),4));for(let c of e.entries){if(i>=r+s-1)break;if(c===null){o(`help|sep|${n}|${i}`,()=>{});continue}let[d,l]=c,u=d.padEnd(a);o(`help|e|${n}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(u),this.term.noFormat(` ${kt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${kt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(S0,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let n=this.term.width,s=this.permissionRows(),r=this.term.height-s-Qe-Ge-Ue+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`perm|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${kt(e.title,n-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";o(`perm|sub|${n}|${a}`,()=>{this.term.dim(` ${kt(a,n-2)}`)}),o(`perm|q|${n}`,()=>{this.term(" Do you want to proceed?")});for(let c=0;c<e.options.length&&!(i>=r+s-1);c++){let d=e.options[c];if(!d)continue;let l=c===e.selectedIndex,f=` ${l?"\u276F":" "} ${c+1}. ${kt(d.label,n-8)}`;o(`perm|o|${n}|${c}|${l?"1":"0"}|${d.label}`,()=>{l?this.term.brightYellow(f):this.term.dim(f)})}o(`perm|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}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 ":""}bannerHitAt(e,n){let s=this.bannerHits;if(!s||n!==s.row)return null;let r=i=>i!==null&&e>=i[0]&&e<=i[1];return r(s.mode)?"mode":r(s.pick)?"pick":r(s.guide)?"guide":r(s.detach)?"detach":null}drawBanner(){let e=this.term.height,n=this.promptRows(),s=e-n-Qe-Ge-Ue;this.drawSeparator(s),this.drawBottomSeparator(e-Ue)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-Qe-Ge-Ue+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Qe-Ge-Ue;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-Qe-Ge-Ue+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-Qe-Ge-Ue;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-Df-Qe-Ge-Ue+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-Qe-Ge-Ue+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Qe-Ge-Ue;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-Qe-Ge-Ue+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,n=Math.max(1,e-2),s=this.dispatcher.state(),r=Ss(s.buffer,n),i=tr(r,s,Of),a=this.term.height-i.rendered-Qe-Ge-Ue+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-Qe-Ge-Ue;this.term.moveTo(Math.min(c,this.term.width),Math.min(a,d))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.optionsPrompt)return this.optionsRows();if(this.confirmPrompt)return Df;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=Ss(s.buffer,n);return Math.min(Of,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(b0,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(v0,2+this.optionsPrompt.options.length):0}drawOptionsPrompt(){let e=this.optionsPrompt;if(!e)return;let n=this.term.width,s=this.optionsRows(),r=this.term.height-s-Qe-Ge-Ue+1,i=r,o=(d,l)=>{i>=r+s||(this.paintRow(i,d,l),i+=1)};o(`opts|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${kt(e.title,n-5)}`)});let a=Math.max(...e.options.map(d=>d.label.length),0);for(let d=0;d<e.options.length&&!(i>=r+s-1);d++){let l=e.options[d];if(!l)continue;let u=d===e.selectedIndex,p=` ${u?"\u276F":" "} ${d+1}. `,h=l.label.padEnd(a),m=n-p.length-3,y=`${p}${kt(`${h} ${l.value}`,m)}`;o(`opts|o|${n}|${d}|${u?"1":"0"}|${l.value}|${l.label}`,()=>{u?this.term.brightYellow(y):this.term.dim(y)})}let c=e.hint??"\u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close";o(`opts|hint|${n}|${c}`,()=>{this.term.dim(` ${c}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),n=this.term.width,s=this.wrapBtwTail(n,e).length;return Math.min(this.btwOverlayMaxHeight,1+s)}wrapBtwTail(e,n){if(e<=4){let o=Math.min(n,this.btwOverlayLines.length);return this.btwOverlayLines.slice(this.btwOverlayLines.length-o)}if(n<=0||this.btwOverlayLines.length===0)return[];let s=[],r=0;for(let o=this.btwOverlayLines.length-1;o>=0;o--){let a=this.btwOverlayLines[o],c=this.wrapOne(a,e);if(s.push(c),r+=c.length,r>=n)break}let i=[];for(let o=s.length-1;o>=0;o--)i.push(...s[o]);return i.length>n?i.slice(i.length-n):i}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let n=this.term.width,r=this.term.height-this.promptRows()-Qe-Ge-Ue,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,c=e-1,d=a,l=this.buildBtwHeaderSegments();this.paintRow(d,`btw|h|${l.signature}`,()=>{this.paintBtwHeader(l)});let u=this.wrapBtwTail(n,c);for(let f=0;f<c;f++){let p=d+1+f,h=u.length-c+f,m=h>=0?u[h]:void 0,y=sb(`btw|c${f}`,n,m);this.paintRow(p,y,()=>{m?this.writeFormattedLine(m,n):this.term.noFormat(" ".repeat(n))})}}wrapTail(e,n){let s=d=>d.collapsed===!0||this.hideThoughts&&d.bodyStyle==="thought";if(e<=4){let d=[];for(let u of this.lines)s(u)||d.push(u);let l=Math.min(n,d.length);return{rows:d.slice(d.length-l),exhausted:n>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),n<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],i=0,o=0,a=!1;for(let d=this.lines.length-1;d>=0;d--){let l=this.lines[d];if(s(l)){d===0&&(a=!0);continue}let u=this.wrapOne(l,e);if(r.push(u),i+=u.length,o=d,i>=n)break}let c=[];for(let d=r.length-1;d>=0;d--)c.push(...r[d]);return{rows:c,exhausted:o===0||a}}wrapOne(e,n){let s=this.lineIds.get(e);if(s!==void 0){let u=this.wrapCache.get(s);if(u)return u}let r=e.prefix??"",i=er(r),o=Math.max(1,n-i-1),a=Sa(e.bodyStyle),c=e.ansi?R0(e.body,o):M0(e.body,o,{stripMarkup:a}),d=[],l=0;for(let u=0;u<c.length;u++){let f=c[u]??"",p={prefix:u===0?e.prefix:" ".repeat(i),body:f};if(e.prefixStyle!==void 0&&(p.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(p.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(p.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(p.hoverSubKey=e.hoverSubKey),e.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),u===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&f.length>0){let h=e.body.indexOf(f,l),m=h===-1?l:h;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:m}),l=m+f.length}d.push(p)}return s!==void 0&&this.wrapCache.set(s,d),d}writeFormattedLine(e,n,s=null,r=0,i=null,o=!1){e.prefix&&vs(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,n-er(e.prefix??"")),c=Sa(e.bodyStyle),d=e.ansi?e.body:kt(e.body,a,{stripMarkup:c}),l=(u,f)=>{if(u.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let p=s!==null&&s>=f?s-f:null;rb(this.term,u,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else vs(this.term,u,e.bodyStyle,o)};if(i!==null&&!e.ansi){let u=Math.max(0,Math.min(d.length,i.start)),f=Math.max(u,Math.min(d.length,i.end)),p=Sa(e.bodyStyle);if(l(d.slice(0,u),0),f>u){let m=d.slice(u,f);p&&(m=ob(m)),vs(this.term,m,"selection-highlight",o)}let h=d.slice(f);if(p&&f>u){let m=E0(d.slice(0,f));m.length>0&&(h=m+h)}l(h,f)}else this.scrollbackHighlight!==null&&!e.ansi?rb(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):vs(this.term,d,e.bodyStyle,o);if(e.fillRow){let u=e.ansi?Ke(d):er(d),f=a-u;if(f>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;vs(this.term," ".repeat(f),p,o)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};ub=/[^\x20-\x7e]/,Uf=new Intl.Segmenter(void 0,{granularity:"grapheme"}),fb=!1;T0=/[a-zA-Z+\-:_!#/]/;Hf=rt});function L0(t,e,n=Bc){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=n[t];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,t-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,t-1)};let r=n.findIndex(i=>i.hotkey.toLowerCase()===s);if(r>=0){let i=n[r];if(i)return{kind:"resolve",action:i.key}}}return{kind:"continue",selected:t}}async function yb(t,e){$n();let n=rt(e.sessionId),s=e.importedFromMachine??"another machine",r=Ze(e.cwd),i=Bc.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+Bc.length*2+2,d=Fn(t,{contentHeight:c,title:"Imported session"}),l=d.contentW,u=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],f=0;for(let p of u)t.moveTo(d.contentX,d.contentY+f),t.dim.noFormat(` ${p.label}`),t.noFormat(ze(p.value,l-p.label.length-2)),f++;return f++,wb(t,d,f,{intro:"What do you want to do?",choices:Bc,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return Gn({term:t,render:o,onKey:(a,c,d,l)=>{let u=B0(a,d);if(!u)return;let f=L0(i,u);if(f.kind==="cancel"){l("cancel");return}if(f.kind==="back"){l("back");return}if(f.kind==="resolve"){l(f.action);return}f.selected!==i&&(i=f.selected,o())}})}function wb(t,e,n,s){let r=e.contentW,i=n;t.moveTo(e.contentX,e.contentY+i),t.noFormat(` ${s.intro}`),i+=2;for(let o=0;o<s.choices.length;o++){let a=s.choices[o];if(!a)continue;let d=` ${o===s.selected?"\u276F":" "} ${a.label}`;t.moveTo(e.contentX,e.contentY+i),o===s.selected?t.brightWhite.bgBlue.noFormat(bc(d,r)):t.noFormat(d),i++,t.moveTo(e.contentX,e.contentY+i),t.dim.noFormat(` ${a.description}`),i++}i++,t.moveTo(e.contentX,e.contentY+i),t.dim.noFormat(` ${s.footer}`)}function B0(t,e){return t==="UP"?{kind:"up"}:t==="DOWN"?{kind:"down"}:t==="ENTER"||t==="KP_ENTER"?{kind:"enter"}:t==="ESCAPE"?{kind:"back"}:t==="CTRL_C"||t==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:t}:null}async function bb(t,e,n){let s=rt(e.sessionId),r=e.title??Ze(e.cwd),i=1,o=[{label:"Launch",hotkey:"l",description:"start a new agent session"},{label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=()=>{let c=Fn(t,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;t.moveTo(c.contentX,c.contentY+l),t.dim.noFormat(" session: "),t.noFormat(ze(s,d-10)),l++,t.moveTo(c.contentX,c.contentY+l),t.noFormat(" "+ze(r,d-2)),l++,l++,wb(t,c,l,{intro:"What do you want to do?",choices:o,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"})};return a(),t.hideCursor(),await new Promise(c=>{let d=!1,l=()=>{d=!0},u=p=>{l(),n.pop(),c(p)},f=(p,h,m)=>{if(p==="CTRL_C"||p==="CTRL_D"){u("cancel");return}if(p==="ESCAPE"){u("back");return}if(p==="ENTER"||p==="KP_ENTER"){u(i===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){i>0&&(i--,a());return}if(p==="DOWN"||p==="TAB"){i<o.length-1&&(i++,a());return}if(m?.isCharacter){let y=p.toLowerCase();if(y==="l"){u("launch");return}if(y==="v"){u("view");return}if(y==="n"){i<o.length-1&&(i++,a());return}if(y==="p"){i>0&&(i--,a());return}}};n.push({onKey:(p,h,m)=>{d||f(p,h,m)},onResize:()=>{d||a()}})})}var Bc,Wf=J(()=>{"use strict";he();qn();qr();Bc=[{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 Ia(t){if(t.length===0)return"";let e=t[0]??"";for(let n=1;n<t.length;n++){let s=t[n]??"",r=0;for(;r<e.length&&r<s.length&&e[r]===s[r];)r+=1;if(e=e.slice(0,r),e.length===0)break}return e}function vb(t){let{matches:e,firstLine:n}=t;if(e.length===0)return null;let s=n.indexOf(" "),r=s===-1?n:n.slice(0,s),i=s===-1?"":n.slice(s);if(e.length===1){let a=e[0]??"",c=i.startsWith(" ")?"":" ";return a+c+i}let o=Ia(e);return o.length<=r.length?null:o+i}var Nc=J(()=>{"use strict"});import*as Sb from"os";async function Yr(t,e,n={}){let s=n.defaultCwd??(e?await Fw(e.cwd):void 0)??Sb.homedir();$n();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:rt(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:Ze(e.cwd)}]:[],a=s,c=null,d=!1,l=null,u=[],f=[],p=()=>{u.push(a),u.length>500&&u.shift(),f=[]},h=()=>{let k=u.pop();k!==void 0&&(f.push(a),a=k)},m=()=>{let k=f.pop();k!==void 0&&(u.push(a),a=k)},y=()=>{let k=o.length+6;l=Fn(t,{contentHeight:k,title:r});let T=l.contentW,F=0;for(let $ of o)t.moveTo(l.contentX,l.contentY+F),t.dim.noFormat(` ${$.label}`),t.noFormat(ze($.value,T-$.label.length-2)),F++;F++,t.moveTo(l.contentX,l.contentY+F),t.noFormat(` ${i}`),F+=2,v(F),F+=2,c!==null?(t.moveTo(l.contentX,l.contentY+F),t.red.noFormat(` ${ze(c,T-2)}`)):(t.moveTo(l.contentX,l.contentY+F),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},b=()=>o.length+3,v=k=>{if(!l)return;let T=k??b();t.moveTo(l.contentX,l.contentY+T).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+T),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+T),t.bold.noFormat(" cwd: ");let F=l.contentW-6-2;t.noFormat(N0(a,F)),d||t.bgWhite(" ")},S=()=>{if(v(),!l)return;let k=b()+2;t.moveTo(l.contentX,l.contentY+k).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+k),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+k),c!==null?t.red.noFormat(` ${ze(c,l.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return Gn({term:t,render:y,hideCursor:!1,onKey:(k,T,F,$)=>{if(!d){if(k==="ENTER"||k==="KP_ENTER"){let B=a;d=!0,c=null,S(),ya(B).then(K=>{if(d=!1,K.ok){$({kind:"ok",path:K.path});return}c=K.reason,S()});return}if(k==="ESCAPE"){$({kind:"back"});return}if(k==="CTRL_C"||k==="CTRL_D"){$({kind:"cancel"});return}if(k==="TAB"){d=!0,Ow(a).then(B=>{if(d=!1,B.matches.length===0)return;let K;if(B.matches.length===1)K=B.prefix+B.matches[0];else{let U=Ia(B.matches);if(U.length<=B.basePrefix.length)return;K=B.prefix+U}K!==a&&(p(),a=K,c=null,S())});return}if(k==="BACKSPACE"){a.length>0&&(p(),a=a.slice(0,-1),c=null,S());return}if(k==="CTRL_U"){a.length>0&&(p(),a="",c=null,S());return}if(k==="CTRL_W"){let B=a.replace(/[/\s]+$/,""),K=Math.max(B.lastIndexOf("/"),B.lastIndexOf(" ")),U=K>=0?B.slice(0,K+1):"";U!==a&&(p(),a=U,c=null,S());return}if(k===""){h(),c=null,S();return}if(k==="\x1B_"||k==="\x1B"){m(),c=null,S();return}if(F?.isCharacter){p(),a+=k,c=null,S();return}}}})}function N0(t,e){return e<=1?"":t.length<=e?t:"\u2026"+t.slice(t.length-(e-1))}var zf=J(()=>{"use strict";he();qn();vf();Nc();qr()});function Jf(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Yf(t,e){let n=()=>{process.stdout.write(Hr),process.stdout.write(ys),process.stdout.write(Ur),process.stdout.write(jr),process.stdout.write(so),process.stdout.write(ro),process.stdout.write(io),process.stdout.write(Dr),process.stdout.write("\x1B>")};n();let s=e.prefs??Jf();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(P=>P.sessionId===e.currentSessionId)?.importedFromMachine&&(s.filters.hostFilter="__all");let r=e.cwd,i=Hc(e.sessions,r),o=R=>{let P=R;return s.filters.cwdOnly&&(P=P.filter(D=>D.cwd===r)),s.filters.includeNonInteractive||(P=P.filter(D=>D.interactive===!0)),P=q0(P,s.filters.hostFilter),P},a=o(i),c={columns:e.config.tui.sessionColumns??Yi,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>Qi(R,Date.now())),l=Gi(d,c),u=1+a.length,f=0,p=0;if(e.currentSessionId!==void 0){let R=a.findIndex(P=>P.sessionId===e.currentSessionId);R>=0&&(f=R+1)}let h=!1,m="",y=120,b=!1,v=0,S="normal",k=null,T=!1,F="input",$=new bs({history:[],collapsePastes:!1}),B=[],K=!1,U=0,L=0,N=null,Z=!1,G="",Se=[],X=[],ce=()=>{Se.push(G),Se.length>500&&Se.shift(),X=[]},Je=()=>{let R=Se.pop();R!==void 0&&(X.push(G),G=R)},sr=()=>{let R=X.pop();R!==void 0&&(Se.push(G),G=R)},ks=()=>{Se=[],X=[]},De=null,Y=!1,xe=new bs({history:[]});e.initialPrompt&&xe.setBuffer(e.initialPrompt);let es=e.config.tui.promptHistoryMaxEntries;qo(_.globalTuiHistoryFile()).then(R=>{let P=R.length>es?R.slice(R.length-es):R;xe.setHistory(P)}).catch(()=>{});let ve=new uo(t),Is=ws(t),ot=an(t),He=0,ho="",xs=0,Mt=[],dn=1,As=0,rr=0,mo=0,Qr="",_e=[],On=1,Ra=0,ir=[],It=1,Ln=0,go=0,Gr=0,yo=()=>{Is=ws(t),ot=an(t);let R=Math.max(10,ot-Kf-1);xs=Math.max(10,ot-kb);let P=Math.max(10,ot-8);ho=j0(r,P);let D=xe.state();Mt=Ss(D.buffer,xs);let Q=tr(Mt,D,Dc);dn=Q.rendered,As=Q.windowStart,rr=Q.cursorVisualRow,mo=Q.cursorVisualCol;let ae=6+dn,ue=Math.max(3,Is-ae);He=Math.min(a.length,ue),Qr=Vs(Vi,l,R,c).padEnd(R),_e=d.map(Be=>Vs(Be,l,R,c).padEnd(R))},Ae=()=>{d=a.map(R=>Qi(R,Date.now())),l=Gi(d,c),u=1+a.length,yo()},st=()=>{let R=o(i);h&&m.length>0?a=R.filter(P=>W0(P,m)):a=R,Ae(),h?(p=0,f=a.length>0?1:0):f>u-1&&(f=Math.max(0,u-1)),p+He>a.length&&(p=Math.max(0,a.length-He)),cn()},ut=R=>{if(R!==void 0){let P=a.findIndex(D=>D.sessionId===R);if(P>=0){f=P+1,cn();return}}f=a.length>0?1:0,p=0,cn()},cn=()=>{if(f===0)return;let R=f-1;R<p?p=R:R>=p+He?p=R-He+1:p+He>a.length&&(p=Math.max(0,a.length-He))},ln=()=>Math.max(2,ot-3),ft=!1,vt=!0,pt=!1,Xr=[],Zr=()=>{let R=ln(),P=`\u2500 ${ho} `,D=Math.max(1,R-P.length),Q="\u2500".repeat(D);(f===0||ft)&&vt?t.brightBlue.noFormat(`\u256D${P}${Q}\u256E`):t.dim.noFormat(`\u256D${P}${Q}\u256E`)},Cs=()=>{let R=ln(),P="\u2500".repeat(R);(f===0||ft)&&vt?t.brightBlue.noFormat(`\u2570${P}\u256F`):t.dim.noFormat(`\u2570${P}\u256F`)},ei=R=>{let P=Mt[R];return P?(xe.state().buffer[P.bufferIdx]??"").slice(P.startCol,P.endCol):""},In=R=>{let P=ln(),D=ei(R),Q=Math.max(0,P-1-D.length),ae=" ".repeat(Q);(f===0||ft)&&vt?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${D}${ae}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${D}${ae}`),t.dim.noFormat("\u2502"))},or=R=>{let P=_e[R]??"",D=a[R],Q=D&&D.priority&&D.priority>0?"* ":" ";f===R+1&&!ft&&vt?t.brightWhite.bgBlue.noFormat(`${Q}${P}`):t.noFormat(`${Q}${P}`)},Rs=()=>{let R=p,P=Math.max(0,a.length-p-He),D=[];if(s.filters.cwdOnly&&D.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let Q=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;D.push({kind:"host",text:Q})}return s.filters.includeNonInteractive&&D.push({kind:"plain",text:"+non-interactive"}),R>0&&D.push({kind:"plain",text:`\u2191 ${R} above`}),P>0&&D.push({kind:"plain",text:`\u2193 ${P} below`}),D},wo=()=>{let R=Rs();return R.length===0?"":` ${R.map(P=>P.text).join(" \xB7 ")}`},xt=R=>rt(R),un=()=>{let R=k?`${k.sessionId}|${k.status}`:"";return["ind",S,R,G,De??"",h?`1|${m}|${a.length}`:"0",wo(),Ms?"h1":"h0",hr?"ho1":"ho0"].join("")},me=()=>{Ne(()=>{ve.paintRow(fn(),un(),()=>{let R=()=>{Vt=null,xn=null};if(S==="confirm-kill"&&k)R(),t.brightYellow.noFormat(` kill ${xt(k.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&k)R(),k.status==="warm"?t.brightRed.noFormat(` kill + delete ${xt(k.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${xt(k.sessionId)}? [y/N]`);else if(S==="busy"&&k)R(),t.dim.noFormat(` working on ${xt(k.sessionId)}\u2026`);else if(S==="rename"&&k)R(),t.brightYellow.noFormat(` title: ${G}`),t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels");else if(De!==null)R(),t.dim.noFormat(` ${De}`);else if(h){R(),t.brightYellow.noFormat(` /${m}`),t.bgBrightYellow(" ");let P=a.length===0?" no matches":` ${a.length} match${a.length===1?"":"es"}`;t.dim.noFormat(`${P} \xB7 ^c clears`)}else{let P=Rs(),D=wo(),Q="Esc \xB7 Go Back",ae=Q.length,ue=5,Be=D.length,jt=Math.max(1,ot-Be-ae-ue);if(xn=null,P.length>0){t.dim.noFormat(" ");let $t=3;for(let Ye=0;Ye<P.length;Ye++){let mt=P[Ye];Ye>0&&(t.dim.noFormat(" \xB7 "),$t+=3),mt.kind==="host"?(xn={start:$t,end:$t+mt.text.length-1},hr?t.noFormat(mt.text):t.dim.noFormat(mt.text)):t.dim.noFormat(mt.text),$t+=mt.text.length}}t.dim(" ".repeat(jt)),Ms?t.noFormat(Q):t.dim.noFormat(Q),Vt={start:ot-ue-ae+1,end:ot-ue}}})})},Ce=R=>On+1+R,ar=()=>On+dn+1,Bt=()=>On+dn+3,Kt=R=>Bt()+1+(R-p),fn=()=>Bt()+1+He,Nt=()=>{let R=rr-As;if(R<0||R>=dn)return;let P=3+mo;t.moveTo(P,Ce(R))},I=()=>vt?f===0?"f":ft?"h":"u":"x",bo=()=>`ct|${I()}|${ln()}|${ho}`,Ta=()=>`cb|${I()}|${ln()}`,Ts=R=>`cbb|${I()}|${ln()}|${ei(R)}`,ti=()=>`h|${Qr}`,dr=R=>{let P=a[R],D=P&&P.priority&&P.priority>0?"* ":" ",Q=_e[R]??"";return`sr|${f===R+1&&!ft&&vt?"1":"0"}|${D}${Q}`},je=()=>{Ne(()=>{t.hideCursor(),yo(),cn(),On=1,ve.ensureSize(ot,Is),ve.paintRow(On,bo(),()=>{Zr()});for(let R=0;R<dn;R++){let P=As+R;ve.paintRow(Ce(R),Ts(P),()=>{In(P)})}ve.paintRow(ar(),Ta(),()=>{Cs()}),ve.paintRow(ar()+1,"blank",()=>{}),ve.paintRow(Bt(),ti(),()=>{t.dim.noFormat(` ${Qr}`)});for(let R=0;R<He;R++){let P=p+R,D=Bt()+1+R;P<a.length?ve.paintRow(D,dr(P),()=>{or(P)}):ve.paintRow(D,"blank",()=>{})}me();for(let R=fn()+1;R<=Is;R++)ve.paintRow(R,"blank",()=>{});f===0&&(Nt(),t.hideCursor(!1))})},ts=()=>{ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),je()},vo=()=>{Ne(()=>{t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
207
+ `);if(s.filter(i=>i.length>0).length>1){this.onKey([{type:"paste",text:n.replace(/\r/g,"")}]);return}for(let i=0;i<s.length;i++)s[i].length>0&&this.handleRawStdin(Buffer.from(s[i],"binary")),i<s.length-1&&this.onKey([{type:"key",name:"ctrl-enter"}]);return}if(n.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(n)){this.handleCsiUStdin(n);return}this.handleRawStdinSegment(n)}}handleCsi27Stdin(e){let n=/\x1b\[27;(\d+);(\d+)~/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=parseInt(r[2],10),a=pb(o,i);a!==null?this.onKey([{type:"key",name:a}]):(i===1||i===2)&&o>=32&&o<127&&this.handleRawStdinSegment(String.fromCharCode(o)),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleCsiUStdin(e){let n=/\x1b\[(\d+)(?:;(\d+))?u/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=r[2]!==void 0?parseInt(r[2],10):1,a=pb(i,o);a!==null&&this.onKey([{type:"key",name:a}]),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleRawStdinSegment(e){let n=so,s=la;for(;e.length>0;){if(this.pasteActive){let i=e.indexOf(s);if(i===-1){this.pasteBuffer+=e;return}this.pasteBuffer+=e.slice(0,i),e=e.slice(i+s.length),this.pasteActive=!1;let o=Buffer.from(this.pasteBuffer,"binary").toString("utf-8").replace(/\r\n?/g,`
208
+ `);this.pasteBuffer="";let a=Kw(o);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:o}]);continue}let r=e.indexOf(n);if(r===-1){let i=E0(e);i!==null?this.onKey([{type:"paste",text:i}]):this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e,"binary"));return}r>0&&this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e.slice(0,r),"binary")),e=e.slice(r+n.length),this.pasteActive=!0}}width(){return this.term.width||0}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){this.scrollOffset>0&&e!==0&&(this.scrollOffset=Math.max(0,this.scrollOffset+e))}wrappedRowsOf(e){let n=this.term.width;return this.wrapCacheWidth!==n&&(this.wrapCache.clear(),this.wrapCacheWidth=n),this.wrapOne(e,n).length}wrappedRowsOfMany(e){let n=0;for(let s of e)n+=this.wrappedRowsOf(s);return n}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let n of e)this.trackLine(n)}forgetLine(e){let n=this.lineIds.get(e);n!==void 0&&this.wrapCache.delete(n)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let n=this.lines.splice(0,e);for(let s of n)this.forgetLine(s);this.invalidateSelectionIfTouches(n);for(let[s,r]of[...this.keyedBlocks.entries()])r.start-=e,r.start<0&&this.keyedBlocks.delete(s)}upsertLine(e,n){this.upsertLines(e,[n])}upsertLines(e,n){if(n.length===0)return;for(let o of n)o.blockKey=e;let s=this.keyedBlocks.get(e),r=!1,i=0;if(s){let o=s.start+s.count;r=o>=this.lines.length;let a=this.wrappedRowsOfMany(this.lines.slice(s.start,o)),c=n.length-s.count,d=this.lines.slice(s.start,o),l=new Array(n.length),u=[];for(let f=0;f<n.length;f++){let p=d[f],h=n[f];p!==void 0&&_0(p,h)?l[f]=p:(p!==void 0&&u.push(p),l[f]=h)}for(let f=n.length;f<d.length;f++)u.push(d[f]);this.lines.splice(s.start,s.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),s.count=n.length,c!==0)for(let[f,p]of this.keyedBlocks)f!==e&&p.start>s.start&&(p.start+=c);i=this.wrappedRowsOfMany(n)-a}else r=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:n.length}),this.lines.push(...n),this.trackLines(n),i=this.wrappedRowsOfMany(n);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(i),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,n,s,r){if(e.length===0)return;let i=e.split(`
209
+ `),[o,...a]=i,c=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+=o??"",c+=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),c+=this.wrappedRowsOf(p)}}let l={prefix:n,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),c+=this.wrappedRowsOf(l)}let d=" ".repeat(n.length);for(let l of a){let u={prefix:d,body:l,bodyStyle:s};this.lines.push(u),this.trackLine(u),c+=this.wrappedRowsOf(u)}this.streamingActive=!0,this.adjustScrollForRowChange(c),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),n=Oc(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:n,i=(this.readonly?`${s} [VIEW ONLY]`:s).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);i!==this.lastWindowTitle&&(this.lastWindowTitle=i,process.stdout.write(`\x1B]0;${i}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,process.stdout.write("\x1B]0;\x1B\\")}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&Ne(()=>{this.term.hideCursor(),e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,n=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},n),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()))}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)),se({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,n){let s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(n.sourceLineId),i=s<r||s===r&&e.offset<=n.offset,o=i?e:n,a=i?n:e;if(o.sourceLineId===a.sourceLineId&&o.offset===a.offset){this.clearSelection();return}let c={startLineId:o.sourceLineId,startOffset:o.offset,endLineId:a.sourceLineId,endOffset:a.offset},d=this.selection;d&&d.startLineId===c.startLineId&&d.startOffset===c.startOffset&&d.endLineId===c.endLineId&&d.endOffset===c.endOffset||(this.selection=c,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 n=this.selection,s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(n.startLineId),i=this.lineIndexById(n.endLineId);if(s<0||r<0||i<0)return null;let o=(u,f,p,h)=>u!==p?u-p:f-h,a=o(s,e.offset,r,n.startOffset),c=o(s,e.offset,i,n.endOffset);if(a<=0)return{sourceLineId:n.endLineId,offset:n.endOffset};if(c>=0)return{sourceLineId:n.startLineId,offset:n.startOffset};let d=Math.abs(s-r)*1e6+Math.abs(e.offset-n.startOffset);return Math.abs(s-i)*1e6+Math.abs(e.offset-n.endOffset)>=d?{sourceLineId:n.endLineId,offset:n.endOffset}:{sourceLineId:n.startLineId,offset:n.startOffset}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let n=[];for(let s=e.loIdx;s<=e.hiIdx;s++){let r=this.lines[s];if(!r)continue;let i=this.lineIds.get(r),o=i===void 0?void 0:e.byId.get(i);if(!o)continue;let a=r.body??"",c;r.ansi?c=a.replace(ib,""):(c=a.slice(o.start,o.end),ka(r.bodyStyle)&&(c=cb(c))),n.push(c)}return n.join(`
210
+ `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let n=this.lineIndexById(e.startLineId),s=this.lineIndexById(e.endLineId);if(n===-1||s===-1)return null;let r=n,i=s,o=e.startOffset,a=e.endOffset;n>s&&(r=s,i=n,o=e.endOffset,a=e.startOffset);let c=new Map;for(let d=r;d<=i;d++){let l=this.lines[d];if(!l)continue;let u=this.lineIds.get(l);if(u===void 0)continue;let f=(l.body??"").length,p=d===r?Math.max(0,Math.min(f,o)):0,h=d===i?Math.max(0,Math.min(f,a)):f;c.set(u,{start:p,end:h,toEnd:d<i})}return{loIdx:r,hiIdx:i,byId:c}}selectionRangeForChunk(e){if(this.selection===null)return null;let n=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(n===null)return null;let s=this.wrapOrigin.get(e);if(!s)return null;let r=n.get(s.sourceLineId);if(!r)return null;let i=s.sourceColOffset,o=i+e.body.length,a=Math.max(r.start,i),c=Math.min(r.end,o);return c<=a?null:e.ansi?{start:0,end:e.body.length,toEndOfLine:!0}:{start:a-i,end:c-i,toEndOfLine:r.toEnd||r.end>o}}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,n=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${n}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}: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 n of e){let s=this.lineIds.get(n);if(s!==void 0&&(s===this.selection.startLineId||s===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 n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count,r=s>=this.lines.length,i=this.wrappedRowsOfMany(this.lines.slice(n.start,s)),o=this.lines.splice(n.start,n.count);for(let a of o)this.forgetLine(a);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[a,c]of this.keyedBlocks)a!==e&&c.start>n.start&&(c.start-=n.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-i),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 n=e.start+e.count;if(n>=this.lines.length)return;let s=this.lines.splice(e.start,e.count);for(let[r,i]of this.keyedBlocks)r!==this.stickyBottomKey&&i.start>=n&&(i.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(n.start,n.start+n.count)),i=this.lines.splice(n.start,n.count);for(let o of i)this.forgetLine(o);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[,o]of this.keyedBlocks)o.start>n.start&&(o.start-=n.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,n){if(!this.keyedBlocks.has(e))return[];let s=[...n].map(c=>{let d=this.keyedBlocks.get(c);return d?{key:c,start:d.start,count:d.count}:null}).filter(c=>c!==null).sort((c,d)=>c.start-d.start),r=s.findIndex(c=>c.key===e);if(r<0)return[];let i=(c,d)=>{for(let[l,u]of this.keyedBlocks)if(!n.has(l)&&u.start>=c&&u.start<d)return!0;return!1},o=r;for(;o>0&&!i(s[o-1].start+s[o-1].count,s[o].start);)o--;let a=r;for(;a<s.length-1&&!i(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(o,a+1).map(c=>c.key)}setRunCollapsed(e,n,s){if(e.length===0)return;let r=e[0];if(!this.keyedBlocks.has(r))return;this.upsertLines(r,s);let i=this.keyedBlocks.get(r),o=i.start+i.count;for(let a of e){let c=this.keyedBlocks.get(a);c&&(o=Math.max(o,c.start+c.count))}for(let a=i.start+i.count;a<o;a++){let c=this.lines[a];c&&(c.collapsed=n)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(ff),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.permissionPrompt=e?{...e}:null,this.repaint()}setOptionsPrompt(e){e!==null&&this.optionsPrompt===null&&this.clearSelection(),this.optionsPrompt=e?{...e,options:e.options.map(n=>({...n}))}:null,this.repaint()}isOptionsPromptActive(){return this.optionsPrompt!==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.compactionPrompt=e?{...e}:null,this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}openBtwOverlay(e){let n=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=n,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let n=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,n=!0),e.usage!==void 0){let s=this.btwOverlayUsage,r=e.usage;(!s||s.used!==r.used||s.size!==r.size||s.costAmount!==r.costAmount||s.costCurrency!==r.costCurrency)&&(this.btwOverlayUsage={...r},n=!0)}n&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let n=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){n=!1;break}if(n)return}this.btwOverlayLines=[...e],this.scheduleRepaint()}setBtwOverlayStatus(e){let n=this.btwOverlayLabel===e.label,s=this.btwOverlayStatus===e.style;n&&s||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,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((s,r)=>{let i=this.completions[r];return i!==void 0&&i.name===s.name&&i.description===s.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let n=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=n!==void 0&&n.start+n.count===this.lines.length,r=s?n.start-1:this.lines.length-1;if(r<0)return;let i=this.lines[r];if(i&&i.body===""&&(i.prefix===void 0||i.prefix===""))return;let o={body:""};e!==void 0&&(o.bodyStyle=e),s?(this.lines.splice(n.start,0,o),n.start+=1):this.lines.push(o),this.trackLine(o),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(o)),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,n){if(n.isCharacter){this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.scrollBy(-this.scrollPageSize());return}let s=Bc(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,n){if(e==="MOUSE_WHEEL_UP"){this.scrollBy(3);return}if(e==="MOUSE_WHEEL_DOWN"){this.scrollBy(-3);return}let r=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||r)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let o=this.mouseCell(n),a=M0(e),c=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?c="move":e.endsWith("_PRESSED")?c="press":e.endsWith("_RELEASED")&&(c="release"),c!==null&&o!==null&&this.onMouse&&this.onMouse({kind:c,button:a,x:o.x,y:o.y,name:e}),c==="move"){let d=o!==null?this.bannerHitAt(o.x,o.y):null;d!==this.hoveredBannerHit&&(this.hoveredBannerHit=d,this.syncedPartialRepaint(()=>this.drawBanner()))}if(o!==null&&c!=="release"){let d=this.keyAndSubAtRow(o.y),l=d!==null&&d.key.startsWith("agent:")?null:d;if(this.setPointerShape(l!==null?"pointer":"default"),c==="move"){let u=l?.key??null,f=l?.sub??null;(u!==this.hoveredBlockKey||f!==this.hoveredSubKey)&&(this.hoveredBlockKey=u,this.hoveredSubKey=f,this.hoveredRunKeys=u!==null&&this.onHoverRun?this.onHoverRun(u)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else o===null&&c==="move"&&(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 d=this.lastLeftClick;d!==null&&o!==null&&Math.abs(o.x-d.x)<=$c&&Math.abs(o.y-d.y)<=$c&&Date.now()-d.t<=$f||this.flushPendingBlockClick(),this.pressCell=o,this.handleSelectionPress(o,P0(n,"shift"));return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),!(e==="MOUSE_RIGHT_BUTTON_PRESSED"&&o!==null&&this.extendSelectionByClick(o))){if(e==="MOUSE_DRAG"&&o!==null){this.handleSelectionDrag(o);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"){let d=this.pressCell;this.pressCell=null;let l=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(d!==null&&o!==null&&o.x===d.x&&o.y===d.y&&!l){let u=this.btwHeaderSidRegion();if(u!==null&&this.onHydraLinkClick&&o.y===u.row&&o.x>=u.colStart&&o.x<=u.colEnd)this.onHydraLinkClick(u.sessionId);else if(this.onBlockClick){let f=this.keyAtRow(o.y);if(f!==null){let p=o.y;for(;p>1&&this.keyAtRow(p-1)===f;)p-=1;this.schedulePendingBlockClick(f,o.y-p)}}}this.handleSelectionRelease(o)}}}handleSelectionPress(e,n=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,!this.inAppSelectionEnabled||e===null)return;let s=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(s===null){this.lastLeftClick=null;return}if(n&&this.selection!==null&&this.extendSelectionByClickResolved(s)){this.lastLeftClick=null;return}this.selectionAnchor=s;let r=Date.now(),i=this.lastLeftClick;if(i!==null&&r-i.t<=$f&&Math.abs(e.x-i.x)<=$c&&Math.abs(e.y-i.y)<=$c){if(this.cancelPendingBlockClick(),this.onBlockDoubleClick&&e!==null){let c=this.keyAtRow(e.y);if(c!==null){let d=e.y;for(;d>1&&this.keyAtRow(d-1)===c;)d-=1;let l=e.y-d;if(this.onBlockDoubleClick(c,l)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.onHydraLinkClick&&e!==null){let c=this.findLinkUrlAt(s);if(c!==null&&ob.test(c)){let l=c.match(ob)?.[1]??null;if(l&&this.onHydraLinkClick(l)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.tryOpenFileAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let a=this.wordBoundsAt(s);a!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:a.start},{sourceLineId:s.sourceLineId,offset:a.end}),this.doubleClickPending=!0),this.lastLeftClick=null}}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;this.extendSelectionToCell(e);let n=this.scrollbackVisibleRows();e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=n&&this.scrollOffset>0?this.startAutoscroll(e,-1):this.stopAutoscroll()}extendSelectionByClick(e){if(!this.inAppSelectionEnabled||this.selection===null)return!1;let s=this.resolveEdgeSource(e.y)??this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);return s===null?!1:this.extendSelectionByClickResolved(s)}resolveEdgeSource(e){let n=this.scrollbackVisibleRows();if(n<=0||this.lines.length===0)return null;let s=this.term.width,{rows:r}=this.wrapTail(s,n+this.scrollOffset),i=r.length-this.scrollOffset,o=Math.max(0,i-n),a=r.slice(o,i),c=Math.max(0,n-a.length),d=e-1,l=this.scrollOffset<this.maxScrollOffset(),u=this.scrollOffset>0,f=d<c;if(d===0&&l||f){let p=this.lines[0];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:0}}}if(d>=n-1&&u){let p=this.lines[this.lines.length-1];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:(p.body??"").length}}}return null}resolveNearestSource(e,n){let s=this.scrollbackVisibleRows();if(s<=0)return null;let r=this.term.width,i=Math.max(1,Math.min(r,e));for(let o=1;o<s;o++){let a=n-o;if(a>=1){let d=this.resolveCellToSource(i,a);if(d!==null){let l=this.lineById(d.sourceLineId);return l?{sourceLineId:d.sourceLineId,offset:(l.body??"").length}:d}}let c=n+o;if(c<=s){let d=this.resolveCellToSource(i,c);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let n=this.farEndpointFrom(e);return n===null?!1:(this.selectionAnchor=n,this.selectionDragStarted=!0,this.setSelection(n,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let n=this.resolveCellToSource(e.x,e.y);n!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,n))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,n){if(this.autoscrollTimer!==null&&this.autoscrollDir===n){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=n,this.autoscrollTimer=setInterval(()=>{if(this.selectionAnchor===null||this.autoscrollCell===null){this.stopAutoscroll();return}let s=this.scrollOffset;if(this.scrollBy(this.autoscrollDir),this.scrollOffset===s){this.stopAutoscroll();return}this.extendSelectionToCell(this.autoscrollCell)},t.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let n=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null&&(this.lastLeftClick={x:e.x,y:e.y,t:Date.now()}),!!this.inAppSelectionEnabled){if(n||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=Uf(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length,a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!Of.test(r[a]))return null;let c=a;for(;c>0&&Of.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Of.test(r[d]);)d++;let l=s.length,u=s.length;for(let f=0;f<i.length;f++)if(i[f]===c&&l===s.length&&(l=f),i[f]===d&&u===s.length){u=f;break}return{start:l,end:u}}pathTokenAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=Uf(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(n.links){for(let p of n.links)if(o>=p.start&&o<p.end){let h=p.url;return{raw:h.startsWith("file://")?h.slice(7):h,line:null}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!Ff.test(r[a]))return null;let c=a;for(;c>0&&Ff.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Ff.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0)return null;let u=null,f=r.slice(d).match(/^:(\d+)(?::\d+)?/);return f&&(u=Number.parseInt(f[1],10)),{raw:l,line:u}}findLinkUrlAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi||!n.links)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=Uf(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;for(let a of n.links)if(o>=a.start&&o<a.end)return a.url;return null}resolvePathToken(e){let n=e;(n==="~"||n.startsWith("~/"))&&(n=n==="~"?sb():`${sb()}/${n.slice(2)}`);let s=rb(n)||e.startsWith("~"),r=n.includes("/");if(!s&&!r)return null;let i=rb(n)?n:v0(this.sessionbar.cwd,n);if(s)return i;try{if(b0(i).isFile())return i}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let n=this.pathTokenAt(e);if(n===null)return!1;let s=n.line===null?"":`:${n.line}`;return this.tryOpenPathString(n.raw+s)}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let n=e,s=null,r=e.match(/^(.*?):(\d+)(?::\d+)?$/);r&&(n=r[1],s=Number.parseInt(r[2],10));let i=this.resolvePathToken(n);if(i===null)return!1;let o=s===null?"":String(s),[a,...c]=this.openFileCommand;if(!a)return!1;let d=!1,l=[];for(let u of c)u.includes("%f")&&(d=!0),!(o===""&&u.includes("%n"))&&l.push(u.replaceAll("%f",i).replaceAll("%n",o));d||l.push(i);try{let u=w0(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});u.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),u.unref();let f=s===null?i:`${i}:${s}`;this.notify(`opening ${f}`)}catch(u){this.notify(`open file failed: ${u.message}`)}return!0}schedulePendingBlockClick(e,n){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,n);return}this.cancelPendingBlockClick();let s=this.onBlockClick,r=setTimeout(()=>{this.pendingBlockClick=null,s(e,n)},$f);typeof r.unref=="function"&&r.unref(),this.pendingBlockClick={timer:r,key:e,rowOffset:n}}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))}lineById(e){for(let n of this.lines)if(this.lineIds.get(n)===e)return n;return null}lineIndexById(e){for(let n=0;n<this.lines.length;n++){let s=this.lines[n];if(s&&this.lineIds.get(s)===e)return n}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&eb(e,{target:this.selectionClipboard}).then(n=>{if(n.ok){let s=e.length;this.notify(`copied ${s} char${s===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${n.reason}`)},n=>{this.notify(`clipboard copy failed: ${n.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let n=e,s=Number(n.x),r=Number(n.y);return!Number.isFinite(s)||!Number.isFinite(r)?null:{x:s,y:r}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,process.stdout.write(e==="pointer"?Xy:yc))}keyAtRow(e){let n=this.term.width,s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let i=e-s;if(i<0||i>=r)return null;let{rows:o}=this.wrapTail(n,r+this.scrollOffset),a=o.length-this.scrollOffset,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),u=i-l;return u<0||u>=d.length?null:d[u]?.blockKey??null}keyAndSubAtRow(e){let n=this.term.width,s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let i=e-s;if(i<0||i>=r)return null;let{rows:o}=this.wrapTail(n,r+this.scrollOffset),a=o.length-this.scrollOffset,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),u=i-l;if(u<0||u>=d.length)return null;let f=d[u];return f?.blockKey?{key:f.blockKey,sub:f.hoverSubKey??null}:null}resolveCellToSource(e,n){if(!Number.isFinite(e)||!Number.isFinite(n))return null;let s=this.term.width,r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=n-r;if(o<0||o>=i||e<1||e>s)return null;let{rows:a}=this.wrapTail(s,i+this.scrollOffset),c=a.length-this.scrollOffset,d=Math.max(0,c-i),l=a.slice(d,c),u=Math.max(0,i-l.length),f=o-u;if(f<0||f>=l.length)return null;let p=l[f];if(!p)return null;let h=this.wrapOrigin.get(p);if(!h)return null;let m=er(p.prefix??""),y=e-1-m;if(y<0)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let b=ka(p.bodyStyle)?Vw(qf(p.body),y):Jw(p.body,y);return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+b}}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=this.maxScrollOffset(),s=Math.min(n,Math.max(0,this.scrollOffset+e));s!==this.scrollOffset&&(this.scrollOffset=s,this.repaint())}scrollToBottom(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,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 n=e.toLowerCase(),s=[];if(n.length>0)for(let r=this.lines.length-1;r>=0;r--){let i=this.lines[r];if(!i||i.body.length===0||i.ansi)continue;let o=i.body.toLowerCase(),a=[],c=0;for(;c<o.length;){let d=o.indexOf(n,c);if(d===-1)break;a.push(d),c=d+n.length}for(let d=a.length-1;d>=0;d--)s.push({lineIdx:r,col:a[d]})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=n.length>0?n:null,s.length>0&&this.scrollToMatch(s[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 n=this.lines[e.lineIdx];if(!n)return null;let s=this.lineIds.get(n);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,n){if(!e||n===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==n.lineId)return null;let r=n.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let n=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(r+=this.wrapOne(u,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let h=p.body.length;if(e.col<u+h){o=l.length-1-f;break}u+=h}}let a=r+o,c=Math.max(0,a-Math.floor(s/2)),d=this.maxScrollOffset();this.scrollOffset=Math.min(d,c)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-Ue-Ve-Je-k0-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,n-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.term.width,Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){this.scheduler.schedule()}paintRow(e,n,s){this.started&&this.painter.paintRow(e,n,s)}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,n=this.term.height;e<20||n<8||(this.painter.ensureSize(e,n),Ne(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-Je-Ve-Ue;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(n-Ue),this.drawSessionbar(),this.placeCursor(),(this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}drawSessionbar(){let e=Math.max(1,this.term.width-1),n=this.term.height,s=this.sessionbar.title?.trim(),r=Qg(this.sessionbar.agent,this.sessionbar.model),i=Ze(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(n,o,()=>{let a=je(r),c=1,d=Math.max(0,e-a-c),l=s?" \xB7 ":"",u=je(l),f,p;if(s){let v=Math.min(s.length,8);f=Math.min(i.length,Math.max(8,d-u-v)),p=Math.max(0,d-f-u)}else p=0,f=d;let h=kt(i,f),m=s?kt(s,p):"",y=je(h)+(s?u+je(m):0),b=Math.max(c,e-y-a);this.term.bold.noFormat(h),s&&this.term(l).bold.noFormat(m),this.term(" ".repeat(b)),this.term.noFormat(r)})}drawSeparator(e){let n=this.term.width,s=Oc(this.sessionbar.sessionId),r=this.banner.status,i=r==="busy"&&this.banner.stalled===!0,o;i?o="Stalled":r==="busy"?o="Busy":o=r.charAt(0).toUpperCase()+r.slice(1);let a=r==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?Qn(this.banner.elapsedMs):"",c=[];if(this.banner.queued>0){let T=`${this.banner.queued} queued`;c.push({text:T,paint:()=>{this.term.brightYellow(T)}})}if(this.scrollOffset>0){let T=`\u2191 ${this.scrollOffset}`;c.push({text:T,paint:()=>{this.term.brightCyan(T)}})}let d=fb(this.sessionbar.usage)??"",l="\u2500\u2500 ",u=a?` ${a}`:"",f=s?" \xB7 ":"",p=" ",h=d?" ":"",m=d?" \u2500\u2500":"\u2500\u2500",y=l.length+je(o)+je(u)+f.length+je(s);for(let T of c)y+=je(" \xB7 ")+je(T.text);y+=je(p);let b=je(h)+je(d)+je(m),v=Math.max(0,n-y-b),S="\u2500".repeat(v),k=`sep|${n}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${d}`;this.paintRow(e,k,()=>{this.term.bold(l),i||r==="disconnected"?this.term.brightRed(o):r==="busy"?this.term.brightYellow(o):r==="cold"?this.term.brightMagenta(o):this.term(o),u&&(i?this.term.brightRed.noFormat(u):r==="busy"?this.term.brightYellow.noFormat(u):this.term.dim.noFormat(u)),s&&(this.term.dim(f),this.term.dim(s));for(let T of c)this.term.dim(" \xB7 "),T.paint();this.term.dim(p),this.term.bold(S),d&&(this.term.dim(h),this.term.noFormat(d)),this.term.bold(m)})}drawBottomSeparator(e){let n=this.term.width,s=this.bannerRightContent(),r=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint,i=" ",o=" \u2500\u2500",a=s?s.text:r,c=je(i)+je(a)+je(o),d=Math.max(0,n-c),l="\u2500".repeat(d),u=s?`${s.kind}|${s.text}`:"",f=s?"":this.hoveredBannerHit??"",p=`bsep|${n}|${this.banner.currentMode??""}|${this.banner.hint}|${u}|${f}`;this.paintRow(e,p,()=>{if(this.term.bold(l),this.term.dim(i),s)s.kind==="search"?this.term.brightCyan.noFormat(s.text):this.term.brightYellow.noFormat(s.text);else{let m=r.split(" \xB7 "),y=this.hoveredBannerHit;for(let b=0;b<m.length;b++){b>0&&this.term.dim(" \xB7 ");let v=m[b];if(v===void 0)continue;let S=null;v.includes("mode")?S="mode":v.includes("pick")?S="pick":v.includes("guide")?S="guide":v.includes("detach")&&(S="detach"),S!==null&&S===y?this.term.noFormat(v):this.term.dim(v)}}this.term.bold(o);let h={mode:null,pick:null,guide:null,detach:null};if(!s){let m=d+je(i)+1,y=r.split(" \xB7 ");for(let b of y){let v=je(b),S=[m,m+v-1];b.includes("mode")&&h.mode===null?h.mode=S:b.includes("pick")&&h.pick===null?h.pick=S:b.includes("guide")&&h.guide===null?h.guide=S:b.includes("detach")&&h.detach===null&&(h.detach=S),m+=v+je(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?Oc(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=fb(this.btwOverlayUsage),c=a?` ${a} `:"",d=a?"\u2500\u2500":"",l=s.length+je(n)+i.length+je(r)+o.length+je(c)+d.length,u="\u2500".repeat(Math.max(0,e-l)),f=`${e}|${r}|${this.btwOverlayStatus}|${a??""}`;return{left:s,label:n,sidSep:i,sid:r,sidTrail:o,middle:u,usage:c,right:d,signature:f}}btwHeaderSidRegion(){if(!this.btwOverlayOpen||!this.btwOverlaySessionId)return null;let e=this.btwOverlayRows();if(e===0)return null;let s=this.term.height-this.promptRows()-Je-Ve-Ue,r=this.chipRows()+this.queuedRows()+this.completionRows(),o=s-1-r-e+1,a="By the way",c="\u2500\u2500 ",d=Oc(this.btwOverlaySessionId),u=1+c.length+je(a)+" \xB7 ".length,f=u+je(d)-1;return{row:o,colStart:u,colEnd:f,sessionId:this.btwOverlaySessionId}}paintBtwHeader(e){switch(this.term.bold(e.left),this.btwOverlayStatus){case"busy":this.term.brightYellow(e.label);break;case"done":this.term(e.label);break;case"cancelled":case"errored":this.term.brightRed(e.label);break;default:this.term(e.label)}this.term.dim(e.sidSep),e.sid&&(this.term.dim(e.sid),this.term.dim(e.sidTrail)),this.term.bold(e.middle),e.usage&&this.term.noFormat(e.usage),this.term.bold(e.right)}drawScrollback(){let e=this.term.width,n=1,s=this.scrollbackVisibleRows();if(s<=0)return;let{rows:r,exhausted:i}=this.wrapTail(e,s+this.scrollOffset);if(i){let f=Math.max(0,r.length-s);this.scrollOffset>f&&(this.scrollOffset=f)}let o=r.length-this.scrollOffset,a=Math.max(0,o-s),c=r.slice(a,o),d=Math.max(0,s-c.length),l=this.currentMatchInfo(),u=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;for(let f=0;f<s;f++){let p=n+f,h=f-d,m=h>=0?c[h]:void 0,y=this.activeMatchCol(m,l),b=m?this.selectionRangeForChunk(m):null,S=m!==void 0&&m.blockKey!==void 0&&(m.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(m.blockKey))&&(this.hoveredSubKey===null||(m.hoverSubKey??null)===this.hoveredSubKey),k=ab("sb",e,m,this.scrollbackHighlight,y,b)+(S?"|H":"");this.paintRow(p,k,()=>{m&&this.writeFormattedLine(m,e,y,u,b,S)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let f=new Set;for(let h of c)h.blockKey!==void 0&&f.add(h.blockKey);let p=[];for(let h of this.pendingVisibleKeys)f.has(h)&&p.push(h);for(let h of p)this.pendingVisibleKeys.delete(h),this.onBlockVisible(h)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(Bf,this.queuedTexts.length)}chipRows(){return Math.min(Df,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((n,s)=>n===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(Nf,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-Ue-Ve-Je,i=this.queuedRows(),o=this.chipRows(),c=r-1-i-o-e+1,d=0;for(let l of this.completions.slice(0,e))l.name.length>d&&(d=l.name.length);for(let l=0;l<e;l++){let u=c+l,f=this.completions[l],p=l===e-1&&this.completions.length>Nf,h=this.completions.length-Nf+1,m=f?p?`comp|${n}|overflow|${h}`:`comp|${n}|${d}|${f.name}|${f.description??""}`:`comp|${n}|empty`;this.paintRow(u,m,()=>{if(!f)return;if(p){this.term.dim(` + ${h} more match(es)`);return}let y=f.name.padEnd(d),b=f.description??"",v=n-y.length-4,S=v>0?kt(b,v):"";this.term(" ").brightCyan(y),S.length>0&&this.term(" ").dim(S)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),o=this.term.height-s-Ue-Ve-Je-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>Df,u=this.attachments.length-Df,f=this.attachments[c],p=f?`${f.name??"image"} \xB7 ${kn(f.sizeBytes)}`:"",h=l?`chip|${n}|overflow|${u}`:f?`chip|${n}|${a?"i":"t"}|${p}|${f.sizeBytes}`:`chip|${n}|empty`;this.paintRow(d,h,()=>{if(l){this.term.dim(` \u{1F4CE} + ${u+1} more attached`);return}f&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(f.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(L0(e,n,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-Ue-Ve-Je,i=this.chipRows(),a=r-1-i-e+1,c=this.dispatcher.state().queueIndex;for(let d=0;d<e;d++){let l=a+d,u=this.queuedTexts[d],f=d===e-1&&this.queuedTexts.length>Bf,p=this.queuedTexts.length-Bf,h=u===void 0?"":f?`+ ${p+1} more queued`:kt(U0(u),n-4),m=!f&&d===c,y=u===void 0?`queued|${n}|empty`:`queued|${n}|${m?"edit":f?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(u===void 0)return;let b=`\u23F3 ${h}`,v=b+" ".repeat(Math.max(0,n-1-b.length));m?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(v)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();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,n=Math.max(1,e-2),s=this.dispatcher.state(),r=Ss(s.buffer,n),i=tr(r,s,Lf),o=this.term.height-i.rendered-Je-Ve-Ue+1,a=!1;for(let c=0;c<i.rendered;c++){let d=r[i.windowStart+c],l=o+c,u="wrap",f="";d&&(d.bufferIdx===0&&d.startCol===0?u="first":d.startCol===0&&(u="newline"),f=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let p=d?`prompt|${this.term.width}|${u}|${f}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{d&&(u==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):u==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(f):this.term.noFormat(f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-Hf-Je-Ve-Ue+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${kt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${kt(e.hint,n-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let n=this.term.width,s=this.compactionRows(),r=this.term.height-s-Je-Ve-Ue+1,i=r,o=(a,c)=>{i>=r+s||(this.paintRow(i,a,c),i+=1)};o(`cpct|msg|${n}|${e.message}`,()=>{this.term.brightYellow(` ${kt(e.message,n-2)}`)}),o(`cpct|q|${n}`,()=>{this.term(" Compact now to reduce future per-turn token cost?")});for(let a=0;a<e.options.length&&!(i>=r+s-1);a++){let c=e.options[a];if(!c)continue;let d=a===e.selectedIndex,u=` ${d?"\u276F":" "} ${a+1}. ${kt(c.label,n-8)}`;o(`cpct|o|${n}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(u):this.term.dim(u)})}o(`cpct|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 y/n quick-pick")})}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let n=this.term.width,s=this.helpRows(),r=this.term.height-s-Je-Ve-Ue+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`help|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${kt(e.title,n-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(c=>c===null?0:c[0].length),4));for(let c of e.entries){if(i>=r+s-1)break;if(c===null){o(`help|sep|${n}|${i}`,()=>{});continue}let[d,l]=c,u=d.padEnd(a);o(`help|e|${n}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(u),this.term.noFormat(` ${kt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${kt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(A0,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let n=this.term.width,s=this.permissionRows(),r=this.term.height-s-Je-Ve-Ue+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`perm|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${kt(e.title,n-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";o(`perm|sub|${n}|${a}`,()=>{this.term.dim(` ${kt(a,n-2)}`)}),o(`perm|q|${n}`,()=>{this.term(" Do you want to proceed?")});for(let c=0;c<e.options.length&&!(i>=r+s-1);c++){let d=e.options[c];if(!d)continue;let l=c===e.selectedIndex,f=` ${l?"\u276F":" "} ${c+1}. ${kt(d.label,n-8)}`;o(`perm|o|${n}|${c}|${l?"1":"0"}|${d.label}`,()=>{l?this.term.brightYellow(f):this.term.dim(f)})}o(`perm|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}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 ":""}bannerHitAt(e,n){let s=this.bannerHits;if(!s||n!==s.row)return null;let r=i=>i!==null&&e>=i[0]&&e<=i[1];return r(s.mode)?"mode":r(s.pick)?"pick":r(s.guide)?"guide":r(s.detach)?"detach":null}drawBanner(){let e=this.term.height,n=this.promptRows(),s=e-n-Je-Ve-Ue;this.drawSeparator(s),this.drawBottomSeparator(e-Ue)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-Je-Ve-Ue+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Je-Ve-Ue;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-Je-Ve-Ue+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-Je-Ve-Ue;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-Hf-Je-Ve-Ue+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-Je-Ve-Ue+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Je-Ve-Ue;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-Je-Ve-Ue+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,n=Math.max(1,e-2),s=this.dispatcher.state(),r=Ss(s.buffer,n),i=tr(r,s,Lf),a=this.term.height-i.rendered-Je-Ve-Ue+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-Je-Ve-Ue;this.term.moveTo(Math.min(c,this.term.width),Math.min(a,d))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.optionsPrompt)return this.optionsRows();if(this.confirmPrompt)return Hf;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=Ss(s.buffer,n);return Math.min(Lf,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(I0,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(x0,2+this.optionsPrompt.options.length):0}drawOptionsPrompt(){let e=this.optionsPrompt;if(!e)return;let n=this.term.width,s=this.optionsRows(),r=this.term.height-s-Je-Ve-Ue+1,i=r,o=(d,l)=>{i>=r+s||(this.paintRow(i,d,l),i+=1)};o(`opts|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${kt(e.title,n-5)}`)});let a=Math.max(...e.options.map(d=>d.label.length),0);for(let d=0;d<e.options.length&&!(i>=r+s-1);d++){let l=e.options[d];if(!l)continue;let u=d===e.selectedIndex,p=` ${u?"\u276F":" "} ${d+1}. `,h=l.label.padEnd(a),m=n-p.length-3,y=`${p}${kt(`${h} ${l.value}`,m)}`;o(`opts|o|${n}|${d}|${u?"1":"0"}|${l.value}|${l.label}`,()=>{u?this.term.brightYellow(y):this.term.dim(y)})}let c=e.hint??"\u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close";o(`opts|hint|${n}|${c}`,()=>{this.term.dim(` ${c}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),n=this.term.width,s=this.wrapBtwTail(n,e).length;return Math.min(this.btwOverlayMaxHeight,1+s)}wrapBtwTail(e,n){if(e<=4){let o=Math.min(n,this.btwOverlayLines.length);return this.btwOverlayLines.slice(this.btwOverlayLines.length-o)}if(n<=0||this.btwOverlayLines.length===0)return[];let s=[],r=0;for(let o=this.btwOverlayLines.length-1;o>=0;o--){let a=this.btwOverlayLines[o],c=this.wrapOne(a,e);if(s.push(c),r+=c.length,r>=n)break}let i=[];for(let o=s.length-1;o>=0;o--)i.push(...s[o]);return i.length>n?i.slice(i.length-n):i}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let n=this.term.width,r=this.term.height-this.promptRows()-Je-Ve-Ue,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,c=e-1,d=a,l=this.buildBtwHeaderSegments();this.paintRow(d,`btw|h|${l.signature}`,()=>{this.paintBtwHeader(l)});let u=this.wrapBtwTail(n,c);for(let f=0;f<c;f++){let p=d+1+f,h=u.length-c+f,m=h>=0?u[h]:void 0,y=ab(`btw|c${f}`,n,m);this.paintRow(p,y,()=>{m?this.writeFormattedLine(m,n):this.term.noFormat(" ".repeat(n))})}}wrapTail(e,n){let s=d=>d.collapsed===!0||this.hideThoughts&&d.bodyStyle==="thought";if(e<=4){let d=[];for(let u of this.lines)s(u)||d.push(u);let l=Math.min(n,d.length);return{rows:d.slice(d.length-l),exhausted:n>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),n<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],i=0,o=0,a=!1;for(let d=this.lines.length-1;d>=0;d--){let l=this.lines[d];if(s(l)){d===0&&(a=!0);continue}let u=this.wrapOne(l,e);if(r.push(u),i+=u.length,o=d,i>=n)break}let c=[];for(let d=r.length-1;d>=0;d--)c.push(...r[d]);return{rows:c,exhausted:o===0||a}}wrapOne(e,n){let s=this.lineIds.get(e);if(s!==void 0){let u=this.wrapCache.get(s);if(u)return u}let r=e.prefix??"",i=er(r),o=Math.max(1,n-i-1),a=ka(e.bodyStyle),c=e.ansi?$0(e.body,o):B0(e.body,o,{stripMarkup:a}),d=[],l=0;for(let u=0;u<c.length;u++){let f=c[u]??"",p={prefix:u===0?e.prefix:" ".repeat(i),body:f};if(e.prefixStyle!==void 0&&(p.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(p.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(p.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(p.hoverSubKey=e.hoverSubKey),e.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),u===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&f.length>0){let h=e.body.indexOf(f,l),m=h===-1?l:h;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:m}),l=m+f.length}d.push(p)}return s!==void 0&&this.wrapCache.set(s,d),d}writeFormattedLine(e,n,s=null,r=0,i=null,o=!1){e.prefix&&Zn(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,n-er(e.prefix??"")),c=ka(e.bodyStyle),d=e.ansi?e.body:kt(e.body,a,{stripMarkup:c}),l=(u,f)=>{if(u.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let p=s!==null&&s>=f?s-f:null;db(this.term,u,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else Zn(this.term,u,e.bodyStyle,o)};if(i!==null&&e.ansi){let u=d.replace(ib,"");Zn(this.term,u,"selection-highlight",o)}else if(i!==null&&!e.ansi){let u=Math.max(0,Math.min(d.length,i.start)),f=Math.max(u,Math.min(d.length,i.end)),p=ka(e.bodyStyle);if(l(d.slice(0,u),0),f>u){let m=d.slice(u,f);p&&(m=cb(m)),Zn(this.term,m,"selection-highlight",o)}let h=d.slice(f);if(p&&f>u){let m=F0(d.slice(0,f));m.length>0&&(h=m+h)}l(h,f)}else this.scrollbackHighlight!==null&&!e.ansi?db(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):Zn(this.term,d,e.bodyStyle,o);if(e.fillRow){let u=e.ansi?je(d):er(d),f=a-u;if(f>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;Zn(this.term," ".repeat(f),p,o)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};hb=/[^\x20-\x7e]/,jf=new Intl.Segmenter(void 0,{granularity:"grapheme"}),mb=!1;O0=/[a-zA-Z+\-:_!#/]/;Oc=rt});function j0(t,e,n=Nc){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=n[t];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,t-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,t-1)};let r=n.findIndex(i=>i.hotkey.toLowerCase()===s);if(r>=0){let i=n[r];if(i)return{kind:"resolve",action:i.key}}}return{kind:"continue",selected:t}}async function vb(t,e){$n();let n=rt(e.sessionId),s=e.importedFromMachine??"another machine",r=Ze(e.cwd),i=Nc.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+Nc.length*2+2,d=On(t,{contentHeight:c,title:"Imported session"}),l=d.contentW,u=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],f=0;for(let p of u)t.moveTo(d.contentX,d.contentY+f),t.dim.noFormat(` ${p.label}`),t.noFormat(Ke(p.value,l-p.label.length-2)),f++;return f++,Sb(t,d,f,{intro:"What do you want to do?",choices:Nc,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return Gn({term:t,render:o,onKey:(a,c,d,l)=>{let u=q0(a,d);if(!u)return;let f=j0(i,u);if(f.kind==="cancel"){l("cancel");return}if(f.kind==="back"){l("back");return}if(f.kind==="resolve"){l(f.action);return}f.selected!==i&&(i=f.selected,o())}})}function Sb(t,e,n,s){let r=e.contentW,i=n;t.moveTo(e.contentX,e.contentY+i),t.noFormat(` ${s.intro}`),i+=2;for(let o=0;o<s.choices.length;o++){let a=s.choices[o];if(!a)continue;let d=` ${o===s.selected?"\u276F":" "} ${a.label}`;t.moveTo(e.contentX,e.contentY+i),o===s.selected?t.brightWhite.bgBlue.noFormat(bc(d,r)):t.noFormat(d),i++,t.moveTo(e.contentX,e.contentY+i),t.dim.noFormat(` ${a.description}`),i++}i++,t.moveTo(e.contentX,e.contentY+i),t.dim.noFormat(` ${s.footer}`)}function q0(t,e){return t==="UP"?{kind:"up"}:t==="DOWN"?{kind:"down"}:t==="ENTER"||t==="KP_ENTER"?{kind:"enter"}:t==="ESCAPE"?{kind:"back"}:t==="CTRL_C"||t==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:t}:null}async function kb(t,e,n){let s=rt(e.sessionId),r=e.title??Ze(e.cwd),i=1,o=[{label:"Launch",hotkey:"l",description:"start a new agent session"},{label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=()=>{let c=On(t,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;t.moveTo(c.contentX,c.contentY+l),t.dim.noFormat(" session: "),t.noFormat(Ke(s,d-10)),l++,t.moveTo(c.contentX,c.contentY+l),t.noFormat(" "+Ke(r,d-2)),l++,l++,Sb(t,c,l,{intro:"What do you want to do?",choices:o,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"})};return a(),t.hideCursor(),await new Promise(c=>{let d=!1,l=()=>{d=!0},u=p=>{l(),n.pop(),c(p)},f=(p,h,m)=>{if(p==="CTRL_C"||p==="CTRL_D"){u("cancel");return}if(p==="ESCAPE"){u("back");return}if(p==="ENTER"||p==="KP_ENTER"){u(i===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){i>0&&(i--,a());return}if(p==="DOWN"||p==="TAB"){i<o.length-1&&(i++,a());return}if(m?.isCharacter){let y=p.toLowerCase();if(y==="l"){u("launch");return}if(y==="v"){u("view");return}if(y==="n"){i<o.length-1&&(i++,a());return}if(y==="p"){i>0&&(i--,a());return}}};n.push({onKey:(p,h,m)=>{d||f(p,h,m)},onResize:()=>{d||a()}})})}var Nc,zf=J(()=>{"use strict";he();qn();qr();Nc=[{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 xa(t){if(t.length===0)return"";let e=t[0]??"";for(let n=1;n<t.length;n++){let s=t[n]??"",r=0;for(;r<e.length&&r<s.length&&e[r]===s[r];)r+=1;if(e=e.slice(0,r),e.length===0)break}return e}function Ib(t){let{matches:e,firstLine:n}=t;if(e.length===0)return null;let s=n.indexOf(" "),r=s===-1?n:n.slice(0,s),i=s===-1?"":n.slice(s);if(e.length===1){let a=e[0]??"",c=i.startsWith(" ")?"":" ";return a+c+i}let o=xa(e);return o.length<=r.length?null:o+i}var Dc=J(()=>{"use strict"});import*as xb from"os";async function Vr(t,e,n={}){let s=n.defaultCwd??(e?await Lw(e.cwd):void 0)??xb.homedir();$n();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:rt(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:Ze(e.cwd)}]:[],a=s,c=null,d=!1,l=null,u=[],f=[],p=()=>{u.push(a),u.length>500&&u.shift(),f=[]},h=()=>{let k=u.pop();k!==void 0&&(f.push(a),a=k)},m=()=>{let k=f.pop();k!==void 0&&(u.push(a),a=k)},y=()=>{let k=o.length+6;l=On(t,{contentHeight:k,title:r});let T=l.contentW,O=0;for(let $ of o)t.moveTo(l.contentX,l.contentY+O),t.dim.noFormat(` ${$.label}`),t.noFormat(Ke($.value,T-$.label.length-2)),O++;O++,t.moveTo(l.contentX,l.contentY+O),t.noFormat(` ${i}`),O+=2,v(O),O+=2,c!==null?(t.moveTo(l.contentX,l.contentY+O),t.red.noFormat(` ${Ke(c,T-2)}`)):(t.moveTo(l.contentX,l.contentY+O),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},b=()=>o.length+3,v=k=>{if(!l)return;let T=k??b();t.moveTo(l.contentX,l.contentY+T).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+T),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+T),t.bold.noFormat(" cwd: ");let O=l.contentW-6-2;t.noFormat(W0(a,O)),d||t.bgWhite(" ")},S=()=>{if(v(),!l)return;let k=b()+2;t.moveTo(l.contentX,l.contentY+k).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+k),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+k),c!==null?t.red.noFormat(` ${Ke(c,l.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return Gn({term:t,render:y,hideCursor:!1,onKey:(k,T,O,$)=>{if(!d){if(k==="ENTER"||k==="KP_ENTER"){let B=a;d=!0,c=null,S(),wa(B).then(K=>{if(d=!1,K.ok){$({kind:"ok",path:K.path});return}c=K.reason,S()});return}if(k==="ESCAPE"){$({kind:"back"});return}if(k==="CTRL_C"||k==="CTRL_D"){$({kind:"cancel"});return}if(k==="TAB"){d=!0,Bw(a).then(B=>{if(d=!1,B.matches.length===0)return;let K;if(B.matches.length===1)K=B.prefix+B.matches[0];else{let U=xa(B.matches);if(U.length<=B.basePrefix.length)return;K=B.prefix+U}K!==a&&(p(),a=K,c=null,S())});return}if(k==="BACKSPACE"){a.length>0&&(p(),a=a.slice(0,-1),c=null,S());return}if(k==="CTRL_U"){a.length>0&&(p(),a="",c=null,S());return}if(k==="CTRL_W"){let B=a.replace(/[/\s]+$/,""),K=Math.max(B.lastIndexOf("/"),B.lastIndexOf(" ")),U=K>=0?B.slice(0,K+1):"";U!==a&&(p(),a=U,c=null,S());return}if(k===""){h(),c=null,S();return}if(k==="\x1B_"||k==="\x1B"){m(),c=null,S();return}if(O?.isCharacter){p(),a+=k,c=null,S();return}}}})}function W0(t,e){return e<=1?"":t.length<=e?t:"\u2026"+t.slice(t.length-(e-1))}var Kf=J(()=>{"use strict";he();qn();Sf();Dc();qr()});function Vf(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Yf(t,e){let n=()=>{process.stdout.write(Hr),process.stdout.write(ws),process.stdout.write(Ur),process.stdout.write(jr),process.stdout.write(ro),process.stdout.write(io),process.stdout.write(oo),process.stdout.write(Dr),process.stdout.write("\x1B>")};n();let s=e.prefs??Vf();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(P=>P.sessionId===e.currentSessionId)?.importedFromMachine&&(s.filters.hostFilter="__all");let r=e.cwd,i=Uc(e.sessions,r),o=R=>{let P=R;return s.filters.cwdOnly&&(P=P.filter(D=>D.cwd===r)),s.filters.includeNonInteractive||(P=P.filter(D=>D.interactive===!0)),P=Y0(P,s.filters.hostFilter),P},a=o(i),c={columns:e.config.tui.sessionColumns??Yi,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>Gi(R,Date.now())),l=Xi(d,c),u=1+a.length,f=0,p=0;if(e.currentSessionId!==void 0){let R=a.findIndex(P=>P.sessionId===e.currentSessionId);R>=0&&(f=R+1)}let h=!1,m="",y=120,b=!1,v=0,S="normal",k=null,T=!1,O="input",$=new vs({history:[],collapsePastes:!1}),B=[],K=!1,U=0,L=0,N=null,Z=!1,G="",Se=[],X=[],ce=()=>{Se.push(G),Se.length>500&&Se.shift(),X=[]},Ye=()=>{let R=Se.pop();R!==void 0&&(X.push(G),G=R)},sr=()=>{let R=X.pop();R!==void 0&&(Se.push(G),G=R)},ks=()=>{Se=[],X=[]},De=null,V=!1,xe=new vs({history:[]});e.initialPrompt&&xe.setBuffer(e.initialPrompt);let ts=e.config.tui.promptHistoryMaxEntries;Wo(_.globalTuiHistoryFile()).then(R=>{let P=R.length>ts?R.slice(R.length-ts):R;xe.setHistory(P)}).catch(()=>{});let ve=new fo(t),Is=bs(t),ot=an(t),He=0,mo="",xs=0,Mt=[],dn=1,As=0,rr=0,go=0,Qr="",_e=[],Fn=1,Ta=0,ir=[],It=1,Ln=0,yo=0,Gr=0,wo=()=>{Is=bs(t),ot=an(t);let R=Math.max(10,ot-Jf-1);xs=Math.max(10,ot-Ab);let P=Math.max(10,ot-8);mo=V0(r,P);let D=xe.state();Mt=Ss(D.buffer,xs);let Q=tr(Mt,D,Hc);dn=Q.rendered,As=Q.windowStart,rr=Q.cursorVisualRow,go=Q.cursorVisualCol;let ae=6+dn,ue=Math.max(3,Is-ae);He=Math.min(a.length,ue),Qr=Ys(Qi,l,R,c).padEnd(R),_e=d.map(Be=>Ys(Be,l,R,c).padEnd(R))},Ae=()=>{d=a.map(R=>Gi(R,Date.now())),l=Xi(d,c),u=1+a.length,wo()},st=()=>{let R=o(i);h&&m.length>0?a=R.filter(P=>Q0(P,m)):a=R,Ae(),h?(p=0,f=a.length>0?1:0):f>u-1&&(f=Math.max(0,u-1)),p+He>a.length&&(p=Math.max(0,a.length-He)),cn()},ut=R=>{if(R!==void 0){let P=a.findIndex(D=>D.sessionId===R);if(P>=0){f=P+1,cn();return}}f=a.length>0?1:0,p=0,cn()},cn=()=>{if(f===0)return;let R=f-1;R<p?p=R:R>=p+He?p=R-He+1:p+He>a.length&&(p=Math.max(0,a.length-He))},ln=()=>Math.max(2,ot-3),ft=!1,vt=!0,pt=!1,Xr=[],Zr=()=>{let R=ln(),P=`\u2500 ${mo} `,D=Math.max(1,R-P.length),Q="\u2500".repeat(D);(f===0||ft)&&vt?t.brightBlue.noFormat(`\u256D${P}${Q}\u256E`):t.dim.noFormat(`\u256D${P}${Q}\u256E`)},Cs=()=>{let R=ln(),P="\u2500".repeat(R);(f===0||ft)&&vt?t.brightBlue.noFormat(`\u2570${P}\u256F`):t.dim.noFormat(`\u2570${P}\u256F`)},ei=R=>{let P=Mt[R];return P?(xe.state().buffer[P.bufferIdx]??"").slice(P.startCol,P.endCol):""},In=R=>{let P=ln(),D=ei(R),Q=Math.max(0,P-1-D.length),ae=" ".repeat(Q);(f===0||ft)&&vt?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${D}${ae}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${D}${ae}`),t.dim.noFormat("\u2502"))},or=R=>{let P=_e[R]??"",D=a[R],Q=D&&D.priority&&D.priority>0?"* ":" ";f===R+1&&!ft&&vt?t.brightWhite.bgBlue.noFormat(`${Q}${P}`):t.noFormat(`${Q}${P}`)},Rs=()=>{let R=p,P=Math.max(0,a.length-p-He),D=[];if(s.filters.cwdOnly&&D.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let Q=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;D.push({kind:"host",text:Q})}return s.filters.includeNonInteractive&&D.push({kind:"plain",text:"+non-interactive"}),R>0&&D.push({kind:"plain",text:`\u2191 ${R} above`}),P>0&&D.push({kind:"plain",text:`\u2193 ${P} below`}),D},bo=()=>{let R=Rs();return R.length===0?"":` ${R.map(P=>P.text).join(" \xB7 ")}`},xt=R=>rt(R),un=()=>{let R=k?`${k.sessionId}|${k.status}`:"";return["ind",S,R,G,De??"",h?`1|${m}|${a.length}`:"0",bo(),Ms?"h1":"h0",hr?"ho1":"ho0"].join("")},me=()=>{Ne(()=>{ve.paintRow(fn(),un(),()=>{let R=()=>{Yt=null,xn=null};if(S==="confirm-kill"&&k)R(),t.brightYellow.noFormat(` kill ${xt(k.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&k)R(),k.status==="warm"?t.brightRed.noFormat(` kill + delete ${xt(k.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${xt(k.sessionId)}? [y/N]`);else if(S==="busy"&&k)R(),t.dim.noFormat(` working on ${xt(k.sessionId)}\u2026`);else if(S==="rename"&&k)R(),t.brightYellow.noFormat(` title: ${G}`),t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels");else if(De!==null)R(),t.dim.noFormat(` ${De}`);else if(h){R(),t.brightYellow.noFormat(` /${m}`),t.bgBrightYellow(" ");let P=a.length===0?" no matches":` ${a.length} match${a.length===1?"":"es"}`;t.dim.noFormat(`${P} \xB7 ^c clears`)}else{let P=Rs(),D=bo(),Q="Esc \xB7 Go Back",ae=Q.length,ue=5,Be=D.length,jt=Math.max(1,ot-Be-ae-ue);if(xn=null,P.length>0){t.dim.noFormat(" ");let $t=3;for(let Qe=0;Qe<P.length;Qe++){let mt=P[Qe];Qe>0&&(t.dim.noFormat(" \xB7 "),$t+=3),mt.kind==="host"?(xn={start:$t,end:$t+mt.text.length-1},hr?t.noFormat(mt.text):t.dim.noFormat(mt.text)):t.dim.noFormat(mt.text),$t+=mt.text.length}}t.dim(" ".repeat(jt)),Ms?t.noFormat(Q):t.dim.noFormat(Q),Yt={start:ot-ue-ae+1,end:ot-ue}}})})},Ce=R=>Fn+1+R,ar=()=>Fn+dn+1,Bt=()=>Fn+dn+3,Kt=R=>Bt()+1+(R-p),fn=()=>Bt()+1+He,Nt=()=>{let R=rr-As;if(R<0||R>=dn)return;let P=3+go;t.moveTo(P,Ce(R))},I=()=>vt?f===0?"f":ft?"h":"u":"x",vo=()=>`ct|${I()}|${ln()}|${mo}`,Ea=()=>`cb|${I()}|${ln()}`,Ts=R=>`cbb|${I()}|${ln()}|${ei(R)}`,ti=()=>`h|${Qr}`,dr=R=>{let P=a[R],D=P&&P.priority&&P.priority>0?"* ":" ",Q=_e[R]??"";return`sr|${f===R+1&&!ft&&vt?"1":"0"}|${D}${Q}`},qe=()=>{Ne(()=>{t.hideCursor(),wo(),cn(),Fn=1,ve.ensureSize(ot,Is),ve.paintRow(Fn,vo(),()=>{Zr()});for(let R=0;R<dn;R++){let P=As+R;ve.paintRow(Ce(R),Ts(P),()=>{In(P)})}ve.paintRow(ar(),Ea(),()=>{Cs()}),ve.paintRow(ar()+1,"blank",()=>{}),ve.paintRow(Bt(),ti(),()=>{t.dim.noFormat(` ${Qr}`)});for(let R=0;R<He;R++){let P=p+R,D=Bt()+1+R;P<a.length?ve.paintRow(D,dr(P),()=>{or(P)}):ve.paintRow(D,"blank",()=>{})}me();for(let R=fn()+1;R<=Is;R++)ve.paintRow(R,"blank",()=>{});f===0&&(Nt(),t.hideCursor(!1))})},ns=()=>{ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),qe()},So=()=>{Ne(()=>{t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
211
211
 
212
- `);for(let R of U0){if(R===null){t(`
213
- `);continue}let[P,D]=R;t.brightCyan.noFormat(` ${P.padEnd(H0)}`),t.noFormat(D)(`
212
+ `);for(let R of J0){if(R===null){t(`
213
+ `);continue}let[P,D]=R;t.brightCyan.noFormat(` ${P.padEnd(K0)}`),t.noFormat(D)(`
214
214
  `)}t(`
215
215
  `),t.dim.noFormat(" press any key to dismiss")(`
216
- `)})},Jt=()=>It+4,zc=2,at=0,Dt=()=>{Is=ws(t);let R=Math.max(2,Is-(It+3)-zc);return Math.max(1,Math.floor(R/2))},So=()=>{let R=Dt();U<at?at=U:U>=at+R&&(at=U-R+1),at+R>B.length&&(at=Math.max(0,B.length-R)),at<0&&(at=0)},Ea=R=>{ot=an(t);let P=Math.max(2,ot-3),D="\u2500 Find sessions ",Q="\u2500".repeat(Math.max(1,P-D.length));R?t.brightBlue.noFormat(`\u256D${D}${Q}\u256E`):t.dim.noFormat(`\u256D${D}${Q}\u256E`),t.styleReset()},cr=()=>{ot=an(t),Ra=Math.max(10,ot-kb);let R=$.state();ir=Ss(R.buffer,Ra);let P=tr(ir,R,D0);It=P.rendered,Ln=P.windowStart,go=P.cursorVisualRow,Gr=P.cursorVisualCol},ko=(R,P)=>{ot=an(t);let D=Math.max(2,ot-3),Q=ir[R],ae="";Q&&(ae=($.state().buffer[Q.bufferIdx]??"").slice(Q.startCol,Q.endCol));let ue=Math.max(0,D-1-ae.length),Be=" ".repeat(ue);P?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${ae}${Be}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${ae}${Be}`),t.dim.noFormat("\u2502")),t.styleReset()},Pa=R=>{ot=an(t);let P=Math.max(2,ot-3),D="\u2500".repeat(P);R?t.brightBlue.noFormat(`\u2570${D}\u256F`):t.dim.noFormat(`\u2570${D}\u256F`),t.styleReset()},lr=()=>3+Gr,ur=()=>2+(go-Ln),Ht=()=>{let R=F==="input";Ne(()=>{R&&t.hideCursor(),t.moveTo(1,1),Ea(R);for(let P=0;P<It;P++)t.moveTo(1,2+P),ko(Ln+P,R);t.moveTo(1,2+It),Pa(R),R&&(t.moveTo(lr(),ur()),t.hideCursor(!1))})},ht=()=>{Ne(()=>{t.hideCursor();for(let R=0;R<It;R++)t.moveTo(1,2+R),ko(Ln+R,!0);t.moveTo(lr(),ur()),t.hideCursor(!1)})},Kc={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},Io=(R,P)=>{let D=B[R];if(!D)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Q=an(t),ae=Math.max(20,Q-Kf),ue=rt(D.sessionId),Be=D.title??Ze(D.cwd),jt=P&&D.snippets.length>1?` [${L+1}/${D.snippets.length}]`:P&&D.totalMatches>D.snippets.length?` [${D.snippets.length} of ${D.totalMatches}]`:"",$t=`${ue} ${D.status==="warm"?"warm":"cold"}`,Ye=Math.max(5,ae-$t.length-jt.length-2),mt=oa(Be,Ye),hn=`${$t} ${mt}${jt}`.padEnd(ae),St=D.snippets[P?L:0],qe=St?Kc[St.kind]??St.kind:"",An=St?.toolName?`${qe} \xB7 ${St.toolName}`:qe,ai=Math.max(10,ae-An.length-6),Cn=St?oa(St.text,ai):"",mr=St?` ${An} ${Cn}`:" (no snippet)";return{rowBudget:ae,line1:hn,line2:mr.padEnd(ae+Kf),focusedRow:P}},fr=(R,P)=>{let{line1:D,focusedRow:Q}=Io(R,P);Q?t.brightWhite.bgBlue.noFormat(`\u276F ${D}`):t.noFormat(` ${D}`),t.styleReset()},ns=(R,P)=>{let{line2:D}=Io(R,P);t.dim.noFormat(D),t.styleReset()},Es=()=>{if(Z)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(N!==null)t.brightRed.noFormat(` ${N}`),t.styleReset(),t.eraseLineAfter();else if(F==="input")B.length>0?t.dim.noFormat(" Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):t.dim.noFormat(" Enter to search \xB7 Esc cancel"),t.styleReset(),t.eraseLineAfter();else{let R=B.length,P=K?" \xB7 truncated":"",D=R>0?` ${R} ${R===1?"session":"sessions"} match${P} \xB7 `:" ";t.dim.noFormat(`${D}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},ss=()=>{cr();let R=F==="input",P=$.state().buffer.join(`
217
- `);Ne(()=>{t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Ea(R);for(let Q=0;Q<It;Q++)t.moveTo(1,2+Q),ko(Ln+Q,R);t.moveTo(1,2+It),Pa(R);let D=B.length;if(D===0)t.moveTo(1,Jt()),Z||(N===null&&P.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):N===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,Jt()+1),Es();else{So();let Q=Dt(),ae=F!=="input";for(let ue=0;ue<Q;ue++){let Be=at+ue;t.moveTo(1,Jt()+ue*2),Be<D?fr(Be,ae&&Be===U):t.eraseLineAfter(),t.moveTo(1,Jt()+ue*2+1),Be<D?ns(Be,ae&&Be===U):t.eraseLineAfter()}t.moveTo(1,Jt()+Q*2),Es()}R&&(t.moveTo(lr(),ur()),t.hideCursor(!1))})},Ps=(R,P)=>{let D=R-at;D<0||D>=Dt()||Ne(()=>{t.moveTo(1,Jt()+D*2),fr(R,P),t.moveTo(1,Jt()+D*2+1),ns(R,P)})},pr=()=>{Ne(()=>{t.moveTo(1,Jt()+Dt()*2),Es()})},ni=()=>{Ne(()=>{let R=Dt(),P=B.length,D=F!=="input";for(let Q=0;Q<R;Q++){let ae=at+Q;t.moveTo(1,Jt()+Q*2),ae<P?fr(ae,D&&ae===U):t.eraseLineAfter(),t.moveTo(1,Jt()+Q*2+1),ae<P?ns(ae,D&&ae===U):t.eraseLineAfter()}t.moveTo(1,Jt()+R*2),Es()})},xo=()=>$.state().buffer.join(`
218
- `),Jc=R=>{let P=It;$.feed({type:"paste",text:R}),cr(),It!==P?ss():ht()},Yc=async()=>{let R=xo().trim();if(R.length!==0){if(a.length===0){N="no sessions in view to search",ss();return}Z=!0,N=null,ss();try{let P=await Kg(e.target,R,{sessionIds:a.map(D=>D.sessionId)});B=P.results,K=P.truncated,U=0,L=0,at=0,F=P.results.length>0?"results":"input",cr()}catch(P){N=`search failed: ${P.message}`}finally{Z=!1,ss()}}},rs=()=>{},Ut=()=>{Ne(()=>{let R=f===0;R&&t.hideCursor(),ve.paintRow(On,bo(),()=>{Zr()}),ve.paintRow(ar(),Ta(),()=>{Cs()});for(let P=0;P<dn;P++){let D=As+P;ve.paintRow(Ce(P),Ts(D),()=>{In(D)})}R&&(Nt(),t.hideCursor(!1))})},pn=()=>{Ne(()=>{let R=xe.state();Mt=Ss(R.buffer,xs);let P=tr(Mt,R,Dc);As=P.windowStart,rr=P.cursorVisualRow,mo=P.cursorVisualCol;let D=f===0;D&&t.hideCursor();for(let Q=0;Q<dn;Q++){let ae=As+Q;ve.paintRow(Ce(Q),Ts(ae),()=>{In(ae)})}D&&(Nt(),t.hideCursor(!1))})},si=R=>{R<p||R>=p+He||Ne(()=>{ve.paintRow(Kt(R),dr(R),()=>{or(R)})})},_t=()=>{Ne(()=>{for(let R=0;R<He;R++){let P=Bt()+1+R,D=p+R;D<a.length?ve.paintRow(P,dr(D),()=>{or(D)}):ve.paintRow(P,"blank",()=>{})}me()})},Bn=()=>{Ne(()=>{ve.paintRow(Bt(),ti(),()=>{t.dim.noFormat(` ${Qr}`)});for(let R=0;R<He;R++){let P=Bt()+1+R,D=p+R;D<a.length?ve.paintRow(P,dr(D),()=>{or(D)}):ve.paintRow(P,"blank",()=>{})}me(),f===0&&(Nt(),t.hideCursor(!1))})},Yt=!1,is="",ri=0,Ma=200,os=null,ii=!1,Vt=null,Ms=!1,xn=null,hr=!1,Qt=null,Ao=null,_a=null,oi=R=>{let P=R.toString("binary");if(P.includes("\x1B[I")||P.includes("\x1B[O")){for(;;){let Q=P.indexOf("\x1B[I"),ae=P.indexOf("\x1B[O"),ue=Q===-1?ae:ae===-1?Q:Math.min(Q,ae);if(ue===-1)break;let Be=vt;vt=ue===Q,vt&&(ri=Date.now()),Be!==vt&&!pt&&Xr.length<=1&&Ne(()=>{Ut(),_t()}),P=P.slice(0,ue)+P.slice(ue+"\x1B[I".length)}if(P.length===0)return}if(!Yt&&P===""&&Ao){Ao();return}if(!Yt&&(P===""||P==="\x1B_"||P==="\x1B")){_a?.(P);return}if(Yt){let Q=P.indexOf(ca);if(Q===-1){is+=P;return}is+=P.slice(0,Q),Yt=!1;let ae=Buffer.from(is,"binary").toString("utf-8").replace(/\r\n?/g,`
219
- `);is="";let ue=P.slice(Q+ca.length);if(T)F==="input"&&!Z&&Jc(ae);else if(f===0&&!h){xe.feed({type:"paste",text:ae});let Be=xe.state(),jt=Ss(Be.buffer,xs);tr(jt,Be,Dc).rendered!==dn?je():pn()}ue.length>0&&Qt&&Qt(Buffer.from(ue,"binary"));return}let D=P.indexOf(no);if(D===-1){Qt?.(R);return}D>0&&Qt?.(Buffer.from(P.slice(0,D),"binary")),P=P.slice(D+no.length),Yt=!0,P.length>0&&oi(Buffer.from(P,"binary"))};return je(),await new Promise(R=>{let P=null,D=!1,Q=null,ae=!1,ue=Xr,Be=E=>{ue.push(E)},jt=()=>{ue.pop(),pt||ue[ue.length-1]?.onResize()},$t={push:Be,pop:jt},Ye=()=>({kind:"new",cwd:r}),mt=async()=>{$s(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Be({onKey:()=>{},onResize:()=>{}});let j;try{j=await Yr(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:"})}finally{jt(),Nn()}j.kind==="ok"&&j.path!==r&&(r=j.path,i=Hc(i,r),st()),pt||je()};rs=()=>{$=new bs({history:[],collapsePastes:!1}),B=[],K=!1,U=0,L=0,at=0,N=null,Z=!1,F="input",T=!1,jt()};let hn=(E,j,ie)=>{ai(),ue[ue.length-1]?.onKey(E,j,ie)},St=()=>{pt||ue[ue.length-1]?.onResize()};_a=E=>{pt||ue[ue.length-1]?.onKey(E,null,{})};let qe=()=>{if(pt)return;pt=!0,ue.length=0,P&&(clearInterval(P),P=null),Q&&(Q.abort(),Q=null,D=!1),t.off("key",hn),t.off("mouse",ls),t.off("resize",St),process.stdout.write(ys),process.stdout.write(ua);let E=t;E.stdin&&Qt&&(E.stdin.removeListener("data",oi),E.stdin.on("data",Qt),Qt=null),Yt=!1,is="",t.grabInput(!1),se({src:"grab",site:"picker.cleanup",on:!1}),t.hideCursor(!1),t.moveTo(1,fn()+1),t(`
220
- `)},An=()=>{if(pt||ue.length>1||S!=="normal"||h||ae)return;D&&Q&&(Q.abort(),Q=null,D=!1);let E=f>0?a[f-1]?.sessionId:void 0;D=!0;let j=new AbortController;Q=j,_s(E,{silent:!0,signal:j.signal}).finally(()=>{Q===j&&(Q=null),D=!1})},ai=()=>{pt||(P&&clearInterval(P),P=setInterval(An,3e3))},Cn=()=>(qe(),R({kind:Y?"exit":"abort"}),!0),mr=()=>{let E=d.map(j=>`${j.session}|${j.upstream}|${j.host}|${j.state}|${j.agent}|${j.model}|${j.age}|${j.title}|${j.cwd}|${j.cost}`).join(`
216
+ `)})},Jt=()=>It+4,Kc=2,at=0,Dt=()=>{Is=bs(t);let R=Math.max(2,Is-(It+3)-Kc);return Math.max(1,Math.floor(R/2))},ko=()=>{let R=Dt();U<at?at=U:U>=at+R&&(at=U-R+1),at+R>B.length&&(at=Math.max(0,B.length-R)),at<0&&(at=0)},Pa=R=>{ot=an(t);let P=Math.max(2,ot-3),D="\u2500 Find sessions ",Q="\u2500".repeat(Math.max(1,P-D.length));R?t.brightBlue.noFormat(`\u256D${D}${Q}\u256E`):t.dim.noFormat(`\u256D${D}${Q}\u256E`),t.styleReset()},cr=()=>{ot=an(t),Ta=Math.max(10,ot-Ab);let R=$.state();ir=Ss(R.buffer,Ta);let P=tr(ir,R,z0);It=P.rendered,Ln=P.windowStart,yo=P.cursorVisualRow,Gr=P.cursorVisualCol},Io=(R,P)=>{ot=an(t);let D=Math.max(2,ot-3),Q=ir[R],ae="";Q&&(ae=($.state().buffer[Q.bufferIdx]??"").slice(Q.startCol,Q.endCol));let ue=Math.max(0,D-1-ae.length),Be=" ".repeat(ue);P?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${ae}${Be}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${ae}${Be}`),t.dim.noFormat("\u2502")),t.styleReset()},Ma=R=>{ot=an(t);let P=Math.max(2,ot-3),D="\u2500".repeat(P);R?t.brightBlue.noFormat(`\u2570${D}\u256F`):t.dim.noFormat(`\u2570${D}\u256F`),t.styleReset()},lr=()=>3+Gr,ur=()=>2+(yo-Ln),Ht=()=>{let R=O==="input";Ne(()=>{R&&t.hideCursor(),t.moveTo(1,1),Pa(R);for(let P=0;P<It;P++)t.moveTo(1,2+P),Io(Ln+P,R);t.moveTo(1,2+It),Ma(R),R&&(t.moveTo(lr(),ur()),t.hideCursor(!1))})},ht=()=>{Ne(()=>{t.hideCursor();for(let R=0;R<It;R++)t.moveTo(1,2+R),Io(Ln+R,!0);t.moveTo(lr(),ur()),t.hideCursor(!1)})},Jc={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},xo=(R,P)=>{let D=B[R];if(!D)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Q=an(t),ae=Math.max(20,Q-Jf),ue=rt(D.sessionId),Be=D.title??Ze(D.cwd),jt=P&&D.snippets.length>1?` [${L+1}/${D.snippets.length}]`:P&&D.totalMatches>D.snippets.length?` [${D.snippets.length} of ${D.totalMatches}]`:"",$t=`${ue} ${D.status==="warm"?"warm":"cold"}`,Qe=Math.max(5,ae-$t.length-jt.length-2),mt=aa(Be,Qe),hn=`${$t} ${mt}${jt}`.padEnd(ae),St=D.snippets[P?L:0],We=St?Jc[St.kind]??St.kind:"",An=St?.toolName?`${We} \xB7 ${St.toolName}`:We,ai=Math.max(10,ae-An.length-6),Cn=St?aa(St.text,ai):"",mr=St?` ${An} ${Cn}`:" (no snippet)";return{rowBudget:ae,line1:hn,line2:mr.padEnd(ae+Jf),focusedRow:P}},fr=(R,P)=>{let{line1:D,focusedRow:Q}=xo(R,P);Q?t.brightWhite.bgBlue.noFormat(`\u276F ${D}`):t.noFormat(` ${D}`),t.styleReset()},ss=(R,P)=>{let{line2:D}=xo(R,P);t.dim.noFormat(D),t.styleReset()},Es=()=>{if(Z)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(N!==null)t.brightRed.noFormat(` ${N}`),t.styleReset(),t.eraseLineAfter();else if(O==="input")B.length>0?t.dim.noFormat(" Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):t.dim.noFormat(" Enter to search \xB7 Esc cancel"),t.styleReset(),t.eraseLineAfter();else{let R=B.length,P=K?" \xB7 truncated":"",D=R>0?` ${R} ${R===1?"session":"sessions"} match${P} \xB7 `:" ";t.dim.noFormat(`${D}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},rs=()=>{cr();let R=O==="input",P=$.state().buffer.join(`
217
+ `);Ne(()=>{t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Pa(R);for(let Q=0;Q<It;Q++)t.moveTo(1,2+Q),Io(Ln+Q,R);t.moveTo(1,2+It),Ma(R);let D=B.length;if(D===0)t.moveTo(1,Jt()),Z||(N===null&&P.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):N===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,Jt()+1),Es();else{ko();let Q=Dt(),ae=O!=="input";for(let ue=0;ue<Q;ue++){let Be=at+ue;t.moveTo(1,Jt()+ue*2),Be<D?fr(Be,ae&&Be===U):t.eraseLineAfter(),t.moveTo(1,Jt()+ue*2+1),Be<D?ss(Be,ae&&Be===U):t.eraseLineAfter()}t.moveTo(1,Jt()+Q*2),Es()}R&&(t.moveTo(lr(),ur()),t.hideCursor(!1))})},Ps=(R,P)=>{let D=R-at;D<0||D>=Dt()||Ne(()=>{t.moveTo(1,Jt()+D*2),fr(R,P),t.moveTo(1,Jt()+D*2+1),ss(R,P)})},pr=()=>{Ne(()=>{t.moveTo(1,Jt()+Dt()*2),Es()})},ni=()=>{Ne(()=>{let R=Dt(),P=B.length,D=O!=="input";for(let Q=0;Q<R;Q++){let ae=at+Q;t.moveTo(1,Jt()+Q*2),ae<P?fr(ae,D&&ae===U):t.eraseLineAfter(),t.moveTo(1,Jt()+Q*2+1),ae<P?ss(ae,D&&ae===U):t.eraseLineAfter()}t.moveTo(1,Jt()+R*2),Es()})},Ao=()=>$.state().buffer.join(`
218
+ `),Vc=R=>{let P=It;$.feed({type:"paste",text:R}),cr(),It!==P?rs():ht()},Yc=async()=>{let R=Ao().trim();if(R.length!==0){if(a.length===0){N="no sessions in view to search",rs();return}Z=!0,N=null,rs();try{let P=await Vg(e.target,R,{sessionIds:a.map(D=>D.sessionId)});B=P.results,K=P.truncated,U=0,L=0,at=0,O=P.results.length>0?"results":"input",cr()}catch(P){N=`search failed: ${P.message}`}finally{Z=!1,rs()}}},is=()=>{},Ut=()=>{Ne(()=>{let R=f===0;R&&t.hideCursor(),ve.paintRow(Fn,vo(),()=>{Zr()}),ve.paintRow(ar(),Ea(),()=>{Cs()});for(let P=0;P<dn;P++){let D=As+P;ve.paintRow(Ce(P),Ts(D),()=>{In(D)})}R&&(Nt(),t.hideCursor(!1))})},pn=()=>{Ne(()=>{let R=xe.state();Mt=Ss(R.buffer,xs);let P=tr(Mt,R,Hc);As=P.windowStart,rr=P.cursorVisualRow,go=P.cursorVisualCol;let D=f===0;D&&t.hideCursor();for(let Q=0;Q<dn;Q++){let ae=As+Q;ve.paintRow(Ce(Q),Ts(ae),()=>{In(ae)})}D&&(Nt(),t.hideCursor(!1))})},si=R=>{R<p||R>=p+He||Ne(()=>{ve.paintRow(Kt(R),dr(R),()=>{or(R)})})},_t=()=>{Ne(()=>{for(let R=0;R<He;R++){let P=Bt()+1+R,D=p+R;D<a.length?ve.paintRow(P,dr(D),()=>{or(D)}):ve.paintRow(P,"blank",()=>{})}me()})},Bn=()=>{Ne(()=>{ve.paintRow(Bt(),ti(),()=>{t.dim.noFormat(` ${Qr}`)});for(let R=0;R<He;R++){let P=Bt()+1+R,D=p+R;D<a.length?ve.paintRow(P,dr(D),()=>{or(D)}):ve.paintRow(P,"blank",()=>{})}me(),f===0&&(Nt(),t.hideCursor(!1))})},Vt=!1,os="",ri=0,_a=200,as=null,ii=!1,Yt=null,Ms=!1,xn=null,hr=!1,Qt=null,Co=null,$a=null,oi=R=>{let P=R.toString("binary");if(P.includes("\x1B[I")||P.includes("\x1B[O")){for(;;){let Q=P.indexOf("\x1B[I"),ae=P.indexOf("\x1B[O"),ue=Q===-1?ae:ae===-1?Q:Math.min(Q,ae);if(ue===-1)break;let Be=vt;vt=ue===Q,vt&&(ri=Date.now()),Be!==vt&&!pt&&Xr.length<=1&&Ne(()=>{Ut(),_t()}),P=P.slice(0,ue)+P.slice(ue+"\x1B[I".length)}if(P.length===0)return}if(!Vt&&P===""&&Co){Co();return}if(!Vt&&(P===""||P==="\x1B_"||P==="\x1B")){$a?.(P);return}if(Vt){let Q=P.indexOf(la);if(Q===-1){os+=P;return}os+=P.slice(0,Q),Vt=!1;let ae=Buffer.from(os,"binary").toString("utf-8").replace(/\r\n?/g,`
219
+ `);os="";let ue=P.slice(Q+la.length);if(T)O==="input"&&!Z&&Vc(ae);else if(f===0&&!h){xe.feed({type:"paste",text:ae});let Be=xe.state(),jt=Ss(Be.buffer,xs);tr(jt,Be,Hc).rendered!==dn?qe():pn()}ue.length>0&&Qt&&Qt(Buffer.from(ue,"binary"));return}let D=P.indexOf(so);if(D===-1){Qt?.(R);return}D>0&&Qt?.(Buffer.from(P.slice(0,D),"binary")),P=P.slice(D+so.length),Vt=!0,P.length>0&&oi(Buffer.from(P,"binary"))};return qe(),await new Promise(R=>{let P=null,D=!1,Q=null,ae=!1,ue=Xr,Be=E=>{ue.push(E)},jt=()=>{ue.pop(),pt||ue[ue.length-1]?.onResize()},$t={push:Be,pop:jt},Qe=()=>({kind:"new",cwd:r}),mt=async()=>{$s(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Be({onKey:()=>{},onResize:()=>{}});let j;try{j=await Vr(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:"})}finally{jt(),Nn()}j.kind==="ok"&&j.path!==r&&(r=j.path,i=Uc(i,r),st()),pt||qe()};is=()=>{$=new vs({history:[],collapsePastes:!1}),B=[],K=!1,U=0,L=0,at=0,N=null,Z=!1,O="input",T=!1,jt()};let hn=(E,j,ie)=>{ai(),ue[ue.length-1]?.onKey(E,j,ie)},St=()=>{pt||ue[ue.length-1]?.onResize()};$a=E=>{pt||ue[ue.length-1]?.onKey(E,null,{})};let We=()=>{if(pt)return;pt=!0,ue.length=0,P&&(clearInterval(P),P=null),Q&&(Q.abort(),Q=null,D=!1),t.off("key",hn),t.off("mouse",us),t.off("resize",St),process.stdout.write(ws),process.stdout.write(fa);let E=t;E.stdin&&Qt&&(E.stdin.removeListener("data",oi),E.stdin.on("data",Qt),Qt=null),Vt=!1,os="",t.grabInput(!1),se({src:"grab",site:"picker.cleanup",on:!1}),t.hideCursor(!1),t.moveTo(1,fn()+1),t(`
220
+ `)},An=()=>{if(pt||ue.length>1||S!=="normal"||h||ae)return;D&&Q&&(Q.abort(),Q=null,D=!1);let E=f>0?a[f-1]?.sessionId:void 0;D=!0;let j=new AbortController;Q=j,_s(E,{silent:!0,signal:j.signal}).finally(()=>{Q===j&&(Q=null),D=!1})},ai=()=>{pt||(P&&clearInterval(P),P=setInterval(An,3e3))},Cn=()=>(We(),R({kind:V?"exit":"abort"}),!0),mr=()=>{let E=d.map(j=>`${j.session}|${j.upstream}|${j.host}|${j.state}|${j.agent}|${j.model}|${j.age}|${j.title}|${j.cwd}|${j.cost}`).join(`
221
221
  `);return`${f}:${p}:${De??""}
222
- ${E}`},_s=async(E,j={})=>{try{let ie=j.silent?mr():"",W=u,te=await Yn(e.target,{includeNonInteractive:!0,signal:j.signal}),re=E??(f>0?a[f-1]?.sessionId:void 0);if(i=Hc(te,r),st(),re!==void 0){let ke=a.findIndex(We=>We.sessionId===re);ke>=0?f=ke+1:f=0}if(f>u-1&&(f=Math.max(0,u-1)),p+He>a.length&&(p=Math.max(0,a.length-He)),cn(),j.silent&&mr()===ie)return;u===W?Bn():je()}catch(ie){if(j.silent)return;De=`refresh failed: ${ie.message}`,je()}},$a=async E=>{if(!k)return;let j=k;S="busy",me();try{await qg(e.target,j.sessionId,E),S="normal",k=null,G="",await _s(j.sessionId)}catch(ie){S="normal",k=null,G="",De=`rename failed: ${ie.message}`,me()}},Co=async E=>{try{await zg(e.target,E.sessionId),De="title regen queued (press r to refresh)",me()}catch(j){De=`regen failed: ${j.message}`,me()}},gt=async E=>{let ie=(E.priority&&E.priority>0?E.priority:0)>0?null:1,W=ie??0;for(let re of i)re.sessionId===E.sessionId&&(re.priority=W>0?W:void 0);let te=E.sessionId;i=Hc(i,r),st(),ut(te),je(),De=W>0?"priority: high":"priority: normal",me();try{await Wg(e.target,E.sessionId,ie)}catch(re){De=`priority failed: ${re.message}`,me()}},as=async()=>{if(ae)return;ae=!0;let E=f>0?a[f-1]?.sessionId:void 0;De="syncing agents\u2026",me();try{let{synced:j,skipped:ie,agents:W}=await jg(e.target);await _s(E),De=`synced ${j} new (${ie} known) from ${W} agent${W===1?"":"s"}`,me()}catch(j){De=`sync failed: ${j.message}`,me()}finally{ae=!1}},ds=async E=>{if(!k)return;let j=k;S="busy",me();try{E==="kill"?await Vn(e.target,j.sessionId):await Jg(e.target,j.sessionId),S="normal",k=null,j.sessionId===e.currentSessionId&&(Y=!0);let ie;if(E==="kill")ie=j.sessionId;else{let W=a.findIndex(te=>te.sessionId===j.sessionId);W>=0&&(ie=a[W+1]?.sessionId??a[W-1]?.sessionId)}await _s(ie)}catch(ie){S="normal",k=null,De=`${E} failed: ${ie.message}`,me()}},Rn=(E,j)=>{E===0!=(j===0)&&(Ut(),j===0?(t.hideCursor(!1),Nt()):t.hideCursor())},dt=E=>{let j=Math.min(u-1,Math.max(0,f+E));if(j===f)return;let ie=f;f=j,cn(),Ne(()=>{_t(),Rn(ie,f)})},gr=()=>De===null?!1:(De=null,me(),!0),Tn=()=>{vo(),Be({onKey:E=>{if(E==="CTRL_C"){qe(),R({kind:"abort"});return}jt()},onResize:()=>vo()})},cs=E=>{let j=null,ie=null,W=!0,te=()=>{Ne(()=>{if(t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${rt(E.sessionId)}`)(`
222
+ ${E}`},_s=async(E,j={})=>{try{let ie=j.silent?mr():"",W=u,te=await Vn(e.target,{includeNonInteractive:!0,signal:j.signal}),re=E??(f>0?a[f-1]?.sessionId:void 0);if(i=Uc(te,r),st(),re!==void 0){let ke=a.findIndex(ze=>ze.sessionId===re);ke>=0?f=ke+1:f=0}if(f>u-1&&(f=Math.max(0,u-1)),p+He>a.length&&(p=Math.max(0,a.length-He)),cn(),j.silent&&mr()===ie)return;u===W?Bn():qe()}catch(ie){if(j.silent)return;De=`refresh failed: ${ie.message}`,qe()}},Oa=async E=>{if(!k)return;let j=k;S="busy",me();try{await zg(e.target,j.sessionId,E),S="normal",k=null,G="",await _s(j.sessionId)}catch(ie){S="normal",k=null,G="",De=`rename failed: ${ie.message}`,me()}},Ro=async E=>{try{await Jg(e.target,E.sessionId),De="title regen queued (press r to refresh)",me()}catch(j){De=`regen failed: ${j.message}`,me()}},gt=async E=>{let ie=(E.priority&&E.priority>0?E.priority:0)>0?null:1,W=ie??0;for(let re of i)re.sessionId===E.sessionId&&(re.priority=W>0?W:void 0);let te=E.sessionId;i=Uc(i,r),st(),ut(te),qe(),De=W>0?"priority: high":"priority: normal",me();try{await Kg(e.target,E.sessionId,ie)}catch(re){De=`priority failed: ${re.message}`,me()}},ds=async()=>{if(ae)return;ae=!0;let E=f>0?a[f-1]?.sessionId:void 0;De="syncing agents\u2026",me();try{let{synced:j,skipped:ie,agents:W}=await Wg(e.target);await _s(E),De=`synced ${j} new (${ie} known) from ${W} agent${W===1?"":"s"}`,me()}catch(j){De=`sync failed: ${j.message}`,me()}finally{ae=!1}},cs=async E=>{if(!k)return;let j=k;S="busy",me();try{E==="kill"?await Yn(e.target,j.sessionId):await Yg(e.target,j.sessionId),S="normal",k=null,j.sessionId===e.currentSessionId&&(V=!0);let ie;if(E==="kill")ie=j.sessionId;else{let W=a.findIndex(te=>te.sessionId===j.sessionId);W>=0&&(ie=a[W+1]?.sessionId??a[W-1]?.sessionId)}await _s(ie)}catch(ie){S="normal",k=null,De=`${E} failed: ${ie.message}`,me()}},Rn=(E,j)=>{E===0!=(j===0)&&(Ut(),j===0?(t.hideCursor(!1),Nt()):t.hideCursor())},dt=E=>{let j=Math.min(u-1,Math.max(0,f+E));if(j===f)return;let ie=f;f=j,cn(),Ne(()=>{_t(),Rn(ie,f)})},gr=()=>De===null?!1:(De=null,me(),!0),Tn=()=>{So(),Be({onKey:E=>{if(E==="CTRL_C"){We(),R({kind:"abort"});return}jt()},onResize:()=>So()})},ls=E=>{let j=null,ie=null,W=!0,te=()=>{Ne(()=>{if(t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${rt(E.sessionId)}`)(`
223
223
 
224
224
  `),W)t.dim.noFormat(" loading\u2026")(`
225
225
  `);else if(ie!==null)t.brightRed.noFormat(` ${ie}`)(`
226
- `);else if(j!==null)for(let We of j)t.noFormat(` ${We}`)(`
226
+ `);else if(j!==null)for(let ze of j)t.noFormat(` ${ze}`)(`
227
227
  `);t(`
228
228
  `),t.dim.noFormat(" Esc / ^C to return")(`
229
- `)})};te();let re=new AbortController,ke={onKey:We=>{if(We==="ESCAPE"||We==="CTRL_C"){re.abort(),jt();return}},onResize:()=>te()};Be(ke),(async()=>{try{let We=await on(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(E.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:re.signal});if(!We.ok)throw new Error(`daemon returned HTTP ${We.status}`);let Xe=await We.json(),ct=_n(Xe),Re=Gu(ct,E.status);j=cc(Re,!1).replace(/\n$/,"").split(`
230
- `)}catch(We){if(re.signal.aborted)return;ie=`failed to load info: ${We.message}`}finally{W=!1,!pt&&ue[ue.length-1]===ke&&te()}})()},yr=()=>{if(a.length===0){De="no sessions to search",me();return}$=new bs({history:[],collapsePastes:!1}),B=[],K=!1,U=0,L=0,at=0,N=null,Z=!1,F="input",T=!0,cr(),ss(),Be({onKey:(j,ie,W)=>{if(F==="input"){if(Z)return;if(j==="ESCAPE"||j==="CTRL_C"){rs();return}if(j==="ENTER"||j==="KP_ENTER"){if(xo().trim().length===0)return;Yc();return}if((j==="DOWN"||j==="TAB"||j==="CTRL_N")&&B.length>0){F="results",U=0,L=0,Ne(()=>{Ht(),Ps(0,!0),pr(),t.hideCursor()});return}let te=$.state(),re=null;if(j==="")re={type:"key",name:"ctrl-underscore"};else if(j==="\x1B_"||j==="\x1B")re={type:"key",name:"alt-underscore"};else if(W?.isCharacter)re={type:"char",ch:j};else{let ct=Lc(j);ct!==null&&(re={type:"key",name:ct})}if(re===null){t.moveTo(lr(),ur());return}$.feed(re);let ke=$.state();if(te.buffer.length===ke.buffer.length&&te.buffer.every((ct,Re)=>ct===ke.buffer[Re])&&te.row===ke.row&&te.col===ke.col){t.moveTo(lr(),ur());return}let Xe=It;cr(),It!==Xe?ss():ht();return}if(F==="results"){if(j==="ESCAPE"||j==="CTRL_C"){rs();return}if(j==="CTRL_F"){F="input",ni(),pr(),Ht();return}if(j==="ENTER"||j==="KP_ENTER"){let re=B[U];if(!re)return;let ke=a.find(Xe=>Xe.sessionId===re.sessionId);if(!!ke?.importedFromMachine&&!ke.upstreamSessionId){qe();let Xe={kind:"attach",sessionId:re.sessionId};ke.agentId!==void 0&&(Xe.agentId=ke.agentId),R(Xe);return}(async()=>{let Xe=await bb(t,{sessionId:re.sessionId,title:re.title,cwd:re.cwd},$t);if(Xe==="cancel"){qe(),R({kind:"abort"});return}if(Xe==="back")return;qe();let ct={kind:"attach",sessionId:re.sessionId,readonly:Xe==="view"};ke?.agentId!==void 0&&(ct.agentId=ke.agentId),R(ct)})();return}if(W?.isCharacter&&(j==="n"||j==="N")){let re=B[U];if(!re||re.snippets.length<=1)return;L=(L+1)%re.snippets.length,Ps(U,!0);return}if(W?.isCharacter&&(j==="p"||j==="P")){let re=B[U];if(!re||re.snippets.length<=1)return;L=(L-1+re.snippets.length)%re.snippets.length,Ps(U,!0);return}let te=re=>{if(re<0&&U===0){F="input",Ne(()=>{Ps(0,!1),pr(),Ht()});return}let ke=Math.min(B.length-1,Math.max(0,U+re));if(ke===U)return;let We=U,Xe=at;U=ke,L=0,So(),at!==Xe?ni():(Ne(()=>{Ps(We,!1),Ps(U,!0)}),pr())};switch(j){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(-Dt());return;case"PAGE_DOWN":te(Dt());return;case"HOME":te(-U);return;case"END":te(B.length);return}return}},onResize:()=>ss()})},di=(E,j,ie)=>{if(S!=="busy"){if(E==="CTRL_O"){mt();return}if(E==="CTRL_L"){ts();return}if(S==="rename"){if(E==="ENTER"||E==="KP_ENTER"){let W=G.trim();if(W.length===0){S="normal",k=null,G="",me();return}$a(W);return}if(E==="ESCAPE"||E==="CTRL_C"){S="normal",k=null,G="",ks(),me();return}if(E==="BACKSPACE"){G.length>0&&(ce(),G=G.slice(0,-1),me());return}if(E==="CTRL_U"){G.length>0&&(ce(),G="",me());return}if(E==="CTRL_W"){let W=G.replace(/\s+$/,""),te=W.lastIndexOf(" "),re=te>=0?W.slice(0,te):"";re!==G&&(ce(),G=re,me());return}if(E===""){Je(),me();return}if(E==="\x1B_"||E==="\x1B"){sr(),me();return}if(ie?.isCharacter){ce(),G+=E,me();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ie?.isCharacter&&(E==="y"||E==="Y")){ds(S==="confirm-kill"?"kill":"delete");return}if(E==="ESCAPE"||E==="CTRL_C"||E==="ENTER"||E==="KP_ENTER"||ie?.isCharacter&&(E==="n"||E==="N")){S="normal",k=null,me();return}return}if(gr(),E==="CTRL_F"&&f!==0){yr();return}if(f===0&&!h){if(E==="ESCAPE"){Cn();return}if(E==="ENTER"||E==="KP_ENTER"){qe();let Re=xe.expandedText(),At=Ye();Re.trim().length>0&&(At.prompt=Re),R(At);return}if(E==="UP"&&b){let Re=Date.now(),At=Re-v;if(v=Re,At<y){Nt();return}b=!1}if(E==="DOWN"){let Re=xe.state(),At=Re.historyIndex!==-1||Re.queueIndex!==-1,qt=Mt.length===0||rr===Mt.length-1;if(!At&&qt&&a.length>0){dt(1);return}}if(E==="PAGE_DOWN"&&(Mt.length===0||rr===Mt.length-1)&&a.length>0){dt(1);return}if(E==="CTRL_P"){a.length>0&&dt(1);return}b=!1;let W=xe.state(),te=null;if(E==="")te={type:"key",name:"ctrl-underscore"};else if(E==="\x1B_"||E==="\x1B")te={type:"key",name:"alt-underscore"};else if(ie?.isCharacter)te={type:"char",ch:E};else{let Re=Lc(E);Re!==null&&(te={type:"key",name:Re})}if(te===null){Nt();return}let re=xe.feed(te),ke=xe.state(),We=W.buffer.length===ke.buffer.length&&W.buffer.every((Re,At)=>Re===ke.buffer[At])&&W.row===ke.row&&W.col===ke.col;if(re.some(Re=>Re.type==="exit")){Cn();return}if(We){Nt();return}let Xe=Ss(ke.buffer,xs);if(tr(Xe,ke,Dc).rendered!==dn){je();return}pn();return}if(!h&&ie?.isCharacter&&E==="?"){Tn();return}if(h){if(ie?.isCharacter){m+=E,st(),je();return}if(E==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),st(),je()):(h=!1,st(),je());return}if(E==="ESCAPE"||E==="CTRL_C"){h=!1,m="",st(),je();return}}if(ie?.isCharacter){if(E==="/"){h=!0,m="",st(),je();return}if(E==="n"||E==="N"){dt(1);return}if(E==="p"||E==="P"){dt(-1);return}if(E==="c"||E==="C"){let W=f>0?a[f-1]:void 0,te=Ye();W?.cwd&&(te.cwd=W.cwd),qe(),R(te);return}if(E==="q"||E==="Q"){Cn();return}if(E==="o"||E==="O"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,st(),ut(W),je();return}if(E==="h"||E==="H"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=Ib(s.filters.hostFilter,i),st(),ut(W),je();return}if(E==="i"&&f>0){let W=a[f-1];if(!W)return;cs(W);return}if(E==="I"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,st(),ut(W),je();return}if(E==="r"||E==="R"){let W=f>0?a[f-1]?.sessionId:void 0;_s(W);return}if(E==="s"||E==="S"){as();return}if((E==="v"||E==="V")&&f>0){let W=a[f-1];if(!W)return;qe();let te={kind:"attach",sessionId:W.sessionId,readonly:!0};W.agentId!==void 0&&(te.agentId=W.agentId),R(te);return}if((E==="f"||E==="F")&&f>0){let W=a[f-1];if(!W)return;qe();let te={kind:"fork",sourceSessionId:W.sessionId,sourceCwd:W.cwd};W.agentId!==void 0&&(te.sourceAgentId=W.agentId),W.importedFromMachine!==void 0&&(te.sourceImportedFromMachine=W.importedFromMachine),W.upstreamSessionId!==void 0&&(te.sourceUpstreamSessionId=W.upstreamSessionId),R(te);return}if((E==="k"||E==="K")&&f>0){let W=a[f-1];if(!W)return;k={sessionId:W.sessionId,cwd:W.cwd,status:W.status},S="confirm-kill",me();return}if(E==="t"&&f>0){let W=a[f-1];if(!W)return;k={sessionId:W.sessionId,cwd:W.cwd,status:W.status},G=W.title??"",S="rename",me();return}if(E==="T"&&f>0){let W=a[f-1];if(!W)return;Co({sessionId:W.sessionId});return}if(E==="*"&&f>0){let W=a[f-1];if(!W)return;gt(W);return}if((E==="d"||E==="D")&&f>0){let W=a[f-1];if(!W)return;k={sessionId:W.sessionId,cwd:W.cwd,status:W.status},S="confirm-delete",me();return}ft=!1,f=0,xe.feed({type:"char",ch:E}),je();return}switch(E){case"UP":case"SHIFT_TAB":case"CTRL_P":E==="UP"&&(f===1&&(b=!0),v=Date.now()),dt(-1);return;case"DOWN":case"TAB":case"CTRL_N":dt(1);return;case"PAGE_UP":dt(-He);return;case"PAGE_DOWN":dt(He);return;case"HOME":dt(1-f);return;case"END":dt(u);return;case"RIGHT":if(ft||f===0)break;case"ENTER":case"KP_ENTER":{if(ft){qe();let re=xe.expandedText(),ke=Ye();re.trim().length>0&&(ke.prompt=re),R(ke);return}if(qe(),f===0){R(Ye());return}let W=a[f-1];if(!W){R({kind:"abort"});return}let te={kind:"attach",sessionId:W.sessionId};W.agentId!==void 0&&(te.agentId=W.agentId),R(te);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":Cn();return}}};Be({onKey:(E,j,ie)=>di(E,j,ie),onResize:()=>{pt||je()}});let ls=(E,j)=>{if(pt||ue.length!==1||S!=="normal")return;let ie=E==="MOUSE_MOTION",W=E==="MOUSE_LEFT_BUTTON_PRESSED",te=E==="MOUSE_LEFT_BUTTON_RELEASED",re=E==="MOUSE_WHEEL_UP",ke=E==="MOUSE_WHEEL_DOWN",We=vt&&Date.now()-ri<Ma,Xe=!vt||We;if(W){os={x:j?.x??-1,y:j?.y??-1},ii=Xe;return}if(ie&&Xe)return;let ct=te&&os!==null&&j?.x===os.x&&j?.y===os.y,Re=ct&&!ii,At=ct&&ii;if(te&&(os=null,ii=!1,!ct))return;if(re||ke){if(a.length===0)return;let $e=re?-3:3,us=Math.max(0,a.length-He),Os=Math.min(us,Math.max(0,p+$e));if(Os===p)return;if(p=Os,f>0){let Wt=f-1;Wt<p?f=p+1:Wt>=p+He&&(f=p+He)}_t();return}if(!ie&&!Re)return;let qt=j?.y;if(typeof qt!="number")return;{let $e=j?.x,us=Vt!==null&&qt===fn()&&typeof $e=="number"&&$e>=Vt.start&&$e<=Vt.end,Os=xn!==null&&qt===fn()&&typeof $e=="number"&&$e>=xn.start&&$e<=xn.end;(us!==Ms||Os!==hr)&&(Ms=us,hr=Os,me(),f===0?(Nt(),t.hideCursor(!1)):t.hideCursor(!0))}if(Re&&Vt!==null&&qt===fn()){let $e=j?.x;if(typeof $e=="number"&&$e>=Vt.start&&$e<=Vt.end){Cn();return}}if(Re&&xn!==null&&qt===fn()){let $e=j?.x;if(typeof $e=="number"&&$e>=xn.start&&$e<=xn.end){let us=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=Ib(s.filters.hostFilter,i),st(),ut(us),je();return}}if(qt>=On&&qt<=ar()){if((Re||At)&&f!==0){ft=!1;let $e=f;f=0,Ne(()=>{_t(),Rn($e,f)});return}ie&&!ft&&f!==0&&(ft=!0,Ne(()=>{Ut(),_t()}));return}ft&&(ft=!1,Ne(()=>{Ut(),_t()}));let mn=Bt()+1,Fs=mn+He-1;if(qt<mn||qt>Fs)return;let gn=p+(qt-mn);if(gn<0||gn>=a.length)return;let wr=a[gn];if(!wr)return;let br=gn+1;if(ie&&f===0)return;let Vc=f===0,Qc=f===br;if(At&&f!==br){let $e=f;f=br,cn(),Ne(()=>{_t(),Rn($e,f)});return}if(At)return;if(f!==br){let $e=f;f=br,cn(),Ne(()=>{_t(),Rn($e,f)})}if(!Re||Vc||!Qc)return;qe();let Fa={kind:"attach",sessionId:wr.sessionId};wr.agentId!==void 0&&(Fa.agentId=wr.agentId),R(Fa)},Nn=()=>{t.grabInput({mouse:"motion"}),se({src:"grab",site:"picker.installGrab",on:!0});let E=t;E.stdin&&typeof E.onStdin=="function"&&(Qt=E.onStdin,E.stdin.removeListener("data",E.onStdin),E.stdin.on("data",oi),process.stdout.write(mc),process.stdout.write(wc)),t.on("key",hn),t.on("mouse",ls),t.on("resize",St)},$s=()=>{process.stdout.write(ys),process.stdout.write(ua);let E=t;E.stdin&&Qt&&(E.stdin.removeListener("data",oi),E.stdin.on("data",Qt),Qt=null),Yt=!1,is="",t.off("key",hn),t.off("mouse",ls),t.off("resize",St),t.grabInput(!1),se({src:"grab",site:"picker.uninstallGrab",on:!1}),t.hideCursor(!1)};if(Nn(),process.platform!=="win32"){let E=!1,j=()=>{E&&(E=!1,t.fullscreen(!0),n(),t.hideCursor(),Nn(),pt||ts())};Ao=()=>{E||pt||(E=!0,$s(),t.fullscreen(!1),process.stdout.write(`${la}${gc}
231
- `),process.once("SIGCONT",j),process.kill(process.pid,"SIGTSTP"))}}P=setInterval(An,3e3)})}function j0(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+oa(Ze(t),s)}function Hc(t,e){let n=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="warm",o=n(r)>0;return i&&r.awaitingInput?5:i&&r.busy?4:i&&o?3:i?2:o?1:0};return[...t].sort((r,i)=>{let o=s(i)-s(r);if(o!==0)return o;let a=n(i)-n(r);return a!==0?a:i.updatedAt.slice(0,16).localeCompare(r.updatedAt.slice(0,16))})}function q0(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function Ib(t,e){let n=new Set;for(let i of e)i.importedFromMachine&&!i.upstreamSessionId&&n.add(i.importedFromMachine);let s=["__local",...[...n].sort(),"__all"],r=s.indexOf(t);return r===-1?"__local":s[(r+1)%s.length]??"__local"}function W0(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[rt(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,Ze(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var Kf,Dc,D0,kb,H0,U0,xb=J(()=>{"use strict";rc();he();qn();ia();wd();xf();qf();Wf();zf();qr();Af();Mf();fa();Mr();Xu();Cr();Kf=2,Dc=4,D0=4,kb=4,H0=20,U0=[["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)"],["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)"]]});function Y0(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function Vf(t,e,n,s){$n();let r=Y0(e,n??z0),i=0,o=()=>{let u=ws(t)-8;return Math.max(1,Math.min(K0,e.length,u))},a=()=>{let u=o();r<i?i=r:r>=i+u&&(i=r-u+1);let f=Math.max(0,e.length-u);i>f&&(i=f),i<0&&(i=0)},c=()=>{a();let u=o(),f=u+4,p=Math.min(J0,Math.max(40,an(t)-8)),h=Fn(t,{contentHeight:f,contentWidth:p,title:s?.title??"Select agent"}),m=h.contentW,y=0;t.moveTo(h.contentX,h.contentY+y),t.noFormat(` ${s?.intro??"Which agent should this session use?"}`),y+=2;let b=Math.min(e.length,i+u);for(let S=i;S<b;S++){let k=e[S];if(!k)continue;let T=S===r?"\u276F":" ",F=k.description??k.name,$=` ${T} ${k.id}`;if(t.moveTo(h.contentX,h.contentY+y),S===r){let B=`${$} ${F}`;t.brightWhite.bgBlue.noFormat(bc(ze(B,m),m))}else{t.noFormat($);let B=m-$.length-2;B>1&&t.dim.noFormat(` ${ze(F,B)}`)}y++}y++,t.moveTo(h.contentX,h.contentY+y);let v=e.length>u?` (${r+1}/${e.length})`:"";return t.dim.noFormat(` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${v}`),h},d=()=>{r<e.length-1&&(r++,c())},l=()=>{r>0&&(r--,c())};return Gn({term:t,render:c,onKey:(u,f,p,h)=>{if(u==="CTRL_C"||u==="CTRL_D"){h({kind:"cancel"});return}if(u==="ESCAPE"){h({kind:"back"});return}if(u==="ENTER"||u==="KP_ENTER"){let m=e[r];m&&h({kind:"select",agentId:m.id,persist:!1});return}if(u==="UP"||u==="SHIFT_TAB"){l();return}if(u==="DOWN"||u==="TAB"){d();return}if(p?.isCharacter){let m=u.toLowerCase();if(m==="s"){let y=e[r];y&&h({kind:"select",agentId:y.id,persist:!0});return}if(m==="j"){d();return}if(m==="k"){l();return}}}})}var z0,K0,J0,Ab=J(()=>{"use strict";qr();z0="opencode",K0=20,J0=88});import V0 from"wrap-ansi";async function Cb(t,e,n,s){$n();let r=s?.canGoBack!==!1,i=e?`Couldn't start ${e}`:"Couldn't start session",o=n.split(`
232
- `).map(d=>d.trimEnd()).filter(d=>d.length>0),a=r?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",c=()=>{let d=an(t),l=ws(t),u=Math.min(Q0,Math.max(20,d-4)),f=Math.max(1,u-1),p=o.flatMap(T=>V0(T,f,{hard:!0,trim:!1}).split(`
233
- `)),h=Math.max(1,l-4-4),m=p.length>h,y=m?p.slice(0,h-1):p,b=y.length+(m?1:0)+4,v=Fn(t,{contentHeight:b,contentWidth:u,title:"Agent failed to start"}),S=v.contentW,k=0;t.moveTo(v.contentX,v.contentY+k),t.brightWhite.bold.noFormat(ze(` ${i}`,S)),k+=2;for(let T of y)t.moveTo(v.contentX,v.contentY+k),t.brightRed.noFormat(ze(` ${T}`,S)),k++;return m&&(t.moveTo(v.contentX,v.contentY+k),t.dim.noFormat(ze(" \u2026 (full details in ~/.hydra-acp/tui.log)",S)),k++),k++,t.moveTo(v.contentX,v.contentY+k),t.dim.noFormat(ze(` ${a}`,S)),v};return Gn({term:t,render:()=>{c()},onKey:(d,l,u,f)=>{if(d==="r"||d==="R"||d==="ENTER"||d==="KP_ENTER"){f("retry");return}if(d==="ESCAPE"){f(r?"back":"cancel");return}d==="CTRL_C"&&f("cancel")}})}var Q0,Rb=J(()=>{"use strict";qr();Q0=100});import*as Eb from"fs";import*as Pb from"os";import*as Uc from"path";function Mb(t,e){let n=e;for(;n>0;){let s=t[n-1]??"";if(/\s/.test(s)){if(s===" "&&t[n-2]==="\\"){n-=2;continue}break}n-=1}return n===e?null:{token:t.slice(n,e),start:n}}function G0(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function X0(t){return t.replace(/\\ /g," ")}function Tb(t){return t.replace(/ /g,"\\ ")}function Z0(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function eT(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=Pb.homedir()+n.slice(1)),Uc.isAbsolute(n)?n:Uc.resolve(e,n)}function tT(t){let e;try{e=Eb.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function _b(t,e,n=tT){if(!G0(t))return null;let s=X0(t),{dirPrefix:r,base:i}=Z0(s),o=eT(r,e),a=n(o);if(a===null)return null;let c=i.startsWith("."),d=a.filter(f=>f.name.startsWith(i)&&(c||!f.name.startsWith(".")));if(d.length===0)return null;let l=d.map(f=>f.isDir?f.name+"/":f.name);if(d.length===1){let f=d[0],p=f.isDir?f.name+"/":f.name;return{replacement:Tb(r+p),candidates:l}}let u=Ia(d.map(f=>f.name));return{replacement:Tb(r+u),candidates:l}}var $b=J(()=>{"use strict";Nc()});function Fb(t){let e={};if(!t||typeof t!="object")return e;let n=t;typeof n.historyPolicy=="string"&&(e.appliedPolicy=n.historyPolicy),typeof n.clientId=="string"&&n.clientId.length>0&&(e.clientId=n.clientId);let s=n._meta;if(s&&typeof s=="object"){let r=s["hydra-acp"];if(r&&typeof r=="object"){let i=r.turnStartedAt;typeof i=="number"&&(e.turnStartedAt=i)}}return e}function Ob(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function Lb(t){return t.daemonTurnStartedAt!==void 0?{pendingTurnsDelta:t.pendingTurns===0?1:0,banner:"busy",busySince:t.daemonTurnStartedAt}:{pendingTurnsDelta:t.pendingTurns>0?-t.pendingTurns:0,banner:"ready"}}var Bb=J(()=>{"use strict"});import{readFileSync as nT}from"fs";import{nanoid as Nb}from"nanoid";import sT from"terminal-kit";import Qf from"fs/promises";import Vr from"path";function rT(t){return t.filter(e=>e.status==="open"||e.status==="pending-delivery")}function iT(t){let e=jc(t);if(t.status==="pending-delivery"&&t.userAnswer){let n=e.indexOf(t.userAnswer);if(n!==-1)return n}return 0}function oT(t){let e=new Map,n=[];for(let s of t){let r=s.question,i=e.get(r);i?i.ids.push(s.id):(e.set(r,{representative:s,ids:[s.id]}),n.push(r))}return n.map(s=>e.get(s))}function jc(t){if(t.options&&t.options.length>0){let e=t.options.filter(n=>n!==t.defaultAnswer);return t.options.includes(t.defaultAnswer)?[t.defaultAnswer,...e]:[t.defaultAnswer,...t.options]}return[t.defaultAnswer]}function aT(t,e){return t.length<=e?t:e<=1?"\u2026":t.slice(0,e-1)+"\u2026"}function dT(t,e,n,s,r=60){let i=t.map((o,a)=>{let c=jc(o.representative),d=e[a]??0,l=n[a]?Xf:c[d]??c[0]??"";return{label:aT(o.representative.question,r),value:l}});return{title:`Open questions (${t.length})`,options:i,selectedIndex:Math.max(0,Math.min(t.length-1,s)),hint:"\u2191/\u2193 row \xB7 \u2190/\u2192 cycle \xB7 d dismiss \xB7 1-9 jump \xB7 \u23CE/Esc save \xB7 ^C discard"}}function cT(t,e,n){return t===Xf?{type:"dismiss",method:Nw,params:{sessionId:n,questionId:e.id}}:{type:"answer",method:Bw,params:{sessionId:n,questionId:e.id,answer:t}}}function lT(t,e,n,s,r){let i=[];for(let o=0;o<t.length;o++){let a=t[o];if(!a||!n[o])continue;let c=s[o]?Xf:jc(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},u=cT(c,l,r);u!==null&&i.push(u)}}return i}function uT(t,e,n,s,r,i,o,a){if(!e||n===null||n.length===0)return{type:"noop"};if(t.type==="char"){if(t.ch==="d"||t.ch==="D")return{type:"dismiss-toggle",selectedRow:o};if(/^[1-9]$/.test(t.ch)){let d=parseInt(t.ch,10)-1;if(d<n.length)return{type:"row",selectedRow:d}}return{type:"noop"}}if(t.type!=="key")return{type:"noop"};let c=d=>{let l=n[o];if(!l)return{type:"noop"};let u=jc(l.representative);if(u.length===0)return{type:"noop"};let p=((s[o]??0)+d+u.length)%u.length;return{type:"cycle",selectedRow:o,newValueIndex:p}};switch(t.name){case"up":return{type:"row",selectedRow:Math.max(0,o-1)};case"down":return{type:"row",selectedRow:Math.min(n.length-1,o+1)};case"right":return c(1);case"left":return c(-1);case"enter":case"escape":case"ctrl-q":return{type:"save",dispatches:lT(n,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function Db(t){if(!Array.isArray(t))return;let e=Kn({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function Gf(t){switch(t.type){case"send":case"amend":case"queue-edit":case"queue-remove":case"plan-toggle":case"attachment-request":return!0;default:return!1}}function hT(t,e){e.has(t)?e.delete(t):e.add(t)}function mT(){if(Hb)return;Hb=!0;let t=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{se({src:"uncaughtException",stack:t(e)}),Kr(),process.stderr.write(`
229
+ `)})};te();let re=new AbortController,ke={onKey:ze=>{if(ze==="ESCAPE"||ze==="CTRL_C"){re.abort(),jt();return}},onResize:()=>te()};Be(ke),(async()=>{try{let ze=await on(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(E.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:re.signal});if(!ze.ok)throw new Error(`daemon returned HTTP ${ze.status}`);let Xe=await ze.json(),ct=_n(Xe),Re=Xu(ct,E.status);j=cc(Re,!1).replace(/\n$/,"").split(`
230
+ `)}catch(ze){if(re.signal.aborted)return;ie=`failed to load info: ${ze.message}`}finally{W=!1,!pt&&ue[ue.length-1]===ke&&te()}})()},yr=()=>{if(a.length===0){De="no sessions to search",me();return}$=new vs({history:[],collapsePastes:!1}),B=[],K=!1,U=0,L=0,at=0,N=null,Z=!1,O="input",T=!0,cr(),rs(),Be({onKey:(j,ie,W)=>{if(O==="input"){if(Z)return;if(j==="ESCAPE"||j==="CTRL_C"){is();return}if(j==="ENTER"||j==="KP_ENTER"){if(Ao().trim().length===0)return;Yc();return}if((j==="DOWN"||j==="TAB"||j==="CTRL_N")&&B.length>0){O="results",U=0,L=0,Ne(()=>{Ht(),Ps(0,!0),pr(),t.hideCursor()});return}let te=$.state(),re=null;if(j==="")re={type:"key",name:"ctrl-underscore"};else if(j==="\x1B_"||j==="\x1B")re={type:"key",name:"alt-underscore"};else if(W?.isCharacter)re={type:"char",ch:j};else{let ct=Bc(j);ct!==null&&(re={type:"key",name:ct})}if(re===null){t.moveTo(lr(),ur());return}$.feed(re);let ke=$.state();if(te.buffer.length===ke.buffer.length&&te.buffer.every((ct,Re)=>ct===ke.buffer[Re])&&te.row===ke.row&&te.col===ke.col){t.moveTo(lr(),ur());return}let Xe=It;cr(),It!==Xe?rs():ht();return}if(O==="results"){if(j==="ESCAPE"||j==="CTRL_C"){is();return}if(j==="CTRL_F"){O="input",ni(),pr(),Ht();return}if(j==="ENTER"||j==="KP_ENTER"){let re=B[U];if(!re)return;let ke=a.find(Xe=>Xe.sessionId===re.sessionId);if(!!ke?.importedFromMachine&&!ke.upstreamSessionId){We();let Xe={kind:"attach",sessionId:re.sessionId};ke.agentId!==void 0&&(Xe.agentId=ke.agentId),R(Xe);return}(async()=>{let Xe=await kb(t,{sessionId:re.sessionId,title:re.title,cwd:re.cwd},$t);if(Xe==="cancel"){We(),R({kind:"abort"});return}if(Xe==="back")return;We();let ct={kind:"attach",sessionId:re.sessionId,readonly:Xe==="view"};ke?.agentId!==void 0&&(ct.agentId=ke.agentId),R(ct)})();return}if(W?.isCharacter&&(j==="n"||j==="N")){let re=B[U];if(!re||re.snippets.length<=1)return;L=(L+1)%re.snippets.length,Ps(U,!0);return}if(W?.isCharacter&&(j==="p"||j==="P")){let re=B[U];if(!re||re.snippets.length<=1)return;L=(L-1+re.snippets.length)%re.snippets.length,Ps(U,!0);return}let te=re=>{if(re<0&&U===0){O="input",Ne(()=>{Ps(0,!1),pr(),Ht()});return}let ke=Math.min(B.length-1,Math.max(0,U+re));if(ke===U)return;let ze=U,Xe=at;U=ke,L=0,ko(),at!==Xe?ni():(Ne(()=>{Ps(ze,!1),Ps(U,!0)}),pr())};switch(j){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(-Dt());return;case"PAGE_DOWN":te(Dt());return;case"HOME":te(-U);return;case"END":te(B.length);return}return}},onResize:()=>rs()})},di=(E,j,ie)=>{if(S!=="busy"){if(E==="CTRL_O"){mt();return}if(E==="CTRL_L"){ns();return}if(S==="rename"){if(E==="ENTER"||E==="KP_ENTER"){let W=G.trim();if(W.length===0){S="normal",k=null,G="",me();return}Oa(W);return}if(E==="ESCAPE"||E==="CTRL_C"){S="normal",k=null,G="",ks(),me();return}if(E==="BACKSPACE"){G.length>0&&(ce(),G=G.slice(0,-1),me());return}if(E==="CTRL_U"){G.length>0&&(ce(),G="",me());return}if(E==="CTRL_W"){let W=G.replace(/\s+$/,""),te=W.lastIndexOf(" "),re=te>=0?W.slice(0,te):"";re!==G&&(ce(),G=re,me());return}if(E===""){Ye(),me();return}if(E==="\x1B_"||E==="\x1B"){sr(),me();return}if(ie?.isCharacter){ce(),G+=E,me();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ie?.isCharacter&&(E==="y"||E==="Y")){cs(S==="confirm-kill"?"kill":"delete");return}if(E==="ESCAPE"||E==="CTRL_C"||E==="ENTER"||E==="KP_ENTER"||ie?.isCharacter&&(E==="n"||E==="N")){S="normal",k=null,me();return}return}if(gr(),E==="CTRL_F"&&f!==0){yr();return}if(f===0&&!h){if(E==="ESCAPE"){Cn();return}if(E==="ENTER"||E==="KP_ENTER"){We();let Re=xe.expandedText(),At=Qe();Re.trim().length>0&&(At.prompt=Re),R(At);return}if(E==="UP"&&b){let Re=Date.now(),At=Re-v;if(v=Re,At<y){Nt();return}b=!1}if(E==="DOWN"){let Re=xe.state(),At=Re.historyIndex!==-1||Re.queueIndex!==-1,qt=Mt.length===0||rr===Mt.length-1;if(!At&&qt&&a.length>0){dt(1);return}}if(E==="PAGE_DOWN"&&(Mt.length===0||rr===Mt.length-1)&&a.length>0){dt(1);return}if(E==="CTRL_P"){a.length>0&&dt(1);return}b=!1;let W=xe.state(),te=null;if(E==="")te={type:"key",name:"ctrl-underscore"};else if(E==="\x1B_"||E==="\x1B")te={type:"key",name:"alt-underscore"};else if(ie?.isCharacter)te={type:"char",ch:E};else{let Re=Bc(E);Re!==null&&(te={type:"key",name:Re})}if(te===null){Nt();return}let re=xe.feed(te),ke=xe.state(),ze=W.buffer.length===ke.buffer.length&&W.buffer.every((Re,At)=>Re===ke.buffer[At])&&W.row===ke.row&&W.col===ke.col;if(re.some(Re=>Re.type==="exit")){Cn();return}if(ze){Nt();return}let Xe=Ss(ke.buffer,xs);if(tr(Xe,ke,Hc).rendered!==dn){qe();return}pn();return}if(!h&&ie?.isCharacter&&E==="?"){Tn();return}if(h){if(ie?.isCharacter){m+=E,st(),qe();return}if(E==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),st(),qe()):(h=!1,st(),qe());return}if(E==="ESCAPE"||E==="CTRL_C"){h=!1,m="",st(),qe();return}}if(ie?.isCharacter){if(E==="/"){h=!0,m="",st(),qe();return}if(E==="n"||E==="N"){dt(1);return}if(E==="p"||E==="P"){dt(-1);return}if(E==="c"||E==="C"){let W=f>0?a[f-1]:void 0,te=Qe();W?.cwd&&(te.cwd=W.cwd),We(),R(te);return}if(E==="q"||E==="Q"){Cn();return}if(E==="o"||E==="O"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,st(),ut(W),qe();return}if(E==="h"||E==="H"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=Cb(s.filters.hostFilter,i),st(),ut(W),qe();return}if(E==="i"&&f>0){let W=a[f-1];if(!W)return;ls(W);return}if(E==="I"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,st(),ut(W),qe();return}if(E==="r"||E==="R"){let W=f>0?a[f-1]?.sessionId:void 0;_s(W);return}if(E==="s"||E==="S"){ds();return}if((E==="v"||E==="V")&&f>0){let W=a[f-1];if(!W)return;We();let te={kind:"attach",sessionId:W.sessionId,readonly:!0};W.agentId!==void 0&&(te.agentId=W.agentId),R(te);return}if((E==="f"||E==="F")&&f>0){let W=a[f-1];if(!W)return;We();let te={kind:"fork",sourceSessionId:W.sessionId,sourceCwd:W.cwd};W.agentId!==void 0&&(te.sourceAgentId=W.agentId),W.importedFromMachine!==void 0&&(te.sourceImportedFromMachine=W.importedFromMachine),W.upstreamSessionId!==void 0&&(te.sourceUpstreamSessionId=W.upstreamSessionId),R(te);return}if((E==="k"||E==="K")&&f>0){let W=a[f-1];if(!W)return;k={sessionId:W.sessionId,cwd:W.cwd,status:W.status},S="confirm-kill",me();return}if(E==="t"&&f>0){let W=a[f-1];if(!W)return;k={sessionId:W.sessionId,cwd:W.cwd,status:W.status},G=W.title??"",S="rename",me();return}if(E==="T"&&f>0){let W=a[f-1];if(!W)return;Ro({sessionId:W.sessionId});return}if(E==="*"&&f>0){let W=a[f-1];if(!W)return;gt(W);return}if((E==="d"||E==="D")&&f>0){let W=a[f-1];if(!W)return;k={sessionId:W.sessionId,cwd:W.cwd,status:W.status},S="confirm-delete",me();return}ft=!1,f=0,xe.feed({type:"char",ch:E}),qe();return}switch(E){case"UP":case"SHIFT_TAB":case"CTRL_P":E==="UP"&&(f===1&&(b=!0),v=Date.now()),dt(-1);return;case"DOWN":case"TAB":case"CTRL_N":dt(1);return;case"PAGE_UP":dt(-He);return;case"PAGE_DOWN":dt(He);return;case"HOME":dt(1-f);return;case"END":dt(u);return;case"RIGHT":if(ft||f===0)break;case"ENTER":case"KP_ENTER":{if(ft){We();let re=xe.expandedText(),ke=Qe();re.trim().length>0&&(ke.prompt=re),R(ke);return}if(We(),f===0){R(Qe());return}let W=a[f-1];if(!W){R({kind:"abort"});return}let te={kind:"attach",sessionId:W.sessionId};W.agentId!==void 0&&(te.agentId=W.agentId),R(te);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":Cn();return}}};Be({onKey:(E,j,ie)=>di(E,j,ie),onResize:()=>{pt||qe()}});let us=(E,j)=>{if(pt||ue.length!==1||S!=="normal")return;let ie=E==="MOUSE_MOTION",W=E==="MOUSE_LEFT_BUTTON_PRESSED",te=E==="MOUSE_LEFT_BUTTON_RELEASED",re=E==="MOUSE_WHEEL_UP",ke=E==="MOUSE_WHEEL_DOWN",ze=vt&&Date.now()-ri<_a,Xe=!vt||ze;if(W){as={x:j?.x??-1,y:j?.y??-1},ii=Xe;return}if(ie&&Xe)return;let ct=te&&as!==null&&j?.x===as.x&&j?.y===as.y,Re=ct&&!ii,At=ct&&ii;if(te&&(as=null,ii=!1,!ct))return;if(re||ke){if(a.length===0)return;let $e=re?-3:3,fs=Math.max(0,a.length-He),Fs=Math.min(fs,Math.max(0,p+$e));if(Fs===p)return;if(p=Fs,f>0){let Wt=f-1;Wt<p?f=p+1:Wt>=p+He&&(f=p+He)}_t();return}if(!ie&&!Re)return;let qt=j?.y;if(typeof qt!="number")return;{let $e=j?.x,fs=Yt!==null&&qt===fn()&&typeof $e=="number"&&$e>=Yt.start&&$e<=Yt.end,Fs=xn!==null&&qt===fn()&&typeof $e=="number"&&$e>=xn.start&&$e<=xn.end;(fs!==Ms||Fs!==hr)&&(Ms=fs,hr=Fs,me(),f===0?(Nt(),t.hideCursor(!1)):t.hideCursor(!0))}if(Re&&Yt!==null&&qt===fn()){let $e=j?.x;if(typeof $e=="number"&&$e>=Yt.start&&$e<=Yt.end){Cn();return}}if(Re&&xn!==null&&qt===fn()){let $e=j?.x;if(typeof $e=="number"&&$e>=xn.start&&$e<=xn.end){let fs=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=Cb(s.filters.hostFilter,i),st(),ut(fs),qe();return}}if(qt>=Fn&&qt<=ar()){if((Re||At)&&f!==0){ft=!1;let $e=f;f=0,Ne(()=>{_t(),Rn($e,f)});return}ie&&!ft&&f!==0&&(ft=!0,Ne(()=>{Ut(),_t()}));return}ft&&(ft=!1,Ne(()=>{Ut(),_t()}));let mn=Bt()+1,Os=mn+He-1;if(qt<mn||qt>Os)return;let gn=p+(qt-mn);if(gn<0||gn>=a.length)return;let wr=a[gn];if(!wr)return;let br=gn+1;if(ie&&f===0)return;let Qc=f===0,Gc=f===br;if(At&&f!==br){let $e=f;f=br,cn(),Ne(()=>{_t(),Rn($e,f)});return}if(At)return;if(f!==br){let $e=f;f=br,cn(),Ne(()=>{_t(),Rn($e,f)})}if(!Re||Qc||!Gc)return;We();let Fa={kind:"attach",sessionId:wr.sessionId};wr.agentId!==void 0&&(Fa.agentId=wr.agentId),R(Fa)},Nn=()=>{t.grabInput({mouse:"motion"}),se({src:"grab",site:"picker.installGrab",on:!0});let E=t;E.stdin&&typeof E.onStdin=="function"&&(Qt=E.onStdin,E.stdin.removeListener("data",E.onStdin),E.stdin.on("data",oi),process.stdout.write(mc),process.stdout.write(wc)),t.on("key",hn),t.on("mouse",us),t.on("resize",St)},$s=()=>{process.stdout.write(ws),process.stdout.write(fa);let E=t;E.stdin&&Qt&&(E.stdin.removeListener("data",oi),E.stdin.on("data",Qt),Qt=null),Vt=!1,os="",t.off("key",hn),t.off("mouse",us),t.off("resize",St),t.grabInput(!1),se({src:"grab",site:"picker.uninstallGrab",on:!1}),t.hideCursor(!1)};if(Nn(),process.platform!=="win32"){let E=!1,j=()=>{E&&(E=!1,t.fullscreen(!0),n(),t.hideCursor(),Nn(),pt||ns())};Co=()=>{E||pt||(E=!0,$s(),t.fullscreen(!1),process.stdout.write(`${ua}${gc}
231
+ `),process.once("SIGCONT",j),process.kill(process.pid,"SIGTSTP"))}}P=setInterval(An,3e3)})}function V0(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+aa(Ze(t),s)}function Uc(t,e){let n=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="warm",o=n(r)>0;return i&&r.awaitingInput?5:i&&r.busy?4:i&&o?3:i?2:o?1:0};return[...t].sort((r,i)=>{let o=s(i)-s(r);if(o!==0)return o;let a=n(i)-n(r);return a!==0?a:i.updatedAt.slice(0,16).localeCompare(r.updatedAt.slice(0,16))})}function Y0(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function Cb(t,e){let n=new Set;for(let i of e)i.importedFromMachine&&!i.upstreamSessionId&&n.add(i.importedFromMachine);let s=["__local",...[...n].sort(),"__all"],r=s.indexOf(t);return r===-1?"__local":s[(r+1)%s.length]??"__local"}function Q0(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[rt(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,Ze(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var Jf,Hc,z0,Ab,K0,J0,Rb=J(()=>{"use strict";rc();he();qn();oa();wd();Af();Wf();zf();Kf();qr();Cf();_f();pa();Mr();Zu();Cr();Jf=2,Hc=4,z0=4,Ab=4,K0=20,J0=[["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)"],["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)"]]});function eT(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function Qf(t,e,n,s){$n();let r=eT(e,n??G0),i=0,o=()=>{let u=bs(t)-8;return Math.max(1,Math.min(X0,e.length,u))},a=()=>{let u=o();r<i?i=r:r>=i+u&&(i=r-u+1);let f=Math.max(0,e.length-u);i>f&&(i=f),i<0&&(i=0)},c=()=>{a();let u=o(),f=u+4,p=Math.min(Z0,Math.max(40,an(t)-8)),h=On(t,{contentHeight:f,contentWidth:p,title:s?.title??"Select agent"}),m=h.contentW,y=0;t.moveTo(h.contentX,h.contentY+y),t.noFormat(` ${s?.intro??"Which agent should this session use?"}`),y+=2;let b=Math.min(e.length,i+u);for(let S=i;S<b;S++){let k=e[S];if(!k)continue;let T=S===r?"\u276F":" ",O=k.description??k.name,$=` ${T} ${k.id}`;if(t.moveTo(h.contentX,h.contentY+y),S===r){let B=`${$} ${O}`;t.brightWhite.bgBlue.noFormat(bc(Ke(B,m),m))}else{t.noFormat($);let B=m-$.length-2;B>1&&t.dim.noFormat(` ${Ke(O,B)}`)}y++}y++,t.moveTo(h.contentX,h.contentY+y);let v=e.length>u?` (${r+1}/${e.length})`:"";return t.dim.noFormat(` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${v}`),h},d=()=>{r<e.length-1&&(r++,c())},l=()=>{r>0&&(r--,c())};return Gn({term:t,render:c,onKey:(u,f,p,h)=>{if(u==="CTRL_C"||u==="CTRL_D"){h({kind:"cancel"});return}if(u==="ESCAPE"){h({kind:"back"});return}if(u==="ENTER"||u==="KP_ENTER"){let m=e[r];m&&h({kind:"select",agentId:m.id,persist:!1});return}if(u==="UP"||u==="SHIFT_TAB"){l();return}if(u==="DOWN"||u==="TAB"){d();return}if(p?.isCharacter){let m=u.toLowerCase();if(m==="s"){let y=e[r];y&&h({kind:"select",agentId:y.id,persist:!0});return}if(m==="j"){d();return}if(m==="k"){l();return}}}})}var G0,X0,Z0,Tb=J(()=>{"use strict";qr();G0="opencode",X0=20,Z0=88});import tT from"wrap-ansi";async function Eb(t,e,n,s){$n();let r=s?.canGoBack!==!1,i=e?`Couldn't start ${e}`:"Couldn't start session",o=n.split(`
232
+ `).map(d=>d.trimEnd()).filter(d=>d.length>0),a=r?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",c=()=>{let d=an(t),l=bs(t),u=Math.min(nT,Math.max(20,d-4)),f=Math.max(1,u-1),p=o.flatMap(T=>tT(T,f,{hard:!0,trim:!1}).split(`
233
+ `)),h=Math.max(1,l-4-4),m=p.length>h,y=m?p.slice(0,h-1):p,b=y.length+(m?1:0)+4,v=On(t,{contentHeight:b,contentWidth:u,title:"Agent failed to start"}),S=v.contentW,k=0;t.moveTo(v.contentX,v.contentY+k),t.brightWhite.bold.noFormat(Ke(` ${i}`,S)),k+=2;for(let T of y)t.moveTo(v.contentX,v.contentY+k),t.brightRed.noFormat(Ke(` ${T}`,S)),k++;return m&&(t.moveTo(v.contentX,v.contentY+k),t.dim.noFormat(Ke(" \u2026 (full details in ~/.hydra-acp/tui.log)",S)),k++),k++,t.moveTo(v.contentX,v.contentY+k),t.dim.noFormat(Ke(` ${a}`,S)),v};return Gn({term:t,render:()=>{c()},onKey:(d,l,u,f)=>{if(d==="r"||d==="R"||d==="ENTER"||d==="KP_ENTER"){f("retry");return}if(d==="ESCAPE"){f(r?"back":"cancel");return}d==="CTRL_C"&&f("cancel")}})}var nT,Pb=J(()=>{"use strict";qr();nT=100});import*as _b from"fs";import*as $b from"os";import*as jc from"path";function Ob(t,e){let n=e;for(;n>0;){let s=t[n-1]??"";if(/\s/.test(s)){if(s===" "&&t[n-2]==="\\"){n-=2;continue}break}n-=1}return n===e?null:{token:t.slice(n,e),start:n}}function sT(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function rT(t){return t.replace(/\\ /g," ")}function Mb(t){return t.replace(/ /g,"\\ ")}function iT(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function oT(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=$b.homedir()+n.slice(1)),jc.isAbsolute(n)?n:jc.resolve(e,n)}function aT(t){let e;try{e=_b.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function Fb(t,e,n=aT){if(!sT(t))return null;let s=rT(t),{dirPrefix:r,base:i}=iT(s),o=oT(r,e),a=n(o);if(a===null)return null;let c=i.startsWith("."),d=a.filter(f=>f.name.startsWith(i)&&(c||!f.name.startsWith(".")));if(d.length===0)return null;let l=d.map(f=>f.isDir?f.name+"/":f.name);if(d.length===1){let f=d[0],p=f.isDir?f.name+"/":f.name;return{replacement:Mb(r+p),candidates:l}}let u=xa(d.map(f=>f.name));return{replacement:Mb(r+u),candidates:l}}var Lb=J(()=>{"use strict";Dc()});function Bb(t){let e={};if(!t||typeof t!="object")return e;let n=t;typeof n.historyPolicy=="string"&&(e.appliedPolicy=n.historyPolicy),typeof n.clientId=="string"&&n.clientId.length>0&&(e.clientId=n.clientId);let s=n._meta;if(s&&typeof s=="object"){let r=s["hydra-acp"];if(r&&typeof r=="object"){let i=r.turnStartedAt;typeof i=="number"&&(e.turnStartedAt=i)}}return e}function Nb(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function Db(t){return t.daemonTurnStartedAt!==void 0?{pendingTurnsDelta:t.pendingTurns===0?1:0,banner:"busy",busySince:t.daemonTurnStartedAt}:{pendingTurnsDelta:t.pendingTurns>0?-t.pendingTurns:0,banner:"ready"}}var Hb=J(()=>{"use strict"});import{readFileSync as dT}from"fs";import{nanoid as Ub}from"nanoid";import cT from"terminal-kit";import Gf from"fs/promises";import Yr from"path";function lT(t){return t.filter(e=>e.status==="open"||e.status==="pending-delivery")}function uT(t){let e=qc(t);if(t.status==="pending-delivery"&&t.userAnswer){let n=e.indexOf(t.userAnswer);if(n!==-1)return n}return 0}function fT(t){let e=new Map,n=[];for(let s of t){let r=s.question,i=e.get(r);i?i.ids.push(s.id):(e.set(r,{representative:s,ids:[s.id]}),n.push(r))}return n.map(s=>e.get(s))}function qc(t){if(t.options&&t.options.length>0){let e=t.options.filter(n=>n!==t.defaultAnswer);return t.options.includes(t.defaultAnswer)?[t.defaultAnswer,...e]:[t.defaultAnswer,...t.options]}return[t.defaultAnswer]}function pT(t,e){return t.length<=e?t:e<=1?"\u2026":t.slice(0,e-1)+"\u2026"}function hT(t,e,n,s,r=60){let i=t.map((o,a)=>{let c=qc(o.representative),d=e[a]??0,l=n[a]?Zf:c[d]??c[0]??"";return{label:pT(o.representative.question,r),value:l}});return{title:`Open questions (${t.length})`,options:i,selectedIndex:Math.max(0,Math.min(t.length-1,s)),hint:"\u2191/\u2193 row \xB7 \u2190/\u2192 cycle \xB7 d dismiss \xB7 1-9 jump \xB7 \u23CE/Esc save \xB7 ^C discard"}}function mT(t,e,n){return t===Zf?{type:"dismiss",method:Hw,params:{sessionId:n,questionId:e.id}}:{type:"answer",method:Dw,params:{sessionId:n,questionId:e.id,answer:t}}}function gT(t,e,n,s,r){let i=[];for(let o=0;o<t.length;o++){let a=t[o];if(!a||!n[o])continue;let c=s[o]?Zf:qc(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},u=mT(c,l,r);u!==null&&i.push(u)}}return i}function yT(t,e,n,s,r,i,o,a){if(!e||n===null||n.length===0)return{type:"noop"};if(t.type==="char"){if(t.ch==="d"||t.ch==="D")return{type:"dismiss-toggle",selectedRow:o};if(/^[1-9]$/.test(t.ch)){let d=parseInt(t.ch,10)-1;if(d<n.length)return{type:"row",selectedRow:d}}return{type:"noop"}}if(t.type!=="key")return{type:"noop"};let c=d=>{let l=n[o];if(!l)return{type:"noop"};let u=qc(l.representative);if(u.length===0)return{type:"noop"};let p=((s[o]??0)+d+u.length)%u.length;return{type:"cycle",selectedRow:o,newValueIndex:p}};switch(t.name){case"up":return{type:"row",selectedRow:Math.max(0,o-1)};case"down":return{type:"row",selectedRow:Math.min(n.length-1,o+1)};case"right":return c(1);case"left":return c(-1);case"enter":case"escape":case"ctrl-q":return{type:"save",dispatches:gT(n,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function jb(t){if(!Array.isArray(t))return;let e=Kn({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function Xf(t){switch(t.type){case"send":case"amend":case"queue-edit":case"queue-remove":case"plan-toggle":case"attachment-request":return!0;default:return!1}}function vT(t,e){e.has(t)?e.delete(t):e.add(t)}function ST(){if(qb)return;qb=!0;let t=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{se({src:"uncaughtException",stack:t(e)}),Kr(),process.stderr.write(`
234
234
  uncaught: ${t(e)}
235
235
  `),process.exit(1)}),process.on("unhandledRejection",e=>{se({src:"unhandledRejection",stack:t(e)}),Kr(),process.stderr.write(`
236
236
  unhandled rejection: ${t(e)}
237
- `),process.exit(1)}),process.on("exit",e=>{e!==0&&se({src:"process-exit",code:e})})}async function qb(t){mT();let e=await be(),n=t.target??await Ft(e);Up(e.tui.logMaxBytes),n.isLocal&&!t.target&&await Js(e);let s=sT.terminal;gb(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:gp(e),defaultEnterAction:e.tui.defaultEnterAction,...t.agentId?{lastChosenAgent:t.agentId}:{}},o=Jf(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(s.fullscreen(!1),a=!1,process.stdout.write(`
238
- `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=t;try{for(;u!==null;)u=await yT(s,e,n,u,r,i,o)}finally{d(),process.off("exit",l)}let f=await ha();if(f&&process.stderr.write(`\u2728 ${ma(f)}
239
- `),process.stdout.isTTY){let p=await Fr(e);if(p?.version!==void 0){let h=p.version!==fe,m=qs(e),y=p.configDigest!==void 0&&p.configDigest!==m;if(h||y){let b=h?`daemon ${p.version} \u2260 cli ${fe}`:"config changed since daemon started",v=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(v(`! ${b} \u2014 run \`${Dn()} daemon restart\` to apply.`)+`
237
+ `),process.exit(1)}),process.on("exit",e=>{e!==0&&se({src:"process-exit",code:e})})}async function Kb(t){ST();let e=await be(),n=t.target??await Ot(e);jp(e.tui.logMaxBytes),n.isLocal&&!t.target&&await Js(e);let s=cT.terminal;bb(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:yp(e),defaultEnterAction:e.tui.defaultEnterAction,...t.agentId?{lastChosenAgent:t.agentId}:{}},o=Vf(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(s.fullscreen(!1),a=!1,process.stdout.write(`
238
+ `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=t;try{for(;u!==null;)u=await IT(s,e,n,u,r,i,o)}finally{d(),process.off("exit",l)}let f=await ma();if(f&&process.stderr.write(`\u2728 ${ga(f)}
239
+ `),process.stdout.isTTY){let p=await Or(e);if(p?.version!==void 0){let h=p.version!==fe,m=qs(e),y=p.configDigest!==void 0&&p.configDigest!==m;if(h||y){let b=h?`daemon ${p.version} \u2260 cli ${fe}`:"config changed since daemon started",v=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(v(`! ${b} \u2014 run \`${Dn()} daemon restart\` to apply.`)+`
240
240
  `)}}}if(r.sessionId&&process.stdout.isTTY){let p=rt(r.sessionId),h=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${Dn()} --session ${p}${h}
241
- `)}}function gT(t){let{order:e,states:n,startedAt:s,endedAt:r,stopReason:i,perToolExpanded:o,collapsedLimit:a=20}=t,c=e.length,d=a>0,l;if(!d||t.expanded)l=e;else{let K=Math.max(0,c-a),U=e.slice(K),L=[];for(let N=0;N<K;N++){let Z=e[N];if(Z===void 0)continue;let G=n.get(Z);G&&!Ku(G.status)&&L.push(Z)}l=[...L,...U]}let u=c-l.length,f=r===null,p=r??Date.now(),h=p-s,m=!f&&i!==null&&i!=="end_turn"?i:null,y=m==="amended",b=y?`amended \xB7 ${Qn(h)}`:`stopped (${m}) \xB7 ${Qn(h)}`,v;if(c===0)m!==null?v=b:v=f?`thinking \xB7 ${Qn(h)}`:`thought \xB7 ${Qn(h)}`;else{let K=c===1?"tool":"tools",U=m!==null?b:f?Qn(h):`took ${Qn(h)}`,L=[`${c} ${K}`,U];f&&d&&u>0&&L.push(`${u} hidden`),v=L.join(" \xB7 ")}let S=c===0&&f,k=y?"tool-status-cancelled":"tool-status-fail",$=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":m!==null?k:"tool",body:v,bodyStyle:S?"tool-status-running":m!==null?k:"dim"}],B=[null];for(let K of l){let U=n.get(K);if(U){let L=da(U,p);for(let N of L)N.hoverSubKey=K;if($.push(...L),B.push(...L.map(()=>K)),o?.has(K)){let N=hy(U);for(let Z of N)Z.hoverSubKey=K;$.push(...N),B.push(...N.map(()=>K))}}}return{lines:$,rowOwners:B}}async function yT(t,e,n,s,r,i,o){let a=await wT(t,e,n,s,o,i);if(!a)return t.grabInput(!1),se({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let c=a.sessionId==="__new__"?"Starting new session\u2026":a.isFreshFork?"Forking session\u2026":"Resuming session\u2026",d=vT(t,c);d.write(c);let l=n.isLocal?async()=>(await Ft(await be())).wsUrl:n.wsUrl,u=["acp.v1",`hydra-acp-token.${n.token}`],f=null,p=null,h=new ao({url:l,subprotocols:u,onConnect:async g=>{g||f&&await f()},onDisconnect:g=>{p&&p(g)},log:g=>se({src:"resilient-ws",line:g})}),m=new zt(h);await h.start(),m.onNotification(nd,g=>{let w=Ih.safeParse(g);w.success&&d.applyProgress(w.data)});let y=[],b=null,v=!1,S=!1,k=(g,w)=>{g&&(b?b(g,w):y.push({event:g,rawUpdate:w}))},T,F=g=>{g!==T&&(T=g,g!==void 0&&I.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},$=null,B=null,K=!1,U=0,L=0,N=!1,Z=!1,G,Se=null,X=null,ce=null,Je=null,sr=()=>setInterval(()=>{if(Se===null||Y===null)return;let g=Je===null?0:Date.now()-Je;Y.setBanner({elapsedMs:Date.now()-Se,stalled:g>=fT}),Wt()},1e3),ks=!1,De=g=>{let w=L;L=Math.max(0,L+g);let x=typeof Y<"u"&&Y!==null;w===0&&L>0?(Z=!1,Se=Date.now(),Je=Date.now(),xe?.setTurnRunning(!0),x&&Y.setBanner({status:"busy",elapsedMs:0,stalled:!1}),X===null&&x&&(X=sr())):w>0&&L===0?(Z=!1,Se=null,Je=null,xe?.setTurnRunning(!1),X!==null&&(clearInterval(X),X=null),x&&Y.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):L>0&&Z&&(Z=!1,x&&Y.setBanner({status:"busy",stalled:!1}))},Y=null,xe=null,es,ve=null,Is=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction","clarifier_question_asked","clarifier_question_answered","clarifier_question_dismissed"]),ot=g=>{let{update:w}=g??{},x=Kn(w,{cwd:ut});bT(w,x),Je=Date.now();let C=w?.sessionUpdate;if(typeof C=="string"&&!Is.has(C)){let A=w??{};typeof A.messageId=="string"&&(es=A.messageId)}if(C==="prompt_received"?De(1):x?.kind==="turn-complete"&&(De(-1),K=!0),C==="permission_resolved"){Qr(w);return}if(C==="hydra_compaction"){As(w);return}if(C==="clarifier_question_asked"){let A=w,M=typeof A.question?.question=="string"?A.question.question:"",H=M.length>50?M.slice(0,49)+"\u2026":M;I.notify(H?`new question: ${H} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}C==="clarifier_question_answered"||C==="clarifier_question_dismissed"||(k(x,w),Ra(w))};m.onNotification("session/update",g=>{if(!v){if(ve!==null){ve.push(g);return}ot(g)}}),m.onNotification("hydra-acp/session/closed",()=>{if(v)return;L>0&&De(-L),typeof Y<"u"&&Y!==null&&Y.setBanner({status:"cold",elapsedMs:void 0})});let He=new Map,ho=200,xs=0,Mt=!1,dn=4e3;m.onNotification("hydra-acp/prompt_queue/added",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string")return;if(typeof w._meta?.["hydra-acp"]?.amending=="string"){let C=w.messageId,A=w.prompt,M=setTimeout(()=>{v||(He.delete(C),Ye.set(C,$t(C,A)),Y&&xe&&An())},ho);He.set(C,M)}else Ye.set(w.messageId,$t(w.messageId,w.prompt)),Y&&xe&&An();if(ln!==void 0&&w.originator?.clientId===ln){let C=mt.shift();C&&(C.messageId=w.messageId,hn.set(w.messageId,C))}}),m.onNotification("hydra-acp/prompt_queue/updated",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string"||!Ye.has(w.messageId))return;Ye.set(w.messageId,$t(w.messageId,w.prompt));let x=hn.get(w.messageId);if(x){let C=Array.isArray(w.prompt)?w.prompt:[],A="",M=[];for(let H of C){if(!H||typeof H!="object")continue;let O=H;O.type==="text"&&typeof O.text=="string"?A+=O.text:O.type==="image"&&typeof O.data=="string"&&typeof O.mimeType=="string"&&M.push({data:O.data,mimeType:O.mimeType,sizeBytes:Math.floor(O.data.length*3/4)})}x.text=A,x.attachments=M}Y&&xe&&An()}),m.onNotification("hydra-acp/prompt_queue/removed",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string")return;w.reason==="started"&&(G=w.messageId);let x=He.get(w.messageId);x!==void 0&&(clearTimeout(x),He.delete(w.messageId)),Ye.delete(w.messageId)&&Y&&xe&&An();let A=hn.get(w.messageId);A&&(hn.delete(w.messageId),w.reason==="started"&&(A.flushed=!0,k({kind:"user-text",text:A.displayText,attachments:A.attachments}),qe=A))}),m.onNotification("hydra-acp/cancel_failed",g=>{if(v)return;let w=g??{};if(!(typeof Y<"u"&&Y!==null))return;xs=Date.now(),Mt=!0;let C=typeof w.code=="number"?` (${w.code})`:"",A=typeof w.message=="string"&&w.message.length>0?`: ${w.message}`:"";Y.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${C}${A} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),m.onNotification("hydra-acp/prompt/amended",g=>{if(v)return;let w=g??{};if(typeof w.cancelledMessageId!="string")return;let x=w.cancelledMessageId;St.add(x),qe!==null&&qe.messageId!==void 0&&qe.messageId===x&&(k({kind:"turn-complete",stopReason:"cancelled",amended:!0}),qe=null,St.delete(x))});let As=g=>{let w=g??{},x=typeof w.phase=="string"?w.phase:void 0;if(x==="started")I.setCompactionIndicator("compacting...");else if(x==="iteration")I.setCompactionIndicator("compacting...");else if(x==="deferred")I.setCompactionIndicator("compaction queued (waiting for idle)");else if(x==="swapped")I.setCompactionIndicator(null),I.notify("compacted",2e3);else if(x==="rolled_back")I.setCompactionIndicator(null),I.notify("rolled back",2e3);else if(x==="failed"){I.setCompactionIndicator(null);let C=typeof w.error=="string"?w.error:"unknown error",A=C.length>40?C.slice(0,40)+"...":C;I.notify(`compaction failed: ${A}`,5e3)}},rr=()=>{ce===null&&(ce=setInterval(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(Ae)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState===void 0?(I.setSynthesisIndicator(null),I.notify("synthesis complete",2e3),ce!==null&&(clearInterval(ce),ce=null)):w.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3),ce!==null&&(clearInterval(ce),ce=null))}catch{}},5e3))},mo=()=>{ce!==null&&(clearInterval(ce),ce=null)},Qr=g=>{let w=g??{},x=typeof w.toolCallId=="string"?w.toolCallId:void 0,C;w.outcome&&typeof w.outcome=="object"?C=w.outcome:typeof w.chosenOptionId=="string"&&(C={kind:"selected",optionId:w.chosenOptionId}),On(x,C?{outcome:C}:void 0)},_e=null,On=(g,w)=>{if(!_e||_e.toolCallId&&g&&_e.toolCallId!==g)return;let x=_e.resolve;_e=null,I.setPermissionPrompt(null),x(w??{outcome:{outcome:"cancelled"}})},Ra=g=>{if(!_e?.toolCallId)return;let w=g??{};w.sessionUpdate!=="tool_call"&&w.sessionUpdate!=="tool_call_update"||w.toolCallId===_e.toolCallId&&(!w.status||w.status==="pending"||On(w.toolCallId,void 0))},ir=()=>{if(!_e){I.setPermissionPrompt(null);return}I.setPermissionPrompt({title:_e.title,detail:_e.detail,options:_e.options.map(g=>({label:g.name})),selectedIndex:_e.selectedIndex})},It=g=>{if(!_e)return;let{options:w,resolve:x}=_e;if(_e=null,I.setPermissionPrompt(null),g===null){x({outcome:{outcome:"cancelled"}});return}x({outcome:{outcome:"selected",optionId:g}})};m.onRequest("session/request_permission",async g=>{if(v)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return Wr(g);let w=g??{},C=(Array.isArray(w.options)?w.options:[]).map(V=>({optionId:V.optionId,name:Ee(V.name??""),...V.kind!==void 0?{kind:V.kind}:{}})),A=w.toolCall?.title??w.toolCall?.name??"tool",M=Ee(A),H=Ee(pw(fw(g))),O=w.toolCall?.toolCallId;return C.length===0?(I.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${M} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(V=>{_e={title:M,detail:H,options:C,selectedIndex:0,resolve:V,toolCallId:O},ir()})}),m.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let Ln,go,Gr=!0,yo=!1;try{let g=await m.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:fe}});go=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(Gr=!1),yo=en(g?._meta??void 0).prompt?.amending===!0}catch{}let Ae=a.sessionId,st=a.agentId,ut=a.cwd,cn,ln,ft,vt,pt,Xr,Zr,Cs,ei,In,or=!1;if(a.sessionId==="__new__"){let g={};s.agentId&&(g.agentId=s.agentId),s.name&&(g.title=s.name),s.model&&(g.model=s.model);let w={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[Tt]:g}}:{}},x;try{x=await sw({request:()=>m.request("session/new",w),showBanner:(M,H,O)=>rw(t,M,H,O,{authenticate:V=>m.request("authenticate",{methodId:V})}),resolveOnboarding:async M=>{if(M)try{return(await Zd(n)).find(V=>V.id===M)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch(M){t.grabInput(!1),se({src:"grab",site:"runSession.session-new-failed",on:!1}),h.close().catch(()=>{});let H=M instanceof Error?M.message:String(M);se({src:"session-new-failed",agentId:s.agentId??null,message:H});let O=await Cb(t,s.agentId,H,{canGoBack:!s.forceNew});if(O==="cancel")return null;let V={...s};return delete V.sessionId,delete V.resume,O==="retry"?V.forceNew=!0:(delete V.forceNew,delete V.agentId),V}if(x.kind==="cancel")return t.grabInput(!1),se({src:"grab",site:"runSession.auth-cancel",on:!1}),h.close().catch(()=>{}),null;if(x.kind==="back"){t.grabInput(!1),se({src:"grab",site:"runSession.auth-back",on:!1}),h.close().catch(()=>{});let M={...s};return delete M.sessionId,delete M.forceNew,delete M.resume,delete M.agentId,M}let C=x.result;d.write(c),Ae=C.sessionId,r.sessionId=Ae,r.readonly=!1;let A=en(C._meta??void 0);A.clientId&&(ln=A.clientId),Ln=A.upstreamSessionId,A.agentId&&(st=A.agentId),A.cwd&&(ut=A.cwd),A.title&&(cn=A.title),ft=A.currentModel,vt=A.currentMode,ei=A.currentUsage,In=A.turnStartedAt,A.availableCommands&&(pt=Fd(A.availableCommands)),A.availableModes&&(Xr=A.availableModes),Zr=Db(C.configOptions),Cs=A.queue}else{let g={};s.readonly===!0&&(g.readonly=!0),e.tui.toolContent==="references"&&(g.toolContent="references"),s.drip===!0&&(g.replayMode="drip",s.dripSpeed!==void 0&&(g.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(g.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let w=await m.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:fe},...Object.keys(g).length>0?{_meta:{[Tt]:g}}:{}});Ae=w.sessionId,w.clientId&&(ln=w.clientId),r.sessionId=Ae,r.readonly=s.readonly===!0;let x=en(w._meta??void 0);or=x.resurrected===!0,Ln=x.upstreamSessionId,x.agentId&&(st=x.agentId),x.cwd&&(ut=x.cwd),x.title&&(cn=x.title),ft=x.currentModel,vt=x.currentMode,ei=x.currentUsage,In=x.turnStartedAt,x.availableCommands&&(pt=Fd(x.availableCommands)),x.availableModes&&(Xr=x.availableModes),Zr=Db(w.configOptions),Cs=x.queue}let Rs=_.tuiHistoryFile(Ae),wo=_.globalTuiHistoryFile(),xt=await qo(Rs).catch(()=>[]),un=await qo(wo).catch(()=>[]);un.length>e.tui.promptHistoryMaxEntries&&(un=un.slice(un.length-e.tui.promptHistoryMaxEntries));let me=[...xt],Ce=new bs({history:yd(un,me)});xe=Ce;let ar=!1,Bt=(g,w)=>{let x=g.replace(/\n+$/,"");if(x.length===0)return;let C=(w??g).replace(/\n+$/,""),A=Wo(xt,x),M=A!==xt;xt=A,me=Wo(me,C);let H=Wo(un,x,e.tui.promptHistoryMaxEntries),O=H!==un;un=H,Ce.setHistory(yd(un,me)),M&&Pr(Rs,xt).catch(()=>{}),O&&vm(wo,x).catch(()=>{})};L>0&&Ce.setTurnRunning(!0);let Kt=null,fn=null;pb(hb(e.tui.ambiguousWidth,process.env)),gy(e.tui.diffContextLines);let Nt=!1,I,bo=()=>{Nt&&(Nt=!1,I.start())},Ta=()=>{Nt||(Nt=!0,I.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",bo);let Ts=null,ti=null;I=new Oc({term:t,dispatcher:Ce,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:i.mouseEnabled,inAppSelection:i.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,openFileCommand:e.tui.openFileCommand,progressIndicator:e.tui.progressIndicator,readonly:s.readonly===!0,onSuspend:process.platform!=="win32"?Ta:void 0,onBlockClick:(g,w)=>{lv(g,w)},onBlockDoubleClick:(g,w)=>cv(g,w),onBlockVisible:g=>{ov(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let w=$s.get(g);if(w!==void 0&&w.length>0)return new Set(w);let x=I.contiguousRun(g,new Set(Nn.keys()));return x.length>0?new Set(x):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){Ts=I.bannerHitAt(g.x,g.y),ti=Ts?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let x=ti,C=Ts;if(ti=null,Ts=null,C!==null&&x!==null&&x.x===g.x&&x.y===g.y&&I.bannerHitAt(g.x,g.y)===C){if(C==="mode"){_s(!0);return}let A=C==="pick"?{type:"switch-session"}:C==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&Gf(A))return;ae(A);return}}if(g.kind!=="press"||g.button!=="middle")return;let w={type:"attachment-request",source:"primary"};s.readonly===!0&&Gf(w)||ae(w)},onKey:g=>{for(let w of g){if(N&&Jc(w)){w.type==="key"&&se({src:"key-swallowed",site:"compactionPrompt",name:w.name});continue}if(_e&&lr(w)){w.type==="key"&&se({src:"key-swallowed",site:"permission",name:w.name});continue}if(Yc(w)){w.type==="key"&&se({src:"key-swallowed",site:"help",name:w.name});continue}if(_a(w)){w.type==="key"&&se({src:"key-swallowed",site:"questions",name:w.name});continue}if(Ao(w)){w.type==="key"&&se({src:"key-swallowed",site:"options",name:w.name});continue}if(Pa(w)){w.type==="key"&&se({src:"key-swallowed",site:"scrollbackSearch",name:w.name});continue}if(Ea(w)){w.type==="key"&&se({src:"key-swallowed",site:"completion",name:w.name});continue}if(ko(w)){w.type==="key"&&se({src:"key-swallowed",site:"btwClose",name:w.name});continue}if(w.type==="key"&&w.name==="escape"&&I.isScrolledBack()){I.scrollToBottom();continue}if(w.type==="attachment-paths"){ue(w.paths);continue}let x=Ce.feed(w);for(let C of x)s.readonly===!0&&Gf(C)||ae(C)}So(),I.setBannerSearchIndicator(Ce.state().historySearchQuery),I.setAttachments(Ce.state().attachments),I.refreshPrompt()}}),Y=I,I.setStickyBottomKey("plan");let dr=[{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:"/model",description:"Switch model: /model <model-id>"},{name:"/agent",description:"Switch agent via config option: /agent <agent-id>"},{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]"}],je=pt??[],ts=Xr??[],vo=Zr??[],Jt=()=>vo.find(g=>g.id==="agent"),zc=()=>{let g=new Set,w=[];for(let x of[...dr,...je])g.has(x.name)||(g.add(x.name),w.push(x));return w},at=()=>{let g=Ce.state().buffer,w=g[0]??"";if(!w.startsWith("/"))return[];if(g.length>1)return[];let x=w.indexOf(" "),C=x===-1?w:w.slice(0,x);if(C.lastIndexOf("/")>0)return[];let A=zc().filter(M=>M.name.startsWith(C));return A.length===1&&A[0]?.name===C?[]:A},Dt=[],So=()=>{let g=at();if(g.length>0){Dt=[],I.setCompletions(g);return}I.setCompletions(Dt)},Ea=g=>{if(g.type!=="key"||g.name!=="tab")return Dt.length>0&&(Dt=[]),!1;let w=at();if(I.isOverlayOpen()&&w.length===0)return I.toggleFocusedPane(),!0;if(w.length>0){Dt=[];let x=Ce.state().buffer[0]??"",C=vb({matches:w.map(A=>A.name),firstLine:x});return C===null||Ce.replaceFirstLine(C),!0}return cr()},cr=()=>{let g=Ce.state(),w=g.buffer[g.row]??"",x=Mb(w,g.col);if(x===null)return!1;let C=_b(x.token,ut);return C===null?!1:(C.replacement!==x.token&&Ce.replaceRangeOnCurrentLine(x.start,g.col,C.replacement),Dt=C.candidates.length>1?C.candidates.map(A=>({name:A})):[],!0)},ko=g=>!I.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:($&&($.cancel(),$=null,B=null),I.closeBtwOverlay(),!0),Pa=g=>{if(!I.isScrollbackSearchActive())return g.type==="key"&&g.name==="ctrl-r"&&I.isScrolledBack()?(I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(""),!0):!1;if(g.type==="char"){let w=I.scrollbackSearchTerm()+g.ch;return I.updateScrollbackSearchTerm(w),!0}if(g.type==="paste"){let w=I.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return I.updateScrollbackSearchTerm(w),!0}if(g.type==="key")switch(g.name){case"ctrl-r":return I.advanceScrollbackSearch(),!0;case"ctrl-s":return I.retreatScrollbackSearch(),!0;case"backspace":{let w=I.scrollbackSearchTerm();return w.length===0?I.cancelScrollbackSearch():I.updateScrollbackSearchTerm(w.slice(0,-1)),!0}case"enter":return I.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return I.cancelScrollbackSearch(),!0;default:return!0}return!0},lr=g=>{if(!_e)return!1;let w=_e.options;if(g.type==="key")switch(g.name){case"up":return _e.selectedIndex=Math.max(0,_e.selectedIndex-1),ir(),!0;case"down":return _e.selectedIndex=Math.min(w.length-1,_e.selectedIndex+1),ir(),!0;case"enter":{let x=w[_e.selectedIndex];return x&&It(x.optionId),!0}case"escape":case"ctrl-c":return It(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let x=parseInt(g.ch,10)-1,C=w[x];return C&&It(C.optionId),!0}return!0},ur=st||go||"?",Ht={...ei??{}};d.finalize(),I.start({skipFullscreen:!0}),I.setHideThoughts(!i.showThoughts),I.setSessionbar({agent:ur,cwd:ut,sessionId:Ae,title:cn,model:ft,usage:{...Ht}}),vt&&I.setBanner({currentMode:vt}),ha().then(g=>{g&&I.notify(`\u2728 ${ma(g)}`,3e4)}).catch(()=>{});let ht=null,Kc=new Promise(g=>{ht=g}),Io=()=>{m.notify("session/cancel",{sessionId:Ae}).catch(()=>{})},fr=()=>{Y!==null&&L===1&&(Z=!0,Y.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},ns=()=>{if(Kt){Kt.cancel(),fr();return}if(L>0){Io(),fr();return}Es()},Es=()=>{R(0)},ss=()=>{let g="enqueue prompt (sends now, or queues during a turn)",w="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",w],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",w]],...pT]},Ps=()=>{if(I.isHelpPromptActive()){I.setHelpPrompt(null);return}I.setHelpPrompt({title:"Hotkeys",entries:ss(),hint:"any key dismisses \xB7 /help lists commands"})},pr=()=>{N=!1,I.setCompactionPrompt(null),I.setCompactionIndicator("compaction queued...");let g=Ae;fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}}).catch(()=>{})},ni=()=>{N=!1,I.setCompactionPrompt(null)},xo=g=>{let w=I.compactionPromptSpec();if(!w)return;let x=w.options.length;if(x===0)return;let C=((w.selectedIndex+g)%x+x)%x;C!==w.selectedIndex&&I.setCompactionPrompt({...w,selectedIndex:C})},Jc=g=>{if(!N)return!1;if(g.type==="key"){if(g.name==="escape")return ni(),!0;if(g.name==="up")return xo(-1),!0;if(g.name==="down")return xo(1),!0;if(g.name==="enter"){let w=I.compactionPromptSpec();return w?.options[w.selectedIndex]?.key==="y"?pr():ni(),!0}}if(g.type==="char"){let w=g.ch.toLowerCase();if(w==="y"||w==="1")return pr(),!0;if(w==="n"||w==="2")return ni(),!0}return!0},Yc=g=>I.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",I.setHelpPrompt(null),!0):!1,rs=["tools","plan","thoughts","diffs","mouse","enter"],Ut=0,pn=null,si=[],_t=[],Bn=[],Yt=0,is=g=>{switch(g){case"tools":return i.toolsExpanded?"expanded":"collapsed";case"plan":return i.planExpanded?"expanded":"collapsed";case"thoughts":return i.showThoughts?"shown":"hidden";case"diffs":return i.showFileUpdates;case"mouse":return i.mouseEnabled?"on":"off";case"enter":return i.defaultEnterAction}},ri=g=>{switch(g){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"}},Ma=()=>({title:"Session options",options:rs.map(g=>({label:ri(g),value:is(g)})),selectedIndex:Ut}),os=()=>{I.isOptionsPromptActive()&&pn===null&&I.setOptionsPrompt(Ma())},ii=()=>{if(I.isOptionsPromptActive()){I.setOptionsPrompt(null);return}Ut=0,I.setOptionsPrompt(Ma())},Vt=()=>{if(pn===null)return;let g=dT(pn,si,Bn,Yt);I.setOptionsPrompt(g)},Ms=()=>{pn=null,si=[],_t=[],Bn=[],Yt=0,I.setOptionsPrompt(null)},xn=async()=>{if(pn!==null){Ms();return}try{let w=await m.request(Lw,{sessionId:Ae}),x=rT(w.questions??[]);if(x.length===0){I.notify("no open questions");return}let C=oT(x);pn=C,Yt=0,si=C.map(A=>iT(A.representative)),_t=C.map(()=>!1),Bn=C.map(()=>!1),Vt()}catch(g){I.notify("clarifier unavailable"),se({src:"questions",step:"list_failed",error:g.message})}},hr=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,yr.clear(),di.clear(),nv();break;case"plan":i.planExpanded=!i.planExpanded,te=null,Xe();break;case"thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",ds.clear(),av();break;case"mouse":{let w=!I.isMouseEnabled();I.setMouseEnabled(w),i.mouseEnabled=w;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}os()},Qt=g=>{(async()=>{try{switch(g){case"tools":case"plan":I.notify(`${ri(g)} is session-only \u2014 not saved`);return;case"thoughts":await To("showThoughts",i.showThoughts);break;case"diffs":await To("showFileUpdates",i.showFileUpdates);break;case"mouse":await To("mouse",i.mouseEnabled);break;case"enter":await To("defaultEnterAction",i.defaultEnterAction);break}I.notify(`saved default: ${ri(g)} ${is(g)}`)}catch(w){I.notify(`save failed: ${w instanceof Error?w.message:String(w)}`)}})()},Ao=g=>{if(pn!==null||!I.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Ut=Math.max(0,Ut-1),os(),!0;case"down":return Ut=Math.min(rs.length-1,Ut+1),os(),!0;case"enter":{let w=rs[Ut];return w&&hr(w),!0}case"ctrl-o":case"escape":case"ctrl-c":return I.setOptionsPrompt(null),!0;case"ctrl-d":return I.setOptionsPrompt(null),!1;default:return!0}if(g.type==="char"){if(/^[1-9]$/.test(g.ch)){let w=parseInt(g.ch,10)-1,x=rs[w];return x&&(Ut=w,hr(x)),!0}if(g.ch==="s"||g.ch==="S"){let w=rs[Ut];return w&&Qt(w),!0}}return!0},_a=g=>{if(pn===null)return!1;let w=uT(g,!0,pn,si,_t,Bn,Yt,Ae);switch(w.type){case"noop":return!0;case"row":return Yt=w.selectedRow,Vt(),!0;case"cycle":return si[w.selectedRow]=w.newValueIndex,_t[w.selectedRow]=!0,Bn[w.selectedRow]=!1,Vt(),!0;case"dismiss-toggle":{let x=w.selectedRow;return Bn[x]?(Bn[x]=!1,_t[x]=!1):(Bn[x]=!0,_t[x]=!0),Vt(),!0}case"discard":return Ms(),!0;case"save":{let x=w.dispatches;return Ms(),x.length===0||(async()=>{let C=0,A=0,M=0;for(let O of x)try{await m.request(O.method,O.params),O.type==="dismiss"?A++:C++}catch(V){M++,se({src:"questions",step:"dispatch_failed",method:O.method,error:V.message})}let H=[];C>0&&H.push(`${C} answered`),A>0&&H.push(`${A} dismissed`),M>0&&H.push(`${M} failed`),H.length>0&&I.notify(`clarifier: ${H.join(", ")}`)})(),!0}}return!1},oi=()=>{v=!0,$?($.cancel(),$=null,B=null):B!==null&&(Vn(n,B).catch(()=>{}),B=null),process.off("SIGINT",ns),process.platform!=="win32"&&process.off("SIGCONT",bo),X!==null&&(clearInterval(X),X=null),ce!==null&&(clearInterval(ce),ce=null);for(let g of He.values())clearTimeout(g);He.clear(),I.clearWindowTitle(),I.stop({keepFullscreen:!0}),Pr(Rs,xt).catch(()=>{}),h.close().catch(()=>{})},R=(g=0)=>{oi(),ht&&(ht(null),ht=null),g!==0&&process.exit(g)},P=async()=>{if(se({src:"switch-session",step:"entered",finishSessionNull:ht===null}),!ht)return;$?($.cancel(),$=null,B=null):B!==null&&(Vn(n,B).catch(()=>{}),B=null),mo(),I.setSynthesisIndicator(null);let g=Ce.state().buffer.join(`
242
- `);g.replace(/\s+$/,"").length>0&&Bt(g),I.pauseRepaint(),I.stop({keepFullscreen:!0}),Pr(Rs,xt).catch(()=>{});let w=!1;try{let x=null,C=null;for(;x===null;){let O=await Yn(n,{includeNonInteractive:!0}),V=await Yf(t,{cwd:ut,sessions:O,config:e,target:n,currentSessionId:Ae,prefs:o});if(V.kind==="abort")return;if(V.kind==="exit"){w=!0,R(0);return}if(V.kind==="new"){x={choice:V,sessions:O};break}if(V.kind==="fork"){let Ie=await Kb(t,n,V,O);if(Ie.kind==="cancel")return;if(Ie.kind==="back")continue;x={choice:{kind:"attach",sessionId:Ie.ctx.sessionId,...Ie.ctx.agentId?{agentId:Ie.ctx.agentId}:{}},sessions:O},C={readonly:!1,cwd:Ie.ctx.cwd},Ie.ctx.resumeHint!==void 0&&(C.resumeHint=Ie.ctx.resumeHint);break}let ge=O.find(Ie=>Ie.sessionId===V.sessionId);if(!(ge!==void 0&&!!ge.importedFromMachine&&!ge.upstreamSessionId&&V.readonly!==!0)){if(n.isLocal&&ge&&!ge.importedFromMachine&&V.readonly!==!0&&!(await ya(ge.cwd)).ok){let Gt=await Yr(t,ge,{defaultCwd:et(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Gt.kind==="cancel")return;if(Gt.kind==="back")continue;x={choice:V,sessions:O},C={readonly:!1,cwd:Gt.path,resumeHint:{agentId:V.agentId??ge.agentId??"",cwd:Gt.path,upstreamSessionId:""}};break}x={choice:V,sessions:O};break}let pe={...s,readonly:!1},ye=await Wb(t,n,ge,V,pe);if(ye.kind==="cancel")return;ye.kind!=="back"&&(x={choice:V,sessions:O},C={readonly:pe.readonly===!0,cwd:ye.ctx.cwd},ye.ctx.resumeHint!==void 0&&(C.resumeHint=ye.ctx.resumeHint))}let{choice:A}=x,M=ht;if(ht=null,process.off("SIGINT",ns),h.close().catch(()=>{}),w=!0,A.kind==="new"){let{sessionId:O,agentId:V,...ge}=s,Pe={...ge,cwd:A.cwd??ut,forceNew:!0,readonly:!1};A.prompt!==void 0&&(Pe.initialPrompt=A.prompt),M(Pe);return}if(A.kind!=="attach")return;let H={...s,sessionId:A.sessionId,cwd:C?.cwd??ut,readonly:C?.readonly??A.readonly===!0};A.agentId!==void 0&&(H.agentId=A.agentId),C?.resumeHint!==void 0?H.resumeHint=C.resumeHint:delete H.resumeHint,M(H)}finally{!w&&ht&&(I.start({skipFullscreen:!0}),I.resumeRepaint())}},D=async(g="next")=>{if(!ht)return;let x=(await Yn(n)).filter(Pe=>Pe.status==="warm");if(x.length<=1)return;let C=x.findIndex(Pe=>Pe.sessionId===Ae),H=((C===-1?0:C)+(g==="prev"?-1:1)+x.length)%x.length,O=x[H],V=ht;ht=null,process.off("SIGINT",ns),h.close().catch(()=>{});let ge={...s,sessionId:O.sessionId,cwd:ut,readonly:!1};O.agentId!==void 0&&(ge.agentId=O.agentId),V(ge)},Q=async g=>{if(!ht)return;let w=await Yn(n,{includeNonInteractive:!0}),x=g.trim();if(!x){I.notify("usage: /session <id|next|prev>");return}let C=x.startsWith(bn)?[x]:[x,bn+x],A=w.find(O=>C.includes(O.sessionId));if(!A){let O=w.filter(V=>C.some(ge=>V.sessionId.startsWith(ge)));if(O.length===1)A=O[0];else if(O.length>1){I.notify(`ambiguous session id: ${x} (${O.length} matches)`);return}}if(!A){I.notify(`no session matches: ${x}`);return}if(A.sessionId===Ae){I.notify("already on that session");return}let M=ht;ht=null,process.off("SIGINT",ns),h.close().catch(()=>{});let H={...s,sessionId:A.sessionId,cwd:A.cwd??ut,readonly:A.status!=="warm"};A.agentId!==void 0&&(H.agentId=A.agentId),delete H.resumeHint,M(H)},ae=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?mr(g.text,g.attachments,g.displayText):Cn(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?Cn(g.text,g.attachments,g.displayText):mr(g.text,g.attachments,g.displayText);return;case"queue-edit":{let w=ai(g.index);if(!w)return;let x=[];g.text.length>0&&x.push({type:"text",text:g.text});for(let C of g.attachments)x.push({type:"image",data:C.data,mimeType:C.mimeType});m.request("hydra-acp/prompt/update",{sessionId:Ae,messageId:w,prompt:x}).then(C=>{let A=C;!A.updated&&A.reason!=="ok"&&I.notify(`queue edit skipped (${A.reason})`)}).catch(C=>{I.notify(`queue edit failed: ${C.message}`)});return}case"queue-remove":{let w=ai(g.index);if(!w)return;m.request("hydra-acp/prompt/cancel",{sessionId:Ae,messageId:w}).then(x=>{let C=x;!C.cancelled&&C.reason!=="ok"&&I.notify(`queue cancel skipped (${C.reason})`)}).catch(x=>{I.notify(`queue cancel failed: ${x.message}`)});return}case"cancel":{if(I.isOverlayOpen()){$&&($.cancel(),$=null,B=null),I.closeBtwOverlay();return}if(g.prefill&&Kt){let w=Ye.size===0,x=Ce.state().buffer.every(C=>C==="");w&&x&&(fn={text:Kt.text,attachments:Kt.attachments})}Kt?Kt.cancel():L>0&&Io(),fr();return}case"exit":Es();return;case"plan-toggle":_s(g.on);return;case"redraw-banner":I.setBanner({});return;case"redraw":I.fullRedraw();return;case"scroll-to-top":I.scrollToTop();return;case"scroll-to-bottom":I.scrollToBottom();return;case"switch-session":P().catch(w=>{se({src:"switch-session-failed",stack:w instanceof Error?w.stack??w.message:String(w)})});return;case"next-live-session":D().catch(()=>{});return;case"toggle-options":ii();return;case"toggle-questions":xn();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts),I.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let w=!I.isMouseEnabled();I.setMouseEnabled(w),i.mouseEnabled=w,I.notify(w?"mouse capture on \u2014 wheel scrolls; shift+drag to select text":"mouse capture off \u2014 click-drag selects text; PgUp/PgDn scrolls");return}case"show-help":Ps();return;case"escalate-search":I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(g.query);return;case"attachment-request":Be(g.source);return}},ue=async g=>{if(!Gr){I.notify("agent does not accept image attachments");return}let w=0;for(let x of g){if(x.startsWith("data:")){let A=Cf(x);if(!A){I.notify("unsupported data: URI");continue}if(A.sizeBytes>Xn){I.notify(`image too large (${kn(A.sizeBytes)}, max ${kn(Xn)})`);continue}Ce.addAttachment({mimeType:A.mimeType,data:A.data,name:"pasted image",sizeBytes:A.sizeBytes}),w++;continue}let C=wa(x);if(!C){I.notify(`unsupported image type: ${Vr.basename(x)}`);continue}try{let A=await Qf.readFile(x);if(A.length>Xn){I.notify(`image too large (${kn(A.length)}, max ${kn(Xn)})`);continue}Ce.addAttachment({mimeType:C,data:A.toString("base64"),name:Vr.basename(x),sizeBytes:A.length}),w++}catch(A){I.notify(`cannot read ${Vr.basename(x)}: ${A.message}`)}}w>0&&(I.setAttachments(Ce.state().attachments),I.refreshPrompt())},Be=async(g="clipboard")=>{let w=g==="primary"?await Gw():await Qw();if(!w.ok){I.notify(w.reason);return}if(w.kind==="image"){if(!Gr){I.notify("agent does not accept image attachments");return}Ce.addAttachment(w.attachment),I.setAttachments(Ce.state().attachments),I.refreshPrompt();return}let x=Ce.feed({type:"paste",text:w.text});for(let C of x)ae(C);I.refreshPrompt()},jt=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,$t=(g,w)=>{let x=Array.isArray(w)?w:[],C="",A=0;for(let M of x){if(!M||typeof M!="object")continue;let H=M;H.type==="text"&&typeof H.text=="string"?C+=H.text:H.type==="image"&&(A+=1)}return{messageId:g,text:Ee(C),attachmentCount:A}},Ye=new Map,mt=[],hn=new Map,St=new Set,qe=null,An=()=>{let g=[...Ye.values()],w=g.map(jt);I.setQueuedPrompts(w),I.setBanner({queued:g.length}),Ce.setQueue(g.map(x=>x.text))},ai=g=>[...Ye.values()][g]?.messageId;if(Cs&&Cs.length>0){for(let g of Cs){if(g.position===0){G=g.messageId;continue}Ye.set(g.messageId,$t(g.messageId,g.prompt))}Ye.size>0&&An()}let Cn=(g,w,x)=>{I.scrollToBottom(),!$a(g)&&(Bt(g,x),Co(g,w,x))},mr=(g,w,x)=>{if(I.scrollToBottom(),$a(g))return;if(Bt(g,x),!yo||G===void 0){Co(g,w,x);return}let C=G,A=[];g.length>0&&A.push({type:"text",text:g});for(let O of w)A.push({type:"image",data:O.data,mimeType:O.mimeType});let M={text:g,displayText:x??g,attachments:w,flushed:!1};mt.push(M);let H=()=>{let O=mt.indexOf(M);O>=0&&mt.splice(O,1),M.messageId!==void 0&&hn.delete(M.messageId)};m.request("hydra-acp/prompt/amend",{sessionId:Ae,targetMessageId:C,prompt:A}).then(O=>{let V=O;if(V.amended&&V.reason==="ok"){De(1);return}if(H(),V.reason==="target_completed"){I.notify("previous response finished \u2014 press Enter to send as a new turn"),Ce.setBuffer(g,w),I.refreshPrompt();return}if(V.reason==="target_cancelled"){I.notify("amend skipped \u2014 previous turn was cancelled"),Ce.setBuffer(g,w),I.refreshPrompt();return}if(V.reason==="target_not_found"){I.notify("amend skipped \u2014 no matching prompt"),Ce.setBuffer(g,w),I.refreshPrompt();return}}).catch(O=>{H(),I.notify(`amend failed: ${O.message}`),Ce.setBuffer(g,w),I.refreshPrompt()})},_s=async g=>{if(ts.length===0){I.notify("no modes advertised by agent");return}let w=I.currentModeId(),x=ts.findIndex(M=>M.id===w),C=x===-1?0:(x+1)%ts.length,A=ts[C]?.id;if(A){I.setBanner({currentMode:A});try{await m.request("session/set_mode",{sessionId:Ae,modeId:A})}catch(M){I.notify(`set_mode failed: ${M.message}`)}}},$a=g=>{let w=g.replace(/\s+$/,"");if(!w.startsWith("/")||w.includes(`
243
- `))return!1;let x=w.indexOf(" ");switch(x===-1?w:w.slice(0,x)){case"/quit":case"/exit":return Es(),!0;case"/clear":return gt.clear(),Rn.clear(),dt.length=0,E=null,j=null,ie=null,as.clear(),ds.clear(),cs.clear(),yr.clear(),Nn.clear(),$s.clear(),I.clearScrollback(),!0;case"/help":{let A=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let M of dr)A.push({prefix:" ",body:` ${M.name.padEnd(12)} ${M.description??""}`,bodyStyle:"info"});if(je.length>0){A.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let M of je)A.push({prefix:" ",body:` ${M.name.padEnd(12)} ${M.description??""}`,bodyStyle:"info"})}return I.appendLines(A),!0}case"/agent":{let A=x===-1?"":w.slice(x+1).trim(),M=Jt();if(!M)return I.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!A){let H=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let O of M.options){let V=O.value===M.currentValue?"* ":" ";H.push({prefix:" ",body:`${V}${O.value.padEnd(16)} ${O.name}`,bodyStyle:"info"})}return I.appendLines(H),!0}return M.options.some(H=>H.value===A)?A===M.currentValue?(I.notify(`already on agent ${A}`),!0):(I.notify(`switching to ${A}\u2026`),m.request("session/set_config_option",{sessionId:Ae,configId:"agent",value:A}).catch(H=>{I.notify(`set_config_option failed: ${H.message}`)}),!0):(I.notify(`unknown agent: ${A}`),!0)}case"/sessions":return I.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return P().catch(A=>{se({src:"switch-session-failed",stack:A instanceof Error?A.stack??A.message:String(A)})}),!0;case"/session":{let A=x===-1?"":w.slice(x+1).trim();return A?A==="next"||A==="prev"?(D(A).catch(M=>{I.notify(`session ${A} failed: ${M.message}`)}),!0):(Q(A).catch(M=>{I.notify(`session switch failed: ${M.message}`)}),!0):(P().catch(M=>{se({src:"switch-session-failed",stack:M instanceof Error?M.stack??M.message:String(M)})}),!0)}case"/rename":{let A=x===-1?"":w.slice(x+1).trim(),M=A.length>0?`/hydra title ${A}`:"/hydra title";return Bt(w,w),Co(M,[],w),!0}case"/btw":{let A=x===-1?"":w.slice(x+1).trim();if(!A)return I.isOverlayOpen()?($&&($.cancel(),$=null,B=null),I.closeBtwOverlay(),!0):(I.reopenBtwOverlay()||I.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(Ae==="__new__")return I.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;U+=1;let M=U;$&&($.cancel(),$=null);let H=null;B!==null&&!K?H=B:B!==null&&(Vn(n,B).catch(()=>{}),B=null),K=!1,I.openBtwOverlay(),I.setBtwOverlayStatus({label:"busy",style:"busy"});let O=new Tc({getMaxWidth:()=>{let pe=I.width();return pe>0?pe:void 0}});O.on("changed",()=>{I.setBtwOverlayContent(O.getLines())});let V={};O.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:A}]});let ge=pe=>{O.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:pe}})},Pe={};return H!==null&&(Pe.reuseSessionId=H),Hw(n,Ae,A,Pe).then(pe=>{if(M!==U){pe.cancel();return}$=pe,B=pe.sessionId,I.setBtwOverlayMeta({sessionId:pe.sessionId}),pe.on("event",ye=>{if(M===U)if(ye.kind==="update"){O.append(ye.update);let Ie=Kn(ye.update);if(Ie&&Ie.kind==="usage-update"){let Gt=!1;Ie.used!==void 0&&V.used!==Ie.used&&(V.used=Ie.used,Gt=!0),Ie.size!==void 0&&V.size!==Ie.size&&(V.size=Ie.size,Gt=!0),Ie.costAmount!==void 0&&V.costAmount!==Ie.costAmount&&(V.costAmount=Ie.costAmount,Gt=!0),Ie.costCurrency!==void 0&&V.costCurrency!==Ie.costCurrency&&(V.costCurrency=Ie.costCurrency,Gt=!0),Gt&&I.setBtwOverlayMeta({usage:{...V}})}}else ye.kind==="completed"?(I.setBtwOverlayStatus({label:"done",style:"done"}),$=null):ye.kind==="cancelled"?(I.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),$=null,B=null):ye.kind==="errored"&&(I.setBtwOverlayStatus({label:"errored",style:"errored"}),ge(`btw errored: ${ye.error.message}`),B!==null&&Vn(n,B).catch(()=>{}),$=null,B=null)})}).catch(pe=>{if(M!==U)return;let ye=pe instanceof Error?pe.message:String(pe);I.setBtwOverlayStatus({label:"errored",style:"errored"}),ge(`btw startup failed: ${ye}`),I.appendLines([{prefix:" ",body:`btw startup failed: ${ye}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(Ae==="__new__")return I.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let A=x===-1?"":w.slice(x+1).trim(),M=Ae;return(async()=>{try{let H=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(M)}/transcript`,{headers:{Authorization:`Bearer ${n.token}`}});if(!H.ok){let ye=await H.text().catch(()=>"");I.appendLines([{prefix:" ",body:`/export failed: HTTP ${H.status} ${ye}`.trim(),bodyStyle:"info"}]);return}let O=await H.text(),V=new Date().toISOString().replace(/[:.]/g,"-"),ge=`hydra-${rt(M)}-${V}.md`,Pe=A.length>0?et(A):ge,pe=Vr.resolve(Pe);await Qf.mkdir(Vr.dirname(pe),{recursive:!0}),await Qf.writeFile(pe,O,{encoding:"utf8",mode:384}),I.appendLines([{prefix:" ",body:`Wrote ${pe}`,bodyStyle:"system"}])}catch(H){I.appendLines([{prefix:" ",body:`/export failed: ${H.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},Co=async(g,w,x)=>{let C=[];g.length>0&&C.push({type:"text",text:g});for(let Pe of w)C.push({type:"image",data:Pe.data,mimeType:Pe.mimeType});De(1);let A={text:g,displayText:x??g,attachments:w,flushed:!1};mt.push(A),Mt=!1;let M=!1,H=null,O=Pe=>{typeof Y<"u"&&Y!==null&&Y.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Pe,bodyStyle:"tool-status-fail"}])},V=!1;Kt={text:g,attachments:w,cancel:()=>{if(Mt){Mt=!1,V=!0,O("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),m.request("hydra-acp/session/force_cancel",{sessionId:Ae}).catch(pe=>{O(`force-stop failed: ${pe.message}`)});return}if(M)return;M=!0,m.notify("session/cancel",{sessionId:Ae}).catch(()=>{});let Pe=Date.now();H=setTimeout(()=>{Kt!==null&&(xs>=Pe||(Mt=!0,O("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},dn)}};let ge;try{let Pe=await m.request("session/prompt",{sessionId:Ae,prompt:C});Pe&&typeof Pe.stopReason=="string"&&(ge=Pe.stopReason)}catch(Pe){let pe=mt.indexOf(A);pe>=0&&mt.splice(pe,1),A.messageId!==void 0&&hn.delete(A.messageId),V?I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):I.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:Pe.message,bodyStyle:"tool-status-fail"}])}finally{if(Kt=null,H!==null&&(clearTimeout(H),H=null),De(-1),A.flushed&&qe===A){let Pe=A.messageId!==void 0&&St.has(A.messageId);Pe&&A.messageId!==void 0&&St.delete(A.messageId);let pe={kind:"turn-complete"};ge!==void 0&&(pe.stopReason=ge),Pe&&(pe.amended=!0),k(pe),qe=null}if(fn!==null){let{text:Pe,attachments:pe}=fn;fn=null,Ce.state().buffer.every(Ie=>Ie==="")&&(Ce.setBuffer(Pe,pe),I.refreshPrompt())}}},gt=new Map,as=new Map,ds=new Map,Rn=new Map,dt=[],gr=0,Tn=`tools:${gr}`,cs=new Map,yr=new Map,di=new Set,ls=new Map,Nn=new Map,$s=new Map,E=null,j=null,ie=null,W=null,te=null,re=e.tui.maxToolItems,ke=e.tui.maxPlanItems,We=()=>({maxPlanItems:te??i.planExpanded?1/0:ke}),Xe=()=>{if(W===null)return;let g=Qs(W,We());g.length>0&&I.upsertLines("plan",[{body:""},...g])},ct="",Re=null,At=0,qt=()=>{if(Re===null)return;let g=I.width(),w=Gs(ct,g>0?{maxWidth:g}:void 0);w.length!==0&&I.upsertLines(Re,w)},rp=g=>{g.length!==0&&(Re===null&&(I.ensureSeparator(),Re=`agent:${At}`,At+=1,ct=""),ct+=g,qt())},mn=()=>{Re=null,ct=""},Fs="",gn=null,wr=0,br=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),Vc=()=>{if(gn===null||Fs.length===0)return;let g=Zi(Fs);g.length!==0&&I.upsertLines(gn,g)},Qc=g=>{let w=Nn.get(g);if(w===void 0)return[];let x=Zi(w.text);return w.workerTaskId&&x.unshift({prefix:" ",body:`[T${w.workerTaskId}] `,bodyStyle:"dim"}),x},Fa=(g,w)=>{g.length!==0&&(gn===null&&(I.ensureSeparator("thought"),gn=`thought:${wr}`,wr+=1,Fs=""),Fs+=g,Nn.set(gn,{text:Fs,workerTaskId:w}),Vc())},$e=()=>{gn=null,Fs=""},us=g=>gT({...g,collapsedLimit:re}),Os=g=>yr.get(g)??i.toolsExpanded,Wt=()=>{if(E===null)return;let{lines:g,rowOwners:w}=us({order:dt,states:gt,startedAt:E,endedAt:j,stopReason:ie,expanded:Os(Tn),perToolExpanded:di});I.upsertLines(Tn,g),ls.set(Tn,w)},Oa=g=>{let w=cs.get(g);if(!w)return;let{lines:x,rowOwners:C}=us({order:w.order,states:w.states,startedAt:w.startedAt,endedAt:w.endedAt,stopReason:w.stopReason,expanded:Os(g),perToolExpanded:di});I.upsertLines(g,x),ls.set(g,C)},nv=()=>{E!==null&&!cs.has(Tn)&&Wt();for(let g of cs.keys())Oa(g)},Gc=()=>{E!==null&&cs.set(Tn,{order:[...dt],states:new Map(gt),startedAt:E,endedAt:j??Date.now(),stopReason:ie,rowOwners:ls.get(Tn)??[]})},ip=()=>{gr+=1,Tn=`tools:${gr}`,E=Date.now(),j=null,ie=null,Wt()};function sv(g){if(!g||typeof g!="object")return null;let w=g,x=Array.isArray(w.content)?w.content:void 0;if(!x)return null;let C=[],A=M=>{if(typeof M=="string"){C.push({text:lt(M)});return}if(M&&typeof M=="object"){let H=M;typeof H.__hydraBlob=="string"&&C.push({hash:H.__hydraBlob})}};for(let M of x){if(!M||typeof M!="object")continue;let H=M;if(H.type==="content"&&H.content&&typeof H.content=="object"){let O=H.content;if(O.text!==void 0){A(O.text);continue}}if(H.type==="text"&&H.text!==void 0){A(H.text);continue}H.text!==void 0&&A(H.text)}return C.length>0?C:null}let op=(g,w)=>{let x=w.map(M=>"text"in M?M.text:"").join(`
244
- `);if(x.length===0)return;let{text:C,truncated:A}=py(x);g.resultText=C,g.resultTruncated=A},La=new Set,rv=(g,w)=>{!w.some(C=>"hash"in C)||La.has(g)||(La.add(g),(async()=>{let C=await Promise.all(w.map(async M=>"text"in M?M:{text:await Xc(M.hash)??""}));La.delete(g);let A=gt.get(g);if(!A)for(let M of cs.values()){let H=M.states.get(g);if(H){A=H;break}}if(A){op(A,C),gt.has(g)&&Wt();for(let[M,H]of cs)H.states.has(g)&&Oa(M);I.repaintNow()}})().catch(()=>{La.delete(g)}))},ap=(g,w,x,C,A,M,H,O,V,ge)=>{let Pe=!gt.has(g),pe=gt.get(g),ye=pe??{initialTitle:w??"tool",latestTitle:w??"tool",status:x??"pending",startedAt:Date.now()};if(!pe&&V!==void 0&&(ye.workerTaskId=V),pe&&w!==void 0&&(ye.latestTitle=w),M!==void 0&&ye.detail===void 0&&(ye.detail=M),H!==void 0&&ye.detailFull===void 0&&(ye.detailFull=H),O!==void 0&&O.length>0&&(ye.locations=O),pe&&x!==void 0&&(ye.status=x),pe||(ye.status=x??"pending"),ye.endedAt===void 0&&Ku(ye.status)&&(ye.endedAt=Date.now()),C!==void 0&&(ye.errorText=C),A!==void 0&&(ye.editDiff=A),ge!==void 0){let Ie=sv(ge);Ie!==null&&(op(ye,Ie),Ie.some(Gt=>"hash"in Gt)&&rv(g,Ie))}gt.set(g,ye),Pe&&(E===null&&(gr+=1,Tn=`tools:${gr}`,E=Date.now(),j=null,ie=null),dt.push(g))},Xc=async g=>{try{let w=await m.request("hydra-acp/session/tool_content",{sessionId:Ae,hash:g});return typeof w?.content=="string"?w.content:null}catch{return null}},Ba=new Set,iv=(g,w)=>{Ba.has(g)||w.oldRef===void 0&&w.newRef===void 0||(Ba.add(g),(async()=>{let[x,C]=await Promise.all([w.oldRef?Xc(w.oldRef.hash):Promise.resolve(w.oldText),w.newRef?Xc(w.newRef.hash):Promise.resolve(w.newText)]);if(w.oldRef!==void 0&&x===null||w.newRef!==void 0&&C===null){Ba.delete(g);let ge=Wu(w,"diff",{deferredStatus:"error"});ge.length>0&&(I.upsertLines(`editdiff:${g}`,ge),I.repaintNow());return}let M={...w.path!==void 0?{path:w.path}:{},oldText:x??"",newText:C??""};as.set(g,M);let H=gt.get(g);H?.editDiff&&(H.editDiff=M),Ba.delete(g);let O=ds.get(g),V=O===void 0?i.showFileUpdates:O?"diff":"edit";V!=="none"&&(Na(g,M,V==="diff"?"diff":"edit"),I.repaintNow())})())},Na=(g,w,x)=>{let C=`editdiff:${g}`,A=Wu(w,x);if(A.length===0){I.removeKey(C);return}I.upsertLines(C,A),x==="diff"&&(w.oldRef!==void 0||w.newRef!==void 0)&&I.notifyWhenVisible(C)},ov=g=>{if(!g.startsWith("editdiff:"))return;let w=g.slice(9),x=as.get(w);x&&(x.oldRef!==void 0||x.newRef!==void 0)&&iv(w,x)},dp=g=>{let w=`editdiff:${g}`,x=i.showFileUpdates,C=gt.get(g),A;if(x==="none"||!C?.editDiff||C.status!=="completed")A=null;else{let H=ds.get(g);A=H!==void 0?H?"diff":"edit":x==="diff"?"diff":"edit"}if(A===null){I.removeKey(w);return}let M=C.editDiff;as.set(g,M),Na(g,M,A)},av=()=>{let g=i.showFileUpdates;for(let[w,x]of as){let C=`editdiff:${w}`,A=ds.get(w),M=A===void 0?g:A?"diff":"edit";if(M==="none"){I.removeKey(C);continue}Na(w,x,M==="diff"?"diff":"edit")}},dv=g=>{if(!g.path)return null;let w=lt(g.oldText).split(`
241
+ `)}}function kT(t){let{order:e,states:n,startedAt:s,endedAt:r,stopReason:i,perToolExpanded:o,collapsedLimit:a=20}=t,c=e.length,d=a>0,l;if(!d||t.expanded)l=e;else{let K=Math.max(0,c-a),U=e.slice(K),L=[];for(let N=0;N<K;N++){let Z=e[N];if(Z===void 0)continue;let G=n.get(Z);G&&!Ju(G.status)&&L.push(Z)}l=[...L,...U]}let u=c-l.length,f=r===null,p=r??Date.now(),h=p-s,m=!f&&i!==null&&i!=="end_turn"?i:null,y=m==="amended",b=y?`amended \xB7 ${Qn(h)}`:`stopped (${m}) \xB7 ${Qn(h)}`,v;if(c===0)m!==null?v=b:v=f?`thinking \xB7 ${Qn(h)}`:`thought \xB7 ${Qn(h)}`;else{let K=c===1?"tool":"tools",U=m!==null?b:f?Qn(h):`took ${Qn(h)}`,L=[`${c} ${K}`,U];f&&d&&u>0&&L.push(`${u} hidden`),v=L.join(" \xB7 ")}let S=c===0&&f,k=y?"tool-status-cancelled":"tool-status-fail",$=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":m!==null?k:"tool",body:v,bodyStyle:S?"tool-status-running":m!==null?k:"dim"}],B=[null];for(let K of l){let U=n.get(K);if(U){let L=ca(U,p);for(let N of L)N.hoverSubKey=K;if($.push(...L),B.push(...L.map(()=>K)),o?.has(K)){let N=gy(U);for(let Z of N)Z.hoverSubKey=K;$.push(...N),B.push(...N.map(()=>K))}}}return{lines:$,rowOwners:B}}async function IT(t,e,n,s,r,i,o){let a=await xT(t,e,n,s,o,i);if(!a)return t.grabInput(!1),se({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let c=a.sessionId==="__new__"?"Starting new session\u2026":a.isFreshFork?"Forking session\u2026":"Resuming session\u2026",d=CT(t,c);d.write(c);let l=n.isLocal?async()=>(await Ot(await be())).wsUrl:n.wsUrl,u=["acp.v1",`hydra-acp-token.${n.token}`],f=null,p=null,h=new co({url:l,subprotocols:u,onConnect:async g=>{g||f&&await f()},onDisconnect:g=>{p&&p(g)},log:g=>se({src:"resilient-ws",line:g})}),m=new zt(h);await h.start(),m.onNotification(sd,g=>{let w=xh.safeParse(g);w.success&&d.applyProgress(w.data)});let y=[],b=null,v=!1,S=!1,k=(g,w)=>{g&&(b?b(g,w):y.push({event:g,rawUpdate:w}))},T,O=g=>{g!==T&&(T=g,g!==void 0&&I.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},$=null,B=null,K=!1,U=0,L=0,N=!1,Z=!1,G,Se=null,X=null,ce=null,Ye=null,sr=()=>setInterval(()=>{if(Se===null||V===null)return;let g=Ye===null?0:Date.now()-Ye;V.setBanner({elapsedMs:Date.now()-Se,stalled:g>=wT}),Wt()},1e3),ks=!1,De=g=>{let w=L;L=Math.max(0,L+g);let x=typeof V<"u"&&V!==null;w===0&&L>0?(Z=!1,Se=Date.now(),Ye=Date.now(),xe?.setTurnRunning(!0),x&&V.setBanner({status:"busy",elapsedMs:0,stalled:!1}),X===null&&x&&(X=sr())):w>0&&L===0?(Z=!1,Se=null,Ye=null,xe?.setTurnRunning(!1),X!==null&&(clearInterval(X),X=null),x&&V.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):L>0&&Z&&(Z=!1,x&&V.setBanner({status:"busy",stalled:!1}))},V=null,xe=null,ts,ve=null,Is=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction","clarifier_question_asked","clarifier_question_answered","clarifier_question_dismissed"]),ot=g=>{let{update:w}=g??{},x=Kn(w,{cwd:ut});AT(w,x),Ye=Date.now();let C=w?.sessionUpdate;if(typeof C=="string"&&!Is.has(C)){let A=w??{};typeof A.messageId=="string"&&(ts=A.messageId)}if(C==="prompt_received"?De(1):x?.kind==="turn-complete"&&(De(-1),K=!0),C==="permission_resolved"){Qr(w);return}if(C==="hydra_compaction"){As(w);return}if(C==="clarifier_question_asked"){let A=w,M=typeof A.question?.question=="string"?A.question.question:"",H=M.length>50?M.slice(0,49)+"\u2026":M;I.notify(H?`new question: ${H} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}C==="clarifier_question_answered"||C==="clarifier_question_dismissed"||(k(x,w),Ta(w))};m.onNotification("session/update",g=>{if(!v){if(ve!==null){ve.push(g);return}ot(g)}}),m.onNotification("hydra-acp/session/closed",()=>{if(v)return;L>0&&De(-L),typeof V<"u"&&V!==null&&V.setBanner({status:"cold",elapsedMs:void 0})});let He=new Map,mo=200,xs=0,Mt=!1,dn=4e3;m.onNotification("hydra-acp/prompt_queue/added",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string")return;if(typeof w._meta?.["hydra-acp"]?.amending=="string"){let C=w.messageId,A=w.prompt,M=setTimeout(()=>{v||(He.delete(C),Qe.set(C,$t(C,A)),V&&xe&&An())},mo);He.set(C,M)}else Qe.set(w.messageId,$t(w.messageId,w.prompt)),V&&xe&&An();if(ln!==void 0&&w.originator?.clientId===ln){let C=mt.shift();C&&(C.messageId=w.messageId,hn.set(w.messageId,C))}}),m.onNotification("hydra-acp/prompt_queue/updated",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string"||!Qe.has(w.messageId))return;Qe.set(w.messageId,$t(w.messageId,w.prompt));let x=hn.get(w.messageId);if(x){let C=Array.isArray(w.prompt)?w.prompt:[],A="",M=[];for(let H of C){if(!H||typeof H!="object")continue;let F=H;F.type==="text"&&typeof F.text=="string"?A+=F.text:F.type==="image"&&typeof F.data=="string"&&typeof F.mimeType=="string"&&M.push({data:F.data,mimeType:F.mimeType,sizeBytes:Math.floor(F.data.length*3/4)})}x.text=A,x.attachments=M}V&&xe&&An()}),m.onNotification("hydra-acp/prompt_queue/removed",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string")return;w.reason==="started"&&(G=w.messageId);let x=He.get(w.messageId);x!==void 0&&(clearTimeout(x),He.delete(w.messageId)),Qe.delete(w.messageId)&&V&&xe&&An();let A=hn.get(w.messageId);A&&(hn.delete(w.messageId),w.reason==="started"&&(A.flushed=!0,k({kind:"user-text",text:A.displayText,attachments:A.attachments}),We=A))}),m.onNotification("hydra-acp/cancel_failed",g=>{if(v)return;let w=g??{};if(!(typeof V<"u"&&V!==null))return;xs=Date.now(),Mt=!0;let C=typeof w.code=="number"?` (${w.code})`:"",A=typeof w.message=="string"&&w.message.length>0?`: ${w.message}`:"";V.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${C}${A} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),m.onNotification("hydra-acp/prompt/amended",g=>{if(v)return;let w=g??{};if(typeof w.cancelledMessageId!="string")return;let x=w.cancelledMessageId;St.add(x),We!==null&&We.messageId!==void 0&&We.messageId===x&&(k({kind:"turn-complete",stopReason:"cancelled",amended:!0}),We=null,St.delete(x))});let As=g=>{let w=g??{},x=typeof w.phase=="string"?w.phase:void 0;if(x==="started")I.setCompactionIndicator("compacting...");else if(x==="iteration")I.setCompactionIndicator("compacting...");else if(x==="deferred")I.setCompactionIndicator("compaction queued (waiting for idle)");else if(x==="swapped")I.setCompactionIndicator(null),I.notify("compacted",2e3);else if(x==="rolled_back")I.setCompactionIndicator(null),I.notify("rolled back",2e3);else if(x==="failed"){I.setCompactionIndicator(null);let C=typeof w.error=="string"?w.error:"unknown error",A=C.length>40?C.slice(0,40)+"...":C;I.notify(`compaction failed: ${A}`,5e3)}},rr=()=>{ce===null&&(ce=setInterval(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(Ae)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState===void 0?(I.setSynthesisIndicator(null),I.notify("synthesis complete",2e3),ce!==null&&(clearInterval(ce),ce=null)):w.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3),ce!==null&&(clearInterval(ce),ce=null))}catch{}},5e3))},go=()=>{ce!==null&&(clearInterval(ce),ce=null)},Qr=g=>{let w=g??{},x=typeof w.toolCallId=="string"?w.toolCallId:void 0,C;w.outcome&&typeof w.outcome=="object"?C=w.outcome:typeof w.chosenOptionId=="string"&&(C={kind:"selected",optionId:w.chosenOptionId}),Fn(x,C?{outcome:C}:void 0)},_e=null,Fn=(g,w)=>{if(!_e||_e.toolCallId&&g&&_e.toolCallId!==g)return;let x=_e.resolve;_e=null,I.setPermissionPrompt(null),x(w??{outcome:{outcome:"cancelled"}})},Ta=g=>{if(!_e?.toolCallId)return;let w=g??{};w.sessionUpdate!=="tool_call"&&w.sessionUpdate!=="tool_call_update"||w.toolCallId===_e.toolCallId&&(!w.status||w.status==="pending"||Fn(w.toolCallId,void 0))},ir=()=>{if(!_e){I.setPermissionPrompt(null);return}I.setPermissionPrompt({title:_e.title,detail:_e.detail,options:_e.options.map(g=>({label:g.name})),selectedIndex:_e.selectedIndex})},It=g=>{if(!_e)return;let{options:w,resolve:x}=_e;if(_e=null,I.setPermissionPrompt(null),g===null){x({outcome:{outcome:"cancelled"}});return}x({outcome:{outcome:"selected",optionId:g}})};m.onRequest("session/request_permission",async g=>{if(v)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return Wr(g);let w=g??{},C=(Array.isArray(w.options)?w.options:[]).map(Y=>({optionId:Y.optionId,name:Ee(Y.name??""),...Y.kind!==void 0?{kind:Y.kind}:{}})),A=w.toolCall?.title??w.toolCall?.name??"tool",M=Ee(A),H=Ee(mw(hw(g))),F=w.toolCall?.toolCallId;return C.length===0?(I.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${M} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(Y=>{_e={title:M,detail:H,options:C,selectedIndex:0,resolve:Y,toolCallId:F},ir()})}),m.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let Ln,yo,Gr=!0,wo=!1;try{let g=await m.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:fe}});yo=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(Gr=!1),wo=en(g?._meta??void 0).prompt?.amending===!0}catch{}let Ae=a.sessionId,st=a.agentId,ut=a.cwd,cn,ln,ft,vt,pt,Xr,Zr,Cs,ei,In,or=!1;if(a.sessionId==="__new__"){let g={};s.agentId&&(g.agentId=s.agentId),s.name&&(g.title=s.name),s.model&&(g.model=s.model);let w={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[Tt]:g}}:{}},x;try{x=await iw({request:()=>m.request("session/new",w),showBanner:(M,H,F)=>ow(t,M,H,F,{authenticate:Y=>m.request("authenticate",{methodId:Y})}),resolveOnboarding:async M=>{if(M)try{return(await Zd(n)).find(Y=>Y.id===M)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch(M){t.grabInput(!1),se({src:"grab",site:"runSession.session-new-failed",on:!1}),h.close().catch(()=>{});let H=M instanceof Error?M.message:String(M);se({src:"session-new-failed",agentId:s.agentId??null,message:H});let F=await Eb(t,s.agentId,H,{canGoBack:!s.forceNew});if(F==="cancel")return null;let Y={...s};return delete Y.sessionId,delete Y.resume,F==="retry"?Y.forceNew=!0:(delete Y.forceNew,delete Y.agentId),Y}if(x.kind==="cancel")return t.grabInput(!1),se({src:"grab",site:"runSession.auth-cancel",on:!1}),h.close().catch(()=>{}),null;if(x.kind==="back"){t.grabInput(!1),se({src:"grab",site:"runSession.auth-back",on:!1}),h.close().catch(()=>{});let M={...s};return delete M.sessionId,delete M.forceNew,delete M.resume,delete M.agentId,M}let C=x.result;d.write(c),Ae=C.sessionId,r.sessionId=Ae,r.readonly=!1;let A=en(C._meta??void 0);A.clientId&&(ln=A.clientId),Ln=A.upstreamSessionId,A.agentId&&(st=A.agentId),A.cwd&&(ut=A.cwd),A.title&&(cn=A.title),ft=A.currentModel,vt=A.currentMode,ei=A.currentUsage,In=A.turnStartedAt,A.availableCommands&&(pt=Od(A.availableCommands)),A.availableModes&&(Xr=A.availableModes),Zr=jb(C.configOptions),Cs=A.queue}else{let g={};s.readonly===!0&&(g.readonly=!0),e.tui.toolContent==="references"&&(g.toolContent="references"),s.drip===!0&&(g.replayMode="drip",s.dripSpeed!==void 0&&(g.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(g.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let w=await m.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:fe},...Object.keys(g).length>0?{_meta:{[Tt]:g}}:{}});Ae=w.sessionId,w.clientId&&(ln=w.clientId),r.sessionId=Ae,r.readonly=s.readonly===!0;let x=en(w._meta??void 0);or=x.resurrected===!0,Ln=x.upstreamSessionId,x.agentId&&(st=x.agentId),x.cwd&&(ut=x.cwd),x.title&&(cn=x.title),ft=x.currentModel,vt=x.currentMode,ei=x.currentUsage,In=x.turnStartedAt,x.availableCommands&&(pt=Od(x.availableCommands)),x.availableModes&&(Xr=x.availableModes),Zr=jb(w.configOptions),Cs=x.queue}let Rs=_.tuiHistoryFile(Ae),bo=_.globalTuiHistoryFile(),xt=await Wo(Rs).catch(()=>[]),un=await Wo(bo).catch(()=>[]);un.length>e.tui.promptHistoryMaxEntries&&(un=un.slice(un.length-e.tui.promptHistoryMaxEntries));let me=[...xt],Ce=new vs({history:yd(un,me)});xe=Ce;let ar=!1,Bt=(g,w)=>{let x=g.replace(/\n+$/,"");if(x.length===0)return;let C=(w??g).replace(/\n+$/,""),A=zo(xt,x),M=A!==xt;xt=A,me=zo(me,C);let H=zo(un,x,e.tui.promptHistoryMaxEntries),F=H!==un;un=H,Ce.setHistory(yd(un,me)),M&&Pr(Rs,xt).catch(()=>{}),F&&km(bo,x).catch(()=>{})};L>0&&Ce.setTurnRunning(!0);let Kt=null,fn=null;gb(yb(e.tui.ambiguousWidth,process.env)),wy(e.tui.diffContextLines);let Nt=!1,I,vo=()=>{Nt&&(Nt=!1,I.start())},Ea=()=>{Nt||(Nt=!0,I.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",vo);let Ts=null,ti=null;I=new Lc({term:t,dispatcher:Ce,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:i.mouseEnabled,inAppSelection:i.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,openFileCommand:e.tui.openFileCommand,progressIndicator:e.tui.progressIndicator,readonly:s.readonly===!0,onSuspend:process.platform!=="win32"?Ea:void 0,onBlockClick:(g,w)=>{pv(g,w)},onBlockDoubleClick:(g,w)=>fv(g,w),onHydraLinkClick:g=>(Q(g),!0),onBlockVisible:g=>{cv(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let w=$s.get(g);if(w!==void 0&&w.length>0)return new Set(w);let x=I.contiguousRun(g,new Set(Nn.keys()));return x.length>0?new Set(x):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){Ts=I.bannerHitAt(g.x,g.y),ti=Ts?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let x=ti,C=Ts;if(ti=null,Ts=null,C!==null&&x!==null&&x.x===g.x&&x.y===g.y&&I.bannerHitAt(g.x,g.y)===C){if(C==="mode"){_s(!0);return}let A=C==="pick"?{type:"switch-session"}:C==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&Xf(A))return;ae(A);return}}if(g.kind!=="press"||g.button!=="middle")return;let w={type:"attachment-request",source:"primary"};s.readonly===!0&&Xf(w)||ae(w)},onKey:g=>{for(let w of g){if(N&&Vc(w)){w.type==="key"&&se({src:"key-swallowed",site:"compactionPrompt",name:w.name});continue}if(_e&&lr(w)){w.type==="key"&&se({src:"key-swallowed",site:"permission",name:w.name});continue}if(Yc(w)){w.type==="key"&&se({src:"key-swallowed",site:"help",name:w.name});continue}if($a(w)){w.type==="key"&&se({src:"key-swallowed",site:"questions",name:w.name});continue}if(Co(w)){w.type==="key"&&se({src:"key-swallowed",site:"options",name:w.name});continue}if(Ma(w)){w.type==="key"&&se({src:"key-swallowed",site:"scrollbackSearch",name:w.name});continue}if(Pa(w)){w.type==="key"&&se({src:"key-swallowed",site:"completion",name:w.name});continue}if(Io(w)){w.type==="key"&&se({src:"key-swallowed",site:"btwClose",name:w.name});continue}if(w.type==="key"&&w.name==="escape"&&I.isScrolledBack()){I.scrollToBottom();continue}if(w.type==="attachment-paths"){ue(w.paths);continue}let x=Ce.feed(w);for(let C of x)s.readonly===!0&&Xf(C)||ae(C)}ko(),I.setBannerSearchIndicator(Ce.state().historySearchQuery),I.setAttachments(Ce.state().attachments),I.refreshPrompt()}}),V=I,I.setStickyBottomKey("plan");let dr=[{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:"/model",description:"Switch model: /model <model-id>"},{name:"/agent",description:"Switch agent via config option: /agent <agent-id>"},{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]"}],qe=pt??[],ns=Xr??[],So=Zr??[],Jt=()=>So.find(g=>g.id==="agent"),Kc=()=>{let g=new Set,w=[];for(let x of[...dr,...qe])g.has(x.name)||(g.add(x.name),w.push(x));return w},at=()=>{let g=Ce.state().buffer,w=g[0]??"";if(!w.startsWith("/"))return[];if(g.length>1)return[];let x=w.indexOf(" "),C=x===-1?w:w.slice(0,x);if(C.lastIndexOf("/")>0)return[];let A=Kc().filter(M=>M.name.startsWith(C));return A.length===1&&A[0]?.name===C?[]:A},Dt=[],ko=()=>{let g=at();if(g.length>0){Dt=[],I.setCompletions(g);return}I.setCompletions(Dt)},Pa=g=>{if(g.type!=="key"||g.name!=="tab")return Dt.length>0&&(Dt=[]),!1;let w=at();if(I.isOverlayOpen()&&w.length===0)return I.toggleFocusedPane(),!0;if(w.length>0){Dt=[];let x=Ce.state().buffer[0]??"",C=Ib({matches:w.map(A=>A.name),firstLine:x});return C===null||Ce.replaceFirstLine(C),!0}return cr()},cr=()=>{let g=Ce.state(),w=g.buffer[g.row]??"",x=Ob(w,g.col);if(x===null)return!1;let C=Fb(x.token,ut);return C===null?!1:(C.replacement!==x.token&&Ce.replaceRangeOnCurrentLine(x.start,g.col,C.replacement),Dt=C.candidates.length>1?C.candidates.map(A=>({name:A})):[],!0)},Io=g=>!I.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:($&&($.cancel(),$=null,B=null),I.closeBtwOverlay(),!0),Ma=g=>{if(!I.isScrollbackSearchActive())return g.type==="key"&&g.name==="ctrl-r"&&I.isScrolledBack()?(I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(""),!0):!1;if(g.type==="char"){let w=I.scrollbackSearchTerm()+g.ch;return I.updateScrollbackSearchTerm(w),!0}if(g.type==="paste"){let w=I.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return I.updateScrollbackSearchTerm(w),!0}if(g.type==="key")switch(g.name){case"ctrl-r":return I.advanceScrollbackSearch(),!0;case"ctrl-s":return I.retreatScrollbackSearch(),!0;case"backspace":{let w=I.scrollbackSearchTerm();return w.length===0?I.cancelScrollbackSearch():I.updateScrollbackSearchTerm(w.slice(0,-1)),!0}case"enter":return I.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return I.cancelScrollbackSearch(),!0;default:return!0}return!0},lr=g=>{if(!_e)return!1;let w=_e.options;if(g.type==="key")switch(g.name){case"up":return _e.selectedIndex=Math.max(0,_e.selectedIndex-1),ir(),!0;case"down":return _e.selectedIndex=Math.min(w.length-1,_e.selectedIndex+1),ir(),!0;case"enter":{let x=w[_e.selectedIndex];return x&&It(x.optionId),!0}case"escape":case"ctrl-c":return It(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let x=parseInt(g.ch,10)-1,C=w[x];return C&&It(C.optionId),!0}return!0},ur=st||yo||"?",Ht={...ei??{}};d.finalize(),I.start({skipFullscreen:!0}),I.setHideThoughts(!i.showThoughts),I.setSessionbar({agent:ur,cwd:ut,sessionId:Ae,title:cn,model:ft,usage:{...Ht}}),vt&&I.setBanner({currentMode:vt}),ma().then(g=>{g&&I.notify(`\u2728 ${ga(g)}`,3e4)}).catch(()=>{});let ht=null,Jc=new Promise(g=>{ht=g}),xo=()=>{m.notify("session/cancel",{sessionId:Ae}).catch(()=>{})},fr=()=>{V!==null&&L===1&&(Z=!0,V.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},ss=()=>{if(Kt){Kt.cancel(),fr();return}if(L>0){xo(),fr();return}Es()},Es=()=>{R(0)},rs=()=>{let g="enqueue prompt (sends now, or queues during a turn)",w="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",w],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",w]],...bT]},Ps=()=>{if(I.isHelpPromptActive()){I.setHelpPrompt(null);return}I.setHelpPrompt({title:"Hotkeys",entries:rs(),hint:"any key dismisses \xB7 /help lists commands"})},pr=()=>{N=!1,I.setCompactionPrompt(null),I.setCompactionIndicator("compaction queued...");let g=Ae;fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}}).catch(()=>{})},ni=()=>{N=!1,I.setCompactionPrompt(null)},Ao=g=>{let w=I.compactionPromptSpec();if(!w)return;let x=w.options.length;if(x===0)return;let C=((w.selectedIndex+g)%x+x)%x;C!==w.selectedIndex&&I.setCompactionPrompt({...w,selectedIndex:C})},Vc=g=>{if(!N)return!1;if(g.type==="key"){if(g.name==="escape")return ni(),!0;if(g.name==="up")return Ao(-1),!0;if(g.name==="down")return Ao(1),!0;if(g.name==="enter"){let w=I.compactionPromptSpec();return w?.options[w.selectedIndex]?.key==="y"?pr():ni(),!0}}if(g.type==="char"){let w=g.ch.toLowerCase();if(w==="y"||w==="1")return pr(),!0;if(w==="n"||w==="2")return ni(),!0}return!0},Yc=g=>I.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",I.setHelpPrompt(null),!0):!1,is=["tools","plan","thoughts","diffs","mouse","enter"],Ut=0,pn=null,si=[],_t=[],Bn=[],Vt=0,os=g=>{switch(g){case"tools":return i.toolsExpanded?"expanded":"collapsed";case"plan":return i.planExpanded?"expanded":"collapsed";case"thoughts":return i.showThoughts?"shown":"hidden";case"diffs":return i.showFileUpdates;case"mouse":return i.mouseEnabled?"on":"off";case"enter":return i.defaultEnterAction}},ri=g=>{switch(g){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"}},_a=()=>({title:"Session options",options:is.map(g=>({label:ri(g),value:os(g)})),selectedIndex:Ut}),as=()=>{I.isOptionsPromptActive()&&pn===null&&I.setOptionsPrompt(_a())},ii=()=>{if(I.isOptionsPromptActive()){I.setOptionsPrompt(null);return}Ut=0,I.setOptionsPrompt(_a())},Yt=()=>{if(pn===null)return;let g=hT(pn,si,Bn,Vt);I.setOptionsPrompt(g)},Ms=()=>{pn=null,si=[],_t=[],Bn=[],Vt=0,I.setOptionsPrompt(null)},xn=async()=>{if(pn!==null){Ms();return}try{let w=await m.request(Nw,{sessionId:Ae}),x=lT(w.questions??[]);if(x.length===0){I.notify("no open questions");return}let C=fT(x);pn=C,Vt=0,si=C.map(A=>uT(A.representative)),_t=C.map(()=>!1),Bn=C.map(()=>!1),Yt()}catch(g){I.notify("clarifier unavailable"),se({src:"questions",step:"list_failed",error:g.message})}},hr=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,yr.clear(),di.clear(),iv();break;case"plan":i.planExpanded=!i.planExpanded,te=null,Xe();break;case"thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",cs.clear(),lv();break;case"mouse":{let w=!I.isMouseEnabled();I.setMouseEnabled(w),i.mouseEnabled=w;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}as()},Qt=g=>{(async()=>{try{switch(g){case"tools":case"plan":I.notify(`${ri(g)} is session-only \u2014 not saved`);return;case"thoughts":await Eo("showThoughts",i.showThoughts);break;case"diffs":await Eo("showFileUpdates",i.showFileUpdates);break;case"mouse":await Eo("mouse",i.mouseEnabled);break;case"enter":await Eo("defaultEnterAction",i.defaultEnterAction);break}I.notify(`saved default: ${ri(g)} ${os(g)}`)}catch(w){I.notify(`save failed: ${w instanceof Error?w.message:String(w)}`)}})()},Co=g=>{if(pn!==null||!I.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Ut=Math.max(0,Ut-1),as(),!0;case"down":return Ut=Math.min(is.length-1,Ut+1),as(),!0;case"enter":{let w=is[Ut];return w&&hr(w),!0}case"ctrl-o":case"escape":case"ctrl-c":return I.setOptionsPrompt(null),!0;case"ctrl-d":return I.setOptionsPrompt(null),!1;default:return!0}if(g.type==="char"){if(/^[1-9]$/.test(g.ch)){let w=parseInt(g.ch,10)-1,x=is[w];return x&&(Ut=w,hr(x)),!0}if(g.ch==="s"||g.ch==="S"){let w=is[Ut];return w&&Qt(w),!0}}return!0},$a=g=>{if(pn===null)return!1;let w=yT(g,!0,pn,si,_t,Bn,Vt,Ae);switch(w.type){case"noop":return!0;case"row":return Vt=w.selectedRow,Yt(),!0;case"cycle":return si[w.selectedRow]=w.newValueIndex,_t[w.selectedRow]=!0,Bn[w.selectedRow]=!1,Yt(),!0;case"dismiss-toggle":{let x=w.selectedRow;return Bn[x]?(Bn[x]=!1,_t[x]=!1):(Bn[x]=!0,_t[x]=!0),Yt(),!0}case"discard":return Ms(),!0;case"save":{let x=w.dispatches;return Ms(),x.length===0||(async()=>{let C=0,A=0,M=0;for(let F of x)try{await m.request(F.method,F.params),F.type==="dismiss"?A++:C++}catch(Y){M++,se({src:"questions",step:"dispatch_failed",method:F.method,error:Y.message})}let H=[];C>0&&H.push(`${C} answered`),A>0&&H.push(`${A} dismissed`),M>0&&H.push(`${M} failed`),H.length>0&&I.notify(`clarifier: ${H.join(", ")}`)})(),!0}}return!1},oi=()=>{v=!0,$?($.cancel(),$=null,B=null):B!==null&&(Yn(n,B).catch(()=>{}),B=null),process.off("SIGINT",ss),process.platform!=="win32"&&process.off("SIGCONT",vo),X!==null&&(clearInterval(X),X=null),ce!==null&&(clearInterval(ce),ce=null);for(let g of He.values())clearTimeout(g);He.clear(),I.clearWindowTitle(),I.stop({keepFullscreen:!0}),Pr(Rs,xt).catch(()=>{}),h.close().catch(()=>{})},R=(g=0)=>{oi(),ht&&(ht(null),ht=null),g!==0&&process.exit(g)},P=async()=>{if(se({src:"switch-session",step:"entered",finishSessionNull:ht===null}),!ht)return;$?($.cancel(),$=null,B=null):B!==null&&(Yn(n,B).catch(()=>{}),B=null),go(),I.setSynthesisIndicator(null);let g=Ce.state().buffer.join(`
242
+ `);g.replace(/\s+$/,"").length>0&&Bt(g),I.pauseRepaint(),I.stop({keepFullscreen:!0}),Pr(Rs,xt).catch(()=>{});let w=!1;try{let x=null,C=null;for(;x===null;){let F=await Vn(n,{includeNonInteractive:!0}),Y=await Yf(t,{cwd:ut,sessions:F,config:e,target:n,currentSessionId:Ae,prefs:o});if(Y.kind==="abort")return;if(Y.kind==="exit"){w=!0,R(0);return}if(Y.kind==="new"){x={choice:Y,sessions:F};break}if(Y.kind==="fork"){let Ie=await Yb(t,n,Y,F);if(Ie.kind==="cancel")return;if(Ie.kind==="back")continue;x={choice:{kind:"attach",sessionId:Ie.ctx.sessionId,...Ie.ctx.agentId?{agentId:Ie.ctx.agentId}:{}},sessions:F},C={readonly:!1,cwd:Ie.ctx.cwd},Ie.ctx.resumeHint!==void 0&&(C.resumeHint=Ie.ctx.resumeHint);break}let ge=F.find(Ie=>Ie.sessionId===Y.sessionId);if(!(ge!==void 0&&!!ge.importedFromMachine&&!ge.upstreamSessionId&&Y.readonly!==!0)){if(n.isLocal&&ge&&!ge.importedFromMachine&&Y.readonly!==!0&&!(await wa(ge.cwd)).ok){let Gt=await Vr(t,ge,{defaultCwd:et(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Gt.kind==="cancel")return;if(Gt.kind==="back")continue;x={choice:Y,sessions:F},C={readonly:!1,cwd:Gt.path,resumeHint:{agentId:Y.agentId??ge.agentId??"",cwd:Gt.path,upstreamSessionId:""}};break}x={choice:Y,sessions:F};break}let pe={...s,readonly:!1},ye=await Jb(t,n,ge,Y,pe);if(ye.kind==="cancel")return;ye.kind!=="back"&&(x={choice:Y,sessions:F},C={readonly:pe.readonly===!0,cwd:ye.ctx.cwd},ye.ctx.resumeHint!==void 0&&(C.resumeHint=ye.ctx.resumeHint))}let{choice:A}=x,M=ht;if(ht=null,process.off("SIGINT",ss),h.close().catch(()=>{}),w=!0,A.kind==="new"){let{sessionId:F,agentId:Y,...ge}=s,Pe={...ge,cwd:A.cwd??ut,forceNew:!0,readonly:!1};A.prompt!==void 0&&(Pe.initialPrompt=A.prompt),M(Pe);return}if(A.kind!=="attach")return;let H={...s,sessionId:A.sessionId,cwd:C?.cwd??ut,readonly:C?.readonly??A.readonly===!0};A.agentId!==void 0&&(H.agentId=A.agentId),C?.resumeHint!==void 0?H.resumeHint=C.resumeHint:delete H.resumeHint,M(H)}finally{!w&&ht&&(I.start({skipFullscreen:!0}),I.resumeRepaint())}},D=async(g="next")=>{if(!ht)return;let x=(await Vn(n)).filter(Pe=>Pe.status==="warm");if(x.length<=1)return;let C=x.findIndex(Pe=>Pe.sessionId===Ae),H=((C===-1?0:C)+(g==="prev"?-1:1)+x.length)%x.length,F=x[H],Y=ht;ht=null,process.off("SIGINT",ss),h.close().catch(()=>{});let ge={...s,sessionId:F.sessionId,cwd:ut,readonly:!1};F.agentId!==void 0&&(ge.agentId=F.agentId),Y(ge)},Q=async g=>{if(!ht)return;let w=await Vn(n,{includeNonInteractive:!0}),x=g.trim();if(!x){I.notify("usage: /session <id|next|prev>");return}let C=x.startsWith(bn)?[x]:[x,bn+x],A=w.find(F=>C.includes(F.sessionId));if(!A){let F=w.filter(Y=>C.some(ge=>Y.sessionId.startsWith(ge)));if(F.length===1)A=F[0];else if(F.length>1){I.notify(`ambiguous session id: ${x} (${F.length} matches)`);return}}if(!A){I.notify(`no session matches: ${x}`);return}if(A.sessionId===Ae){I.notify("already on that session");return}let M=ht;ht=null,process.off("SIGINT",ss),h.close().catch(()=>{});let H={...s,sessionId:A.sessionId,cwd:A.cwd??ut,readonly:A.status!=="warm"};A.agentId!==void 0&&(H.agentId=A.agentId),delete H.resumeHint,M(H)},ae=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?mr(g.text,g.attachments,g.displayText):Cn(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?Cn(g.text,g.attachments,g.displayText):mr(g.text,g.attachments,g.displayText);return;case"queue-edit":{let w=ai(g.index);if(!w)return;let x=[];g.text.length>0&&x.push({type:"text",text:g.text});for(let C of g.attachments)x.push({type:"image",data:C.data,mimeType:C.mimeType});m.request("hydra-acp/prompt/update",{sessionId:Ae,messageId:w,prompt:x}).then(C=>{let A=C;!A.updated&&A.reason!=="ok"&&I.notify(`queue edit skipped (${A.reason})`)}).catch(C=>{I.notify(`queue edit failed: ${C.message}`)});return}case"queue-remove":{let w=ai(g.index);if(!w)return;m.request("hydra-acp/prompt/cancel",{sessionId:Ae,messageId:w}).then(x=>{let C=x;!C.cancelled&&C.reason!=="ok"&&I.notify(`queue cancel skipped (${C.reason})`)}).catch(x=>{I.notify(`queue cancel failed: ${x.message}`)});return}case"cancel":{if(I.isOverlayOpen()){$&&($.cancel(),$=null,B=null),I.closeBtwOverlay();return}if(g.prefill&&Kt){let w=Qe.size===0,x=Ce.state().buffer.every(C=>C==="");w&&x&&(fn={text:Kt.text,attachments:Kt.attachments})}Kt?Kt.cancel():L>0&&xo(),fr();return}case"exit":Es();return;case"plan-toggle":_s(g.on);return;case"redraw-banner":I.setBanner({});return;case"redraw":I.fullRedraw();return;case"scroll-to-top":I.scrollToTop();return;case"scroll-to-bottom":I.scrollToBottom();return;case"switch-session":P().catch(w=>{se({src:"switch-session-failed",stack:w instanceof Error?w.stack??w.message:String(w)})});return;case"next-live-session":D().catch(()=>{});return;case"toggle-options":ii();return;case"toggle-questions":xn();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts),I.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let w=!I.isMouseEnabled();I.setMouseEnabled(w),i.mouseEnabled=w,I.notify(w?"mouse capture on \u2014 wheel scrolls; shift+drag to select text":"mouse capture off \u2014 click-drag selects text; PgUp/PgDn scrolls");return}case"show-help":Ps();return;case"escalate-search":I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(g.query);return;case"attachment-request":Be(g.source);return}},ue=async g=>{if(!Gr){I.notify("agent does not accept image attachments");return}let w=0;for(let x of g){if(x.startsWith("data:")){let A=Rf(x);if(!A){I.notify("unsupported data: URI");continue}if(A.sizeBytes>Xn){I.notify(`image too large (${kn(A.sizeBytes)}, max ${kn(Xn)})`);continue}Ce.addAttachment({mimeType:A.mimeType,data:A.data,name:"pasted image",sizeBytes:A.sizeBytes}),w++;continue}let C=ba(x);if(!C){I.notify(`unsupported image type: ${Yr.basename(x)}`);continue}try{let A=await Gf.readFile(x);if(A.length>Xn){I.notify(`image too large (${kn(A.length)}, max ${kn(Xn)})`);continue}Ce.addAttachment({mimeType:C,data:A.toString("base64"),name:Yr.basename(x),sizeBytes:A.length}),w++}catch(A){I.notify(`cannot read ${Yr.basename(x)}: ${A.message}`)}}w>0&&(I.setAttachments(Ce.state().attachments),I.refreshPrompt())},Be=async(g="clipboard")=>{let w=g==="primary"?await Zw():await Xw();if(!w.ok){I.notify(w.reason);return}if(w.kind==="image"){if(!Gr){I.notify("agent does not accept image attachments");return}Ce.addAttachment(w.attachment),I.setAttachments(Ce.state().attachments),I.refreshPrompt();return}let x=Ce.feed({type:"paste",text:w.text});for(let C of x)ae(C);I.refreshPrompt()},jt=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,$t=(g,w)=>{let x=Array.isArray(w)?w:[],C="",A=0;for(let M of x){if(!M||typeof M!="object")continue;let H=M;H.type==="text"&&typeof H.text=="string"?C+=H.text:H.type==="image"&&(A+=1)}return{messageId:g,text:Ee(C),attachmentCount:A}},Qe=new Map,mt=[],hn=new Map,St=new Set,We=null,An=()=>{let g=[...Qe.values()],w=g.map(jt);I.setQueuedPrompts(w),I.setBanner({queued:g.length}),Ce.setQueue(g.map(x=>x.text))},ai=g=>[...Qe.values()][g]?.messageId;if(Cs&&Cs.length>0){for(let g of Cs){if(g.position===0){G=g.messageId;continue}Qe.set(g.messageId,$t(g.messageId,g.prompt))}Qe.size>0&&An()}let Cn=(g,w,x)=>{I.scrollToBottom(),!Oa(g)&&(Bt(g,x),Ro(g,w,x))},mr=(g,w,x)=>{if(I.scrollToBottom(),Oa(g))return;if(Bt(g,x),!wo||G===void 0){Ro(g,w,x);return}let C=G,A=[];g.length>0&&A.push({type:"text",text:g});for(let F of w)A.push({type:"image",data:F.data,mimeType:F.mimeType});let M={text:g,displayText:x??g,attachments:w,flushed:!1};mt.push(M);let H=()=>{let F=mt.indexOf(M);F>=0&&mt.splice(F,1),M.messageId!==void 0&&hn.delete(M.messageId)};m.request("hydra-acp/prompt/amend",{sessionId:Ae,targetMessageId:C,prompt:A}).then(F=>{let Y=F;if(Y.amended&&Y.reason==="ok"){De(1);return}if(H(),Y.reason==="target_completed"){I.notify("previous response finished \u2014 press Enter to send as a new turn"),Ce.setBuffer(g,w),I.refreshPrompt();return}if(Y.reason==="target_cancelled"){I.notify("amend skipped \u2014 previous turn was cancelled"),Ce.setBuffer(g,w),I.refreshPrompt();return}if(Y.reason==="target_not_found"){I.notify("amend skipped \u2014 no matching prompt"),Ce.setBuffer(g,w),I.refreshPrompt();return}}).catch(F=>{H(),I.notify(`amend failed: ${F.message}`),Ce.setBuffer(g,w),I.refreshPrompt()})},_s=async g=>{if(ns.length===0){I.notify("no modes advertised by agent");return}let w=I.currentModeId(),x=ns.findIndex(M=>M.id===w),C=x===-1?0:(x+1)%ns.length,A=ns[C]?.id;if(A){I.setBanner({currentMode:A});try{await m.request("session/set_mode",{sessionId:Ae,modeId:A})}catch(M){I.notify(`set_mode failed: ${M.message}`)}}},Oa=g=>{let w=g.replace(/\s+$/,"");if(!w.startsWith("/")||w.includes(`
243
+ `))return!1;let x=w.indexOf(" ");switch(x===-1?w:w.slice(0,x)){case"/quit":case"/exit":return Es(),!0;case"/clear":return gt.clear(),Rn.clear(),dt.length=0,E=null,j=null,ie=null,ds.clear(),cs.clear(),ls.clear(),yr.clear(),Nn.clear(),$s.clear(),I.clearScrollback(),!0;case"/help":{let A=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let M of dr)A.push({prefix:" ",body:` ${M.name.padEnd(12)} ${M.description??""}`,bodyStyle:"info"});if(qe.length>0){A.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let M of qe)A.push({prefix:" ",body:` ${M.name.padEnd(12)} ${M.description??""}`,bodyStyle:"info"})}return I.appendLines(A),!0}case"/agent":{let A=x===-1?"":w.slice(x+1).trim(),M=Jt();if(!M)return I.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!A){let H=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let F of M.options){let Y=F.value===M.currentValue?"* ":" ";H.push({prefix:" ",body:`${Y}${F.value.padEnd(16)} ${F.name}`,bodyStyle:"info"})}return I.appendLines(H),!0}return M.options.some(H=>H.value===A)?A===M.currentValue?(I.notify(`already on agent ${A}`),!0):(I.notify(`switching to ${A}\u2026`),m.request("session/set_config_option",{sessionId:Ae,configId:"agent",value:A}).catch(H=>{I.notify(`set_config_option failed: ${H.message}`)}),!0):(I.notify(`unknown agent: ${A}`),!0)}case"/sessions":return I.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return P().catch(A=>{se({src:"switch-session-failed",stack:A instanceof Error?A.stack??A.message:String(A)})}),!0;case"/session":{let A=x===-1?"":w.slice(x+1).trim();return A?A==="next"||A==="prev"?(D(A).catch(M=>{I.notify(`session ${A} failed: ${M.message}`)}),!0):(Q(A).catch(M=>{I.notify(`session switch failed: ${M.message}`)}),!0):(P().catch(M=>{se({src:"switch-session-failed",stack:M instanceof Error?M.stack??M.message:String(M)})}),!0)}case"/rename":{let A=x===-1?"":w.slice(x+1).trim(),M=A.length>0?`/hydra title ${A}`:"/hydra title";return Bt(w,w),Ro(M,[],w),!0}case"/btw":{let A=x===-1?"":w.slice(x+1).trim();if(!A)return I.isOverlayOpen()?($&&($.cancel(),$=null,B=null),I.closeBtwOverlay(),!0):(I.reopenBtwOverlay()||I.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(Ae==="__new__")return I.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;U+=1;let M=U;$&&($.cancel(),$=null);let H=null;B!==null&&!K?H=B:B!==null&&(Yn(n,B).catch(()=>{}),B=null),K=!1,I.openBtwOverlay(),I.setBtwOverlayStatus({label:"busy",style:"busy"});let F=new Tc({getMaxWidth:()=>{let pe=I.width();return pe>0?pe:void 0}});F.on("changed",()=>{I.setBtwOverlayContent(F.getLines())});let Y={};F.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:A}]});let ge=pe=>{F.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:pe}})},Pe={};return H!==null&&(Pe.reuseSessionId=H),jw(n,Ae,A,Pe).then(pe=>{if(M!==U){pe.cancel();return}$=pe,B=pe.sessionId,I.setBtwOverlayMeta({sessionId:pe.sessionId}),pe.on("event",ye=>{if(M===U)if(ye.kind==="update"){F.append(ye.update);let Ie=Kn(ye.update);if(Ie&&Ie.kind==="usage-update"){let Gt=!1;Ie.used!==void 0&&Y.used!==Ie.used&&(Y.used=Ie.used,Gt=!0),Ie.size!==void 0&&Y.size!==Ie.size&&(Y.size=Ie.size,Gt=!0),Ie.costAmount!==void 0&&Y.costAmount!==Ie.costAmount&&(Y.costAmount=Ie.costAmount,Gt=!0),Ie.costCurrency!==void 0&&Y.costCurrency!==Ie.costCurrency&&(Y.costCurrency=Ie.costCurrency,Gt=!0),Gt&&I.setBtwOverlayMeta({usage:{...Y}})}}else ye.kind==="completed"?(I.setBtwOverlayStatus({label:"done",style:"done"}),$=null):ye.kind==="cancelled"?(I.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),$=null,B=null):ye.kind==="errored"&&(I.setBtwOverlayStatus({label:"errored",style:"errored"}),ge(`btw errored: ${ye.error.message}`),B!==null&&Yn(n,B).catch(()=>{}),$=null,B=null)})}).catch(pe=>{if(M!==U)return;let ye=pe instanceof Error?pe.message:String(pe);I.setBtwOverlayStatus({label:"errored",style:"errored"}),ge(`btw startup failed: ${ye}`),I.appendLines([{prefix:" ",body:`btw startup failed: ${ye}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(Ae==="__new__")return I.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let A=x===-1?"":w.slice(x+1).trim(),M=Ae;return(async()=>{try{let H=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(M)}/transcript`,{headers:{Authorization:`Bearer ${n.token}`}});if(!H.ok){let ye=await H.text().catch(()=>"");I.appendLines([{prefix:" ",body:`/export failed: HTTP ${H.status} ${ye}`.trim(),bodyStyle:"info"}]);return}let F=await H.text(),Y=new Date().toISOString().replace(/[:.]/g,"-"),ge=`hydra-${rt(M)}-${Y}.md`,Pe=A.length>0?et(A):ge,pe=Yr.resolve(Pe);await Gf.mkdir(Yr.dirname(pe),{recursive:!0}),await Gf.writeFile(pe,F,{encoding:"utf8",mode:384}),I.appendLines([{prefix:" ",body:`Wrote ${pe}`,bodyStyle:"system"}])}catch(H){I.appendLines([{prefix:" ",body:`/export failed: ${H.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},Ro=async(g,w,x)=>{let C=[];g.length>0&&C.push({type:"text",text:g});for(let Pe of w)C.push({type:"image",data:Pe.data,mimeType:Pe.mimeType});De(1);let A={text:g,displayText:x??g,attachments:w,flushed:!1};mt.push(A),Mt=!1;let M=!1,H=null,F=Pe=>{typeof V<"u"&&V!==null&&V.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Pe,bodyStyle:"tool-status-fail"}])},Y=!1;Kt={text:g,attachments:w,cancel:()=>{if(Mt){Mt=!1,Y=!0,F("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),m.request("hydra-acp/session/force_cancel",{sessionId:Ae}).catch(pe=>{F(`force-stop failed: ${pe.message}`)});return}if(M)return;M=!0,m.notify("session/cancel",{sessionId:Ae}).catch(()=>{});let Pe=Date.now();H=setTimeout(()=>{Kt!==null&&(xs>=Pe||(Mt=!0,F("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},dn)}};let ge;try{let Pe=await m.request("session/prompt",{sessionId:Ae,prompt:C});Pe&&typeof Pe.stopReason=="string"&&(ge=Pe.stopReason)}catch(Pe){let pe=mt.indexOf(A);pe>=0&&mt.splice(pe,1),A.messageId!==void 0&&hn.delete(A.messageId),Y?I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):I.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:Pe.message,bodyStyle:"tool-status-fail"}])}finally{if(Kt=null,H!==null&&(clearTimeout(H),H=null),De(-1),A.flushed&&We===A){let Pe=A.messageId!==void 0&&St.has(A.messageId);Pe&&A.messageId!==void 0&&St.delete(A.messageId);let pe={kind:"turn-complete"};ge!==void 0&&(pe.stopReason=ge),Pe&&(pe.amended=!0),k(pe),We=null}if(fn!==null){let{text:Pe,attachments:pe}=fn;fn=null,Ce.state().buffer.every(Ie=>Ie==="")&&(Ce.setBuffer(Pe,pe),I.refreshPrompt())}}},gt=new Map,ds=new Map,cs=new Map,Rn=new Map,dt=[],gr=0,Tn=`tools:${gr}`,ls=new Map,yr=new Map,di=new Set,us=new Map,Nn=new Map,$s=new Map,E=null,j=null,ie=null,W=null,te=null,re=e.tui.maxToolItems,ke=e.tui.maxPlanItems,ze=()=>({maxPlanItems:te??i.planExpanded?1/0:ke}),Xe=()=>{if(W===null)return;let g=Qs(W,ze());g.length>0&&I.upsertLines("plan",[{body:""},...g])},ct="",Re=null,At=0,qt=()=>{if(Re===null)return;let g=I.width(),w=Gs(ct,g>0?{maxWidth:g}:void 0);w.length!==0&&I.upsertLines(Re,w)},ip=g=>{g.length!==0&&(Re===null&&(I.ensureSeparator(),Re=`agent:${At}`,At+=1,ct=""),ct+=g,qt())},mn=()=>{Re=null,ct=""},Os="",gn=null,wr=0,br=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),Qc=()=>{if(gn===null||Os.length===0)return;let g=eo(Os);g.length!==0&&I.upsertLines(gn,g)},Gc=g=>{let w=Nn.get(g);if(w===void 0)return[];let x=eo(w.text);return w.workerTaskId&&x.unshift({prefix:" ",body:`[T${w.workerTaskId}] `,bodyStyle:"dim"}),x},Fa=(g,w)=>{g.length!==0&&(gn===null&&(I.ensureSeparator("thought"),gn=`thought:${wr}`,wr+=1,Os=""),Os+=g,Nn.set(gn,{text:Os,workerTaskId:w}),Qc())},$e=()=>{gn=null,Os=""},fs=g=>kT({...g,collapsedLimit:re}),Fs=g=>yr.get(g)??i.toolsExpanded,Wt=()=>{if(E===null)return;let{lines:g,rowOwners:w}=fs({order:dt,states:gt,startedAt:E,endedAt:j,stopReason:ie,expanded:Fs(Tn),perToolExpanded:di});I.upsertLines(Tn,g),us.set(Tn,w)},La=g=>{let w=ls.get(g);if(!w)return;let{lines:x,rowOwners:C}=fs({order:w.order,states:w.states,startedAt:w.startedAt,endedAt:w.endedAt,stopReason:w.stopReason,expanded:Fs(g),perToolExpanded:di});I.upsertLines(g,x),us.set(g,C)},iv=()=>{E!==null&&!ls.has(Tn)&&Wt();for(let g of ls.keys())La(g)},Xc=()=>{E!==null&&ls.set(Tn,{order:[...dt],states:new Map(gt),startedAt:E,endedAt:j??Date.now(),stopReason:ie,rowOwners:us.get(Tn)??[]})},op=()=>{gr+=1,Tn=`tools:${gr}`,E=Date.now(),j=null,ie=null,Wt()};function ov(g){if(!g||typeof g!="object")return null;let w=g,x=Array.isArray(w.content)?w.content:void 0;if(!x)return null;let C=[],A=M=>{if(typeof M=="string"){C.push({text:lt(M)});return}if(M&&typeof M=="object"){let H=M;typeof H.__hydraBlob=="string"&&C.push({hash:H.__hydraBlob})}};for(let M of x){if(!M||typeof M!="object")continue;let H=M;if(H.type==="content"&&H.content&&typeof H.content=="object"){let F=H.content;if(F.text!==void 0){A(F.text);continue}}if(H.type==="text"&&H.text!==void 0){A(H.text);continue}H.text!==void 0&&A(H.text)}return C.length>0?C:null}let ap=(g,w)=>{let x=w.map(M=>"text"in M?M.text:"").join(`
244
+ `);if(x.length===0)return;let{text:C,truncated:A}=my(x);g.resultText=C,g.resultTruncated=A},Ba=new Set,av=(g,w)=>{!w.some(C=>"hash"in C)||Ba.has(g)||(Ba.add(g),(async()=>{let C=await Promise.all(w.map(async M=>"text"in M?M:{text:await Zc(M.hash)??""}));Ba.delete(g);let A=gt.get(g);if(!A)for(let M of ls.values()){let H=M.states.get(g);if(H){A=H;break}}if(A){ap(A,C),gt.has(g)&&Wt();for(let[M,H]of ls)H.states.has(g)&&La(M);I.repaintNow()}})().catch(()=>{Ba.delete(g)}))},dp=(g,w,x,C,A,M,H,F,Y,ge)=>{let Pe=!gt.has(g),pe=gt.get(g),ye=pe??{initialTitle:w??"tool",latestTitle:w??"tool",status:x??"pending",startedAt:Date.now()};if(!pe&&Y!==void 0&&(ye.workerTaskId=Y),pe&&w!==void 0&&(ye.latestTitle=w),M!==void 0&&ye.detail===void 0&&(ye.detail=M),H!==void 0&&ye.detailFull===void 0&&(ye.detailFull=H),F!==void 0&&F.length>0&&(ye.locations=F),pe&&x!==void 0&&(ye.status=x),pe||(ye.status=x??"pending"),ye.endedAt===void 0&&Ju(ye.status)&&(ye.endedAt=Date.now()),C!==void 0&&(ye.errorText=C),A!==void 0&&(ye.editDiff=A),ge!==void 0){let Ie=ov(ge);Ie!==null&&(ap(ye,Ie),Ie.some(Gt=>"hash"in Gt)&&av(g,Ie))}gt.set(g,ye),Pe&&(E===null&&(gr+=1,Tn=`tools:${gr}`,E=Date.now(),j=null,ie=null),dt.push(g))},Zc=async g=>{try{let w=await m.request("hydra-acp/session/tool_content",{sessionId:Ae,hash:g});return typeof w?.content=="string"?w.content:null}catch{return null}},Na=new Set,dv=(g,w)=>{Na.has(g)||w.oldRef===void 0&&w.newRef===void 0||(Na.add(g),(async()=>{let[x,C]=await Promise.all([w.oldRef?Zc(w.oldRef.hash):Promise.resolve(w.oldText),w.newRef?Zc(w.newRef.hash):Promise.resolve(w.newText)]);if(w.oldRef!==void 0&&x===null||w.newRef!==void 0&&C===null){Na.delete(g);let ge=zu(w,"diff",{deferredStatus:"error"});ge.length>0&&(I.upsertLines(`editdiff:${g}`,ge),I.repaintNow());return}let M={...w.path!==void 0?{path:w.path}:{},oldText:x??"",newText:C??""};ds.set(g,M);let H=gt.get(g);H?.editDiff&&(H.editDiff=M),Na.delete(g);let F=cs.get(g),Y=F===void 0?i.showFileUpdates:F?"diff":"edit";Y!=="none"&&(Da(g,M,Y==="diff"?"diff":"edit"),I.repaintNow())})())},Da=(g,w,x)=>{let C=`editdiff:${g}`,A=zu(w,x);if(A.length===0){I.removeKey(C);return}I.upsertLines(C,A),x==="diff"&&(w.oldRef!==void 0||w.newRef!==void 0)&&I.notifyWhenVisible(C)},cv=g=>{if(!g.startsWith("editdiff:"))return;let w=g.slice(9),x=ds.get(w);x&&(x.oldRef!==void 0||x.newRef!==void 0)&&dv(w,x)},cp=g=>{let w=`editdiff:${g}`,x=i.showFileUpdates,C=gt.get(g),A;if(x==="none"||!C?.editDiff||C.status!=="completed")A=null;else{let H=cs.get(g);A=H!==void 0?H?"diff":"edit":x==="diff"?"diff":"edit"}if(A===null){I.removeKey(w);return}let M=C.editDiff;ds.set(g,M),Da(g,M,A)},lv=()=>{let g=i.showFileUpdates;for(let[w,x]of ds){let C=`editdiff:${w}`,A=cs.get(w),M=A===void 0?g:A?"diff":"edit";if(M==="none"){I.removeKey(C);continue}Da(w,x,M==="diff"?"diff":"edit")}},uv=g=>{if(!g.path)return null;let w=lt(g.oldText).split(`
245
245
  `),x=lt(g.newText).split(`
246
- `),C=0,A=Math.min(w.length,x.length);for(;C<A&&w[C]===x[C];)C++;let M=x[C];if(!M)return null;let H=Vr.isAbsolute(g.path)?g.path:Vr.resolve(ut,g.path),O;try{O=nT(H,"utf8")}catch{return null}let V=O.split(`
247
- `);for(let ge=0;ge<V.length;ge++)if(V[ge]===M)return ge+1;return null},cv=(g,w)=>{if(g.startsWith("editdiff:")){let x=g.slice(9),C=as.get(x),M=gt.get(x)?.locations?.[0],H=M?.path??C?.path;if(!H)return!1;let O=null;M?.line!==void 0?O=M.line:C&&(O=dv(C));let V=O===null?"":`:${O}`;return I.tryOpenPathString(H+V)}if(g.startsWith("tools:")){if(w===0)return!1;let x=ls.get(g),C=x?x[w]:void 0;if(!C)return!1;let A=gt.get(C),M=A?.locations?.[0];if(M){let O=M.line===void 0?"":`:${M.line}`;if(I.tryOpenPathString(M.path+O))return!0}let H=A?.detailFull??A?.detail;if(H)return I.tryOpenPathString(H)}return!1},lv=(g,w)=>{if(g.startsWith("editdiff:")){let x=g.slice(9),C=as.get(x);if(!C)return;let A=ds.get(x)??i.showFileUpdates==="diff";ds.set(x,!A),Na(x,C,A?"edit":"diff"),I.repaintNow();return}if(g==="plan"){if(W===null)return;te=!(te??i.planExpanded),Xe(),I.repaintNow();return}if(g.startsWith("tools:")){if(w===0){let A=yr.get(g)??i.toolsExpanded;yr.set(g,!A),g===Tn&&E!==null?Wt():Oa(g),I.repaintNow();return}let x=ls.get(g);if(!x)return;let C=x[w];if(!C)return;hT(C,di),Oa(g),I.repaintNow();return}if(g.startsWith("thought:")){if(!Nn.has(g))return;let x=$s.get(g);if(x!==void 0){$s.delete(g),I.setRunCollapsed(x,!1,Qc(g)),I.repaintNow();return}let C=I.contiguousRun(g,new Set(Nn.keys()));if(C.length===0)return;let A=C[0];$s.set(A,C),I.setRunCollapsed(C,!0,[br()]),I.repaintNow();return}};b=(g,w)=>{if(g.kind==="available-commands"){je=g.commands,So();return}if(g.kind==="available-modes"){ts=g.modes;return}if(g.kind==="config-options"){vo=g.options;let C=g.options.find(M=>M.id==="agent");C&&C.currentValue&&C.currentValue!==st&&(st=C.currentValue,I.setSessionbar({agent:C.currentValue}));let A=g.options.find(M=>M.id==="mode");A&&(ts=A.options.map(M=>({id:M.value,name:M.name??M.value,...M.description!==void 0?{description:M.description}:{}})));return}if(g.kind==="mode-changed"){I.setBanner({currentMode:g.mode||void 0});return}if(g.kind==="session-info"){g.title!==void 0&&I.setSessionbar({title:g.title}),g.agentId!==void 0&&g.agentId!==st&&(st=g.agentId,I.setSessionbar({agent:g.agentId})),g.pendingAgentSwap!==void 0&&(typeof g.pendingAgentSwap=="string"?I.setCompactionIndicator(`switching to ${g.pendingAgentSwap}...`):(I.setCompactionIndicator(null),g.agentId!==void 0&&I.notify(`switched to ${g.agentId}`,2e3)));return}if(g.kind==="usage-update"){let C=!1;g.used!==void 0&&Ht.used!==g.used&&(Ht.used=g.used,C=!0),g.size!==void 0&&Ht.size!==g.size&&(Ht.size=g.size,C=!0),g.costAmount!==void 0&&Ht.costAmount!==g.costAmount&&(Ht.costAmount=g.costAmount,C=!0),g.costCurrency!==void 0&&Ht.costCurrency!==g.costCurrency&&(Ht.costCurrency=g.costCurrency,C=!0),C&&I.setSessionbar({usage:{...Ht}});return}if(g.kind==="user-text"){ar&&Bt(g.text),mn(),$e(),E!==null&&(j=Date.now(),Wt()),qe=null,I.ensureSeparator();let C=Qs(g);C.length>0&&I.appendLines(C),Gc(),I.clearKey("plan"),W=null,te=null,gt.clear(),Rn.clear(),dt.length=0,j=null,ip(),I.redraw();return}if(g.kind==="agent-text"){$e(),Re===null&&F(g.workerTaskId),rp(g.text);return}if(g.kind==="agent-thought"){mn(),gn===null&&F(g.workerTaskId),Fa(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){mn(),$e();let C=Rn.get(g.toolCallId),A={plan:g.plan??C?.plan??"",status:g.status??C?.status};if(Rn.set(g.toolCallId,A),A.plan.length===0)return;let M=by(A);M.length>0&&I.upsertLines(g.toolCallId,M);return}if(g.kind==="tool-call"){mn(),$e(),gt.has(g.toolCallId)||F(g.workerTaskId),ap(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),Wt(),dp(g.toolCallId);return}if(g.kind==="plan"){mn(),$e(),W=g;let C=Qs(g,We());C.length>0&&I.upsertLines("plan",[{body:""},...C]);let A=g.entries.length>0&&g.entries.every(M=>(M.status??"pending")==="completed");I.setStickyBottomKey(A?null:"plan");return}if(g.kind==="tool-call-update"){mn(),$e(),ap(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),g.upstreamInterrupted&&(ks=!0),Wt(),dp(g.toolCallId);return}g.kind==="model-changed"&&I.setSessionbar({model:g.model});let x=Qs(g);if(x.length>0&&I.appendLines(x),g.kind==="turn-complete"){G=void 0,mn(),$e();let C=g.amended?"amended":g.stopReason;if(!g.amended&&ks&&(C===void 0||C==="end_turn")&&(C="error"),W!==null&&C!==void 0&&C!=="end_turn"){let A=Qs({...W,stopped:!0,amended:g.amended===!0},We());A.length>0&&I.upsertLines("plan",[{body:""},...A])}W=null,te=null,I.clearKey("plan"),I.setStickyBottomKey("plan"),E!==null?(j=Date.now(),ie=C??null,Wt(),Gc()):C!==void 0&&C!=="end_turn"&&C!=="amended"&&I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${C}`,bodyStyle:"tool-status-fail"}]),gt.clear(),Rn.clear(),dt.length=0,E=null,j=null,ie=null,ks=!1,I.ensureSeparator(),Ob({pendingTurns:L,queueSize:Ye.size,ownTurnInFlight:Kt!==null,hasInFlightHead:G!==void 0,replayDraining:S,amended:g.amended===!0})&&De(-L)}};let cp=y;y=[];let Da=[];for(let{event:g}of cp)g.kind==="user-text"&&typeof g.text=="string"&&Da.push(g.text);I.pauseRepaint(),S=!0;try{for(let{event:g,rawUpdate:w}of cp)b(g,w)}finally{S=!1,I.resumeRepaint()}if(Da.length>0){let g=cu(xt,Da);g!==xt&&(xt=g,me=cu(me,Da),Ce.setHistory(yd(un,me)),Pr(Rs,xt).catch(()=>{}))}ar=!0,(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(Ae)}/compact/status`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json(),x=w.compactionState?.status;if(x==="requested"||x==="running"?I.setCompactionIndicator("compacting..."):(x==="swap_pending"||x==="swap_deferred")&&I.setCompactionIndicator("compaction queued (waiting for idle)"),!or||w.shouldCompact!==!0)return;let C=w.approxTokens??0;N=!0,I.setCompactionPrompt({message:`This session has ~${Hm(C)} tokens of history above the compaction watermark.`,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(Ae)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState==="running"?(I.setSynthesisIndicator("synthesizing context\u2026"),rr()):w.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),In!==void 0&&L>0?(Se=In,I.setBanner({status:"busy",elapsedMs:Date.now()-In}),X===null&&(X=sr()),E===null&&ip(),E=In,Wt()):In===void 0&&L>0&&De(-L);let uv=()=>{if(_e){let g=_e.resolve;_e=null,I.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}mn(),$e()},lp=()=>{E!==null&&(j=Date.now(),ie="reconnect-recovery-failed",Wt(),Gc(),gt.clear(),Rn.clear(),dt.length=0,E=null,j=null,ie=null)};return p=g=>{se({src:"reconnect",step:"disconnect",message:g?.message}),I.setBanner({status:"disconnected",elapsedMs:void 0})},f=async()=>{if(se({src:"reconnect",step:"begin",sessionId:Ae}),n.isLocal)try{let O=await Ft(await be());(O.baseUrl!==n.baseUrl||O.wsUrl!==n.wsUrl)&&(se({src:"reconnect",step:"target-refresh",oldBase:n.baseUrl,newBase:O.baseUrl}),n.baseUrl=O.baseUrl,n.wsUrl=O.wsUrl,n.display=O.display)}catch(O){se({src:"reconnect",step:"target-refresh-failed",message:O instanceof Error?O.message:String(O)})}uv();let g={jsonrpc:"2.0",id:`tui-reinit-${Nb()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:fe}}};se({src:"reconnect",step:"initialize-send"});try{await h.request(g),se({src:"reconnect",step:"initialize-ok"})}catch(O){se({src:"reconnect",step:"initialize-fail",message:O.message})}let w=es!==void 0,x={jsonrpc:"2.0",id:`tui-reattach-${Nb()}`,method:"session/attach",params:{sessionId:Ae,historyPolicy:w?"after_message":"none",...w?{afterMessageId:es}:{},clientInfo:{name:"hydra-acp-tui",version:fe},...(()=>{let O={};return Ln!==void 0&&(O.resume={upstreamSessionId:Ln,agentId:st,cwd:ut}),e.tui.toolContent==="references"&&(O.toolContent="references"),Object.keys(O).length>0?{_meta:{[Tt]:O}}:{}})()}};ve=[];let C,A,M;se({src:"reconnect",step:"attach-send",useAfterMessage:w,lastSeenMessageId:es});try{let O=await h.request(x);if(se({src:"reconnect",step:"attach-resp",hasError:!!O.error}),O.error)throw new Error(O.error.message);M=Fb(O.result),C=M.appliedPolicy,M.clientId!==void 0&&(ln=M.clientId)}catch(O){A=O,se({src:"reconnect",step:"attach-fail",message:A.message})}let H=ve??[];if(ve=null,A)lp(),I.appendLines([{prefix:" ",body:`reattach failed: ${A.message}`,bodyStyle:"tool-status-fail"}]);else if(w&&C!=="after_message")lp(),I.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{S=!0;try{for(let O of H)ot(O)}finally{S=!1}}if(M){let O=Lb({daemonTurnStartedAt:M.turnStartedAt,pendingTurns:L});O.pendingTurnsDelta!==0&&De(O.pendingTurnsDelta),O.banner==="busy"&&O.busySince!==void 0?(Se=O.busySince,I.setBanner({status:"busy",elapsedMs:Date.now()-O.busySince}),X===null&&(X=sr())):I.setBanner({status:"ready",elapsedMs:void 0})}else I.setBanner({status:L>0?"busy":"ready",elapsedMs:L>0?0:void 0});se({src:"reconnect",step:"end"})},m.onClose(g=>{g&&t.red(`
246
+ `),C=0,A=Math.min(w.length,x.length);for(;C<A&&w[C]===x[C];)C++;let M=x[C];if(!M)return null;let H=Yr.isAbsolute(g.path)?g.path:Yr.resolve(ut,g.path),F;try{F=dT(H,"utf8")}catch{return null}let Y=F.split(`
247
+ `);for(let ge=0;ge<Y.length;ge++)if(Y[ge]===M)return ge+1;return null},fv=(g,w)=>{if(g.startsWith("editdiff:")){let x=g.slice(9),C=ds.get(x),M=gt.get(x)?.locations?.[0],H=M?.path??C?.path;if(!H)return!1;let F=null;M?.line!==void 0?F=M.line:C&&(F=uv(C));let Y=F===null?"":`:${F}`;return I.tryOpenPathString(H+Y)}if(g.startsWith("tools:")){if(w===0)return!1;let x=us.get(g),C=x?x[w]:void 0;if(!C)return!1;let A=gt.get(C),M=A?.locations?.[0];if(M){let F=M.line===void 0?"":`:${M.line}`;if(I.tryOpenPathString(M.path+F))return!0}let H=A?.detailFull??A?.detail;if(H)return I.tryOpenPathString(H)}return!1},pv=(g,w)=>{if(g.startsWith("editdiff:")){let x=g.slice(9),C=ds.get(x);if(!C)return;let A=cs.get(x)??i.showFileUpdates==="diff";cs.set(x,!A),Da(x,C,A?"edit":"diff"),I.repaintNow();return}if(g==="plan"){if(W===null)return;te=!(te??i.planExpanded),Xe(),I.repaintNow();return}if(g.startsWith("tools:")){if(w===0){let A=yr.get(g)??i.toolsExpanded;yr.set(g,!A),g===Tn&&E!==null?Wt():La(g),I.repaintNow();return}let x=us.get(g);if(!x)return;let C=x[w];if(!C)return;vT(C,di),La(g),I.repaintNow();return}if(g.startsWith("thought:")){if(!Nn.has(g))return;let x=$s.get(g);if(x!==void 0){$s.delete(g),I.setRunCollapsed(x,!1,Gc(g)),I.repaintNow();return}let C=I.contiguousRun(g,new Set(Nn.keys()));if(C.length===0)return;let A=C[0];$s.set(A,C),I.setRunCollapsed(C,!0,[br()]),I.repaintNow();return}};b=(g,w)=>{if(g.kind==="available-commands"){qe=g.commands,ko();return}if(g.kind==="available-modes"){ns=g.modes;return}if(g.kind==="config-options"){So=g.options;let C=g.options.find(M=>M.id==="agent");C&&C.currentValue&&C.currentValue!==st&&(st=C.currentValue,I.setSessionbar({agent:C.currentValue}));let A=g.options.find(M=>M.id==="mode");A&&(ns=A.options.map(M=>({id:M.value,name:M.name??M.value,...M.description!==void 0?{description:M.description}:{}})));return}if(g.kind==="mode-changed"){I.setBanner({currentMode:g.mode||void 0});return}if(g.kind==="session-info"){g.title!==void 0&&I.setSessionbar({title:g.title}),g.agentId!==void 0&&g.agentId!==st&&(st=g.agentId,I.setSessionbar({agent:g.agentId})),g.pendingAgentSwap!==void 0&&(typeof g.pendingAgentSwap=="string"?I.setCompactionIndicator(`switching to ${g.pendingAgentSwap}...`):(I.setCompactionIndicator(null),g.agentId!==void 0&&I.notify(`switched to ${g.agentId}`,2e3)));return}if(g.kind==="usage-update"){let C=!1;g.used!==void 0&&Ht.used!==g.used&&(Ht.used=g.used,C=!0),g.size!==void 0&&Ht.size!==g.size&&(Ht.size=g.size,C=!0),g.costAmount!==void 0&&Ht.costAmount!==g.costAmount&&(Ht.costAmount=g.costAmount,C=!0),g.costCurrency!==void 0&&Ht.costCurrency!==g.costCurrency&&(Ht.costCurrency=g.costCurrency,C=!0),C&&I.setSessionbar({usage:{...Ht}});return}if(g.kind==="user-text"){ar&&Bt(g.text),mn(),$e(),E!==null&&(j=Date.now(),Wt()),We=null,I.ensureSeparator();let C=Qs(g);C.length>0&&I.appendLines(C),Xc(),I.clearKey("plan"),W=null,te=null,gt.clear(),Rn.clear(),dt.length=0,j=null,op(),I.redraw();return}if(g.kind==="agent-text"){$e(),Re===null&&O(g.workerTaskId),ip(g.text);return}if(g.kind==="agent-thought"){mn(),gn===null&&O(g.workerTaskId),Fa(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){mn(),$e();let C=Rn.get(g.toolCallId),A={plan:g.plan??C?.plan??"",status:g.status??C?.status};if(Rn.set(g.toolCallId,A),A.plan.length===0)return;let M=Sy(A);M.length>0&&I.upsertLines(g.toolCallId,M);return}if(g.kind==="tool-call"){mn(),$e(),gt.has(g.toolCallId)||O(g.workerTaskId),dp(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),Wt(),cp(g.toolCallId);return}if(g.kind==="plan"){mn(),$e(),W=g;let C=Qs(g,ze());C.length>0&&I.upsertLines("plan",[{body:""},...C]);let A=g.entries.length>0&&g.entries.every(M=>(M.status??"pending")==="completed");I.setStickyBottomKey(A?null:"plan");return}if(g.kind==="tool-call-update"){mn(),$e(),dp(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),g.upstreamInterrupted&&(ks=!0),Wt(),cp(g.toolCallId);return}g.kind==="model-changed"&&I.setSessionbar({model:g.model});let x=Qs(g);if(x.length>0&&I.appendLines(x),g.kind==="turn-complete"){G=void 0,mn(),$e();let C=g.amended?"amended":g.stopReason;if(!g.amended&&ks&&(C===void 0||C==="end_turn")&&(C="error"),W!==null&&C!==void 0&&C!=="end_turn"){let A=Qs({...W,stopped:!0,amended:g.amended===!0},ze());A.length>0&&I.upsertLines("plan",[{body:""},...A])}W=null,te=null,I.clearKey("plan"),I.setStickyBottomKey("plan"),E!==null?(j=Date.now(),ie=C??null,Wt(),Xc()):C!==void 0&&C!=="end_turn"&&C!=="amended"&&I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${C}`,bodyStyle:"tool-status-fail"}]),gt.clear(),Rn.clear(),dt.length=0,E=null,j=null,ie=null,ks=!1,I.ensureSeparator(),Nb({pendingTurns:L,queueSize:Qe.size,ownTurnInFlight:Kt!==null,hasInFlightHead:G!==void 0,replayDraining:S,amended:g.amended===!0})&&De(-L)}};let lp=y;y=[];let Ha=[];for(let{event:g}of lp)g.kind==="user-text"&&typeof g.text=="string"&&Ha.push(g.text);I.pauseRepaint(),S=!0;try{for(let{event:g,rawUpdate:w}of lp)b(g,w)}finally{S=!1,I.resumeRepaint()}if(Ha.length>0){let g=lu(xt,Ha);g!==xt&&(xt=g,me=lu(me,Ha),Ce.setHistory(yd(un,me)),Pr(Rs,xt).catch(()=>{}))}ar=!0,(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(Ae)}/compact/status`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json(),x=w.compactionState?.status;if(x==="requested"||x==="running"?I.setCompactionIndicator("compacting..."):(x==="swap_pending"||x==="swap_deferred")&&I.setCompactionIndicator("compaction queued (waiting for idle)"),!or||w.shouldCompact!==!0)return;let C=w.approxTokens??0;N=!0,I.setCompactionPrompt({message:`This session has ~${jm(C)} tokens of history above the compaction watermark.`,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(Ae)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState==="running"?(I.setSynthesisIndicator("synthesizing context\u2026"),rr()):w.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),In!==void 0&&L>0?(Se=In,I.setBanner({status:"busy",elapsedMs:Date.now()-In}),X===null&&(X=sr()),E===null&&op(),E=In,Wt()):In===void 0&&L>0&&De(-L);let hv=()=>{if(_e){let g=_e.resolve;_e=null,I.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}mn(),$e()},up=()=>{E!==null&&(j=Date.now(),ie="reconnect-recovery-failed",Wt(),Xc(),gt.clear(),Rn.clear(),dt.length=0,E=null,j=null,ie=null)};return p=g=>{se({src:"reconnect",step:"disconnect",message:g?.message}),I.setBanner({status:"disconnected",elapsedMs:void 0})},f=async()=>{if(se({src:"reconnect",step:"begin",sessionId:Ae}),n.isLocal)try{let F=await Ot(await be());(F.baseUrl!==n.baseUrl||F.wsUrl!==n.wsUrl)&&(se({src:"reconnect",step:"target-refresh",oldBase:n.baseUrl,newBase:F.baseUrl}),n.baseUrl=F.baseUrl,n.wsUrl=F.wsUrl,n.display=F.display)}catch(F){se({src:"reconnect",step:"target-refresh-failed",message:F instanceof Error?F.message:String(F)})}hv();let g={jsonrpc:"2.0",id:`tui-reinit-${Ub()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:fe}}};se({src:"reconnect",step:"initialize-send"});try{await h.request(g),se({src:"reconnect",step:"initialize-ok"})}catch(F){se({src:"reconnect",step:"initialize-fail",message:F.message})}let w=ts!==void 0,x={jsonrpc:"2.0",id:`tui-reattach-${Ub()}`,method:"session/attach",params:{sessionId:Ae,historyPolicy:w?"after_message":"none",...w?{afterMessageId:ts}:{},clientInfo:{name:"hydra-acp-tui",version:fe},...(()=>{let F={};return Ln!==void 0&&(F.resume={upstreamSessionId:Ln,agentId:st,cwd:ut}),e.tui.toolContent==="references"&&(F.toolContent="references"),Object.keys(F).length>0?{_meta:{[Tt]:F}}:{}})()}};ve=[];let C,A,M;se({src:"reconnect",step:"attach-send",useAfterMessage:w,lastSeenMessageId:ts});try{let F=await h.request(x);if(se({src:"reconnect",step:"attach-resp",hasError:!!F.error}),F.error)throw new Error(F.error.message);M=Bb(F.result),C=M.appliedPolicy,M.clientId!==void 0&&(ln=M.clientId)}catch(F){A=F,se({src:"reconnect",step:"attach-fail",message:A.message})}let H=ve??[];if(ve=null,A)up(),I.appendLines([{prefix:" ",body:`reattach failed: ${A.message}`,bodyStyle:"tool-status-fail"}]);else if(w&&C!=="after_message")up(),I.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{S=!0;try{for(let F of H)ot(F)}finally{S=!1}}if(M){let F=Db({daemonTurnStartedAt:M.turnStartedAt,pendingTurns:L});F.pendingTurnsDelta!==0&&De(F.pendingTurnsDelta),F.banner==="busy"&&F.busySince!==void 0?(Se=F.busySince,I.setBanner({status:"busy",elapsedMs:Date.now()-F.busySince}),X===null&&(X=sr())):I.setBanner({status:"ready",elapsedMs:void 0})}else I.setBanner({status:L>0?"busy":"ready",elapsedMs:L>0?0:void 0});se({src:"reconnect",step:"end"})},m.onClose(g=>{g&&t.red(`
248
248
  connection lost: ${g.message}
249
- `),R(g?1:0)}),process.on("SIGINT",ns),s.initialPrompt&&a.sessionId==="__new__"&&Cn(s.initialPrompt,[]),await Kc}async function wT(t,e,n,s,r,i){let o=s.cwd??process.cwd();if(s.sessionId){let a={sessionId:s.sessionId,agentId:s.agentId??"",cwd:o};return s.resumeHint!==void 0&&(a.resumeHint=s.resumeHint),a}if(s.forceNew)return await jb(t,n,s,i)!=="ok"?null:Ub(s,o,e);if(s.resume){let a=await Yn(n,{cwd:o,all:!0}),c=tc(a,o);return c?{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o}:(t.yellow(`No sessions found for ${o}.
250
- `),null)}for(;;){let a=await Yn(n,{includeNonInteractive:!0}),c=await Yf(t,{cwd:o,sessions:a,config:e,target:n,prefs:r,...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{}});if(c.kind==="abort"||c.kind==="exit")return null;if(c.kind==="new"){c.prompt!==void 0&&(s.initialPrompt=c.prompt),c.cwd!==void 0&&(o=c.cwd,s.cwd=c.cwd);let u=await jb(t,n,s,i);if(u==="cancel")return null;if(u==="back")continue;return Ub(s,o,e)}if(c.kind==="fork"){let u=await Kb(t,n,c,a);if(u.kind==="cancel")return null;if(u.kind==="back")continue;return u.ctx}s.readonly=c.readonly===!0;let d=a.find(u=>u.sessionId===c.sessionId);if(d!==void 0&&!!d.importedFromMachine&&!d.upstreamSessionId&&!s.readonly){let u=await Wb(t,n,d,c,s);if(u.kind==="cancel")return null;if(u.kind==="back")continue;return u.ctx}if(n.isLocal&&d&&!d.importedFromMachine&&!s.readonly&&!(await ya(d.cwd)).ok){let f=await Yr(t,d,{defaultCwd:et(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(f.kind==="cancel")return null;if(f.kind==="back")continue;let p=c.agentId??d.agentId??"";return{sessionId:c.sessionId,agentId:p,cwd:f.path,resumeHint:{agentId:p,cwd:f.path,upstreamSessionId:""}}}return{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o}}}async function Wb(t,e,n,s,r){for(;;){let i=await yb(t,n);if(i==="cancel")return{kind:"cancel"};if(i==="back")return{kind:"back"};if(i==="view"){r.readonly=!0;let d=s.agentId??n.agentId??"";return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:d,cwd:n.cwd}}}let o=await zb(t,e,s.agentId??n.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await Yr(t,n);if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")continue;let c=o.agentId;return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:c,cwd:a.path,resumeHint:{agentId:c,cwd:a.path,upstreamSessionId:""}}}}}async function zb(t,e,n){if(!n)return{kind:"ok",agentId:n,changed:!1};let s;try{s=await Zd(e)}catch{return{kind:"ok",agentId:n,changed:!1}}if(s.length===0||s.some(i=>i.id===n))return{kind:"ok",agentId:n,changed:!1};let r=await Vf(t,s,n,{title:"Agent not available here",intro:`Source agent "${n}" isn't installed on this machine \u2014 pick a local agent to fork to:`});return r.kind==="cancel"?{kind:"cancel"}:r.kind==="back"?{kind:"back"}:{kind:"ok",agentId:r.agentId,changed:!0}}async function Kb(t,e,n,s){let r=s.find(u=>u.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd,a=await zb(t,e,n.sourceAgentId??r?.agentId??"");if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")return{kind:"back"};let c=a.changed?a.agentId:void 0;if(i){if(!r)return{kind:"back"};let u=await Yr(t,r);if(u.kind==="cancel")return{kind:"cancel"};if(u.kind==="back")return{kind:"back"};o=u.path}let d=c??n.sourceAgentId??"",l;try{l=await ec(e,n.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(u){return t.red(`
249
+ `),R(g?1:0)}),process.on("SIGINT",ss),s.initialPrompt&&a.sessionId==="__new__"&&Cn(s.initialPrompt,[]),await Jc}async function xT(t,e,n,s,r,i){let o=s.cwd??process.cwd();if(s.sessionId){let a={sessionId:s.sessionId,agentId:s.agentId??"",cwd:o};return s.resumeHint!==void 0&&(a.resumeHint=s.resumeHint),a}if(s.forceNew)return await zb(t,n,s,i)!=="ok"?null:Wb(s,o,e);if(s.resume){let a=await Vn(n,{cwd:o,all:!0}),c=tc(a,o);return c?{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o}:(t.yellow(`No sessions found for ${o}.
250
+ `),null)}for(;;){let a=await Vn(n,{includeNonInteractive:!0}),c=await Yf(t,{cwd:o,sessions:a,config:e,target:n,prefs:r,...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{}});if(c.kind==="abort"||c.kind==="exit")return null;if(c.kind==="new"){c.prompt!==void 0&&(s.initialPrompt=c.prompt),c.cwd!==void 0&&(o=c.cwd,s.cwd=c.cwd);let u=await zb(t,n,s,i);if(u==="cancel")return null;if(u==="back")continue;return Wb(s,o,e)}if(c.kind==="fork"){let u=await Yb(t,n,c,a);if(u.kind==="cancel")return null;if(u.kind==="back")continue;return u.ctx}s.readonly=c.readonly===!0;let d=a.find(u=>u.sessionId===c.sessionId);if(d!==void 0&&!!d.importedFromMachine&&!d.upstreamSessionId&&!s.readonly){let u=await Jb(t,n,d,c,s);if(u.kind==="cancel")return null;if(u.kind==="back")continue;return u.ctx}if(n.isLocal&&d&&!d.importedFromMachine&&!s.readonly&&!(await wa(d.cwd)).ok){let f=await Vr(t,d,{defaultCwd:et(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(f.kind==="cancel")return null;if(f.kind==="back")continue;let p=c.agentId??d.agentId??"";return{sessionId:c.sessionId,agentId:p,cwd:f.path,resumeHint:{agentId:p,cwd:f.path,upstreamSessionId:""}}}return{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o}}}async function Jb(t,e,n,s,r){for(;;){let i=await vb(t,n);if(i==="cancel")return{kind:"cancel"};if(i==="back")return{kind:"back"};if(i==="view"){r.readonly=!0;let d=s.agentId??n.agentId??"";return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:d,cwd:n.cwd}}}let o=await Vb(t,e,s.agentId??n.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await Vr(t,n);if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")continue;let c=o.agentId;return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:c,cwd:a.path,resumeHint:{agentId:c,cwd:a.path,upstreamSessionId:""}}}}}async function Vb(t,e,n){if(!n)return{kind:"ok",agentId:n,changed:!1};let s;try{s=await Zd(e)}catch{return{kind:"ok",agentId:n,changed:!1}}if(s.length===0||s.some(i=>i.id===n))return{kind:"ok",agentId:n,changed:!1};let r=await Qf(t,s,n,{title:"Agent not available here",intro:`Source agent "${n}" isn't installed on this machine \u2014 pick a local agent to fork to:`});return r.kind==="cancel"?{kind:"cancel"}:r.kind==="back"?{kind:"back"}:{kind:"ok",agentId:r.agentId,changed:!0}}async function Yb(t,e,n,s){let r=s.find(u=>u.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd,a=await Vb(t,e,n.sourceAgentId??r?.agentId??"");if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")return{kind:"back"};let c=a.changed?a.agentId:void 0;if(i){if(!r)return{kind:"back"};let u=await Vr(t,r);if(u.kind==="cancel")return{kind:"cancel"};if(u.kind==="back")return{kind:"back"};o=u.path}let d=c??n.sourceAgentId??"",l;try{l=await ec(e,n.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(u){return t.red(`
251
251
  fork failed: ${u.message}
252
- `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function Ub(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function jb(t,e,n,s){if(n.agentId||await kp())return"ok";let r;try{r=await Zd(e)}catch{return"ok"}if(r.length===0)return"ok";let i=await be(),o=s.lastChosenAgent??i.defaultAgent,a=await Vf(t,r,o);if(a.kind==="cancel")return"cancel";if(a.kind==="back")return"back";if(n.agentId=a.agentId,s.lastChosenAgent=a.agentId,a.persist)try{await ja(a.agentId)}catch{}return"ok"}function bT(t,e){se({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function vT(t,e){let n=!1,s="",r=!1,i=c=>{n||c===3&&r||c===0&&!r||(r=c===3,process.stdout.write(`\x1B]9;4;${c}\x1B\\`))},o=c=>{n||(process.stdout.write("\r"),t.eraseLineAfter(),t.brightYellow(c),s=c)},a=c=>{let d=`${c.agentId}@${c.version}`;if(c.source==="npm")return c.phase==="install_start"||c.phase==="download_start"?`${e} installing ${d} via npm\u2026`:c.phase==="installed"?`${e} ${d} installed`:`${e} installing ${d} via npm\u2026`;if(c.phase==="download_start"||c.phase==="download_progress"){let l=c.receivedBytes??0,u=c.totalBytes??0,f=(l/1e6).toFixed(1);if(u>0){let p=(u/1e6).toFixed(1),h=Math.min(100,Math.floor(l/u*100));return`${e} downloading ${d} ${f}/${p} MB (${h}%)`}return`${e} downloading ${d} ${f} MB`}return c.phase==="download_done"?`${e} downloaded ${d}, verifying\u2026`:c.phase==="extract"?`${e} extracting ${d}\u2026`:c.phase==="installed"?`${e} ${d} installed`:s||e};return{write(c){n||(t.brightYellow(c),s=c)},applyProgress(c){if(n)return;c.phase==="download_start"||c.phase==="download_progress"||c.phase==="install_start"||c.phase==="extract"||c.phase==="download_done"?i(3):c.phase==="installed"&&i(0),o(a(c))},finalize(){n||(n=!0,i(0),process.stdout.write(`
253
- `))}}}var Xf,fT,pT,Hb,Jb=J(()=>{"use strict";Tr();Et();mf();Ve();vf();Ar();Or();Xo();Po();Dw();qn();he();Cr();nn();Ic();wf();wd();ia();Uw();jw();xb();zf();Wf();Ab();hf();Rb();qf();Su();xf();Mc();Pf();Nc();$b();Bb();Ws();eo();Xf="dismiss";fT=12e4;pT=[["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"],["^T","show / hide thoughts"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter)"],null,["^R","history reverse search (^S walks forward once engaged)"],["PgUp / PgDn","scroll scrollback"],["Mouse wheel","scroll scrollback (when mouse capture is on)"],["Middle-click","paste PRIMARY selection (terminal-style)"],["^X","toggle mouse capture (wheel scroll vs. text selection)"],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"]];Hb=!1});var Yb={};Zc(Yb,{runTui:()=>qb});var Vb=J(()=>{"use strict";Jb()});import{readFileSync as ST}from"fs";import{fileURLToPath as kT}from"url";import{dirname as IT,resolve as xT}from"path";var up=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","raw","reattach","readonly","replace","rotate-token","verbose","version"]),pv=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function fp(t){for(let e of Object.keys(t))if(!up.has(e)&&!pv.has(e))return e}function el(t){let e=[],n={},s=0;for(;s<t.length;){let r=t[s];if(r===void 0)break;if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1){let c=r.slice(2,i);n[c]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(up.has(o)){n[o]=!0,s+=1;continue}let a=t[s+1];if(a!==void 0&&!a.startsWith("--")){n[o]=a,s+=2;continue}n[o]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:n}}function hv(t,e){let n=t[e];if(typeof n=="string")return n}function ci(t,e){return t[e]===!0||t[e]==="true"}var mv="HYDRA_ACP_";function gv(t){return mv+t.toUpperCase().replace(/-/g,"_")}function yt(t,e){let n=hv(t,e);return n!==void 0?n:process.env[gv(e)]}Ve();Ar();async function Dp(t,e){let n=typeof t=="string"&&t.trim().length>0?t.trim():void 0;if(n===void 0)return;if(n.startsWith("hydra://")){let i=ol(n);return{target:await Bp(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await be();return{target:await Ft(s),sessionId:n,fromUrl:!1}}function yl(t){let e=t.session;if(typeof e=="string"&&e.length>0)return e;let n=process.env.HYDRA_ACP_SESSION;if(typeof n=="string"&&n.length>0)return n}Cr();he();Ve();fs();import*as jp from"fs/promises";async function qp(t){if(await jp.mkdir(_.home(),{recursive:!0}),await Ua(),!await fi()){let n=ui();await pi(n),process.stdout.write(`Initialized ${_.authToken()}
252
+ `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function Wb(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function zb(t,e,n,s){if(n.agentId||await Ip())return"ok";let r;try{r=await Zd(e)}catch{return"ok"}if(r.length===0)return"ok";let i=await be(),o=s.lastChosenAgent??i.defaultAgent,a=await Qf(t,r,o);if(a.kind==="cancel")return"cancel";if(a.kind==="back")return"back";if(n.agentId=a.agentId,s.lastChosenAgent=a.agentId,a.persist)try{await qa(a.agentId)}catch{}return"ok"}function AT(t,e){se({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function CT(t,e){let n=!1,s="",r=!1,i=c=>{n||c===3&&r||c===0&&!r||(r=c===3,process.stdout.write(`\x1B]9;4;${c}\x1B\\`))},o=c=>{n||(process.stdout.write("\r"),t.eraseLineAfter(),t.brightYellow(c),s=c)},a=c=>{let d=`${c.agentId}@${c.version}`;if(c.source==="npm")return c.phase==="install_start"||c.phase==="download_start"?`${e} installing ${d} via npm\u2026`:c.phase==="installed"?`${e} ${d} installed`:`${e} installing ${d} via npm\u2026`;if(c.phase==="download_start"||c.phase==="download_progress"){let l=c.receivedBytes??0,u=c.totalBytes??0,f=(l/1e6).toFixed(1);if(u>0){let p=(u/1e6).toFixed(1),h=Math.min(100,Math.floor(l/u*100));return`${e} downloading ${d} ${f}/${p} MB (${h}%)`}return`${e} downloading ${d} ${f} MB`}return c.phase==="download_done"?`${e} downloaded ${d}, verifying\u2026`:c.phase==="extract"?`${e} extracting ${d}\u2026`:c.phase==="installed"?`${e} ${d} installed`:s||e};return{write(c){n||(t.brightYellow(c),s=c)},applyProgress(c){if(n)return;c.phase==="download_start"||c.phase==="download_progress"||c.phase==="install_start"||c.phase==="extract"||c.phase==="download_done"?i(3):c.phase==="installed"&&i(0),o(a(c))},finalize(){n||(n=!0,i(0),process.stdout.write(`
253
+ `))}}}var Zf,wT,bT,qb,Qb=J(()=>{"use strict";Tr();Et();gf();Ge();Sf();Ar();Fr();Zo();Mo();Uw();qn();he();Cr();nn();Ic();bf();wd();oa();qw();Ww();Rb();Kf();zf();Tb();mf();Pb();Wf();ku();Af();Mc();Mf();Dc();Lb();Hb();Ws();to();Zf="dismiss";wT=12e4;bT=[["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"],["^T","show / hide thoughts"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter)"],null,["^R","history reverse search (^S walks forward once engaged)"],["PgUp / PgDn","scroll scrollback"],["Mouse wheel","scroll scrollback (when mouse capture is on)"],["Middle-click","paste PRIMARY selection (terminal-style)"],["Right-click","extend selection to click (drag past top/bottom to autoscroll)"],["^X","toggle mouse capture (wheel scroll vs. text selection)"],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"]];qb=!1});var Gb={};el(Gb,{runTui:()=>Kb});var Xb=J(()=>{"use strict";Qb()});import{readFileSync as RT}from"fs";import{fileURLToPath as TT}from"url";import{dirname as ET,resolve as PT}from"path";var fp=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","raw","reattach","readonly","replace","rotate-token","verbose","version"]),gv=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function pp(t){for(let e of Object.keys(t))if(!fp.has(e)&&!gv.has(e))return e}function tl(t){let e=[],n={},s=0;for(;s<t.length;){let r=t[s];if(r===void 0)break;if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1){let c=r.slice(2,i);n[c]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(fp.has(o)){n[o]=!0,s+=1;continue}let a=t[s+1];if(a!==void 0&&!a.startsWith("--")){n[o]=a,s+=2;continue}n[o]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:n}}function yv(t,e){let n=t[e];if(typeof n=="string")return n}function ci(t,e){return t[e]===!0||t[e]==="true"}var wv="HYDRA_ACP_";function bv(t){return wv+t.toUpperCase().replace(/-/g,"_")}function yt(t,e){let n=yv(t,e);return n!==void 0?n:process.env[bv(e)]}Ge();Ar();async function Hp(t,e){let n=typeof t=="string"&&t.trim().length>0?t.trim():void 0;if(n===void 0)return;if(n.startsWith("hydra://")){let i=al(n);return{target:await Np(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await be();return{target:await Ot(s),sessionId:n,fromUrl:!1}}function wl(t){let e=t.session;if(typeof e=="string"&&e.length>0)return e;let n=process.env.HYDRA_ACP_SESSION;if(typeof n=="string"&&n.length>0)return n}Cr();he();Ge();ps();import*as qp from"fs/promises";async function Wp(t){if(await qp.mkdir(_.home(),{recursive:!0}),await ja(),!await fi()){let n=ui();await pi(n),process.stdout.write(`Initialized ${_.authToken()}
254
254
  Service token: ${n}
255
255
  `);return}if(ci(t,"rotate-token")){let n=ui();await pi(n),process.stdout.write(`Rotated token in ${_.authToken()}
256
256
  New token: ${n}
257
257
  `);return}process.stdout.write(`Service token already exists at ${_.authToken()}.
258
258
  `),process.stdout.write(`Pass --rotate-token to generate a new service token.
259
- `)}he();mi();Ve();fs();import{setTimeout as lA}from"timers/promises";import Og from"chalk";import*as Eg from"fs";import*as Ui from"fs/promises";import*as Pg from"net";import*as Mg from"tls";import Zx from"fastify";import eA from"@fastify/websocket";var Wp="acp.v1";function zp(t,e){return t.has(Wp)?Wp:!1}Ve();import Tg from"pino";import tA from"pino-roll";he();import*as Rt from"fs/promises";import{createHash as tS}from"crypto";import{gzip as nS,gunzip as sS}from"zlib";import{promisify as Kp}from"util";var Jp=Kp(nS),rS=Kp(sS),Yp=/^[A-Za-z0-9_-]+$/,iS=/^[a-f0-9]{64}$/,wl=!0;function Vp(t){wl=t}function Ja(t,e){return Yp.test(t)?e===void 0||iS.test(e):!1}function Ya(t,e){return`${_.toolBlobFile(t,e)}.gz`}async function bl(t,e){if(!Ja(t))return null;let n=tS("sha256").update(e,"utf8").digest("hex"),s=Ya(t,n),r=_.toolBlobFile(t,n);for(let a of[s,r])try{return await Rt.access(a),n}catch{}await Rt.mkdir(_.toolsDir(t),{recursive:!0});let i=wl?s:r,o=wl?await Jp(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await Rt.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function Va(t,e){if(!Ja(t,e))return null;try{let n=await Rt.readFile(Ya(t,e));return(await rS(n)).toString("utf8")}catch{}try{return await Rt.readFile(_.toolBlobFile(t,e),"utf8")}catch{return null}}async function Qp(t,e){if(!Ja(t,e))return null;try{return await Rt.readFile(Ya(t,e))}catch{}try{let n=await Rt.readFile(_.toolBlobFile(t,e));return await Jp(n)}catch{return null}}async function Gp(t,e,n){if(!Ja(t,e))return;let s=Ya(t,e);try{await Rt.access(s);return}catch{}await Rt.mkdir(_.toolsDir(t),{recursive:!0}),await Rt.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Xp(t){Yp.test(t)&&await Rt.rm(_.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}he();Ve();Sr();import*as ch from"fs/promises";import*as Ga from"path";import{z as oe}from"zod";he();import*as eh from"fs";import*as Ot from"fs/promises";import*as Bs from"path";import{spawn as th}from"child_process";import{Readable as oS}from"stream";function Hn(){let t=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!t||!e))return`${t}-${e}`}function kl(t,e=Hn()){if(e)return t[e]}var gi=t=>{process.stderr.write(t+`
260
- `)};function Il(t){gi=t??(e=>process.stderr.write(e+`
261
- `))}async function nh(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${Hn()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=Hn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=_.agentInstallDir(t.agentId,e,t.version),s=Bs.resolve(n,t.target.cmd);if(await Sl(s))return s;if(await aS({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await Sl(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await Ot.chmod(s,493).catch(()=>{}),s}async function aS(t){await Ot.mkdir(Bs.dirname(t.installDir),{recursive:!0});let e=await Ot.mkdtemp(`${t.installDir}.partial-`);try{gi(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await dS({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});gi(`hydra-acp: extracting ${t.agentId}`),yi(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await lS(n,e),await Ot.unlink(n).catch(()=>{});try{await Ot.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Sl(t.installDir)){await Ot.rm(e,{recursive:!0,force:!0}).catch(()=>{}),yi(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}gi(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),yi(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Ot.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function yi(t,e){if(t)try{t(e)}catch{}}async function dS(t){let e=cS(t.url),n=Bs.join(t.dir,e),s=await fetch(t.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${t.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=eh.createWriteStream(n),o=oS.fromWeb(s.body);yi(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,c=Date.now(),d=0,l=2e3,u=150;return o.on("data",f=>{a+=f.length;let p=Date.now();p-d>=u&&(d=p,yi(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,gi(Zp(t.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),gi(Zp(t.agentId,a,r,!0)),yi(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function Zp(t,e,n,s=!1){let r=(e/1e6).toFixed(1);if(n>0){let o=(n/1e6).toFixed(1),a=Math.min(100,Math.floor(e/n*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r} MB`}function cS(t){let e=new URL(t);return Bs.posix.basename(e.pathname)||"archive"}async function lS(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await vl("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await uS("unzip")){await vl("unzip",["-q",t,"-d",e]);return}await vl("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function vl(t,e){return new Promise((n,s)=>{let r=th(t,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){n();return}s(new Error(`${t} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function uS(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=th(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function Sl(t){try{return await Ot.access(t),!0}catch{return!1}}he();import*as Zt from"fs/promises";import*as Un from"path";import{spawn as fS}from"child_process";var Al=t=>{process.stderr.write(t+`
262
- `)};function Cl(t){Al=t??(e=>process.stderr.write(e+`
263
- `))}async function rh(t){let e=Hn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=_.agentNpmInstallDir(t.agentId,e,t.version),s=yS(t.packageSpec),r=wS(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=Un.join(n,"node_modules",".bin",t.bin);if(await Rr(o))return o;if(await Rr(n)){let u=await sh(i);if(u)return u.binPath}await pS({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await sh(i);if(a)return a.binPath;let c=await oh(n,s),d=typeof c=="object"&&c!==null?Object.keys(c):typeof c=="string"?[r]:[],l=d.length>0?` (package declares bins: ${d.join(", ")})`:"";throw new Error(`Agent ${t.agentId}: npm install of ${t.packageSpec} did not produce bin ${t.bin} (looked in ${n}/node_modules/.bin/)${l}`)}async function pS(t){await Zt.mkdir(Un.dirname(t.installDir),{recursive:!0});let e=await Zt.mkdtemp(`${t.installDir}.partial-`);try{Al(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),xl(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await gS({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await Zt.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Rr(t.installDir)){await Zt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),xl(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}Al(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),xl(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Zt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function xl(t,e){if(t)try{t(e)}catch{}}var hS=5,mS=25;function gS(t){return ih(t,0)}async function ih(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=fS("npm",["install","--no-audit","--no-fund","--silent",...r,t.packageSpec],{cwd:t.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let o="";i.stdout?.on("data",a=>{}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{o=(o+a).slice(-4096)}),i.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),i.on("exit",(a,c)=>{if(a===0){n();return}let d=a!==null?`exit code ${a}`:`signal ${c??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${t.packageSpec} failed (${d})
264
- stderr: ${l}`:`npm install ${t.packageSpec} failed (${d})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<hS)return await new Promise(r=>setTimeout(r,mS*(e+1))),ih(t,e+1);throw n}}function yS(t){if(t.startsWith("@")){let n=t.indexOf("/");if(n===-1)return t;let r=t.slice(n+1).indexOf("@");return r===-1?t:t.slice(0,n+1+r)}let e=t.indexOf("@");return e<=0?t:t.slice(0,e)}function wS(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function oh(t,e){let n=Un.join(t,"node_modules",e,"package.json");try{let s=await Zt.readFile(n,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function sh(t){let e=Un.join(t.installDir,"node_modules",".bin"),n=Un.join(e,t.hint);if(await Rr(n))return{binName:t.hint,binPath:n};let s=await oh(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=Un.join(e,i);if(await Rr(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[t.hint,t.basename])if(r.includes(i)){let o=Un.join(e,i);if(await Rr(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=Un.join(e,t.basename);if(await Rr(r))return{binName:t.basename,binPath:r}}}async function Rr(t){try{return await Zt.access(t),!0}catch{return!1}}var bS=oe.object({package:oe.string(),bin:oe.string().optional(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),wi=oe.object({archive:oe.string().url().optional(),cmd:oe.string().optional(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),vS=oe.object({"darwin-aarch64":wi.optional(),"darwin-x86_64":wi.optional(),"linux-aarch64":wi.optional(),"linux-x86_64":wi.optional(),"windows-x86_64":wi.optional(),"windows-aarch64":wi.optional()}),SS=oe.object({package:oe.string(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),kS=oe.object({command:oe.string(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),IS=oe.object({command:oe.string().optional(),url:oe.string().optional(),description:oe.string().optional()}),xS=oe.object({npx:bS.optional(),binary:vS.optional(),uvx:SS.optional(),exec:kS.optional()}),AS=oe.object({id:oe.string(),name:oe.string(),version:oe.string().optional(),description:oe.string().optional(),authors:oe.array(oe.string()).optional(),license:oe.string().optional(),icon:oe.string().optional(),repository:oe.string().optional(),website:oe.string().optional(),distribution:xS,onboarding:IS.optional(),requiredEnv:oe.array(oe.string().min(1)).optional()}),ah=oe.object({version:oe.string(),agents:oe.array(AS),extensions:oe.array(oe.unknown()).optional()}),Qa=class{constructor(e,n={}){this.config=e;this.options=n}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let n=await this.fetchFromNetwork();return this.cache=n,await this.writeDiskCache(n),n.data}catch(n){if(e)return this.cache=e,e.data;throw n}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let n=this.localAgents().find(a=>a.id===e);if(n)return n;let s=await this.load(),r=s.agents.find(a=>a.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(a=>Rl(a)===e);if(i)return this.applyOverride(i);let o=e.toLowerCase();if(o.length>0){let a=s.agents.filter(c=>c.id.toLowerCase().startsWith(o));if(a.length===1)return this.applyOverride(a[0])}}localAgents(){return Object.entries(this.config.agents??{}).map(([e,n])=>({id:e,name:n.name??e,description:n.description,version:"local",distribution:{exec:{command:et(n.command??e),args:n.args?.map(et),env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:CS(n.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:n.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let n=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return n<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let n=await e.json(),s=ah.parse(n),r={fetchedAt:Date.now(),raw:n,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await yn(_.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=ah.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await Xt(_.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function CS(t){let e=t.lastIndexOf("@"),s=(e>0?t.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function Rl(t){let e=t.distribution.npx?.package;if(!e)return;let n=e.lastIndexOf("/"),s=n===-1?e:e.slice(n+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function bi(t){let e=typeof t.localAgents=="function"?t.localAgents():[],n;try{n=await t.load()}catch(o){if(e.length===0)throw o;n={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...n.agents.filter(o=>!s.has(o.id))],i=await Promise.all(r.map(async o=>({id:o.id,name:o.name,version:o.version,description:o.description,distributions:Object.keys(o.distribution),installed:await Tl(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function Tl(t){let e=Hn();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=kl(t.distribution.binary,e);if(s?.cmd){let r=Ga.resolve(_.agentInstallDir(t.id,e,n),s.cmd);if(await dh(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??Rl(t)??s.package,i=_.agentNpmInstallDir(t.id,e,n),o=Ga.join(i,"node_modules",".bin",r);if(await dh(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function dh(t){try{return await ch.access(t),!0}catch{return!1}}async function wn(t,e=[],n={}){let s=t.version??"current";if(t.distribution.npx){let r=t.distribution.npx,i=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...i],env:r.env??{},version:s};let o=r.bin??Rl(t)??r.package,a=n.onInstallProgress;return{command:await rh({agentId:t.id,version:s,packageSpec:r.package,bin:o,registry:n.npmRegistry,onProgress:a?d=>a({source:"npm",...d}):void 0}),args:i,env:r.env??{},version:s}}if(t.distribution.binary){let r=kl(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${Hn()??"this platform"}.`);let i=n.onInstallProgress,o=await nh({agentId:t.id,version:s,target:r,onProgress:i?c=>i({source:"binary",...c}):void 0}),a=e.length>0?e:r.args??[];return{command:o,args:a,env:r.env??{},version:s}}if(t.distribution.uvx){let r=t.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(t.distribution.exec){let r=t.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${t.id} has no usable distribution method.`)}import{spawn as MS}from"child_process";import*as rd from"fs";import*as Ah from"path";Et();function sd(t,e){let n="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let c of r)c(a)}};return t.setEncoding("utf8"),t.on("data",a=>{n+=a;let c=n.indexOf(`
259
+ `)}he();mi();Ge();ps();import{setTimeout as hA}from"timers/promises";import Bg from"chalk";import*as Mg from"fs";import*as ji from"fs/promises";import*as _g from"net";import*as $g from"tls";import sA from"fastify";import rA from"@fastify/websocket";var zp="acp.v1";function Kp(t,e){return t.has(zp)?zp:!1}Ge();import Pg from"pino";import iA from"pino-roll";he();import*as Rt from"fs/promises";import{createHash as rS}from"crypto";import{gzip as iS,gunzip as oS}from"zlib";import{promisify as Jp}from"util";var Vp=Jp(iS),aS=Jp(oS),Yp=/^[A-Za-z0-9_-]+$/,dS=/^[a-f0-9]{64}$/,bl=!0;function Qp(t){bl=t}function Va(t,e){return Yp.test(t)?e===void 0||dS.test(e):!1}function Ya(t,e){return`${_.toolBlobFile(t,e)}.gz`}async function vl(t,e){if(!Va(t))return null;let n=rS("sha256").update(e,"utf8").digest("hex"),s=Ya(t,n),r=_.toolBlobFile(t,n);for(let a of[s,r])try{return await Rt.access(a),n}catch{}await Rt.mkdir(_.toolsDir(t),{recursive:!0});let i=bl?s:r,o=bl?await Vp(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await Rt.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function Qa(t,e){if(!Va(t,e))return null;try{let n=await Rt.readFile(Ya(t,e));return(await aS(n)).toString("utf8")}catch{}try{return await Rt.readFile(_.toolBlobFile(t,e),"utf8")}catch{return null}}async function Gp(t,e){if(!Va(t,e))return null;try{return await Rt.readFile(Ya(t,e))}catch{}try{let n=await Rt.readFile(_.toolBlobFile(t,e));return await Vp(n)}catch{return null}}async function Xp(t,e,n){if(!Va(t,e))return;let s=Ya(t,e);try{await Rt.access(s);return}catch{}await Rt.mkdir(_.toolsDir(t),{recursive:!0}),await Rt.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Zp(t){Yp.test(t)&&await Rt.rm(_.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}he();Ge();Sr();import*as lh from"fs/promises";import*as Xa from"path";import{z as oe}from"zod";he();import*as th from"fs";import*as Ft from"fs/promises";import*as Bs from"path";import{spawn as nh}from"child_process";import{Readable as cS}from"stream";function Hn(){let t=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!t||!e))return`${t}-${e}`}function Il(t,e=Hn()){if(e)return t[e]}var gi=t=>{process.stderr.write(t+`
260
+ `)};function xl(t){gi=t??(e=>process.stderr.write(e+`
261
+ `))}async function sh(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${Hn()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=Hn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=_.agentInstallDir(t.agentId,e,t.version),s=Bs.resolve(n,t.target.cmd);if(await kl(s))return s;if(await lS({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await kl(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await Ft.chmod(s,493).catch(()=>{}),s}async function lS(t){await Ft.mkdir(Bs.dirname(t.installDir),{recursive:!0});let e=await Ft.mkdtemp(`${t.installDir}.partial-`);try{gi(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await uS({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});gi(`hydra-acp: extracting ${t.agentId}`),yi(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await pS(n,e),await Ft.unlink(n).catch(()=>{});try{await Ft.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await kl(t.installDir)){await Ft.rm(e,{recursive:!0,force:!0}).catch(()=>{}),yi(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}gi(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),yi(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Ft.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function yi(t,e){if(t)try{t(e)}catch{}}async function uS(t){let e=fS(t.url),n=Bs.join(t.dir,e),s=await fetch(t.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${t.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=th.createWriteStream(n),o=cS.fromWeb(s.body);yi(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,c=Date.now(),d=0,l=2e3,u=150;return o.on("data",f=>{a+=f.length;let p=Date.now();p-d>=u&&(d=p,yi(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,gi(eh(t.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),gi(eh(t.agentId,a,r,!0)),yi(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function eh(t,e,n,s=!1){let r=(e/1e6).toFixed(1);if(n>0){let o=(n/1e6).toFixed(1),a=Math.min(100,Math.floor(e/n*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r} MB`}function fS(t){let e=new URL(t);return Bs.posix.basename(e.pathname)||"archive"}async function pS(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await Sl("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await hS("unzip")){await Sl("unzip",["-q",t,"-d",e]);return}await Sl("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function Sl(t,e){return new Promise((n,s)=>{let r=nh(t,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){n();return}s(new Error(`${t} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function hS(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=nh(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function kl(t){try{return await Ft.access(t),!0}catch{return!1}}he();import*as Zt from"fs/promises";import*as Un from"path";import{spawn as mS}from"child_process";var Cl=t=>{process.stderr.write(t+`
262
+ `)};function Rl(t){Cl=t??(e=>process.stderr.write(e+`
263
+ `))}async function ih(t){let e=Hn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=_.agentNpmInstallDir(t.agentId,e,t.version),s=vS(t.packageSpec),r=SS(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=Un.join(n,"node_modules",".bin",t.bin);if(await Rr(o))return o;if(await Rr(n)){let u=await rh(i);if(u)return u.binPath}await gS({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await rh(i);if(a)return a.binPath;let c=await ah(n,s),d=typeof c=="object"&&c!==null?Object.keys(c):typeof c=="string"?[r]:[],l=d.length>0?` (package declares bins: ${d.join(", ")})`:"";throw new Error(`Agent ${t.agentId}: npm install of ${t.packageSpec} did not produce bin ${t.bin} (looked in ${n}/node_modules/.bin/)${l}`)}async function gS(t){await Zt.mkdir(Un.dirname(t.installDir),{recursive:!0});let e=await Zt.mkdtemp(`${t.installDir}.partial-`);try{Cl(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),Al(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await bS({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await Zt.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Rr(t.installDir)){await Zt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Al(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}Cl(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Al(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Zt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Al(t,e){if(t)try{t(e)}catch{}}var yS=5,wS=25;function bS(t){return oh(t,0)}async function oh(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=mS("npm",["install","--no-audit","--no-fund","--silent",...r,t.packageSpec],{cwd:t.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let o="";i.stdout?.on("data",a=>{}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{o=(o+a).slice(-4096)}),i.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),i.on("exit",(a,c)=>{if(a===0){n();return}let d=a!==null?`exit code ${a}`:`signal ${c??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${t.packageSpec} failed (${d})
264
+ stderr: ${l}`:`npm install ${t.packageSpec} failed (${d})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<yS)return await new Promise(r=>setTimeout(r,wS*(e+1))),oh(t,e+1);throw n}}function vS(t){if(t.startsWith("@")){let n=t.indexOf("/");if(n===-1)return t;let r=t.slice(n+1).indexOf("@");return r===-1?t:t.slice(0,n+1+r)}let e=t.indexOf("@");return e<=0?t:t.slice(0,e)}function SS(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function ah(t,e){let n=Un.join(t,"node_modules",e,"package.json");try{let s=await Zt.readFile(n,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function rh(t){let e=Un.join(t.installDir,"node_modules",".bin"),n=Un.join(e,t.hint);if(await Rr(n))return{binName:t.hint,binPath:n};let s=await ah(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=Un.join(e,i);if(await Rr(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[t.hint,t.basename])if(r.includes(i)){let o=Un.join(e,i);if(await Rr(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=Un.join(e,t.basename);if(await Rr(r))return{binName:t.basename,binPath:r}}}async function Rr(t){try{return await Zt.access(t),!0}catch{return!1}}var kS=oe.object({package:oe.string(),bin:oe.string().optional(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),wi=oe.object({archive:oe.string().url().optional(),cmd:oe.string().optional(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),IS=oe.object({"darwin-aarch64":wi.optional(),"darwin-x86_64":wi.optional(),"linux-aarch64":wi.optional(),"linux-x86_64":wi.optional(),"windows-x86_64":wi.optional(),"windows-aarch64":wi.optional()}),xS=oe.object({package:oe.string(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),AS=oe.object({command:oe.string(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),CS=oe.object({command:oe.string().optional(),url:oe.string().optional(),description:oe.string().optional()}),RS=oe.object({npx:kS.optional(),binary:IS.optional(),uvx:xS.optional(),exec:AS.optional()}),TS=oe.object({id:oe.string(),name:oe.string(),version:oe.string().optional(),description:oe.string().optional(),authors:oe.array(oe.string()).optional(),license:oe.string().optional(),icon:oe.string().optional(),repository:oe.string().optional(),website:oe.string().optional(),distribution:RS,onboarding:CS.optional(),requiredEnv:oe.array(oe.string().min(1)).optional()}),dh=oe.object({version:oe.string(),agents:oe.array(TS),extensions:oe.array(oe.unknown()).optional()}),Ga=class{constructor(e,n={}){this.config=e;this.options=n}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let n=await this.fetchFromNetwork();return this.cache=n,await this.writeDiskCache(n),n.data}catch(n){if(e)return this.cache=e,e.data;throw n}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let n=this.localAgents().find(a=>a.id===e);if(n)return n;let s=await this.load(),r=s.agents.find(a=>a.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(a=>Tl(a)===e);if(i)return this.applyOverride(i);let o=e.toLowerCase();if(o.length>0){let a=s.agents.filter(c=>c.id.toLowerCase().startsWith(o));if(a.length===1)return this.applyOverride(a[0])}}localAgents(){return Object.entries(this.config.agents??{}).map(([e,n])=>({id:e,name:n.name??e,description:n.description,version:"local",distribution:{exec:{command:et(n.command??e),args:n.args?.map(et),env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:ES(n.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:n.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let n=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return n<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let n=await e.json(),s=dh.parse(n),r={fetchedAt:Date.now(),raw:n,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await yn(_.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=dh.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await Xt(_.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function ES(t){let e=t.lastIndexOf("@"),s=(e>0?t.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function Tl(t){let e=t.distribution.npx?.package;if(!e)return;let n=e.lastIndexOf("/"),s=n===-1?e:e.slice(n+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function bi(t){let e=typeof t.localAgents=="function"?t.localAgents():[],n;try{n=await t.load()}catch(o){if(e.length===0)throw o;n={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...n.agents.filter(o=>!s.has(o.id))],i=await Promise.all(r.map(async o=>({id:o.id,name:o.name,version:o.version,description:o.description,distributions:Object.keys(o.distribution),installed:await El(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function El(t){let e=Hn();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=Il(t.distribution.binary,e);if(s?.cmd){let r=Xa.resolve(_.agentInstallDir(t.id,e,n),s.cmd);if(await ch(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??Tl(t)??s.package,i=_.agentNpmInstallDir(t.id,e,n),o=Xa.join(i,"node_modules",".bin",r);if(await ch(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function ch(t){try{return await lh.access(t),!0}catch{return!1}}async function wn(t,e=[],n={}){let s=t.version??"current";if(t.distribution.npx){let r=t.distribution.npx,i=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...i],env:r.env??{},version:s};let o=r.bin??Tl(t)??r.package,a=n.onInstallProgress;return{command:await ih({agentId:t.id,version:s,packageSpec:r.package,bin:o,registry:n.npmRegistry,onProgress:a?d=>a({source:"npm",...d}):void 0}),args:i,env:r.env??{},version:s}}if(t.distribution.binary){let r=Il(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${Hn()??"this platform"}.`);let i=n.onInstallProgress,o=await sh({agentId:t.id,version:s,target:r,onProgress:i?c=>i({source:"binary",...c}):void 0}),a=e.length>0?e:r.args??[];return{command:o,args:a,env:r.env??{},version:s}}if(t.distribution.uvx){let r=t.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(t.distribution.exec){let r=t.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${t.id} has no usable distribution method.`)}import{spawn as OS}from"child_process";import*as id from"fs";import*as Ch from"path";Et();function rd(t,e){let n="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let c of r)c(a)}};return t.setEncoding("utf8"),t.on("data",a=>{n+=a;let c=n.indexOf(`
265
265
  `);for(;c!==-1;){let d=n.slice(0,c).trim();if(n=n.slice(c+1),d.length>0)try{let l=JSON.parse(d);for(let u of s)u(l)}catch(l){for(let u of s)u({jsonrpc:"2.0",id:null,error:{code:z.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}c=n.indexOf(`
266
266
  `)}}),t.on("end",()=>o()),t.on("error",a=>o(a)),e.on("error",a=>o(a)),{async send(a){if(i)throw new Error("stream is closed");let c=JSON.stringify(a)+`
267
- `;await new Promise((d,l)=>{e.write(c,u=>{if(u){l(u);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}Tr();he();var _S=4096,Ds=class t{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,n){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=n,this.stderrTailBytes=e.stderrTailBytes??_S,this.killEscalationMs=e.killEscalationMs??$S,this.logger=e.logger,this.fileLog=FS(e.agentId),this.writeLog(`--- spawn pid=${n.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
268
- `),!n.stdout||!n.stdin)throw new Error("agent subprocess missing stdio");let s=sd(n.stdout,n.stdin);this.connection=new zt(s),n.stderr?.setEncoding("utf8"),n.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let i of r.split(/\r?\n/))i.length>0&&this.logger.info(`[${e.agentId}] ${i}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),n.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
267
+ `;await new Promise((d,l)=>{e.write(c,u=>{if(u){l(u);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}Tr();he();var FS=4096,Ds=class t{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,n){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=n,this.stderrTailBytes=e.stderrTailBytes??FS,this.killEscalationMs=e.killEscalationMs??LS,this.logger=e.logger,this.fileLog=BS(e.agentId),this.writeLog(`--- spawn pid=${n.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
268
+ `),!n.stdout||!n.stdin)throw new Error("agent subprocess missing stdio");let s=rd(n.stdout,n.stdin);this.connection=new zt(s),n.stderr?.setEncoding("utf8"),n.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let i of r.split(/\r?\n/))i.length>0&&this.logger.info(`[${e.agentId}] ${i}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),n.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
269
269
  `),this.connection.fail(new Error(i))}),n.on("exit",(r,i)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${i} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
270
270
  `),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${n.pid} exited after kill code=${r} signal=${i}`);else{let o=`agent ${e.agentId} exited before responding (code=${r} signal=${i})`;this.connection.fail(new Error(this.formatFailure(o))),this.logger?.warn(`agent ${e.agentId} pid=${n.pid} exited unexpectedly code=${r} signal=${i}`)}for(let o of this.exitHandlers)o(r,i)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let n=this.stderrTail.trim();return n?`${e}
271
- stderr: ${n}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=MS(e.plan.command,e.plan.args,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new t(e,s)}onExit(e){this.exitHandlers.push(e)}isAlive(){return!this.exited}async kill(e="SIGTERM"){this.exited||(this.killed=!0,this.writeLog(`--- kill requested signal=${e} time=${new Date().toISOString()} ---
271
+ stderr: ${n}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=OS(e.plan.command,e.plan.args,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new t(e,s)}onExit(e){this.exitHandlers.push(e)}isAlive(){return!this.exited}async kill(e="SIGTERM"){this.exited||(this.killed=!0,this.writeLog(`--- kill requested signal=${e} time=${new Date().toISOString()} ---
272
272
  `),this.logger?.info(`agent ${this.agentId} pid=${this.child.pid} kill requested signal=${e}`),await this.connection.close().catch(()=>{}),this.signalProcessGroup(e),await this.waitForExit(this.killEscalationMs),!this.exited&&(this.writeLog(`--- kill escalating signal=SIGKILL time=${new Date().toISOString()} ---
273
- `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let n=this.child.pid;if(n!==void 0)try{process.kill(-n,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(n=>{let s=setTimeout(()=>{this.child.off("exit",r),n()},e),r=()=>{clearTimeout(s),n()};this.child.once("exit",r)})}},$S=2e3;function FS(t){try{let e=_.agentLogFile(t);rd.mkdirSync(Ah.dirname(e),{recursive:!0});let n=rd.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as _r from"fs/promises";import*as Sd from"os";import*as Yo from"path";import{customAlphabet as qk}from"nanoid";$l();qn();Zl();he();Sr();import*as ms from"fs/promises";import{z as Wn}from"zod";var Rk=Wn.object({version:Wn.literal(1),agentId:Wn.string(),upstreamSessionId:Wn.string(),deletedAt:Wn.string(),upstreamUpdatedAt:Wn.string().optional(),cwd:Wn.string().optional(),title:Wn.string().optional(),reason:Wn.enum(["user","expired"]).optional(),interactive:Wn.boolean().optional()}),fd=class{async add(e){let n={version:1,...e};await Xt(_.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await ms.access(_.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=_.tombstoneFile(e,n),r=await yn(s);if(r===void 0)return await this.has(e,n)?{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}:void 0;try{return Rk.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await ms.unlink(_.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await ms.rmdir(_.tombstoneAgentDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}}async list(e){if(e!==void 0)return this.listForAgent(e);let n;try{n=await ms.readdir(_.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let n;try{n=await ms.readdir(_.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function Zh(t,e){return t.reason==="user"||e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as fm from"fs/promises";Et();nn();ld();dd();var Pk=12e4;async function tm(t,e,n){let s=t.timeoutMs??Pk,r,i,o=!1;try{let a=(async()=>{r=Ds.spawn({agentId:t.agentId,cwd:t.cwd,plan:t.plan,logger:t.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:fe}}),d=await r.connection.request("session/new",{cwd:t.cwd,mcpServers:[]}),l=d.sessionId;if(typeof l!="string"){t.logger?.warn(`synopsis: agent ${t.agentId} returned non-string sessionId from session/new`),t.onFailure?.(`agent ${t.agentId} did not return a sessionId from session/new`);return}if(t.onWorkerSpawned?.(l,r.pid),t.modelId){let h=_k(d);if(h.size===0||h.has(t.modelId))try{await r.connection.request("session/set_model",{sessionId:l,modelId:t.modelId})}catch(m){t.logger?.warn(`synopsis: agent ${t.agentId} rejected set_model ${JSON.stringify(t.modelId)}: ${m.message}; continuing on default`)}else t.logger?.warn(`synopsis: model ${JSON.stringify(t.modelId)} not advertised by agent ${t.agentId} (have [${[...h].join(", ")}]); continuing on default`)}let u=[];r.connection.onNotification("session/update",h=>{let m=Mk(h);m.length>0&&u.push(m)}),await r.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let f=u.join(""),p=n(f);if(!p){let h=JSON.stringify(f.slice(0,200));t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse (replyLen=${f.length} preview=${h})`);let m=f.slice(0,120).replace(/\s+/g," ").trim();t.onFailure?.(`agent ${t.agentId} returned unparseable JSON (${f.length} chars): ${m}${f.length>120?"\u2026":""}`)}return p})();return await new Promise((c,d)=>{i=setTimeout(()=>{o=!0,t.logger?.warn(`synopsis: agent ${t.agentId} timed out after ${s}ms`),t.onFailure?.(`agent ${t.agentId} timed out after ${s}ms`),c(void 0)},s),i.unref?.(),a.then(l=>{i&&clearTimeout(i),o||c(l)},l=>{i&&clearTimeout(i),o||d(l)})})}catch(a){let c=a.message;t.logger?.warn(`synopsis: agent ${t.agentId} failed: ${c}`),t.onFailure?.(`agent ${t.agentId} failed: ${c}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function hd(t){let e=Ai(t.history,{maxChars:t.maxTranscriptChars}),n=t.sessionId!==void 0?`[hydra-acp title-regen worker for session ${t.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${n}
273
+ `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let n=this.child.pid;if(n!==void 0)try{process.kill(-n,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(n=>{let s=setTimeout(()=>{this.child.off("exit",r),n()},e),r=()=>{clearTimeout(s),n()};this.child.once("exit",r)})}},LS=2e3;function BS(t){try{let e=_.agentLogFile(t);id.mkdirSync(Ch.dirname(e),{recursive:!0});let n=id.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as _r from"fs/promises";import*as Sd from"os";import*as Yo from"path";import{customAlphabet as Jk}from"nanoid";Ol();qn();eu();he();Sr();import*as gs from"fs/promises";import{z as Wn}from"zod";var Mk=Wn.object({version:Wn.literal(1),agentId:Wn.string(),upstreamSessionId:Wn.string(),deletedAt:Wn.string(),upstreamUpdatedAt:Wn.string().optional(),cwd:Wn.string().optional(),title:Wn.string().optional(),reason:Wn.enum(["user","expired"]).optional(),interactive:Wn.boolean().optional()}),fd=class{async add(e){let n={version:1,...e};await Xt(_.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await gs.access(_.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=_.tombstoneFile(e,n),r=await yn(s);if(r===void 0)return await this.has(e,n)?{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}:void 0;try{return Mk.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await gs.unlink(_.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await gs.rmdir(_.tombstoneAgentDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}}async list(e){if(e!==void 0)return this.listForAgent(e);let n;try{n=await gs.readdir(_.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let n;try{n=await gs.readdir(_.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function tm(t,e){return t.reason==="user"||e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as hm from"fs/promises";Et();nn();ld();dd();var Ok=12e4;async function sm(t,e,n){let s=t.timeoutMs??Ok,r,i,o=!1;try{let a=(async()=>{r=Ds.spawn({agentId:t.agentId,cwd:t.cwd,plan:t.plan,logger:t.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:fe}}),d=await r.connection.request("session/new",{cwd:t.cwd,mcpServers:[]}),l=d.sessionId;if(typeof l!="string"){t.logger?.warn(`synopsis: agent ${t.agentId} returned non-string sessionId from session/new`),t.onFailure?.(`agent ${t.agentId} did not return a sessionId from session/new`);return}if(t.onWorkerSpawned?.(l,r.pid),t.modelId){let h=Lk(d);if(h.size===0||h.has(t.modelId))try{await r.connection.request("session/set_model",{sessionId:l,modelId:t.modelId})}catch(m){t.logger?.warn(`synopsis: agent ${t.agentId} rejected set_model ${JSON.stringify(t.modelId)}: ${m.message}; continuing on default`)}else t.logger?.warn(`synopsis: model ${JSON.stringify(t.modelId)} not advertised by agent ${t.agentId} (have [${[...h].join(", ")}]); continuing on default`)}let u=[];r.connection.onNotification("session/update",h=>{let m=Fk(h);m.length>0&&u.push(m)}),await r.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let f=u.join(""),p=n(f);if(!p){let h=JSON.stringify(f.slice(0,200));t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse (replyLen=${f.length} preview=${h})`);let m=f.slice(0,120).replace(/\s+/g," ").trim();t.onFailure?.(`agent ${t.agentId} returned unparseable JSON (${f.length} chars): ${m}${f.length>120?"\u2026":""}`)}return p})();return await new Promise((c,d)=>{i=setTimeout(()=>{o=!0,t.logger?.warn(`synopsis: agent ${t.agentId} timed out after ${s}ms`),t.onFailure?.(`agent ${t.agentId} timed out after ${s}ms`),c(void 0)},s),i.unref?.(),a.then(l=>{i&&clearTimeout(i),o||c(l)},l=>{i&&clearTimeout(i),o||d(l)})})}catch(a){let c=a.message;t.logger?.warn(`synopsis: agent ${t.agentId} failed: ${c}`),t.onFailure?.(`agent ${t.agentId} failed: ${c}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function hd(t){let e=Ci(t.history,{maxChars:t.maxTranscriptChars}),n=t.sessionId!==void 0?`[hydra-acp title-regen worker for session ${t.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${n}
274
274
 
275
275
  ${e}
276
276
 
277
- ${zl}`:`${n}
277
+ ${Kl}`:`${n}
278
278
 
279
- ${zl}`;return tm(t,s,Qh)}async function nm(t){let e=Ai(t.history,{maxChars:t.maxTranscriptChars}),n=t.sessionId!==void 0?`[hydra-acp compaction worker for session ${t.sessionId}]`:"[hydra-acp compaction worker]",s=e.length>0?`${n}
279
+ ${Kl}`;return sm(t,s,Xh)}async function rm(t){let e=Ci(t.history,{maxChars:t.maxTranscriptChars}),n=t.sessionId!==void 0?`[hydra-acp compaction worker for session ${t.sessionId}]`:"[hydra-acp compaction worker]",s=e.length>0?`${n}
280
280
 
281
281
  ${e}
282
282
 
283
- ${Kl}`:`${n}
283
+ ${Jl}`:`${n}
284
284
 
285
- ${Kl}`;return tm(t,s,Gh)}function Mk(t){if(!t||typeof t!="object")return"";let e=t.update;if(!e||typeof e!="object")return"";let n=e;if(n.sessionUpdate!=="agent_message_chunk")return"";let s=n.content;return s&&typeof s.text=="string"?s.text:""}function _k(t){let e=new Set;em(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&em(e,n.availableModels),e}function em(t,e){if(Array.isArray(e)){for(let n of e)if(n&&typeof n=="object"){let s=n.modelId??n.value??n.id;typeof s=="string"&&s.length>0&&t.add(s)}}}nu();he();var $k=2,md=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??$k}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,n){if(this.stopped)return;let s=n?.targetAgentId;if(this.inflight.has(e))return;let r=this.queued[e];if(r&&r.kind==="title"){this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}};return}this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let n=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=n-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(i=>{setTimeout(i,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(i=>{setTimeout(i,s).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 n=Object.keys(this.queued)[0];if(!n)return;let s=this.queued[n];delete this.queued[n];let r=this.runOne(n,s).finally(()=>{this.inflight.delete(n),this.drain()});this.inflight.set(n,r)}}async runOne(e,n){let s=n.kind,r=n.targetAgentId;try{let i=await this.opts.store.read(e);if(!i){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let o=await this.opts.histories.load(e,{maxEntries:1/0}),a=i.summarizedThroughEntry;if(a!==void 0&&o.length<=a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${o.length})`);return}let c=s==="compaction"?r??this.opts.compactionAgent??i.agentId:this.opts.synopsisAgent??i.agentId,d=await this.opts.registry.getAgent(c);if(!d){this.opts.logger?.warn(`synopsis: agent ${c} not in registry for session ${e}; skipping`);return}let l=await wn(d,[],{npmRegistry:this.opts.npmRegistry}),u=this.opts.compactionAgent===void 0&&r===void 0,f=s==="compaction"?this.opts.compactionModel??(u?i.currentModel:void 0):this.opts.synopsisModel,p=_.sessionDir(e);if(await fm.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${c} historyLen=${o.length} model=${JSON.stringify(f??"(default)")} cwd=${p}`),s==="compaction"){let h=this.opts.compactionMaxIterations??3,m=0,y=a??0,b,v=0,S,k=Date.now(),T={targetAgentId:r},F=B=>this.opts.onCompactionStateChange?.(e,B,T)??Promise.resolve(),$=B=>{this.opts.broadcastHydraCompaction?.(e,B,T)};await F({status:"requested",requestedAt:k}),$({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:k});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${o.length} watermark=${y}`);let B=await this.opts.histories.load(e,{maxEntries:1/0});if(B.length<=y)break;let K=await nm({agentId:c,cwd:p,plan:l,history:B,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(L,N)=>{F({status:"running",requestedAt:k,iter:m,worker:{upstreamSessionId:L,pid:N??0}})},onFailure:L=>{S=L}});if(K){let L=cm(K.synopsis,B);L&&lm(L)&&(await this.opts.persistSynopsis(e,L,B.length),b=L,v=B.length,S=void 0,await F({status:"running",requestedAt:k,iter:m}),$({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:B.length}),await this.opts.onSynthesisArtifact?.(e,L,v,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${um(L)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${m} returned no result`);if(y=B.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===y)break}while(m<h);if(b)m>=h&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${v} iterations=${m}`);else{m>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${h} without producing artifact sessionId=${e}: ${S??"no reason captured"}`);let B=S??(m===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${m} iteration(s)`);await F({status:"failed",requestedAt:k,iter:m,lastError:B}),$({sessionUpdate:"hydra_compaction",phase:"failed",error:B})}}catch(B){let K=B instanceof Error?B.message:String(B);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${K}`),await F({status:"failed",requestedAt:k,iter:m,lastError:K}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:K},{targetAgentId:r})}}else{let h=await hd({agentId:c,cwd:p,plan:l,history:o,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!h){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let m=cm(h.synopsis,o);m&&lm(m)?(await this.opts.persistSynopsis(e,m,o.length),h.title&&await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!h.title)} fields=${um(m)}`)):h.title&&(await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(i){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${i.message}`)}}};function cm(t,e){let n=om(e),s=im(e);return t?{...t,files_touched:n.length>0?n:t.files_touched,tools_used:s.length>0?s:t.tools_used}:n.length===0&&s.length===0?void 0:{files_touched:n.length>0?n:void 0,tools_used:s.length>0?s:void 0}}function lm(t){return!!(t.goal&&t.goal.trim().length>0||t.outcome&&t.outcome.trim().length>0||t.files_touched&&t.files_touched.length>0||t.tools_used&&t.tools_used.length>0||t.rejected_approaches&&t.rejected_approaches.length>0||t.open_threads&&t.open_threads.length>0)}function um(t){let e=[];return t.goal&&e.push("goal"),t.outcome&&e.push("outcome"),t.files_touched&&t.files_touched.length>0&&e.push(`files=${t.files_touched.length}`),t.tools_used&&t.tools_used.length>0&&e.push(`tools=${t.tools_used.length}`),t.rejected_approaches&&t.rejected_approaches.length>0&&e.push(`rejected=${t.rejected_approaches.length}`),t.open_threads&&t.open_threads.length>0&&e.push(`open=${t.open_threads.length}`),`[${e.join(",")}]`}he();import*as Lt from"fs/promises";function pm(t){return t==="summary"?"summary":"inline"}var su=256;function hm(t,e){return e!=="summary"?t:t.map(Fk)}function Fk(t){if(t.method!=="session/update")return t;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return t;let n=e,s=n.update;if(!s||typeof s!="object"||Array.isArray(s))return t;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return t;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(mm));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=ru(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...t,params:{...n,update:i}}}function Ok(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function mm(t){if(Ok(t)){let s=t,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!t||typeof t!="object"||Array.isArray(t))return t;let e=t,n={...e};return typeof e.text=="string"&&(n.text=ru(e.text)),typeof e.content=="string"?n.content=ru(e.content):e.content&&typeof e.content=="object"&&(n.content=mm(e.content)),n}function ru(t){if(typeof t=="string"&&t.length>su){let e=t.length-su;return`${t.slice(0,su)}\u2026[+${e} chars omitted from summary export]`}return t}var Lk=2048;function gm(t){let e=new Set,n=s=>{if(ym(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)n(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))n(r)};for(let s of t)n(s.params);return e}function ym(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function Bk(t){if(t.method!=="session/update")return!1;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return!1;let s=n.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function au(t,e){if(!Bk(t))return t;let n=t.params,s=n.update,r=await iu(s,e);return{...t,params:{...n,update:r}}}async function iu(t,e){if(typeof t=="string"){if(t.length<=Lk)return t;let n=await e(t);return n===null?t:{__hydraBlob:n,bytes:t.length}}if(Array.isArray(t)){let n=[];for(let s of t)n.push(await iu(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await iu(r,e);return n}return t}async function wm(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await ou(n,e);return s===n?t:{...t,params:s}}async function ou(t,e){if(ym(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await ou(r,e);i!==r&&(n=!0),s.push(i)}return n?s:t}if(t&&typeof t=="object"){let n=!1,s={};for(let[r,i]of Object.entries(t)){let o=await ou(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var Uo=/^[A-Za-z0-9_-]+$/,Nk=1e3,gd=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Nk}async append(e,n){if(Uo.test(e))return this.enqueue(e,async()=>{await Lt.mkdir(_.sessionDir(e),{recursive:!0});let s=await au(n,i=>bl(e,i)),r=JSON.stringify(s)+`
286
- `;await Lt.appendFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(Uo.test(e))return this.enqueue(e,async()=>{await Lt.mkdir(_.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await au(i,o=>bl(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
285
+ ${Jl}`;return sm(t,s,Zh)}function Fk(t){if(!t||typeof t!="object")return"";let e=t.update;if(!e||typeof e!="object")return"";let n=e;if(n.sessionUpdate!=="agent_message_chunk")return"";let s=n.content;return s&&typeof s.text=="string"?s.text:""}function Lk(t){let e=new Set;nm(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&nm(e,n.availableModels),e}function nm(t,e){if(Array.isArray(e)){for(let n of e)if(n&&typeof n=="object"){let s=n.modelId??n.value??n.id;typeof s=="string"&&s.length>0&&t.add(s)}}}su();he();var Bk=2,md=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Bk}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,n){if(this.stopped)return;let s=n?.targetAgentId;if(this.inflight.has(e))return;let r=this.queued[e];if(r&&r.kind==="title"){this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}};return}this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let n=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=n-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(i=>{setTimeout(i,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(i=>{setTimeout(i,s).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 n=Object.keys(this.queued)[0];if(!n)return;let s=this.queued[n];delete this.queued[n];let r=this.runOne(n,s).finally(()=>{this.inflight.delete(n),this.drain()});this.inflight.set(n,r)}}async runOne(e,n){let s=n.kind,r=n.targetAgentId;try{let i=await this.opts.store.read(e);if(!i){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let o=await this.opts.histories.load(e,{maxEntries:1/0}),a=i.summarizedThroughEntry;if(a!==void 0&&o.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${o.length})`);return}a!==void 0&&o.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${o.length}) for ${e} \u2014 re-baselining`);let c=s==="compaction"?r??this.opts.compactionAgent??i.agentId:this.opts.synopsisAgent??i.agentId,d=await this.opts.registry.getAgent(c);if(!d){this.opts.logger?.warn(`synopsis: agent ${c} not in registry for session ${e}; skipping`);return}let l=await wn(d,[],{npmRegistry:this.opts.npmRegistry}),u=this.opts.compactionAgent===void 0&&r===void 0,f=s==="compaction"?this.opts.compactionModel??(u?i.currentModel:void 0):this.opts.synopsisModel,p=_.sessionDir(e);if(await hm.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${c} historyLen=${o.length} model=${JSON.stringify(f??"(default)")} cwd=${p}`),s==="compaction"){let h=this.opts.compactionMaxIterations??3,m=0,y=a??0,b,v=0,S,k=Date.now(),T={targetAgentId:r},O=B=>this.opts.onCompactionStateChange?.(e,B,T)??Promise.resolve(),$=B=>{this.opts.broadcastHydraCompaction?.(e,B,T)};await O({status:"requested",requestedAt:k}),$({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:k});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${o.length} watermark=${y}`);let B=await this.opts.histories.load(e,{maxEntries:1/0});if(B.length===y)break;let K=await rm({agentId:c,cwd:p,plan:l,history:B,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(L,N)=>{O({status:"running",requestedAt:k,iter:m,worker:{upstreamSessionId:L,pid:N??0}})},onFailure:L=>{S=L}});if(K){let L=um(K.synopsis,B);L&&fm(L)&&(await this.opts.persistSynopsis(e,L,B.length),b=L,v=B.length,S=void 0,await O({status:"running",requestedAt:k,iter:m}),$({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:B.length}),await this.opts.onSynthesisArtifact?.(e,L,v,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${pm(L)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${m} returned no result`);if(y=B.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===y)break}while(m<h);if(b)m>=h&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${v} iterations=${m}`);else{m>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${h} without producing artifact sessionId=${e}: ${S??"no reason captured"}`);let B=S??(m===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${m} iteration(s)`);await O({status:"failed",requestedAt:k,iter:m,lastError:B}),$({sessionUpdate:"hydra_compaction",phase:"failed",error:B})}}catch(B){let K=B instanceof Error?B.message:String(B);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${K}`),await O({status:"failed",requestedAt:k,iter:m,lastError:K}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:K},{targetAgentId:r})}}else{let h=await hd({agentId:c,cwd:p,plan:l,history:o,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!h){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let m=um(h.synopsis,o);m&&fm(m)?(await this.opts.persistSynopsis(e,m,o.length),h.title&&await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!h.title)} fields=${pm(m)}`)):h.title&&(await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(i){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${i.message}`)}}};function um(t,e){let n=dm(e),s=am(e);return t?{...t,files_touched:n.length>0?n:t.files_touched,tools_used:s.length>0?s:t.tools_used}:n.length===0&&s.length===0?void 0:{files_touched:n.length>0?n:void 0,tools_used:s.length>0?s:void 0}}function fm(t){return!!(t.goal&&t.goal.trim().length>0||t.outcome&&t.outcome.trim().length>0||t.files_touched&&t.files_touched.length>0||t.tools_used&&t.tools_used.length>0||t.rejected_approaches&&t.rejected_approaches.length>0||t.open_threads&&t.open_threads.length>0)}function pm(t){let e=[];return t.goal&&e.push("goal"),t.outcome&&e.push("outcome"),t.files_touched&&t.files_touched.length>0&&e.push(`files=${t.files_touched.length}`),t.tools_used&&t.tools_used.length>0&&e.push(`tools=${t.tools_used.length}`),t.rejected_approaches&&t.rejected_approaches.length>0&&e.push(`rejected=${t.rejected_approaches.length}`),t.open_threads&&t.open_threads.length>0&&e.push(`open=${t.open_threads.length}`),`[${e.join(",")}]`}he();import*as Lt from"fs/promises";function mm(t){return t==="summary"?"summary":"inline"}var ru=256;function gm(t,e){return e!=="summary"?t:t.map(Nk)}function Nk(t){if(t.method!=="session/update")return t;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return t;let n=e,s=n.update;if(!s||typeof s!="object"||Array.isArray(s))return t;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return t;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(ym));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=iu(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...t,params:{...n,update:i}}}function Dk(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function ym(t){if(Dk(t)){let s=t,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!t||typeof t!="object"||Array.isArray(t))return t;let e=t,n={...e};return typeof e.text=="string"&&(n.text=iu(e.text)),typeof e.content=="string"?n.content=iu(e.content):e.content&&typeof e.content=="object"&&(n.content=ym(e.content)),n}function iu(t){if(typeof t=="string"&&t.length>ru){let e=t.length-ru;return`${t.slice(0,ru)}\u2026[+${e} chars omitted from summary export]`}return t}var Hk=2048;function wm(t){let e=new Set,n=s=>{if(bm(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)n(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))n(r)};for(let s of t)n(s.params);return e}function bm(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function Uk(t){if(t.method!=="session/update")return!1;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return!1;let s=n.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function du(t,e){if(!Uk(t))return t;let n=t.params,s=n.update,r=await ou(s,e);return{...t,params:{...n,update:r}}}async function ou(t,e){if(typeof t=="string"){if(t.length<=Hk)return t;let n=await e(t);return n===null?t:{__hydraBlob:n,bytes:t.length}}if(Array.isArray(t)){let n=[];for(let s of t)n.push(await ou(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await ou(r,e);return n}return t}async function vm(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await au(n,e);return s===n?t:{...t,params:s}}async function au(t,e){if(bm(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await au(r,e);i!==r&&(n=!0),s.push(i)}return n?s:t}if(t&&typeof t=="object"){let n=!1,s={};for(let[r,i]of Object.entries(t)){let o=await au(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var jo=/^[A-Za-z0-9_-]+$/,jk=1e3,gd=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??jk}async append(e,n){if(jo.test(e))return this.enqueue(e,async()=>{await Lt.mkdir(_.sessionDir(e),{recursive:!0});let s=await du(n,i=>vl(e,i)),r=JSON.stringify(s)+`
286
+ `;await Lt.appendFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(jo.test(e))return this.enqueue(e,async()=>{await Lt.mkdir(_.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await du(i,o=>vl(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
287
287
  `)+`
288
- `;await Lt.writeFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(Uo.test(e))return this.enqueue(e,async()=>{let s;try{s=await Lt.readFile(_.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
288
+ `;await Lt.writeFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(jo.test(e))return this.enqueue(e,async()=>{let s;try{s=await Lt.readFile(_.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
289
289
  `).filter(o=>o.length>0);if(r.length<=n)return;let i=r.slice(-n);await Lt.writeFile(_.historyFile(e),i.join(`
290
290
  `)+`
291
- `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!Uo.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Lt.readFile(_.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let o=[];for(let f of i.split(`
292
- `)){if(f.length===0)continue;let p;try{p=JSON.parse(f)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let h=p;typeof h.method=="string"&&typeof h.recordedAt=="number"&&o.push({method:h.method,params:h.params,recordedAt:h.recordedAt})}let a=n.maxEntries??this.maxEntries,c=o.length>a?o.slice(-a):o;if(!s)return c;let d=new Map,l=async f=>{let p=d.get(f);if(p!==void 0)return p;let h=await Va(e,f);return d.set(f,h),h},u=[];for(let f of c)u.push(await wm(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Uo.test(e))return this.enqueue(e,async()=>{try{await Lt.unlink(_.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await Xp(e);try{await Lt.rmdir(_.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}})}enqueue(e,n){let r=(this.writeQueues.get(e)??Promise.resolve()).then(n,n),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};he();Ve();wd();Mr();ad();Et();Et();nn();Hl();var Sm=900*1e3,Wk="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",bd=qk(Wk,16),vd=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>Ds.spawn(a)),this.store=s??new ud,this.tombstones=r.tombstones??new fd,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new gd({maxEntries:this.sessionHistoryMaxEntries}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let i=r.compaction??{},o=i.tailK??20;this.compactionTailK=o,this.synopsisCoordinator=new md({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:i.maxIterations,persistTitle:async(a,c)=>{let d=this.get(a);if(d){await d.retitle(c);return}await this.persistTitle(a,c)},persistSynopsis:(a,c,d)=>this.persistSynopsis(a,c,d),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,c,d)=>{if(d.targetAgentId)return;let l=this.get(a);l&&(l.compactionState=c),await this.mutateRecord(a,{compactionState:c})},broadcastHydraCompaction:(a,c,d)=>{this.emitSwapPhase(a,d.targetAgentId,c)},onSynthesisArtifact:async(a,c,d,l)=>{await this.dispatchSynthesisSwap(a,c,d,l)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;pendingDeletions=new Map;pendingSwapDisposers=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async dispatchSynthesisSwap(e,n,s,r){let i=this.get(e);if(!i){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:n,summarizedThroughEntry:s});return}let o=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,n,o,s,r);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,r,{phase:"deferred"});let c=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(a){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let n=this.get(e);if(!n)return;let s=this.compactionTailK;try{if(!await n.isQuiescedForSwap()){let c=await this.store.read(e).catch(()=>{});c?.synopsis&&c.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,c.synopsis,c.summarizedThroughEntry,c.pendingAgentSwap);return}let i=await this.store.read(e).catch(()=>{});if(!i?.synopsis||i.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let o=i.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>i.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${i.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),o?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:o}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(n,i.synopsis,s,i.summarizedThroughEntry,o)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performSynthesisSwap(e,n,s,r,i){try{await e.swapUpstream({artifact:n,tailK:s,summarizedThroughEntry:r,...i?{newAgentId:i}:{}}),i?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(o){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${o instanceof Error?o.message:String(o)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await bi(this.registry);this.agentCatalog=e.map(n=>({id:n.id,name:n.name,...n.description!==void 0?{description:n.description}:{}}))}catch{}}async create(e){let n=await this.registry.getAgent(e.agentId);n&&n.id!==e.agentId&&(e={...e,agentId:n.id});let s=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let i={...s.agentCapabilities??{}};for(let o of e.transformChain)if(o.intercepts.has("agent:initialize"))try{let a=await o.connection.request("hydra-acp/transformer/message",{token:`t_${bd()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:i});a.action==="stop"&&a.payload&&(i=a.payload)}catch{}s.agentCapabilities=i}let r=new Ti({cwd:e.cwd,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:i=>this.bootstrapAgent({...i,mcpServers:i.mcpServers??[]}),loadExistingAgentSession:(i,o)=>this.bootstrapAgentLoad(i,{...o,mcpServers:o.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:s.initialModel,currentMode:s.initialMode,agentModes:s.initialModes,agentModels:s.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(r.sessionId),scheduleCompaction:i=>this.scheduleCompaction(r.sessionId,i),getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),onCompactionSwapHook:i=>{this.mutateRecord(r.sessionId,{rollbackBreadcrumb:i}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(r.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(r),r}async resurrect(e){let n=this.sessions.get(e.hydraSessionId);if(n){if(n.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=z.AlreadyAttached,i}return n}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let n=this.sessions.get(e.hydraSessionId);if(n)return n;let s=await this.registry.getAgent(e.agentId);if(!s){let m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=z.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await wn(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:vi,clientInfo:{name:"hydra",version:fe}});o=m.agentCapabilities,i.authMethods=Ko(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Us(m,i)}let a;try{let m=km(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===z.AuthRequired)throw await i.kill().catch(()=>{}),Us(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
293
- `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=hu(a??{}),d=e.agentModes??uu(pu(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(d?.map(m=>m.id))}`);let l=await Si({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:d,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let u=lu(a??{}),f=uu(fu(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(f?.map(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await ki({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let h=new Ti({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:m.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(m,y)=>this.bootstrapAgentLoad(m,{...y,mcpServers:y.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:d,agentModels:f,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(h.sessionId),scheduleCompaction:m=>this.scheduleCompaction(h.sessionId,m),getCompactionState:()=>this.getCompactionState(h.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(h.sessionId),uncompactHook:()=>this.performUncompact(h.sessionId),onCompactionSwapHook:m=>{this.mutateRecord(h.sessionId,{rollbackBreadcrumb:m}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(h.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(h),h}async doResurrectFromImport(e){let n=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:n,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Si({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await ki({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new Ti({sessionId:e.hydraSessionId,cwd:n,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(d,l)=>this.bootstrapAgentLoad(d,{...l,mcpServers:l.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(c.sessionId),scheduleCompaction:d=>this.scheduleCompaction(c.sessionId,d),getCompactionState:()=>this.getCompactionState(c.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(c.sessionId),uncompactHook:()=>this.performUncompact(c.sessionId),onCompactionSwapHook:d=>{this.mutateRecord(c.sessionId,{rollbackBreadcrumb:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(c.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(c),e.forkedFromSessionId&&e.synopsis?c.seedFromFork(e.synopsis).catch(()=>{}):e.forkedFromSessionId&&(e.summarizedThroughEntry??0)>0?this.logger?.info(`fork ${c.sessionId}: synthesis pending or failed \u2014 skipping seed, recall available`):c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await _r.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let n=this.sessions.get(e);!n||n.attachedCount>0||n.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await n.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:et(this.defaultCwd)}async syncFromAgent(e){let n=await this.registry.getAgent(e);if(!n){let p=new Error(`agent ${e} not found in registry`);throw p.code=z.AgentNotInstalled,p}let s=await wn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Sd.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:vi,clientInfo:{name:"hydra",version:fe}})}catch(p){throw await r.kill().catch(()=>{}),Us(p,r)}if(r.authMethods=Ko(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let c=new Set;for(let p of this.sessions.values())c.add(`${p.agentId}::${p.upstreamSessionId}`);let d=await this.store.list().catch(()=>[]);for(let p of d)c.add(`${p.agentId}::${p.upstreamSessionId}`);let l=_.sessionsDir(),u=[],f=0;for(let p of a){let h=`${e}::${p.sessionId}`;if(c.has(h)){f+=1;continue}if(zk(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!Zh(m,p.updatedAt)){f+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}c.add(h);let y=`${bn}${bd()}`,b=new Date().toISOString(),v=p.updatedAt??b,S={sessionId:y,lineageId:Do(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:v,updatedAt:v};p.title!==void 0&&(S.title=p.title);let k=Xl(S);await this.store.write(k),u.push({version:1,...k})}return{synced:u,skipped:f}}async collectAgentSessions(e){let n=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),c=Array.isArray(a.sessions)?a.sessions:[];for(let d of c){if(typeof d.sessionId!="string"||typeof d.cwd!="string")continue;let l={sessionId:d.sessionId,cwd:d.cwd};typeof d.title=="string"&&(l.title=d.title),typeof d.updatedAt=="string"&&(l.updatedAt=d.updatedAt),n.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return n}async applySeedModel(e,n,s,r){try{return await e.connection.request("session/set_model",{sessionId:n,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let n=await this.registry.getAgent(e.agentId);if(!n){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=z.AgentNotInstalled,i}let s=await wn(n,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:vi,clientInfo:{name:"hydra",version:fe}}),o=i.agentCapabilities;r.authMethods=Ko(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),c=a.sessionId;if(typeof c!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let d=lu(a),l=fu(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==d){let h=xi(u,l),m=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(h.kind==="exact"||h.kind==="none")await this.applySeedModel(r,c,u,m)&&(d=u);else if(h.kind==="resolved")(h.modelId===d||await this.applySeedModel(r,c,h.modelId,`${m} resolved to ${JSON.stringify(h.modelId)}`))&&(d=h.modelId);else if(h.kind==="ambiguous")this.logger?.warn(`${m} is ambiguous (trailing-segment matches [${h.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(d)}`);else{let y=l.map(b=>b.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let f=pu(a),p=hu(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:o,initialModel:d,initialModels:l.length>0?l:void 0,initialModes:f.length>0?f:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),Us(xm(i,r,e.agentId,{command:s.command,args:s.args,cwd:e.cwd}),r)}}async bootstrapAgentLoad(e,n){let s=await this.registry.getAgent(n.agentId);if(!s){let o=new Error(`agent ${n.agentId} not found in registry`);throw o.code=z.AgentNotInstalled,o}let r=await wn(s,n.agentArgs??[],{npmRegistry:this.npmRegistry}),i=this.spawner({agentId:n.agentId,cwd:n.cwd,plan:r,...n.forwardedEnv?{extraEnv:n.forwardedEnv}:{}});try{let o=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:vi,clientInfo:{name:"hydra",version:fe}}),a=o.agentCapabilities;i.authMethods=Ko(o.authMethods);let c=km(n.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:n.cwd,mcpServers:n.mcpServers??[],...c&&{_meta:c}}),l=lu(d),u=uu(fu(d)),f=pu(d),p=hu(d);return{agent:i,upstreamSessionId:e,agentMeta:d._meta,agentCapabilities:a,initialModel:l,initialModels:u,initialModes:f.length>0?f:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),Us(xm(o,i,n.agentId,{command:r.command,args:r.args,cwd:n.cwd}),i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let n=this.get(e);if(!n)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)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 i=s.compactionState;if(i!=null)throw new Error(`compaction is in progress (status: ${i.status}) \u2014 wait for it to complete before rolling back`);if(!await n.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await n.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,n){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let c=new Error(`agent ${e} not found in registry`);throw c.code=z.AgentNotInstalled,c}let i=await wn(r,[],{npmRegistry:this.npmRegistry}),o=n??et(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:vi,clientInfo:{name:"hydra",version:fe}});a.authMethods=Ko(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),Us(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let n=await this.registry.getAgent(e);if(!n){let s=new Error(`agent ${e} not found in registry`);throw s.code=z.AgentNotInstalled,s}return wn(n,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let n=this.pendingAuthAgents.get(e);if(n&&(this.pendingAuthAgents.delete(e),!!n.isAlive()))return n}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:n})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),n){if(e.upstreamSessionId){let r=_i({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),i=this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===i&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,i);return}let s=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===s&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,s);return}}),e.onTitleChange(n=>{this.persistTitle(e.sessionId,n).catch(()=>{})}),e.onPriorityChange(n=>{this.persistPriority(e.sessionId,n).catch(()=>{})}),e.onAgentChange(({agentId:n,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,n,s).catch(()=>{})}),e.onModelChange(n=>{this.persistSnapshot(e.sessionId,{currentModel:n}).catch(()=>{})}),e.onModeChange(n=>{this.persistSnapshot(e.sessionId,{currentMode:n}).catch(()=>{})}),e.onInteractiveChange(n=>{this.persistSnapshot(e.sessionId,{interactive:n}).catch(()=>{})}),e.onUsageChange(n=>{this.persistSnapshot(e.sessionId,{currentUsage:Cm(n)}).catch(()=>{})}),e.onAgentCommandsChange(n=>{this.persistSnapshot(e.sessionId,{agentCommands:n.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(n=>{this.persistSnapshot(e.sessionId,{agentModes:n.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(n=>{this.persistSnapshot(e.sessionId,{agentModels:n.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(n=>{this.mutateRecord(e.sessionId,{attentionFlags:n}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let n=await this.store.read(e.sessionId),s=Kk(e,n);await this.store.write(s)}).catch(()=>{})}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 loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,n){return Va(e,n)}async loadFromDisk(e){let n=await this.store.read(e);if(!n)return;let s=n.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,agentId:n.agentId,cwd:n.cwd,title:s,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:Jk(n.currentUsage?{...n.currentUsage,cumulativeCost:(n.currentUsage.cumulativeCost??0)+(n.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,createdAt:n.createdAt,pendingHistorySync:n.pendingHistorySync,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,forwardedEnv:n.forwardedEnv,compactionState:n.compactionState,attentionFlags:n.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,n){if(n===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=n),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:n};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let n=await this.store.read(e);if(!n||n.pendingHistorySync!==!0)return;let s={...n};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let n=await this.histories.load(e).catch(()=>[]);for(let s of n){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Ci(r.update.prompt),o=Wl(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let n of this.sessions.values()){let s=n.agent.agentId,r=n.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(bn))return;let n=bn+e;if(this.sessions.has(n)||await this.store.read(n))return n}require(e){let n=this.sessions.get(e);if(!n){let s=new Error(`session ${e} not found`);throw s.code=z.SessionNotFound,s}return n}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let n=this.sessions.get(e);if(n){let a=await Jo(n.sessionId),c=_i({interactive:n.interactive,...n.originatingClient?{originatingClient:n.originatingClient}:{}},a.hasContent),d=a.mtime??new Date(n.updatedAt).toISOString();return{sessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:c,priority:n.priority,updatedAt:d,attachedClients:n.attachedCount,status:"warm",busy:n.turnStartedAt!==void 0,awaitingInput:n.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await Jo(s.sessionId),i=_i(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let n=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(n);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(n,{expiresAt:s+t.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(n);o&&o.promise===i&&this.listCache.delete(n)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let n=[],s=new Set,r=l=>e.includeNonInteractive?!0:l===!0,i=[...this.sessions.values()].filter(l=>!e.cwd||l.cwd===e.cwd),o=await Promise.all(i.map(l=>Jo(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=_i({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},f.hasContent);if(!r(p))continue;let h=f.mtime??new Date(u.updatedAt).toISOString();n.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:u.attachedCount,status:"warm",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}let c=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!s.has(l.sessionId)&&(!e.cwd||l.cwd===e.cwd)),d=await Promise.all(c.map(l=>Jo(l.sessionId)));for(let l=0;l<c.length;l+=1){let u=c[l],f=d[l],p=_i(u,f.hasContent);if(!r(p))continue;let h=f.mtime??u.updatedAt;n.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}return n.sort((l,u)=>l.updatedAt<u.updatedAt?1:-1),n}async exportBundle(e,n={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let d=Do(),l={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:d}))}).catch(()=>{}),r=l}let i=n.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Am(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of gm(o)){let l=await Qp(e,d);l&&(c[d]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:c}}async importBundle(e,n={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!n.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=z.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:n.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${bn}${bd()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:n.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,n={}){let s=await this.store.read(e);if(!s){let S=new Error(`source session not found: ${e}`);throw S.code=z.SessionNotFound,S}let r=n.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let k=new Error(`agent ${r} not found in registry`);throw k.code=z.AgentNotInstalled,k}let o=await this.histories.load(e).catch(()=>[]),a=o,c,d=n.mode??"synthesis",l,u,f,p=12e4;if(d==="verbatim")if(n.forkAt!==void 0){let S=ql(o,n.forkAt);if(S<0){let k=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw k.code=z.InvalidParams,k}c=n.forkAt,a=o.slice(0,S+1)}else{let S=Vk(o);S?(c=S.messageId,a=o.slice(0,S.index+1)):(c="",a=o.slice(0,0))}else{n.forkAt!==void 0&&this.logger?.warn(`synthesis fork: ignoring forkAt=${n.forkAt} (synthesis covers full history)`),c="",a=o;let S=await this.registry.getAgent(r);if(!S){let k=new Error(`agent ${r} not found in registry`);throw k.code=z.AgentNotInstalled,k}f=S,u=s.currentModel,l="running"}let h=await Am(e),m=d==="synthesis",y={...s,lineageId:Do(),agentId:r,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},...m?{summarizedThroughEntry:o.length}:{},...n.title!==void 0?{title:n.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},b=zo({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:fe,machine:Sd.hostname()}),v=`${bn}${bd()}`;return await this.writeImportedRecord({sessionId:v,bundle:b,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let S=await wn(f,[],{npmRegistry:this.npmRegistry}),k=await hd({agentId:r,cwd:n.cwd??_.sessionDir(e),plan:S,history:o,modelId:u,sessionId:e,logger:this.logger,timeoutMs:p});k&&k.synopsis?await this.mutateRecord(v,{synopsis:k.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(v,{},["forkSynthesisState"]))}catch(S){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${S.message}`);try{await this.mutateRecord(v,{},["forkSynthesisState"])}catch(k){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${k.message}`)}}})(),{sessionId:v,forkedFromSessionId:e,forkedAt:c}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await Gp(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await _r.utimes(_.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Pr(_.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{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,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??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,n="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await Jo(e),i=_i(s,r.hasContent);await this.tombstones.add({agentId:s.agentId,upstreamSessionId:s.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:s.updatedAt,cwd:s.cwd,title:s.title,reason:n,...i!==void 0?{interactive:i}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let n=this.pendingDeletions.get(e);n&&await n}async isTombstoned(e,n){return(await this.tombstones.read(e,n).catch(()=>{}))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,n){let s=this.get(e);if(s)return s.setPriority(n),!0;if(!await this.hasRecord(e))return!1;let r=n===void 0||n<=0?void 0:Math.floor(n);return await this.persistPriority(e,r),!0}async persistPriority(e,n){n===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:n}),this.invalidateListCache()}async setTitle(e,n){let s=this.get(e);return s?(await s.retitle(n),!0):await this.hasRecord(e)?(await this.persistTitle(e,n),!0):!1}async persistTitle(e,n){await this.mutateRecord(e,{title:n})}async persistSynopsis(e,n,s){await this.mutateRecord(e,{synopsis:n,summarizedThroughEntry:s})}async persistAgentChange(e,n,s){await this.mutateRecord(e,{agentId:n,upstreamSessionId:s})}async persistSnapshot(e,n){let s={};n.currentModel!==void 0&&(s.currentModel=n.currentModel),n.currentMode!==void 0&&(s.currentMode=n.currentMode),n.currentUsage!==void 0&&(s.currentUsage=n.currentUsage),n.agentCommands!==void 0&&(s.agentCommands=n.agentCommands),n.agentModes!==void 0&&(s.agentModes=n.agentModes),n.agentModels!==void 0&&(s.agentModels=n.agentModels),n.interactive!==void 0&&(s.interactive=n.interactive),n.cwd!==void 0&&(s.cwd=n.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,n,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...n,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}enqueueMetaWrite(e,n){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(n),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(n=>n.close({deleteRecord:!1}))),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,n){n?.targetAgentId&&this.mutateRecord(e,{pendingAgentSwap:n.targetAgentId}).catch(s=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${s instanceof Error?s.message:String(s)}`)}),this.synopsisCoordinator.scheduleCompaction(e,n)}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 getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,n,s){let r=this.get(e);if(r){if(n){let i=s.phase==="failed";r.broadcastPendingAgentSwap(i?null:n);return}r.broadcastCompactionPhase(s)}}async getSummarizedThroughEntry(e){let n=this.sessions.get(e);return n?n.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(()=>[]),n=0;for(let s of e){let r=s.attentionFlags??[],i=r.filter(o=>!(o.source==="daemon"&&o.reason.startsWith("permission:")));if(i.length!==r.length){let o=r.length-i.length;n+=o,await this.mutateRecord(s.sessionId,{attentionFlags:i}).catch(()=>{})}}n>0&&this.logger?.info(`cleared ${n} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),n=await this.store.list().catch(()=>[]);for(let s of n){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(i){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=n.pendingAgentSwap;if(s)try{let r=await this.histories.load(n.sessionId).catch(()=>[]);n.synopsis!==void 0&&n.summarizedThroughEntry!==void 0&&n.summarizedThroughEntry>=r.length&&n.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${n.sessionId} target=${s} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(n.sessionId,n.synopsis,n.summarizedThroughEntry??r.length,s)):(this.logger?.info(`agent-swap: resuming sessionId=${n.sessionId} target=${s} via fresh synthesis (history=${r.length} watermark=${n.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(n.sessionId,{targetAgentId:s}))}catch(r){this.logger?.warn(`agent-swap: resume failed for sessionId=${n.sessionId}: ${r instanceof Error?r.message:String(r)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=await Lh(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<Sm),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${Sm/1e3}s)`),await Lo(n.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(n.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${n.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await Lo(n.sessionId,[]).catch(()=>{});continue}try{let c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${n.sessionId} and replaying ${i.length} prompt(s)`),c.replayPersistedQueue(i)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${n.sessionId}: ${c.message}`)}}}};function zk(t,e){if(typeof t!="string"||t.length===0)return!1;let n=Yo.resolve(t),s=Yo.resolve(e);return n===s||n.startsWith(s+Yo.sep)}function Kk(t,e){let s=(t.mergedAvailableCommands().length>0?t.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=t.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=t.availableModels(),d=(a.length>0?a.map(l=>{let u={modelId:l.modelId};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModels;return Xl({sessionId:t.sessionId,lineageId:e?.lineageId??Do(),upstreamSessionId:t.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel??e?.currentModel,currentMode:t.currentMode??e?.currentMode,currentUsage:Cm(t.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:d,parentSessionId:t.parentSessionId??e?.parentSessionId,forkedFromSessionId:t.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:t.originatingClient??e?.originatingClient,interactive:t.interactive??e?.interactive,priority:t.priority??e?.priority,forwardedEnv:t.forwardedEnv??e?.forwardedEnv,attentionFlags:t.listAttentionFlags(),createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function Cm(t){if(!t)return;let e={};return t.used!==void 0&&(e.used=t.used),t.size!==void 0&&(e.size=t.size),t.costAmount!==void 0&&(e.costAmount=t.costAmount),t.costCurrency!==void 0&&(e.costCurrency=t.costCurrency),t.cumulativeCost!==void 0&&(e.cumulativeCost=t.cumulativeCost),Object.keys(e).length>0?e:void 0}function Jk(t){return t?{...t}:void 0}function km(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function kd(t,e){let n=e.fromObject(t);if(n!==void 0)return n;let s=t[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=t._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let c=e.fromObject(a);if(c!==void 0)return c}}let i=Yk(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function lu(t){return kd(t,{nestedKey:"models",configId:"model",fromObject:e=>zn(e.currentModelId)??zn(e.currentModel)??zn(e.modelId)??zn(e.model),fromConfig:e=>zn(e.currentValue)})}function Us(t,e){if(!t||typeof t!="object")return t;let n=t;if(n.code!==z.AuthRequired)return t;let s=d=>!!d&&typeof d=="object"&&!Array.isArray(d),r=s(n.data)?n.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof n.message=="string"?n.message:"authentication required",c=new Error(a);return c.code=z.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function Im(t){return/^[A-Za-z0-9_\-./=:@]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function xm(t,e,n,s){if(t&&typeof t=="object"&&t.code===z.AuthRequired)return t;let r=t instanceof Error?t.message:String(t),i=r.includes("stderr:"),o=i?"":e.stderrTailText(),a=s?`to reproduce: (cd ${Im(s.cwd)} && ${[s.command,...s.args].map(Im).join(" ")})`:"";if(!o&&!a)return t;let c=[i?r:`agent ${n} failed to start: ${r}`];o&&c.push(`stderr: ${o}`),a&&c.push(a);let d=new Error(c.join(`
294
- `));if(t&&typeof t=="object"){let l=t;typeof l.code=="number"&&(d.code=l.code),l.data!==void 0&&(d.data=l.data)}return d}function Ko(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,c=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...c&&{_meta:c}})}return e.length>0?e:void 0}function zn(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function Yk(t,e){let n=t.configOptions;if(Array.isArray(n))for(let s of n){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function uu(t){return t.length>0?t:void 0}function fu(t){return kd(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=Ri(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=Ri(e.options);return n.length>0?n:void 0}})??[]}function pu(t){return kd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>{let n=Bo(e.availableModes);return n.length>0?n:void 0},fromConfig:e=>{let n=Bo(e.options);return n.length>0?n:void 0}})??[]}function hu(t){return kd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>zn(e.currentModeId)??zn(e.currentMode)??zn(e.modeId)??zn(e.mode),fromConfig:e=>zn(e.currentValue)})}function Vk(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(!n||n.method!=="session/update")continue;let s=n.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function Am(t){try{let e=await _r.readFile(_.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
295
- `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function Jo(t){try{let e=await _r.stat(_.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function _i(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===Er?!1:e?!0:void 0}import{spawn as Qk}from"child_process";import*as Fi from"fs";import*as js from"fs/promises";import*as Rm from"path";var Id=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,n,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${n}\``;return this.tripped_=o,{tripped:o}}let r=this.now();this.recentExits.push(r);let i=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<i;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let o=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${o}m (crash loop); fix and run \`${s}s start ${n}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};Ve();var Gk=1e3,Xk=6e4,mu=3e3,$i=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,n,s,r={}){this.adapter=n,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??Gk,this.restartCapMs=r.restartCapMs??Xk;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,n){let s=this.entries.get(e);s&&(s.version=n)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await js.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();for(let e of this.entries.values())e.config.enabled&&this.spawn(e,0)}async stop(){this.stopping=!0;let e=[];for(let n of this.entries.values()){n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},mu);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let n of this.entries.values()){try{n.logStream?.end()}catch{}n.child=void 0,n.logStream=void 0,n.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let n=this.entries.get(e);return n?this.infoFor(n):void 0}has(e){return this.entries.has(e)}async startByName(e){let n=this.entries.get(e);if(!n)throw Vo(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw Vo(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0),n.manuallyStopped=!1,n.restartCount=0,n.breaker.reset(),n.failureReason=void 0,this.spawn(n,0),this.infoFor(n)}async stopByName(e){let n=this.entries.get(e);if(!n)throw Vo(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;return s?(await this.terminate(n,s),this.infoFor(n)):this.infoFor(n)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw Vo(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 n=this.makeEntry(e);return this.entries.set(e.name,n),e.enabled&&this.spawn(n,0),this.infoFor(n)}async unregister(e){let n=this.entries.get(e);if(!n)throw Vo(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;s&&await this.terminate(n,s);try{n.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,n){if(n.exitCode!==null||n.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{n.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},mu);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let n;return e.failureReason!==void 0?n="failed":e.child?n="running":e.restartTimer?n="restarting":e.config.enabled?n="stopped":n="disabled",{name:e.config.name,status:n,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 Id(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await js.readdir(this.adapter.paths.dir())}catch(n){if(n.code==="ENOENT")return;throw n}for(let n of e){if(!n.endsWith(".pid"))continue;let s=Rm.join(this.adapter.paths.dir(),n),r;try{let i=await js.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&gu(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+mu;for(;Date.now()<i&&gu(r);)await new Promise(o=>setTimeout(o,50));if(gu(r))try{process.kill(r,"SIGKILL")}catch{}}await js.unlink(s).catch(()=>{})}}spawn(e,n){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,i=r.command.length>0?r.command:[r.name],o=Fi.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});o.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${n+1})
291
+ `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!jo.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Lt.readFile(_.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let o=[];for(let f of i.split(`
292
+ `)){if(f.length===0)continue;let p;try{p=JSON.parse(f)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let h=p;typeof h.method=="string"&&typeof h.recordedAt=="number"&&o.push({method:h.method,params:h.params,recordedAt:h.recordedAt})}let a=n.maxEntries??this.maxEntries,c=o.length>a?o.slice(-a):o;if(!s)return c;let d=new Map,l=async f=>{let p=d.get(f);if(p!==void 0)return p;let h=await Qa(e,f);return d.set(f,h),h},u=[];for(let f of c)u.push(await vm(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(jo.test(e))return this.enqueue(e,async()=>{try{await Lt.unlink(_.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await Zp(e);try{await Lt.rmdir(_.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}})}enqueue(e,n){let r=(this.writeQueues.get(e)??Promise.resolve()).then(n,n),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};he();Ge();wd();Mr();ad();Et();Et();nn();Ul();var Im=900*1e3,Vk="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",bd=Jk(Vk,16),vd=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>Ds.spawn(a)),this.store=s??new ud,this.tombstones=r.tombstones??new fd,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new gd({maxEntries:this.sessionHistoryMaxEntries}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let i=r.compaction??{},o=i.tailK??20;this.compactionTailK=o,this.synopsisCoordinator=new md({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:i.maxIterations,persistTitle:async(a,c)=>{let d=this.get(a);if(d){await d.retitle(c);return}await this.persistTitle(a,c)},persistSynopsis:(a,c,d)=>this.persistSynopsis(a,c,d),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,c,d)=>{if(d.targetAgentId)return;let l=this.get(a);l&&(l.compactionState=c),await this.mutateRecord(a,{compactionState:c})},broadcastHydraCompaction:(a,c,d)=>{this.emitSwapPhase(a,d.targetAgentId,c)},onSynthesisArtifact:async(a,c,d,l)=>{await this.dispatchSynthesisSwap(a,c,d,l)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;pendingDeletions=new Map;pendingSwapDisposers=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async dispatchSynthesisSwap(e,n,s,r){let i=this.get(e);if(!i){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:n,summarizedThroughEntry:s});return}let o=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,n,o,s,r);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,r,{phase:"deferred"});let c=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(a){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let n=this.get(e);if(!n)return;let s=this.compactionTailK;try{if(!await n.isQuiescedForSwap()){let c=await this.store.read(e).catch(()=>{});c?.synopsis&&c.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,c.synopsis,c.summarizedThroughEntry,c.pendingAgentSwap);return}let i=await this.store.read(e).catch(()=>{});if(!i?.synopsis||i.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let o=i.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>i.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${i.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),o?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:o}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(n,i.synopsis,s,i.summarizedThroughEntry,o)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performSynthesisSwap(e,n,s,r,i){try{let o=i?Math.min(5,s):0;await e.swapUpstream({artifact:n,tailK:s,tailFloor:o,summarizedThroughEntry:r,...i?{newAgentId:i}:{}}),i?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(o){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${o instanceof Error?o.message:String(o)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await bi(this.registry);this.agentCatalog=e.map(n=>({id:n.id,name:n.name,...n.description!==void 0?{description:n.description}:{}}))}catch{}}async create(e){let n=await this.registry.getAgent(e.agentId);n&&n.id!==e.agentId&&(e={...e,agentId:n.id});let s=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let i={...s.agentCapabilities??{}};for(let o of e.transformChain)if(o.intercepts.has("agent:initialize"))try{let a=await o.connection.request("hydra-acp/transformer/message",{token:`t_${bd()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:i});a.action==="stop"&&a.payload&&(i=a.payload)}catch{}s.agentCapabilities=i}let r=new Ei({cwd:e.cwd,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:i=>this.bootstrapAgent({...i,mcpServers:i.mcpServers??[]}),loadExistingAgentSession:(i,o)=>this.bootstrapAgentLoad(i,{...o,mcpServers:o.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:s.initialModel,currentMode:s.initialMode,agentModes:s.initialModes,agentModels:s.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(r.sessionId),scheduleCompaction:i=>this.scheduleCompaction(r.sessionId,i),getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),onCompactionSwapHook:i=>{this.mutateRecord(r.sessionId,{rollbackBreadcrumb:i}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(r.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(r),r}async resurrect(e){let n=this.sessions.get(e.hydraSessionId);if(n){if(n.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=z.AlreadyAttached,i}return n}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let n=this.sessions.get(e.hydraSessionId);if(n)return n;let s=await this.registry.getAgent(e.agentId);if(!s){let m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=z.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await wn(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:vi,clientInfo:{name:"hydra",version:fe}});o=m.agentCapabilities,i.authMethods=Jo(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Us(m,i)}let a;try{let m=xm(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===z.AuthRequired)throw await i.kill().catch(()=>{}),Us(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
293
+ `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=mu(a??{}),d=e.agentModes??fu(hu(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(d?.map(m=>m.id))}`);let l=await Si({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:d,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let u=uu(a??{}),f=fu(pu(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(f?.map(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await ki({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let h=new Ei({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:m.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(m,y)=>this.bootstrapAgentLoad(m,{...y,mcpServers:y.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:d,agentModels:f,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(h.sessionId),scheduleCompaction:m=>this.scheduleCompaction(h.sessionId,m),getCompactionState:()=>this.getCompactionState(h.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(h.sessionId),uncompactHook:()=>this.performUncompact(h.sessionId),onCompactionSwapHook:m=>{this.mutateRecord(h.sessionId,{rollbackBreadcrumb:m}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(h.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(h),h}async doResurrectFromImport(e){let n=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:n,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Si({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await ki({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new Ei({sessionId:e.hydraSessionId,cwd:n,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(d,l)=>this.bootstrapAgentLoad(d,{...l,mcpServers:l.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(c.sessionId),scheduleCompaction:d=>this.scheduleCompaction(c.sessionId,d),getCompactionState:()=>this.getCompactionState(c.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(c.sessionId),uncompactHook:()=>this.performUncompact(c.sessionId),onCompactionSwapHook:d=>{this.mutateRecord(c.sessionId,{rollbackBreadcrumb:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(c.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(c),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${c.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?c.seedFromFork(e.synopsis).catch(()=>{}):c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await _r.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let n=this.sessions.get(e);!n||n.attachedCount>0||n.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await n.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:et(this.defaultCwd)}async syncFromAgent(e){let n=await this.registry.getAgent(e);if(!n){let p=new Error(`agent ${e} not found in registry`);throw p.code=z.AgentNotInstalled,p}let s=await wn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Sd.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:vi,clientInfo:{name:"hydra",version:fe}})}catch(p){throw await r.kill().catch(()=>{}),Us(p,r)}if(r.authMethods=Jo(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let c=new Set;for(let p of this.sessions.values())c.add(`${p.agentId}::${p.upstreamSessionId}`);let d=await this.store.list().catch(()=>[]);for(let p of d)c.add(`${p.agentId}::${p.upstreamSessionId}`);let l=_.sessionsDir(),u=[],f=0;for(let p of a){let h=`${e}::${p.sessionId}`;if(c.has(h)){f+=1;continue}if(Yk(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!tm(m,p.updatedAt)){f+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}c.add(h);let y=`${bn}${bd()}`,b=new Date().toISOString(),v=p.updatedAt??b,S={sessionId:y,lineageId:Ho(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:v,updatedAt:v};p.title!==void 0&&(S.title=p.title);let k=Zl(S);await this.store.write(k),u.push({version:1,...k})}return{synced:u,skipped:f}}async collectAgentSessions(e){let n=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),c=Array.isArray(a.sessions)?a.sessions:[];for(let d of c){if(typeof d.sessionId!="string"||typeof d.cwd!="string")continue;let l={sessionId:d.sessionId,cwd:d.cwd};typeof d.title=="string"&&(l.title=d.title),typeof d.updatedAt=="string"&&(l.updatedAt=d.updatedAt),n.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return n}async applySeedModel(e,n,s,r){try{return await e.connection.request("session/set_model",{sessionId:n,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let n=await this.registry.getAgent(e.agentId);if(!n){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=z.AgentNotInstalled,i}let s=await wn(n,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:vi,clientInfo:{name:"hydra",version:fe}}),o=i.agentCapabilities;r.authMethods=Jo(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),c=a.sessionId;if(typeof c!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let d=uu(a),l=pu(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==d){let h=Ai(u,l),m=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(h.kind==="exact"||h.kind==="none")await this.applySeedModel(r,c,u,m)&&(d=u);else if(h.kind==="resolved")(h.modelId===d||await this.applySeedModel(r,c,h.modelId,`${m} resolved to ${JSON.stringify(h.modelId)}`))&&(d=h.modelId);else if(h.kind==="ambiguous")this.logger?.warn(`${m} is ambiguous (trailing-segment matches [${h.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(d)}`);else{let y=l.map(b=>b.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let f=hu(a),p=mu(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:o,initialModel:d,initialModels:l.length>0?l:void 0,initialModes:f.length>0?f:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),Us(Cm(i,r,e.agentId,{command:s.command,args:s.args,cwd:e.cwd}),r)}}async bootstrapAgentLoad(e,n){let s=await this.registry.getAgent(n.agentId);if(!s){let o=new Error(`agent ${n.agentId} not found in registry`);throw o.code=z.AgentNotInstalled,o}let r=await wn(s,n.agentArgs??[],{npmRegistry:this.npmRegistry}),i=this.spawner({agentId:n.agentId,cwd:n.cwd,plan:r,...n.forwardedEnv?{extraEnv:n.forwardedEnv}:{}});try{let o=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:vi,clientInfo:{name:"hydra",version:fe}}),a=o.agentCapabilities;i.authMethods=Jo(o.authMethods);let c=xm(n.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:n.cwd,mcpServers:n.mcpServers??[],...c&&{_meta:c}}),l=uu(d),u=fu(pu(d)),f=hu(d),p=mu(d);return{agent:i,upstreamSessionId:e,agentMeta:d._meta,agentCapabilities:a,initialModel:l,initialModels:u,initialModes:f.length>0?f:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),Us(Cm(o,i,n.agentId,{command:r.command,args:r.args,cwd:n.cwd}),i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let n=this.get(e);if(!n)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)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 i=s.compactionState;if(i!=null)throw new Error(`compaction is in progress (status: ${i.status}) \u2014 wait for it to complete before rolling back`);if(!await n.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await n.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,n){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let c=new Error(`agent ${e} not found in registry`);throw c.code=z.AgentNotInstalled,c}let i=await wn(r,[],{npmRegistry:this.npmRegistry}),o=n??et(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:vi,clientInfo:{name:"hydra",version:fe}});a.authMethods=Jo(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),Us(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let n=await this.registry.getAgent(e);if(!n){let s=new Error(`agent ${e} not found in registry`);throw s.code=z.AgentNotInstalled,s}return wn(n,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let n=this.pendingAuthAgents.get(e);if(n&&(this.pendingAuthAgents.delete(e),!!n.isAlive()))return n}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:n})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),n){if(e.upstreamSessionId){let r=$i({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),i=this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===i&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,i);return}let s=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===s&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,s);return}}),e.onTitleChange(n=>{this.persistTitle(e.sessionId,n).catch(()=>{})}),e.onPriorityChange(n=>{this.persistPriority(e.sessionId,n).catch(()=>{})}),e.onAgentChange(({agentId:n,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,n,s).catch(()=>{})}),e.onModelChange(n=>{this.persistSnapshot(e.sessionId,{currentModel:n}).catch(()=>{})}),e.onModeChange(n=>{this.persistSnapshot(e.sessionId,{currentMode:n}).catch(()=>{})}),e.onInteractiveChange(n=>{this.persistSnapshot(e.sessionId,{interactive:n}).catch(()=>{})}),e.onUsageChange(n=>{this.persistSnapshot(e.sessionId,{currentUsage:Tm(n)}).catch(()=>{})}),e.onAgentCommandsChange(n=>{this.persistSnapshot(e.sessionId,{agentCommands:n.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(n=>{this.persistSnapshot(e.sessionId,{agentModes:n.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(n=>{this.persistSnapshot(e.sessionId,{agentModels:n.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(n=>{this.mutateRecord(e.sessionId,{attentionFlags:n}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let n=await this.store.read(e.sessionId),s=Qk(e,n);await this.store.write(s)}).catch(()=>{})}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 loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,n){return Qa(e,n)}async loadFromDisk(e){let n=await this.store.read(e);if(!n)return;let s=n.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,agentId:n.agentId,cwd:n.cwd,title:s,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:Gk(n.currentUsage?{...n.currentUsage,cumulativeCost:(n.currentUsage.cumulativeCost??0)+(n.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,createdAt:n.createdAt,pendingHistorySync:n.pendingHistorySync,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,forwardedEnv:n.forwardedEnv,compactionState:n.compactionState,attentionFlags:n.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,n){if(n===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=n),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:n};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let n=await this.store.read(e);if(!n||n.pendingHistorySync!==!0)return;let s={...n};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let n=await this.histories.load(e).catch(()=>[]);for(let s of n){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Ri(r.update.prompt),o=zl(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let n of this.sessions.values()){let s=n.agent.agentId,r=n.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(bn))return;let n=bn+e;if(this.sessions.has(n)||await this.store.read(n))return n}require(e){let n=this.sessions.get(e);if(!n){let s=new Error(`session ${e} not found`);throw s.code=z.SessionNotFound,s}return n}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let n=this.sessions.get(e);if(n){let a=await Vo(n.sessionId),c=$i({interactive:n.interactive,...n.originatingClient?{originatingClient:n.originatingClient}:{}},a.hasContent),d=a.mtime??new Date(n.updatedAt).toISOString();return{sessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:c,priority:n.priority,updatedAt:d,attachedClients:n.attachedCount,status:"warm",busy:n.turnStartedAt!==void 0,awaitingInput:n.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await Vo(s.sessionId),i=$i(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let n=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(n);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(n,{expiresAt:s+t.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(n);o&&o.promise===i&&this.listCache.delete(n)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let n=[],s=new Set,r=l=>e.includeNonInteractive?!0:l===!0,i=[...this.sessions.values()].filter(l=>!e.cwd||l.cwd===e.cwd),o=await Promise.all(i.map(l=>Vo(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=$i({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},f.hasContent);if(!r(p))continue;let h=f.mtime??new Date(u.updatedAt).toISOString();n.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:u.attachedCount,status:"warm",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}let c=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!s.has(l.sessionId)&&(!e.cwd||l.cwd===e.cwd)),d=await Promise.all(c.map(l=>Vo(l.sessionId)));for(let l=0;l<c.length;l+=1){let u=c[l],f=d[l],p=$i(u,f.hasContent);if(!r(p))continue;let h=f.mtime??u.updatedAt;n.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}return n.sort((l,u)=>l.updatedAt<u.updatedAt?1:-1),n}async exportBundle(e,n={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let d=Ho(),l={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:d}))}).catch(()=>{}),r=l}let i=n.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Rm(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of wm(o)){let l=await Gp(e,d);l&&(c[d]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:c}}async importBundle(e,n={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!n.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=z.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:n.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${bn}${bd()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:n.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,n={}){let s=await this.store.read(e);if(!s){let S=new Error(`source session not found: ${e}`);throw S.code=z.SessionNotFound,S}let r=n.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let k=new Error(`agent ${r} not found in registry`);throw k.code=z.AgentNotInstalled,k}let o=await this.histories.load(e).catch(()=>[]),a=o,c,d=n.mode??"synthesis",l,u,f,p=12e4;if(d==="verbatim")if(n.forkAt!==void 0){let S=Wl(o,n.forkAt);if(S<0){let k=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw k.code=z.InvalidParams,k}c=n.forkAt,a=o.slice(0,S+1)}else{let S=Zk(o);S?(c=S.messageId,a=o.slice(0,S.index+1)):(c="",a=o.slice(0,0))}else{n.forkAt!==void 0&&this.logger?.warn(`synthesis fork: ignoring forkAt=${n.forkAt} (synthesis covers full history)`),c="",a=o;let S=await this.registry.getAgent(r);if(!S){let k=new Error(`agent ${r} not found in registry`);throw k.code=z.AgentNotInstalled,k}f=S,u=s.currentModel,l="running"}let h=await Rm(e),m=d==="synthesis",y={...s,lineageId:Ho(),agentId:r,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},summarizedThroughEntry:a.length,...n.title!==void 0?{title:n.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...n.model!==void 0?{currentModel:n.model}:{}},b=Ko({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:fe,machine:Sd.hostname()}),v=`${bn}${bd()}`;return await this.writeImportedRecord({sessionId:v,bundle:b,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let S=await wn(f,[],{npmRegistry:this.npmRegistry}),k=await hd({agentId:r,cwd:n.cwd??_.sessionDir(e),plan:S,history:o,modelId:u,sessionId:e,logger:this.logger,timeoutMs:p});k&&k.synopsis?await this.mutateRecord(v,{synopsis:k.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(v,{},["forkSynthesisState"]))}catch(S){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${S.message}`);try{await this.mutateRecord(v,{},["forkSynthesisState"])}catch(k){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${k.message}`)}}})(),{sessionId:v,forkedFromSessionId:e,forkedAt:c}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await Xp(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await _r.utimes(_.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Pr(_.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{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,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??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,n="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await Vo(e),i=$i(s,r.hasContent);await this.tombstones.add({agentId:s.agentId,upstreamSessionId:s.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:s.updatedAt,cwd:s.cwd,title:s.title,reason:n,...i!==void 0?{interactive:i}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let n=this.pendingDeletions.get(e);n&&await n}async isTombstoned(e,n){return(await this.tombstones.read(e,n).catch(()=>{}))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,n){let s=this.get(e);if(s)return s.setPriority(n),!0;if(!await this.hasRecord(e))return!1;let r=n===void 0||n<=0?void 0:Math.floor(n);return await this.persistPriority(e,r),!0}async persistPriority(e,n){n===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:n}),this.invalidateListCache()}async setTitle(e,n){let s=this.get(e);return s?(await s.retitle(n),!0):await this.hasRecord(e)?(await this.persistTitle(e,n),!0):!1}async persistTitle(e,n){await this.mutateRecord(e,{title:n})}async persistSynopsis(e,n,s){await this.mutateRecord(e,{synopsis:n,summarizedThroughEntry:s})}async persistAgentChange(e,n,s){await this.mutateRecord(e,{agentId:n,upstreamSessionId:s})}async persistSnapshot(e,n){let s={};n.currentModel!==void 0&&(s.currentModel=n.currentModel),n.currentMode!==void 0&&(s.currentMode=n.currentMode),n.currentUsage!==void 0&&(s.currentUsage=n.currentUsage),n.agentCommands!==void 0&&(s.agentCommands=n.agentCommands),n.agentModes!==void 0&&(s.agentModes=n.agentModes),n.agentModels!==void 0&&(s.agentModels=n.agentModels),n.interactive!==void 0&&(s.interactive=n.interactive),n.cwd!==void 0&&(s.cwd=n.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,n,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...n,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}enqueueMetaWrite(e,n){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(n),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(n=>n.close({deleteRecord:!1}))),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,n){n?.targetAgentId&&this.mutateRecord(e,{pendingAgentSwap:n.targetAgentId}).catch(s=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${s instanceof Error?s.message:String(s)}`)}),this.synopsisCoordinator.scheduleCompaction(e,n)}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 getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,n,s){let r=this.get(e);if(r){if(n){let i=s.phase==="failed";r.broadcastPendingAgentSwap(i?null:n);return}r.broadcastCompactionPhase(s)}}async getSummarizedThroughEntry(e){let n=this.sessions.get(e);return n?n.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(()=>[]),n=0;for(let s of e){let r=s.attentionFlags??[],i=r.filter(o=>!(o.source==="daemon"&&o.reason.startsWith("permission:")));if(i.length!==r.length){let o=r.length-i.length;n+=o,await this.mutateRecord(s.sessionId,{attentionFlags:i}).catch(()=>{})}}n>0&&this.logger?.info(`cleared ${n} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),n=await this.store.list().catch(()=>[]);for(let s of n){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(i){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=n.pendingAgentSwap;if(s)try{let r=await this.histories.load(n.sessionId).catch(()=>[]);n.synopsis!==void 0&&n.summarizedThroughEntry!==void 0&&n.summarizedThroughEntry>=r.length&&n.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${n.sessionId} target=${s} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(n.sessionId,n.synopsis,n.summarizedThroughEntry??r.length,s)):(this.logger?.info(`agent-swap: resuming sessionId=${n.sessionId} target=${s} via fresh synthesis (history=${r.length} watermark=${n.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(n.sessionId,{targetAgentId:s}))}catch(r){this.logger?.warn(`agent-swap: resume failed for sessionId=${n.sessionId}: ${r instanceof Error?r.message:String(r)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=await Dh(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<Im),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${Im/1e3}s)`),await Bo(n.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(n.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${n.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await Bo(n.sessionId,[]).catch(()=>{});continue}try{let c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${n.sessionId} and replaying ${i.length} prompt(s)`),c.replayPersistedQueue(i)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${n.sessionId}: ${c.message}`)}}}};function Yk(t,e){if(typeof t!="string"||t.length===0)return!1;let n=Yo.resolve(t),s=Yo.resolve(e);return n===s||n.startsWith(s+Yo.sep)}function Qk(t,e){let s=(t.mergedAvailableCommands().length>0?t.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=t.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=t.availableModels(),d=(a.length>0?a.map(l=>{let u={modelId:l.modelId};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModels;return Zl({sessionId:t.sessionId,lineageId:e?.lineageId??Ho(),upstreamSessionId:t.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel??e?.currentModel,currentMode:t.currentMode??e?.currentMode,currentUsage:Tm(t.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:d,parentSessionId:t.parentSessionId??e?.parentSessionId,forkedFromSessionId:t.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:t.originatingClient??e?.originatingClient,interactive:t.interactive??e?.interactive,priority:t.priority??e?.priority,forwardedEnv:t.forwardedEnv??e?.forwardedEnv,attentionFlags:t.listAttentionFlags(),createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function Tm(t){if(!t)return;let e={};return t.used!==void 0&&(e.used=t.used),t.size!==void 0&&(e.size=t.size),t.costAmount!==void 0&&(e.costAmount=t.costAmount),t.costCurrency!==void 0&&(e.costCurrency=t.costCurrency),t.cumulativeCost!==void 0&&(e.cumulativeCost=t.cumulativeCost),Object.keys(e).length>0?e:void 0}function Gk(t){return t?{...t}:void 0}function xm(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function kd(t,e){let n=e.fromObject(t);if(n!==void 0)return n;let s=t[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=t._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let c=e.fromObject(a);if(c!==void 0)return c}}let i=Xk(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function uu(t){return kd(t,{nestedKey:"models",configId:"model",fromObject:e=>zn(e.currentModelId)??zn(e.currentModel)??zn(e.modelId)??zn(e.model),fromConfig:e=>zn(e.currentValue)})}function Us(t,e){if(!t||typeof t!="object")return t;let n=t;if(n.code!==z.AuthRequired)return t;let s=d=>!!d&&typeof d=="object"&&!Array.isArray(d),r=s(n.data)?n.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof n.message=="string"?n.message:"authentication required",c=new Error(a);return c.code=z.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function Am(t){return/^[A-Za-z0-9_\-./=:@]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Cm(t,e,n,s){if(t&&typeof t=="object"&&t.code===z.AuthRequired)return t;let r=t instanceof Error?t.message:String(t),i=r.includes("stderr:"),o=i?"":e.stderrTailText(),a=s?`to reproduce: (cd ${Am(s.cwd)} && ${[s.command,...s.args].map(Am).join(" ")})`:"";if(!o&&!a)return t;let c=[i?r:`agent ${n} failed to start: ${r}`];o&&c.push(`stderr: ${o}`),a&&c.push(a);let d=new Error(c.join(`
294
+ `));if(t&&typeof t=="object"){let l=t;typeof l.code=="number"&&(d.code=l.code),l.data!==void 0&&(d.data=l.data)}return d}function Jo(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,c=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...c&&{_meta:c}})}return e.length>0?e:void 0}function zn(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function Xk(t,e){let n=t.configOptions;if(Array.isArray(n))for(let s of n){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function fu(t){return t.length>0?t:void 0}function pu(t){return kd(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=Ti(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=Ti(e.options);return n.length>0?n:void 0}})??[]}function hu(t){return kd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>{let n=No(e.availableModes);return n.length>0?n:void 0},fromConfig:e=>{let n=No(e.options);return n.length>0?n:void 0}})??[]}function mu(t){return kd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>zn(e.currentModeId)??zn(e.currentMode)??zn(e.modeId)??zn(e.mode),fromConfig:e=>zn(e.currentValue)})}function Zk(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(!n||n.method!=="session/update")continue;let s=n.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function Rm(t){try{let e=await _r.readFile(_.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
295
+ `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function Vo(t){try{let e=await _r.stat(_.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function $i(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===Er?!1:e?!0:void 0}import{spawn as eI}from"child_process";import*as Fi from"fs";import*as js from"fs/promises";import*as Em from"path";var Id=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,n,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${n}\``;return this.tripped_=o,{tripped:o}}let r=this.now();this.recentExits.push(r);let i=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<i;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let o=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${o}m (crash loop); fix and run \`${s}s start ${n}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};Ge();var tI=1e3,nI=6e4,gu=3e3,Oi=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,n,s,r={}){this.adapter=n,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??tI,this.restartCapMs=r.restartCapMs??nI;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,n){let s=this.entries.get(e);s&&(s.version=n)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await js.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();for(let e of this.entries.values())e.config.enabled&&this.spawn(e,0)}async stop(){this.stopping=!0;let e=[];for(let n of this.entries.values()){n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},gu);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let n of this.entries.values()){try{n.logStream?.end()}catch{}n.child=void 0,n.logStream=void 0,n.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let n=this.entries.get(e);return n?this.infoFor(n):void 0}has(e){return this.entries.has(e)}async startByName(e){let n=this.entries.get(e);if(!n)throw Qo(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw Qo(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0),n.manuallyStopped=!1,n.restartCount=0,n.breaker.reset(),n.failureReason=void 0,this.spawn(n,0),this.infoFor(n)}async stopByName(e){let n=this.entries.get(e);if(!n)throw Qo(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;return s?(await this.terminate(n,s),this.infoFor(n)):this.infoFor(n)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw Qo(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 n=this.makeEntry(e);return this.entries.set(e.name,n),e.enabled&&this.spawn(n,0),this.infoFor(n)}async unregister(e){let n=this.entries.get(e);if(!n)throw Qo(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;s&&await this.terminate(n,s);try{n.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,n){if(n.exitCode!==null||n.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{n.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},gu);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let n;return e.failureReason!==void 0?n="failed":e.child?n="running":e.restartTimer?n="restarting":e.config.enabled?n="stopped":n="disabled",{name:e.config.name,status:n,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 Id(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await js.readdir(this.adapter.paths.dir())}catch(n){if(n.code==="ENOENT")return;throw n}for(let n of e){if(!n.endsWith(".pid"))continue;let s=Em.join(this.adapter.paths.dir(),n),r;try{let i=await js.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&yu(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+gu;for(;Date.now()<i&&yu(r);)await new Promise(o=>setTimeout(o,50));if(yu(r))try{process.kill(r,"SIGKILL")}catch{}}await js.unlink(s).catch(()=>{})}}spawn(e,n){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,i=r.command.length>0?r.command:[r.name],o=Fi.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});o.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${n+1})
296
296
  `);let a=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=a,e.version=void 0;let c={...process.env,HYDRA_ACP_DAEMON_URL:s.daemonUrl,HYDRA_ACP_DAEMON_HOST:s.daemonHost,HYDRA_ACP_DAEMON_PORT:String(s.daemonPort),HYDRA_ACP_TOKEN:a,HYDRA_ACP_WS_URL:s.daemonWsUrl,HYDRA_ACP_HOME:s.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[d,...l]=i;if(d===void 0){o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
297
- `),o.end();return}let u=et(d),f=[...l,...r.args].map(et),p;try{p=Qk(u,f,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(h){o.write(`[hydra-acp] failed to spawn ${r.name}: ${h.message}
297
+ `),o.end();return}let u=et(d),f=[...l,...r.args].map(et),p;try{p=eI(u,f,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(h){o.write(`[hydra-acp] failed to spawn ${r.name}: ${h.message}
298
298
  `),o.end(),this.scheduleRestart(e,n);return}if(p.stdout&&p.stdout.pipe(o,{end:!1}),p.stderr&&p.stderr.pipe(o,{end:!1}),typeof p.pid=="number")try{Fi.writeFileSync(this.adapter.paths.pidFile(r.name),`${p.pid}
299
299
  `,{encoding:"utf8",mode:384})}catch(h){o.write(`[hydra-acp] failed to write pid file for ${r.name}: ${h.message}
300
300
  `)}e.child=p,e.logStream=o,e.pid=typeof p.pid=="number"?p.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,p.on("error",h=>{o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${h.message}
301
301
  `)}),p.on("exit",(h,m)=>{try{Fi.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${h??"null"} signal=${m??"null"}
302
302
  `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof h=="number"?h:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let y=e.exitWaiters.splice(0);for(let v of y)v();if(this.stopping||e.manuallyStopped){try{o.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let b=e.breaker.recordExit(h,r.name,this.adapter.kind);if(typeof b=="object"){e.failureReason=b.tripped,o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${b.tripped}
303
- `);try{o.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,n+1)})}scheduleRestart(e,n){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(n,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,n)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function gu(t){try{return process.kill(t,0),!0}catch{return!1}}function Vo(t,e){return t.code=e,t}he();var Zk={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:_.extensionsDir,logFile:_.extensionLogFile,pidFile:_.extensionPidFile}},xd=class extends $i{constructor(e,n,s={}){super(e,Zk,n,s)}};he();var eI={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:_.transformersDir,logFile:_.transformerLogFile,pidFile:_.transformerPidFile}},Ad=class extends $i{connected=new Map;constructor(e,n,s={}){super(e,eI,n,s)}registerConnection(e,n,s){this.connected.set(e,{name:e,connection:n,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let n=[];for(let s of e){let r=this.connected.get(s);r&&n.push(r)}return n}};var Cd=class{entries=new Map;changeHandlers=[];register(e,n,s){this.entries.set(e,{connection:n,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[n,s]of this.entries)for(let r of s.commands)e.push({name:n,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};he();mi();he();import*as Go from"fs/promises";import*as Rd from"path";var Qo=t=>{process.stderr.write(t+`
304
- `)};function yu(t){Qo=t??(e=>process.stderr.write(e+`
305
- `))}async function Tm(t,e){let n=Hn();if(!n)return;let s=await t.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let i=e.activeAgentVersions(),o=Rd.join(_.agentsDir(),n),a;try{a=await Go.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;Qo(`hydra-acp: prune: failed to read ${o}: ${d.message}`);return}for(let c of a){if(!c.isDirectory())continue;let d=c.name,l=r.get(d);if(l===void 0)continue;let u=i.get(d)??new Set,f=Rd.join(o,d),p;try{p=await Go.readdir(f,{withFileTypes:!0})}catch(h){Qo(`hydra-acp: prune: failed to read ${f}: ${h.message}`);continue}for(let h of p){if(!h.isDirectory())continue;let m=h.name;if(m===l||u.has(m)||m.includes(".partial-"))continue;let y=Rd.join(f,m);try{await Go.rm(y,{recursive:!0,force:!0}),Qo(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(b){Qo(`hydra-acp: prune: failed to remove ${y}: ${b.message}`)}}}}function Em(t){let e,n=!1,s=0,r=(a,c)=>{t.logger&&t.logger[a](`agent-sync: ${c}`)},i=async()=>{let a=[];try{let l=await t.registry.load();for(let u of l.agents)await Tl(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),t.intervalMs}if(a.length===0)return t.intervalMs;let c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:u}=await t.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${d}: ${l.message}`)}return Math.max(1,Math.floor(t.intervalMs/a.length))},o=a=>{n||(e=setTimeout(()=>{i().then(c=>{o(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),o(t.intervalMs)})},a),e.unref())};return o(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}async function wu(t){let e=t.maxDeletions??200,n=(p,h)=>{t.logger&&t.logger[p](`session-gc: ${h}`)},s=Date.now(),r=t.maxAgeMs>0?s-t.maxAgeMs:Number.POSITIVE_INFINITY,i=await t.manager.list({includeNonInteractive:!0}).catch(p=>(n("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((t.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(t.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,h)=>p.lastUsedMs-h.lastUsedMs);let a=o.slice(0,e),c=a[0]?.lastUsedMs,d=0,l=0;for(let{sessionId:p}of a)try{await t.manager.deleteRecord(p,"expired")&&(d+=1)}catch(h){l+=1,n("warn",`delete ${p} failed: ${h.message}`)}let u=o.length-a.length;if(t.verbose||d>0||l>0){let p=(t.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";n("info",`swept ${d} ${p} session(s) older than ${tI(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:d,failed:l,deferred:u};return c!==void 0&&(f.oldestLastUsedMs=c),f}function Pm(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await wu({manager:t.manager,maxAgeMs:t.maxAgeMs,selection:"unpromoted",...t.maxDeletionsPerSweep!==void 0?{maxDeletions:t.maxDeletionsPerSweep}:{},...t.logger?{logger:t.logger}:{}})}finally{s=!1}}})().catch(a=>{t.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(t.intervalMs)})},i),e.unref())};return r(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}function tI(t){if(t<=0)return"any age";let e=t/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let n=t/(3600*1e3);return`${n.toFixed(n>=10?0:1)}h`}nn();Xo();he();Sr();import*as $m from"path";import{createHash as sI,randomBytes as rI,timingSafeEqual as iI}from"crypto";var Fm="hydra_session_",oI=3600*24*30,Mm=12,aI=32,dI=50;function cI(){return $m.join(_.home(),"session-tokens.json")}function _m(t){return sI("sha256").update(t).digest("hex")}function Om(t){return rI(t).toString("hex")}function lI(){return Om(Mm).slice(0,Mm*2)}function uI(){return`${Fm}${Om(aI)}`}var Td=class t{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,n){this.filePath=n;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],n=cI(),s=await yn(n);s&&Array.isArray(s.records)&&(e=s.records.filter(fI));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=uI(),s=_m(n),r=lI(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:oI,a=new Date(i.getTime()+o*1e3),c={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,c),this.scheduleWrite(),{id:r,token:n,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Fm))return;let n=_m(e),s=this.records.get(n);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(n,"hex");if(r.length!==i.length||!iI(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(n),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[n,s]of this.records)if(s.id===e)return this.records.delete(n),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,n)=>n.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let n=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),n+=1);return n>0&&this.scheduleWrite(),n}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},dI))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Xt(this.filePath,{records:Array.from(this.records.values())},{mode:384}));return this.writeInflight=e,e.catch(()=>{}).finally(()=>{this.writeInflight===e&&(this.writeInflight=null)}),e}};function fI(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}fs();var Lm="Bearer ",Ed=class{constructor(e){this.token=e}token;async validate(e){return pI(e,this.token)?"service":void 0}},Pd=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Md=class{constructor(e){this.validators=e}validators;async validate(e){for(let n of this.validators){let s=await n.validate(e);if(s!==void 0)return s}}};function Bm(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(Lm)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Lm.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function Nm(t){let e=t.headers["sec-websocket-protocol"],n=Array.isArray(e)?e.join(","):e;if(n)for(let s of n.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(t.url)try{let r=new URL(t.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var _d=class{tokens=new Map;mint(e,n){let s=ui();return this.tokens.set(s,{name:e,kind:n}),s}revoke(e){for(let[n,s]of this.tokens)s.name===e&&this.tokens.delete(n)}resolve(e){return this.tokens.get(e)}async validate(e){let n=this.tokens.get(e);if(n)return`${n.kind}:${n.name}`}};function pI(t,e){if(t.length!==e.length)return!1;let n=0;for(let s=0;s<t.length;s+=1)n|=t.charCodeAt(s)^e.charCodeAt(s);return n===0}var $d=class{entries=new Map;maxFails;windowMs;constructor(e=10,n=900*1e3){this.maxFails=e,this.windowMs=n}isBlocked(e){let n=this.entries.get(e);return n?Date.now()-n.windowStart>this.windowMs?(this.entries.delete(e),!1):n.fails>=this.maxFails:!1}recordFailure(e){let n=Date.now(),s=this.entries.get(e);if(!s||n-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:n});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[n,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(n)}};he();Ve();Su();Mr();Ld();import*as Au from"fs";import*as ta from"os";import*as sg from"path";import*as Cu from"readline";Ws();qn();function Bd(t){let e=UI(t),n=jI(e),s=[];qI(s,t),WI(s,e,n);let r=s.join(`
303
+ `);try{o.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,n+1)})}scheduleRestart(e,n){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(n,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,n)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function yu(t){try{return process.kill(t,0),!0}catch{return!1}}function Qo(t,e){return t.code=e,t}he();var sI={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:_.extensionsDir,logFile:_.extensionLogFile,pidFile:_.extensionPidFile}},xd=class extends Oi{constructor(e,n,s={}){super(e,sI,n,s)}};he();var rI={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:_.transformersDir,logFile:_.transformerLogFile,pidFile:_.transformerPidFile}},Ad=class extends Oi{connected=new Map;constructor(e,n,s={}){super(e,rI,n,s)}registerConnection(e,n,s){this.connected.set(e,{name:e,connection:n,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let n=[];for(let s of e){let r=this.connected.get(s);r&&n.push(r)}return n}};var Cd=class{entries=new Map;changeHandlers=[];register(e,n,s){this.entries.set(e,{connection:n,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[n,s]of this.entries)for(let r of s.commands)e.push({name:n,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};he();mi();he();import*as Xo from"fs/promises";import*as Rd from"path";var Go=t=>{process.stderr.write(t+`
304
+ `)};function wu(t){Go=t??(e=>process.stderr.write(e+`
305
+ `))}async function Pm(t,e){let n=Hn();if(!n)return;let s=await t.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let i=e.activeAgentVersions(),o=Rd.join(_.agentsDir(),n),a;try{a=await Xo.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;Go(`hydra-acp: prune: failed to read ${o}: ${d.message}`);return}for(let c of a){if(!c.isDirectory())continue;let d=c.name,l=r.get(d);if(l===void 0)continue;let u=i.get(d)??new Set,f=Rd.join(o,d),p;try{p=await Xo.readdir(f,{withFileTypes:!0})}catch(h){Go(`hydra-acp: prune: failed to read ${f}: ${h.message}`);continue}for(let h of p){if(!h.isDirectory())continue;let m=h.name;if(m===l||u.has(m)||m.includes(".partial-"))continue;let y=Rd.join(f,m);try{await Xo.rm(y,{recursive:!0,force:!0}),Go(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(b){Go(`hydra-acp: prune: failed to remove ${y}: ${b.message}`)}}}}function Mm(t){let e,n=!1,s=0,r=(a,c)=>{t.logger&&t.logger[a](`agent-sync: ${c}`)},i=async()=>{let a=[];try{let l=await t.registry.load();for(let u of l.agents)await El(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),t.intervalMs}if(a.length===0)return t.intervalMs;let c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:u}=await t.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${d}: ${l.message}`)}return Math.max(1,Math.floor(t.intervalMs/a.length))},o=a=>{n||(e=setTimeout(()=>{i().then(c=>{o(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),o(t.intervalMs)})},a),e.unref())};return o(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}async function bu(t){let e=t.maxDeletions??200,n=(p,h)=>{t.logger&&t.logger[p](`session-gc: ${h}`)},s=Date.now(),r=t.maxAgeMs>0?s-t.maxAgeMs:Number.POSITIVE_INFINITY,i=await t.manager.list({includeNonInteractive:!0}).catch(p=>(n("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((t.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(t.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,h)=>p.lastUsedMs-h.lastUsedMs);let a=o.slice(0,e),c=a[0]?.lastUsedMs,d=0,l=0;for(let{sessionId:p}of a)try{await t.manager.deleteRecord(p,"expired")&&(d+=1)}catch(h){l+=1,n("warn",`delete ${p} failed: ${h.message}`)}let u=o.length-a.length;if(t.verbose||d>0||l>0){let p=(t.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";n("info",`swept ${d} ${p} session(s) older than ${iI(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:d,failed:l,deferred:u};return c!==void 0&&(f.oldestLastUsedMs=c),f}function _m(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await bu({manager:t.manager,maxAgeMs:t.maxAgeMs,selection:"unpromoted",...t.maxDeletionsPerSweep!==void 0?{maxDeletions:t.maxDeletionsPerSweep}:{},...t.logger?{logger:t.logger}:{}})}finally{s=!1}}})().catch(a=>{t.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(t.intervalMs)})},i),e.unref())};return r(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}function iI(t){if(t<=0)return"any age";let e=t/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let n=t/(3600*1e3);return`${n.toFixed(n>=10?0:1)}h`}nn();Zo();he();Sr();import*as Fm from"path";import{createHash as aI,randomBytes as dI,timingSafeEqual as cI}from"crypto";var Lm="hydra_session_",lI=3600*24*30,$m=12,uI=32,fI=50;function pI(){return Fm.join(_.home(),"session-tokens.json")}function Om(t){return aI("sha256").update(t).digest("hex")}function Bm(t){return dI(t).toString("hex")}function hI(){return Bm($m).slice(0,$m*2)}function mI(){return`${Lm}${Bm(uI)}`}var Td=class t{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,n){this.filePath=n;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],n=pI(),s=await yn(n);s&&Array.isArray(s.records)&&(e=s.records.filter(gI));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=mI(),s=Om(n),r=hI(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:lI,a=new Date(i.getTime()+o*1e3),c={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,c),this.scheduleWrite(),{id:r,token:n,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Lm))return;let n=Om(e),s=this.records.get(n);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(n,"hex");if(r.length!==i.length||!cI(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(n),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[n,s]of this.records)if(s.id===e)return this.records.delete(n),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,n)=>n.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let n=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),n+=1);return n>0&&this.scheduleWrite(),n}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},fI))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Xt(this.filePath,{records:Array.from(this.records.values())},{mode:384}));return this.writeInflight=e,e.catch(()=>{}).finally(()=>{this.writeInflight===e&&(this.writeInflight=null)}),e}};function gI(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}ps();var Nm="Bearer ",Ed=class{constructor(e){this.token=e}token;async validate(e){return yI(e,this.token)?"service":void 0}},Pd=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Md=class{constructor(e){this.validators=e}validators;async validate(e){for(let n of this.validators){let s=await n.validate(e);if(s!==void 0)return s}}};function Dm(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(Nm)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Nm.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function Hm(t){let e=t.headers["sec-websocket-protocol"],n=Array.isArray(e)?e.join(","):e;if(n)for(let s of n.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(t.url)try{let r=new URL(t.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var _d=class{tokens=new Map;mint(e,n){let s=ui();return this.tokens.set(s,{name:e,kind:n}),s}revoke(e){for(let[n,s]of this.tokens)s.name===e&&this.tokens.delete(n)}resolve(e){return this.tokens.get(e)}async validate(e){let n=this.tokens.get(e);if(n)return`${n.kind}:${n.name}`}};function yI(t,e){if(t.length!==e.length)return!1;let n=0;for(let s=0;s<t.length;s+=1)n|=t.charCodeAt(s)^e.charCodeAt(s);return n===0}var $d=class{entries=new Map;maxFails;windowMs;constructor(e=10,n=900*1e3){this.maxFails=e,this.windowMs=n}isBlocked(e){let n=this.entries.get(e);return n?Date.now()-n.windowStart>this.windowMs?(this.entries.delete(e),!1):n.fails>=this.maxFails:!1}recordFailure(e){let n=Date.now(),s=this.entries.get(e);if(!s||n-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:n});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[n,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(n)}};he();Ge();ku();Mr();Ld();import*as Cu from"fs";import*as na from"os";import*as ig from"path";import*as Ru from"readline";Ws();qn();function Bd(t){let e=zI(t),n=KI(e),s=[];JI(s,t),VI(s,e,n);let r=s.join(`
306
306
  `);return r.endsWith(`
307
307
  `)||(r+=`
308
- `),r}function UI(t){let e=[];for(let n of t.history){if(n.method!=="session/update")continue;let s=n.params;if(!s||typeof s!="object")continue;let r=Kn(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function jI(t){let e=new Map;for(let{event:n}of t){if(n.kind==="tool-call"){let s=e.get(n.toolCallId);e.set(n.toolCallId,{title:n.title,status:n.status??s?.status??"pending"});continue}if(n.kind==="tool-call-update"){let s=e.get(n.toolCallId)??{title:"tool call",status:"pending"};e.set(n.toolCallId,{title:n.title??s.title,status:n.status??s.status})}}return e}function qI(t,e){let n=e.session,s=rt(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${$r(r)}`),t.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${n.lineageId}\`)`);let o=[n.agentId];n.currentModel&&o.push(`model: ${n.currentModel}`),n.currentMode&&o.push(`mode: ${n.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${n.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=n.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let c=[];if(a.used!==void 0){let d=a.size!==void 0?`${Iu(a.size)}`:void 0;c.push(d?`${Iu(a.used)} / ${d} tokens`:`${Iu(a.used)} tokens`)}if(a.costAmount!==void 0){let d=a.costCurrency??"USD";c.push(`$${a.costAmount.toFixed(2)} ${d}`)}i.push(`- **Usage:** ${c.join(" \xB7 ")}`)}t.push(i.join(`
309
- `)),t.push("")}function WI(t,e,n){if(!e.some(d=>zI(d.event))){t.push("_No conversation history recorded._"),t.push("");return}let s=new Set,r=0,i="",o=!1,a=()=>{i.length!==0&&(t.push(i.trimEnd()),t.push(""),i="")},c=()=>{o||(r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),o=!0)};for(let{event:d}of e)switch(d.kind){case"user-text":{a(),r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),t.push("**User:**"),t.push("");for(let l of d.text.split(`
308
+ `),r}function zI(t){let e=[];for(let n of t.history){if(n.method!=="session/update")continue;let s=n.params;if(!s||typeof s!="object")continue;let r=Kn(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function KI(t){let e=new Map;for(let{event:n}of t){if(n.kind==="tool-call"){let s=e.get(n.toolCallId);e.set(n.toolCallId,{title:n.title,status:n.status??s?.status??"pending"});continue}if(n.kind==="tool-call-update"){let s=e.get(n.toolCallId)??{title:"tool call",status:"pending"};e.set(n.toolCallId,{title:n.title??s.title,status:n.status??s.status})}}return e}function JI(t,e){let n=e.session,s=rt(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${$r(r)}`),t.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${n.lineageId}\`)`);let o=[n.agentId];n.currentModel&&o.push(`model: ${n.currentModel}`),n.currentMode&&o.push(`mode: ${n.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${n.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=n.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let c=[];if(a.used!==void 0){let d=a.size!==void 0?`${xu(a.size)}`:void 0;c.push(d?`${xu(a.used)} / ${d} tokens`:`${xu(a.used)} tokens`)}if(a.costAmount!==void 0){let d=a.costCurrency??"USD";c.push(`$${a.costAmount.toFixed(2)} ${d}`)}i.push(`- **Usage:** ${c.join(" \xB7 ")}`)}t.push(i.join(`
309
+ `)),t.push("")}function VI(t,e,n){if(!e.some(d=>YI(d.event))){t.push("_No conversation history recorded._"),t.push("");return}let s=new Set,r=0,i="",o=!1,a=()=>{i.length!==0&&(t.push(i.trimEnd()),t.push(""),i="")},c=()=>{o||(r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),o=!0)};for(let{event:d}of e)switch(d.kind){case"user-text":{a(),r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),t.push("**User:**"),t.push("");for(let l of d.text.split(`
310
310
  `))t.push(`> ${$r(l)}`);t.push(""),t.push("**Assistant:**"),t.push(""),o=!0;break}case"agent-text":c(),i+=d.text;break;case"agent-thought":{c(),a();let l=d.text.split(`
311
- `);for(let u of l)t.push(`> _${$r(u)}_`);t.push("");break}case"tool-call":{if(c(),a(),s.has(d.toolCallId))break;s.add(d.toolCallId);let l=n.get(d.toolCallId)??{title:d.title,status:d.status??"pending"};t.push(`- ${JI(l.status)} ${KI(l)}`),t.push("");break}case"tool-call-update":break;case"plan":{c(),a(),t.push("**Plan:**"),t.push("");for(let l of d.entries){let u=l.status==="completed"?"[x]":"[ ]";t.push(`- ${u} ${$r(l.content)}`)}t.push("");break}case"mode-changed":c(),a(),t.push(`_mode: ${$r(d.mode)}_`),t.push("");break;case"model-changed":c(),a(),t.push(`_model: ${$r(d.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function zI(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function KI(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${$r(t.title)}${n}`}function JI(t){switch(t){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function $r(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Iu(t){return t.toLocaleString("en-US")}Et();nn();Eo();Ws();function YI(t){let e=t.trim();if(e.length===0)return{operator:"OR",terms:[]};let n=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=n.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,c=[];for(let l of s){let u=l.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>VI(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function VI(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:Vm(e[1]),term:e[2]};let n=/^"([^"]*)"$/.exec(t);if(n)return{scope:"all",term:n[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(t);return s?{scope:Vm(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function Vm(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function QI(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var GI=5,XI=200,Qm=30;async function Zm(t,e,n={}){let s=YI(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??GI,i=n.maxSessions??XI,o=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),c=o?a.filter(u=>o.has(u.sessionId)):a,d=[],l=!1;for(let u of c){if(d.length>=i){l=!0;break}let f=await t.loadHistory(u.sessionId).catch(()=>[]),p=ZI(f,s,r);if(p.snippets.length===0)continue;let h={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(h.title=u.title),d.push(h)}return{query:e,truncated:l,results:d}}function ZI(t,e,n){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=ex(t,o,i,n-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function ex(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=tx(a).filter(d=>QI(n,d.kind));for(let d of c){let l=d.text.toLowerCase(),u=l.indexOf(r);if(u===-1)continue;let f=0;for(;u!==-1;)f++,u=l.indexOf(r,u+r.length);if(i+=f,o.length<s){let p=l.indexOf(r),h={kind:d.kind,text:ox(d.text,p,r.length),recordedAt:a.recordedAt};d.toolName!==void 0&&(h.toolName=d.toolName),o.push(h)}}}return{totalMatches:i,snippets:o}}function tx(t){if(t.method!=="session/update")return[];let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return[];let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=Nd(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?lt(s.text):Nd(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(rx(s))return[];let i=Nd(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=ix(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return nx(s);default:return[]}}function nx(t){let e=Gm(t,"name"),n=Gm(t,"title"),s=[];if(n!==void 0){let a=Ee(n);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==n){let a=Ee(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=Xm(r);if(a.length>0){let c={kind:"tool-input",text:Ee(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=Xm(i);if(a.length>0){let c={kind:"tool-input",text:Ee(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=sx(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function sx(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=s.content;if(!i||typeof i!="object")continue;let o=i;if(o.type==="text"&&typeof o.text=="string"){let a=Ee(o.text);if(a.length>0)return a}}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"){let r=Ee(s);if(r.length>0)return r}}return null}function rx(t){let e=t._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e["hydra-acp"];return!n||typeof n!="object"||Array.isArray(n)?!1:n.compatFor==="prompt_received"}function Nd(t){if(typeof t=="string")return lt(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?lt(e.text):""}function ix(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=Nd(n);s.length>0&&e.push(s)}return e.join("")}function Gm(t,e){let n=t[e];return typeof n=="string"?n:void 0}function Xm(t){try{return JSON.stringify(t)}catch{return""}}function ox(t,e,n){let s=t.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=t.slice(e,e+n).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-Qm),c=Math.min(s.length,o+i.length+Qm),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as tg}from"crypto";function eg(t){let e=tg(32).toString("hex");return t.tokenRegistry.reserve(e).complete(t.session),t.session.onClose(()=>{t.tokenRegistry.unbind(e)}),{name:t.name,type:"http",url:`${t.getOrigin()}/mcp/${t.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function xu(t){if(t.deps.mcpTokenRegistry===void 0||t.deps.getDaemonOrigin===void 0)return;let e=t.deps.mcpTokenRegistry,n=t.deps.getDaemonOrigin;return async s=>{let r=[...t.baselineMcpServers??[]];t.stdinEnabled&&r.push(eg({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push(eg({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=Bi(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function Bi(t){if(t.extensionMcp===void 0||t.mcpTokenRegistry===void 0||t.getDaemonOrigin===void 0)return;let e=t.extensionMcp.list();if(e.length===0)return;let n=tg(32).toString("hex"),s=t.mcpTokenRegistry.reserve(n),r=t.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${n}`}]})),o=t.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(n)})},abandon:a=>s.abandon(a)}}var Dd=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function ng(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!kr(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function rg(t,e,n,s={}){t.get("/v1/sessions",async d=>{let l=d.query,u=l?.includeNonInteractive==="1"||l?.includeNonInteractive==="true";return{sessions:await e.list({cwd:l?.cwd,includeNonInteractive:u})}}),t.get("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.getOne(f);return p||(l.code(404).send({error:"session not found"}),l)}),t.post("/v1/sessions/search",async(d,l)=>{let u=d.body??{},f=typeof u.q=="string"?u.q:"";if(f.trim().length===0)return l.code(400).send({error:"q is required"}),l;let p=Array.isArray(u.sessionIds)?u.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await Zm(e,f,{sessionIds:p})}),t.post("/v1/sessions",async(d,l)=>{let u=d.body??{},f=et(u.cwd??n.cwd),p=u.agentId??n.agentId,h=Bi(s),m=h!==void 0?[...u.mcpServers??[],...h.descriptors]:u.mcpServers;try{let y=await e.create({cwd:f,agentId:p,mcpServers:m});h!==void 0&&h.bindToSession(y),l.code(201).send({sessionId:y.sessionId,agentId:y.agentId,cwd:y.cwd})}catch(y){h!==void 0&&h.abandon(y instanceof Error?y:void 0),l.code(500).send({error:y.message})}}),t.post("/v1/sessions/collect",async(d,l)=>{let u=d.body??{},f=typeof u.maxAgeDays=="number"&&u.maxAgeDays>0?u.maxAgeDays*24*60*60*1e3:0,p=typeof u.limit=="number"&&u.limit>0?u.limit:1e3,h=u.selection==="explicit"||u.selection==="unpromoted"?u.selection:"unpromoted";try{let m=await wu({manager:e,maxAgeMs:f,maxDeletions:p,selection:h,verbose:!1});l.code(200).send(m)}catch(m){l.code(500).send({error:m.message})}}),t.post("/v1/sessions/:id/kill",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){p.close({deleteRecord:!1}).catch(()=>{}),l.code(202).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.post("/v1/sessions/:id/stdin/open",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m={};(h.mode==="memory"||h.mode==="file")&&(m.mode=h.mode),typeof h.capacityBytes=="number"&&(m.capacityBytes=h.capacityBytes),typeof h.fileCapBytes=="number"&&(m.fileCapBytes=h.fileCapBytes),(m.mode??"memory")==="file"&&(m.filePathFor=y=>sg.join(ta.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return p.openStream(m)}catch(y){return l.code(409).send({error:y.message}),l}}),t.post("/v1/sessions/:id/stdin",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m=typeof h.chunk=="string"?h.chunk:"",y=h.eof===!0;try{return p.streamWrite(m,y)}catch(b){return l.code(409).send({error:b.message}),l}}),t.patch("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.body??{};if(p.priority!==void 0){let m=p.priority,y;if(m===null||m===0)y=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)y=m;else{l.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(f,y)){l.code(404).send({error:"session not found"});return}l.code(204).send();return}if(p.regen===!0){if(!(e.get(f)!==void 0||await e.hasRecord(f))){l.code(404).send({error:"session not found"});return}e.scheduleSynopsis(f),l.code(202).send();return}if(typeof p.title!="string"||p.title.trim().length===0){l.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(f,p.title)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.delete("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){await p.close({deleteRecord:!0}),await e.waitForDeletion(f),await e.hasRecord(f)&&await e.deleteRecord(f),l.code(204).send();return}if(!await e.deleteRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.get("/v1/sessions/:id/export",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.query?.tools,h=p==="references"?"references":pm(p),m=await e.exportBundle(f,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=zo({record:m.record,history:h==="summary"?hm(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:fe,machine:ta.hostname(),hydraHost:ng(n)}),b=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${f}-${b}.hydra"`),l.code(200).send(y)}),t.get("/v1/sessions/:id/diff",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let h=d.query??{},m=h.fold==="true"||h.fold==="1",y=typeof h.paths=="string"&&h.paths.length>0?new Set(h.paths.split(",").map(v=>v.trim()).filter(v=>v.length>0)):void 0,b=Oi(p.history);y&&(b=b.filter(v=>y.has(v.path))),m&&(b=b.map(v=>({...v,hunks:Li(v.hunks)}))),l.code(200).send(b)}),t.get("/v1/sessions/:id/tools/:hash",async(d,l)=>{let u=d.params,f=await e.resolveCanonicalId(u.id)??u.id,p=await e.loadToolBlob(f,u.hash);if(p===null){l.code(404).send({error:"tool blob not found"});return}l.header("Content-Type","text/plain; charset=utf-8"),l.code(200).send(p)}),t.get("/v1/sessions/:id/transcript",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let h=zo({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:fe,machine:ta.hostname(),hydraHost:ng(n)});l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(Bd(h))}),t.post("/v1/sessions/:id/fork",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.body??{},h={};if(p.forkAt!==void 0){if(typeof p.forkAt!="string"||p.forkAt.length===0){l.code(400).send({error:"forkAt must be a non-empty string"});return}h.forkAt=p.forkAt}if(p.cwd!==void 0){if(typeof p.cwd!="string"||p.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}h.cwd=et(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){l.code(400).send({error:"agentId must be a non-empty string"});return}h.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){l.code(400).send({error:"title must be a string"});return}h.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){l.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}h.mode=p.mode}try{let m=await e.forkSession(f,h);l.code(201).send(m)}catch(m){let y=m;if(y.code===z.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===z.InvalidParams||y.code===z.AgentNotInstalled){l.code(400).send({error:y.message});return}l.code(500).send({error:y.message})}}),t.post("/v1/sessions/import",async(d,l)=>{let u=d.body??{};if(u.bundle===void 0){l.code(400).send({error:"missing bundle"});return}let f;if(u.cwd!==void 0){if(typeof u.cwd!="string"||u.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}f=u.cwd}let p;try{p=_n(u.bundle)}catch(h){l.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(p,{replace:u.replace===!0,...f!==void 0?{cwd:f}:{}});l.code(201).send(h)}catch(h){let m=h;if(m.code===z.BundleAlreadyImported){l.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}l.code(500).send({error:m.message})}}),t.get("/v1/sessions/:id/compact/status",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f),h;if(p?h=p.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(f),h===void 0&&!await e.hasRecord(f))return l.code(404).send({error:"session not found"}),l;let m=await e.getCompactionState(f),y=await e.getRollbackBreadcrumb(f),b=!1,v,k=await e.getHistory(f).catch(()=>[])??[];if(k.length>0&&n.compaction){let T=h??0,F=k.length,B=k.slice(T).reduce((N,Z)=>N+JSON.stringify(Z.params).length,0);v=vu(B);let K=p?.currentModel,U=k.at(-1).recordedAt,L=p?.currentUsage;b=Dm({summarizedThroughEntry:T,totalEntries:F,unsummarizedChars:B,compactionInFlight:e.getCompactionInFlight(),currentModel:K,lastActivityMs:U,nowMs:Date.now(),config:n.compaction,...typeof L?.used=="number"?{agentReportedUsed:L.used}:{},...typeof L?.size=="number"?{agentReportedSize:L.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:b,...v!=null?{approxTokens:v}:{},...m!=null?{compactionState:m}:{},...y!=null?{rollbackBreadcrumb:y}:{}}}),t.post("/v1/sessions/:id/compact",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(e.get(f)){e.scheduleCompaction(f),l.code(202).send({scheduled:!0});return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}e.scheduleCompaction(f),l.code(202).send({scheduled:!0})}),t.post("/v1/sessions/:id/compact/rollback",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}try{await e.performUncompact(f),l.code(202).send({rolledBack:!0})}catch(p){let h=p instanceof Error?p.message:String(p);l.code(409).send({error:h})}}),t.get("/v1/sessions/:id/history",async(d,l)=>{let u=d.params.id,f=d.query,p=f?.follow==="1"||f?.follow==="true",h=await e.resolveCanonicalId(u)??u,m=e.get(h),y,b,v=!1,S=1e4,k=[];if(m){p&&(b=m.onBroadcast(F=>{l.raw.writableEnded||(v?l.raw.write(JSON.stringify(F)+`
312
- `):(k.push(F),k.length>S&&k.shift()))})),d.raw.on("close",()=>{b?.(),l.raw.writableEnded||l.raw.end()});try{y=await m.getHistorySnapshot()}catch(F){throw b?.(),F}}else{let F=await e.getHistory(h);if(F===void 0)return l.code(404).send({error:"session not found"}),l;y=F}l.raw.setHeader("Content-Type","application/x-ndjson"),l.raw.setHeader("Cache-Control","no-cache"),l.raw.statusCode=200;let T=new Set;for(let F of y??[]){l.raw.write(JSON.stringify(F)+`
313
- `);let $=F;typeof $.recordedAt=="number"&&T.add(String($.recordedAt))}for(;k.length>0;){let F=k.splice(0,k.length);for(let $ of F){let B=$,K=typeof B.recordedAt=="number"?String(B.recordedAt):"";K&&T.has(K)||l.raw.write(JSON.stringify($)+`
314
- `)}}return v=!0,b||l.raw.end(),l});function r(d,l,u){let f=typeof d=="string"?d.trim():"";if(f.length===0)return null;let p;try{p=JSON.parse(f)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!p||typeof p!="object"||Array.isArray(p))return console.debug("events endpoint: skipping non-object JSONL line"),null;let h=p;if(typeof h.recordedAt!="number"||u!==void 0&&h.recordedAt<u||typeof h.params!="object"||h.params===null||Array.isArray(h.params))return null;let m=h.params;if(typeof m.update!="object"||m.update===null||Array.isArray(m.update))return null;let b=m.update.sessionUpdate;return typeof b!="string"||!l.has(b)?null:{recordedAt:h.recordedAt,entry:p}}function i(d,l,u){let p=l.params.update,h={sessionId:d,ts:new Date(l.recordedAt).toISOString(),kind:u,update:p};return p.messageId!==void 0&&p.messageId!==null&&(h.messageId=p.messageId),h}async function*o(d,l,u,f){for await(let p of l){let h=r(p,u,f);if(h){let m=h.entry.params.update.sessionUpdate;yield{ts:h.recordedAt,row:i(d,h.entry,m)}}}}async function a(d,l,u,f){let p=Cu.createInterface({input:Au.createReadStream(l),crlfDelay:1/0}),h=o(d,p,u,f),m=await h.next(),y=m.done?null:m.value;return{sessionId:d,rl:p,gen:h,current:y,exhausted:y===null}}async function c(d){let l=await d.gen.next();l.done?(d.exhausted=!0,d.current=null):d.current=l.value}t.get("/v1/sessions/events",async(d,l)=>{let u=d.query,f=u.kinds;if(!f||f.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let p=f.split(",").map(S=>S.trim());if(p.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let S of p)if(!Dd.has(S))return l.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...Dd].join(", ")}`}),l;let h=new Set(p),m;if(u.since!==void 0&&u.since.trim().length>0){let S=new Date(u.since);if(isNaN(S.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;m=S.getTime()}let y=await e.list({includeNonInteractive:!0}),b=m!==void 0?y.filter(S=>new Date(S.updatedAt).getTime()>=m):y;l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;let v=[];for(let S of b)try{let k=_.historyFile(S.sessionId),T=await a(S.sessionId,k,h,m);T.exhausted||v.push(T)}catch(k){if(k.code==="ENOENT")continue;throw k}d.raw.on("close",()=>{for(let S of v)try{S.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;v.length>0;){let S=-1,k=1/0;for(let F=0;F<v.length;F++){let $=v[F];$.current!==null&&$.current.ts<k&&(k=$.current.ts,S=F)}if(S===-1)break;let T=v[S];if(l.raw.write(JSON.stringify(T.current.row)+`
315
- `),await c(T),T.exhausted){try{T.rl.close()}catch{}v.splice(S,1)}}}catch(S){for(let k of v)try{k.rl.close()}catch{}throw S}return l.raw.end(),l}),t.get("/v1/sessions/:id/events",async(d,l)=>{let u=d.params.id,f=d.query,p=await e.resolveCanonicalId(u)??u;if(!e.get(p)&&!await e.hasRecord(p))return l.code(404).send({error:"session not found"}),l;let m=f.kinds;if(!m||m.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let y=m.split(",").map(F=>F.trim());if(y.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let F of y)if(!Dd.has(F))return l.code(400).send({error:`kind "${F}" is not queryable; allowed kinds: ${[...Dd].join(", ")}`}),l;let b=new Set(y),v;if(f.since!==void 0&&f.since.trim().length>0){let F=new Date(f.since);if(isNaN(F.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;v=F.getTime()}let S=_.historyFile(p),k=Au.createReadStream(S),T=Cu.createInterface({input:k,crlfDelay:1/0});l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;try{for await(let F of T){let $=typeof F=="string"?F.trim():"";if($.length===0)continue;let B;try{B=JSON.parse($)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",S);continue}if(!B||typeof B!="object"||Array.isArray(B)){console.debug("events endpoint: skipping non-object JSONL line in %s",S);continue}let K=B;if(typeof K.recordedAt!="number"||typeof K.params!="object"||K.params===null||Array.isArray(K.params))continue;let U=K.params;if(typeof U.update!="object"||U.update===null||Array.isArray(U.update))continue;let L=U.update,N=L.sessionUpdate;if(typeof N!="string"||!b.has(N)||v!==void 0&&K.recordedAt<v)continue;let Z={ts:new Date(K.recordedAt).toISOString(),kind:N,update:L};L.messageId!==void 0&&L.messageId!==null&&(Z.messageId=L.messageId),l.raw.write(JSON.stringify(Z)+`
316
- `)}}catch(F){if(F.code==="ENOENT")return l.raw.end(),l;throw F}return l.raw.end(),l}),t.get("/v1/sessions/:id/attention",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);return!p&&!await e.hasRecord(f)?(l.code(404).send({error:"session not found"}),l):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(f))?.attentionFlags??[]}}),t.get("/v1/sessions/attention",async(d,l)=>{let u=d.query;if(!u.source||u.source.trim().length===0)return l.code(400).send({error:"source query parameter is required"}),l;let f=await e.list({includeNonInteractive:!0}),p=[];for(let h of f){let m=e.get(h.sessionId),y;m?y=m.listAttentionFlags():y=(await e.store.read(h.sessionId))?.attentionFlags??[];for(let b of y)b.source===u.source&&p.push({...b,sessionId:h.sessionId})}return{flags:p}}),t.post("/v1/sessions/:id/attention/clear",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,h=d.body??{},m=typeof h.source=="string"?h.source:"",y=typeof h.reason=="string"?h.reason:"";if((m.length>0||y.length>0)&&!(m.length>0&&y.length>0)){l.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}m.length===0&&y.length;let b=e.get(f);if(b){if(m.length>0&&y.length>0)b.clearAttentionFlag(m,y);else{let F=Array.from(b.listAttentionFlags()).map($=>`${$.source}::${$.reason}`);for(let $ of F)b.clearAttentionFlag($.split("::")[0],$.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}let v=e.store,S=await v.read(f);if(!S){l.code(404).send({error:"session not found"});return}let k=S.attentionFlags??[],T;if(m.length>0&&y.length>0){let F=`${m}::${y}`;T=k.filter($=>`${$.source}::${$.reason}`!==F)}else T=[];if(T.length===k.length&&T.every((F,$)=>F.source===k[$].source&&F.reason===k[$].reason)){l.code(204).send();return}await v.write({...S,attentionFlags:T}),l.code(204).send()})}Et();function ig(t,e,n,s={}){t.get("/v1/agents",async()=>bi(e)),t.get("/v1/registry",async()=>e.load()),t.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),t.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.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 c=await wn(a,[],{npmRegistry:s.npmRegistry}),d=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:c.version,distribution:d,installed:!0,command:c.command})}catch(c){i.code(500).send({error:c.message})}}),t.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:c}=await n.syncFromAgent(o);return{synced:a.map(d=>({sessionId:d.sessionId,upstreamSessionId:d.upstreamSessionId,agentId:d.agentId,cwd:d.cwd,title:d.title,updatedAt:d.updatedAt})),skipped:c}}catch(a){let c=a;if(c.code===z.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function og(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var ax=/^[A-Za-z0-9._-]+$/;function Hd(t,e,n){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;t.get(r,async()=>({[s]:n.list()})),t.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,c=n.get(a);if(!c){o.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),t.post(r,async(i,o)=>{let a=i.body??{},c=dx(a);if("error"in c){o.code(400).send({error:c.error});return}try{let d=n.register(c.config);o.code(201).send(d)}catch(d){na(o,d)}}),t.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await n.unregister(a),o.code(204).send()}catch(c){na(o,c)}}),t.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let c=await n.startByName(a);o.code(200).send(c)}catch(c){na(o,c)}}),t.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let c=await n.stopByName(a);o.code(200).send(c)}catch(c){na(o,c)}}),t.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let c=await n.restartByName(a);o.code(200).send(c)}catch(c){na(o,c)}})}function na(t,e){let n=e.code,s=e.message??"unknown error";if(n==="NOT_FOUND"){t.code(404).send({error:s});return}if(n==="CONFLICT"){t.code(409).send({error:s});return}t.code(500).send({error:s})}function dx(t){let e=t.name;if(typeof e!="string"||!ax.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let n=t.command;if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=t.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=t.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=t.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:n??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function ag(t,e){Hd(t,"extension",e)}function dg(t,e){Hd(t,"transformer",e)}function cg(t,e){t.get("/v1/config",async()=>e)}import{z as Ni}from"zod";he();import*as zs from"fs/promises";import*as pg from"path";import{randomBytes as cx,scrypt as lx,timingSafeEqual as ux}from"crypto";import{promisify as fx}from"util";var hg=fx(lx);function Ru(){return pg.join(_.home(),"password-hash")}var lg=32768,ug=8,fg=1,px=64,hx=16,mg=128*1024*1024;async function gg(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=cx(hx),n=await hg(t,e,px,{N:lg,r:ug,p:fg,maxmem:mg}),s=`scrypt$${lg}$${ug}$${fg}$${e.toString("hex")}$${n.toString("hex")}
317
- `;await zs.mkdir(_.home(),{recursive:!0}),await zs.writeFile(Ru(),s,{encoding:"utf8",mode:384})}async function Ud(){try{return(await zs.readFile(Ru(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jd(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await zs.readFile(Ru(),"utf8")).trim()}catch(d){if(d.code==="ENOENT")return!1;throw d}let n=e.split("$");if(n.length!==6||n[0]!=="scrypt")return!1;let s=parseInt(n[1],10),r=parseInt(n[2],10),i=parseInt(n[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(n[4],"hex"),a=Buffer.from(n[5],"hex");if(o.length===0||a.length===0)return!1;let c=await hg(t,o,a.length,{N:s,r,p:i,maxmem:mg});return c.length!==a.length?!1:ux(c,a)}var mx=Ni.object({password:Ni.string().min(1),label:Ni.string().min(1).max(256).optional(),ttlSec:Ni.number().int().positive().optional()}),gx=Ni.object({id:Ni.string().optional()}).optional();function yg(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=yx(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=mx.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Ud())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await jd(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),t.post("/v1/auth/logout",async(n,s)=>{let r;try{r=gx.parse(n.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??n.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),t.get("/v1/auth/verify",async(n,s)=>s.code(200).send({ok:!0})),t.get("/v1/auth/sessions",async(n,s)=>s.code(200).send({sessions:e.store.list()})),t.delete("/v1/auth/sessions/:id",async(n,s)=>{let r=n.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function yx(t){return t.ip||"unknown"}Tr();Di();import{nanoid as _u}from"nanoid";ad();Et();nn();import{randomBytes as bg}from"crypto";import*as vg from"os";import*as Sg from"path";function le(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function kx(t){if(!t||typeof t!="object")return 512;let s=t.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let c=a;if(typeof c.text=="string"&&(r+=c.text.length),c.content&&typeof c.content=="object"){let d=c.content;typeof d.text=="string"&&(r+=d.text.length)}}return r}function sn(t,e,n){let s=t.get(e);if(!s)throw le(z.SessionNotFound,n??`session ${e} not found`);return s}async function Tu(t,e){let n=Bi(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=bg(32).toString("hex"),r=t.mcpTokenRegistry.reserve(s),i={name:"hydra-acp-recall",type:"http",url:`${t.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...n?.descriptors??[],...i!==void 0?[i]:[]],c=xu({baselineMcpServers:void 0,stdinEnabled:!1,deps:t}),d;try{d=await t.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(l){throw n!==void 0&&n.abandon(l instanceof Error?l:void 0),r!==void 0&&r.abandon(l instanceof Error?l:void 0),l}if(n!==void 0&&n.bindToSession(d),s!==void 0&&r!==void 0&&t.mcpTokenRegistry!==void 0){let l=s,u=t.mcpTokenRegistry;r.complete(d),d.onClose(()=>{u.unbind(l)})}return Px(d,t),d}function kg(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=Nm({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){n.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=Jn(n),a=new zt(o),c={clientId:`hydra_client_${_u(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of c.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);c.attached.clear()});let d=(u,f)=>{if(c.attached.get(u)?.readonly)throw le(z.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=lh.parse(u??{});f.clientInfo?.name&&(c.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let p=f.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),Ex()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},h=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let y=m;if(typeof y.verb!="string")return;let b={verb:y.verb};return typeof y.argsHint=="string"&&(b.argsHint=y.argsHint),typeof y.description=="string"&&(b.description=y.description),b}).filter(m=>m!==void 0):[];return u.register(i.name,a,h),{ok:!0,registered:h.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async f=>{let p=f??{},h=typeof p.instructions=="string"?p.instructions:void 0,m=Array.isArray(p.tools)?p.tools.map(y=>{if(!y||typeof y!="object")return;let b=y;if(typeof b.name!="string"||b.name.length===0||typeof b.description!="string"||b.inputSchema===null||typeof b.inputSchema!="object")return;let v={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(v.outputSchema=b.outputSchema),v}).filter(y=>y!==void 0):[];if(m.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,h,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let f=u??{},p=Array.isArray(f.intercepts)?f.intercepts.filter(h=>typeof h=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let h=e.transformers.resolveChain([i.name])[0];if(h)for(let m of e.manager.liveSessions())m.addTransformer(h)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0,h=typeof f.method=="string"?f.method:void 0,m=f.envelope,y=f.route;if(!p)throw le(-32602,"emit_message requires sessionId");if(!h&&y!=="client_broadcast")throw le(-32602,"emit_message requires method");let b=sn(e.manager,p),v=typeof f.respondsTo=="string"?f.respondsTo:void 0;if(v)return b.dischargeClaim(v,m),{ok:!0};if(y==="chain")return{ok:!0,response:await b.emitToChain(i.name,h,m)};if(y==="queue"){if(h!=="session/prompt")throw le(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await b.emitToQueue(i.name,m)}}if(y==="daemon")return{ok:!0,response:await b.emitToChain(i.name,h,m)};if(y==="client_broadcast"){if(!m||typeof m!="object")throw le(-32602,"client_broadcast requires an envelope object");return b.broadcastClientUpdate(m),{ok:!0}}throw le(-32602,`unsupported route: ${JSON.stringify(y)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw le(-32602,"hydra-acp/session/request_permission requires sessionId");return sn(e.manager,p).requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async u=>Ax(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let f=u??{},p=typeof f.agentId=="string"?f.agentId:e.defaultAgent,h=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.parentSessionId=="string"?f.parentSessionId:void 0,y=f._meta&&typeof f._meta=="object"?f._meta:void 0,b=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,v=b&&typeof b.title=="string"?b.title:void 0,S=b&&typeof b.model=="string"?b.model:void 0;if(!h&&m){let F=e.manager.get(m);F&&(h=F.cwd)}if(!h)throw le(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let k=typeof f.interactive=="boolean"?f.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:h,parentSessionId:m,interactive:k,transformChain:[],title:v,model:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw le(z.InvalidParams,"fork_session requires sessionId");let p=typeof f.forkAt=="string"?f.forkAt:void 0,h=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.agentId=="string"?f.agentId:void 0,y=typeof f.mode=="string"&&(f.mode==="verbatim"||f.mode==="synthesis")?f.mode:void 0;return await e.manager.forkSession(f.sessionId,{...p!==void 0?{forkAt:p}:{},...h!==void 0?{cwd:h}:{},...m!==void 0?{agentId:m}:{},...y!==void 0?{mode:y}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw le(z.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,h=e.manager.get(p);if(h)return await h.close({deleteRecord:!0}),await e.manager.waitForDeletion(p),await e.manager.hasRecord(p)&&await e.manager.deleteRecord(p),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw le(z.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0,h=f.until==="idle"?"idle":"turn_complete",m=typeof f.timeoutMs=="number"?Math.min(f.timeoutMs,18e5):3e5;if(!p)throw le(-32602,"await_child requires childSessionId");let y=sn(e.manager,p,`child session ${p} not found`);return new Promise(b=>{let k=[],T=[],F=0,$=!1,B,K,U=!1,L=()=>{U||(U=!0,clearTimeout(N),B?.(),K?.(),b($?{entries:k,truncated:!0}:{entries:k}))};B=y.onBroadcast(Z=>{let G=kx(Z);for(k.push(Z),T.push(G),F+=G;k.length>0&&(k.length>1e3||F>1048576);)k.shift(),F-=T.shift()??0,$=!0;h==="turn_complete"&&Z.params?.update?.sessionUpdate==="turn_complete"&&L()});let N=setTimeout(L,m);typeof N.unref=="function"&&N.unref(),K=y.onClose(()=>L())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0;if(!p)throw le(-32602,"close_child_session requires childSessionId");let h=e.manager.get(p);return h&&await h.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async u=>Cx(u,i.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>Rx(u,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let f=u??{},p=typeof f.token=="string"?f.token:void 0,h=typeof f.sessionId=="string"?f.sessionId:void 0,m=typeof f.estimatedRemainingMs=="number"?f.estimatedRemainingMs:void 0;return p&&h&&e.manager.get(h)?.keepAliveClaim(p,m),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let f=u??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw le(z.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,h=await e.manager.loadToolBlob(p,f.hash);if(h===null)throw le(z.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async u=>Ix(u,e)),a.onRequest("session/new",async u=>{let f=uh.parse(u),p=en(u?._meta),h=Array.isArray(p.transformers)&&p.transformers.every(N=>typeof N=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(h)??[],y,b,v=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=bg(32).toString("hex"),b=e.mcpTokenRegistry.reserve(y);let Z={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};v=[...f.mcpServers??[],Z]}let S,k,T=Bi(e);T!==void 0&&(v=[...v??[],...T.descriptors]);let F=xu({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),$;try{$=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:v,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:wg(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...F?{mintMcpServersForSwap:F}:{}})}catch(N){throw b!==void 0&&b.abandon(N instanceof Error?N:void 0),k!==void 0&&k.abandon(N instanceof Error?N:void 0),T!==void 0&&T.abandon(N instanceof Error?N:void 0),N}if(y!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let N=y,Z=e.mcpTokenRegistry;b.complete($),$.onClose(()=>{Z.unbind(N)})}if(S!==void 0&&k!==void 0&&e.mcpTokenRegistry!==void 0){let N=S,Z=e.mcpTokenRegistry;k.complete($),$.onClose(()=>{Z.unbind(N)})}T!==void 0&&T.bindToSession($);let B,K;try{B=qd(a,$,c),{entries:K}=await $.attach(B,"full")}catch(N){throw await $.close({deleteRecord:!1}).catch(()=>{}),N}c.attached.set($.sessionId,{sessionId:$.sessionId,clientId:B.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let N of K){if(a.isClosed())break;await a.notify(N.method,N.params).catch(()=>{})}})()});let U=Eu($),L=Pu($);return{sessionId:$.sessionId,...U?{modes:U}:{},...L?{models:L}:{},configOptions:$.buildConfigOptions(),_meta:Mu(e.manager,$,{clientId:B.clientId})}}),a.onRequest("session/attach",async u=>{let f=ph.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=en(f._meta),m=h.resume,y=h.readonly===!0,b=h.env;t.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${y}`);let v=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,S=e.manager.get(v);if(!S&&y){let L=await e.manager.loadFromDisk(v);if(!L)throw le(z.SessionNotFound,`session ${f.sessionId} not found`);let N=await e.manager.loadHistory(v),Z=f.clientId??`cli_${_u(8)}`;c.attached.set(L.hydraSessionId,{sessionId:L.hydraSessionId,clientId:Z,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${L.hydraSessionId} clientId=${Z} attachedCount=${c.attached.size} replayed=${N.length}`);for(let G of N)await a.notify(G.method,G.params).catch(()=>{});return{sessionId:L.hydraSessionId,clientId:Z,connectedClients:[Z],historyPolicy:"full",replayed:N.length,_meta:Tx(L)}}let k=!S;if(!S){let L=await e.manager.loadFromDisk(v),N=L;if(m&&(N={...L,hydraSessionId:f.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!N)throw le(z.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(N.agentId,N.upstreamSessionId))throw le(z.SessionNotFound,`session ${f.sessionId} was deleted`);let Z=N.originatingClient?N:{...N,originatingClient:c.clientInfo},G=b!==void 0?{...Z,forwardedEnv:b}:Z;S=await Tu(e,{...G,onInstallProgress:wg(a)})}let T=qd(a,S,c,f.clientInfo,f.clientId),F=h.replayMode==="drip",{entries:$,appliedPolicy:B}=await S.attach(T,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:F,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:T.clientId,readonly:y}),b!==void 0&&await e.manager.setForwardedEnv(S.sessionId,b).catch(()=>{}),t.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${T.clientId} attachedCount=${c.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${B} replayed=${$.length} readonly=${y}${F?" replayMode=drip":""}`),F){let L=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,N=750;(async()=>{let Z=null;for(let G of $){let Se=typeof G.recordedAt=="number"?G.recordedAt:null;if(Z!==null&&Se!==null){let X=Math.min(N,Math.max(0,(Se-Z)/L));X>0&&await new Promise(ce=>setTimeout(ce,X))}Se!==null&&(Z=Se);try{await a.notify(G.method,G.params)}catch{return}}})()}else for(let L=0;L<$.length&&!a.isClosed();L++){let N=$[L],Z=a.notify(N.method,N.params).catch(()=>{});(L+1)%200===0&&await Z}S.replayPendingPermissions(T);let K=Eu(S),U=Pu(S);return{sessionId:S.sessionId,clientId:T.clientId,connectedClients:S.connectedClients(T.clientId),historyPolicy:B,replayed:$.length,...K?{modes:K}:{},...U?{models:U}:{},configOptions:S.buildConfigOptions(),_meta:Mu(e.manager,S,{resurrected:k})}}),a.onRequest("session/detach",async u=>{let f=hh.parse(u),p=c.attached.get(f.sessionId);if(!p)throw le(z.SessionNotFound,"client not attached to that session");let h=e.manager.get(f.sessionId);return h?.detach(p.clientId),c.attached.delete(f.sessionId),h&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[Tt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=mh.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==Er).map(gh)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw le(z.InternalError,"agent registry unavailable");return bi(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async u=>{let f=u??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw le(z.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(f.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async u=>{let f=yh.parse(u);d(f.sessionId,"session/prompt");let p=c.attached.get(f.sessionId);if(!p)throw t.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),le(z.SessionNotFound,"not attached to session");let h=e.manager.get(f.sessionId);if(!h){let m=await e.manager.loadFromDisk(f.sessionId);if(!m)throw le(z.SessionNotFound,`session ${f.sessionId} not found`);t.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),h=await Tu(e,m);let y=qd(a,h,c,void 0,p.clientId);await h.attach(y,"none")}return h.prompt(p.clientId,f)});let l=u=>{let f;try{f=td.parse(u)}catch(m){t.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=c.attached.get(f.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let h=e.manager.get(f.sessionId);h&&h.cancel(p.clientId).catch(m=>{t.log.warn(`session/cancel for ${f.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async u=>{let f=td.parse(u);return d(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=bh.parse(u);return d(f.sessionId,"hydra-acp/prompt/cancel"),sn(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=td.parse(u);return d(f.sessionId,"hydra-acp/session/force_cancel"),sn(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=vh.parse(u);return d(f.sessionId,"hydra-acp/prompt/update"),sn(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=Sh.parse(u);d(f.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(f.sessionId);if(!p)throw le(z.SessionNotFound,"not attached to session");return sn(e.manager,f.sessionId).amendPrompt(p.clientId,f)}),a.onRequest("session/load",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw le(z.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let k=await e.manager.loadFromDisk(h);if(!k)throw le(z.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Tu(e,k)}let y=qd(a,m,c),{entries:b}=await m.attach(y,"pending_only");c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1});for(let k of b){if(a.isClosed())break;await a.notify(k.method,k.params).catch(()=>{})}m.replayPendingPermissions(y);let v=Eu(m),S=Pu(m);return{sessionId:m.sessionId,...v?{modes:v}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:Mu(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/set_model",async u=>{let f=u?.sessionId;typeof f=="string"&&d(f,"session/set_model");let p=xx(u,e.manager);if(p.kind==="error")throw t.log.warn(p.logMessage),le(p.code,p.message);if(p.kind==="no_op")return t.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;t.log.info(p.logMessage);let{modelId:h}=p,m=await p.session.forwardRequest("session/set_model",{...u,modelId:h});return p.session.applyModelChange(h),m}),a.onRequest("session/set_mode",async u=>{let f=u,p=f?.sessionId;if(typeof p=="string"&&d(p,"session/set_mode"),!f||typeof f.sessionId!="string")throw le(z.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw le(z.InvalidParams,"session/set_mode requires string modeId");let h=sn(e.manager,f.sessionId),m=await h.forwardRequest("session/set_mode",u);return h.applyModeChange(f.modeId),m}),a.onRequest("session/set_config_option",async u=>{let f=u,p=b=>le(z.InvalidParams,b),h=f?.sessionId;if(typeof h=="string"&&d(h,"session/set_config_option"),!f||typeof f.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw p("session/set_config_option requires string configId");if(typeof f.value!="string")throw p("session/set_config_option requires string value");let m=sn(e.manager,f.sessionId),y=m.buildConfigOptions().find(b=>b.id===f.configId);if(!y)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!y.options.some(b=>b.value===f.value))throw p(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{f.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:f.sessionId,modelId:f.value}),m.applyModelChange(f.value);break}case"mode":{f.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),m.applyModeChange(f.value);break}case"agent":{f.value!==m.agentId&&await m.setAgent(f.value);break}default:throw p(`configId ${JSON.stringify(f.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(u,f)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),h=f.startsWith("session/"),m=f.startsWith("hydra-acp/");if(!h&&!m||u===null||typeof u!="object"||p.has(f))throw le(z.MethodNotFound,`Method not found: ${f}`);let y=u.sessionId;if(typeof y!="string")throw le(z.MethodNotFound,`Method not found: ${f}`);return d(y,f),sn(e.manager,y).forwardRequest(f,u)})})}async function Ix(t,e){let n=t??{};if(typeof n.methodId!="string"||n.methodId.length===0)throw le(z.InvalidParams,"authenticate requires a non-empty methodId string");let s=n.methodId,r=n._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let p=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let c=a.authMethods??[],d=c.find(p=>p.id===s);if(!d){let p=c.map(h=>h.id);throw le(z.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${p.map(h=>JSON.stringify(h)).join(", ")}]`)}let l=d._meta?.type,u=(()=>{let p=d._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((d.type??(l==="agent"||l==="terminal"?l:u!==void 0?"terminal":"agent"))==="terminal"){let p=(S,k)=>{if(!Array.isArray(S))throw le(z.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be a string[]; got ${S===null?"null":typeof S}`);for(let T of S)if(typeof T!="string")throw le(z.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be string[]; got non-string entry ${JSON.stringify(T)}`);return S},h=await e.manager.planSpawnForAgent(a.agentId),m,y;if(u?.args!==void 0){let S=typeof u.command=="string"?u.command:void 0;m=S!==void 0&&Sg.isAbsolute(S)?S:h.command,y=p(u.args,'_meta["terminal-auth"].args')}else{let S=d.args!==void 0?{raw:d.args,label:"args"}:d._meta?.args!==void 0?{raw:d._meta.args,label:"_meta.args"}:void 0,k=S!==void 0?p(S.raw,S.label):[];m=h.command,y=[...h.args,...k]}let b={};for(let[S,k]of Object.entries(process.env))typeof k=="string"&&(b[S]=k);Object.assign(b,h.env);let v=vg.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:y,env:b,cwd:v}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw Us(p,a)}}function wg(t){return e=>{let n={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(n.receivedBytes=e.receivedBytes),"totalBytes"in e&&(n.totalBytes=e.totalBytes),"packageSpec"in e&&(n.packageSpec=e.packageSpec),t.notify(nd,n).catch(()=>{})}}function Eu(t){let e=t.availableModes();if(e.length===0)return;let n=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:t.currentMode??e[0].id,availableModes:n}}function Pu(t){let e=t.availableModels();if(e.length===0)return;let n=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:t.currentModel??e[0].modelId,availableModels:n}}function xx(t,e){if(!t||typeof t!="object")return{kind:"error",code:z.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let n=t;if(typeof n.sessionId!="string")return{kind:"error",code:z.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof n.modelId!="string")return{kind:"error",code:z.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${n.sessionId}`};let s=e.get(n.sessionId);if(!s)return{kind:"error",code:z.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),i=xi(n.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model accepted sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(c=>c.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:n.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:z.InvalidParams,message:`model "${n.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function Ax(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw le(z.InvalidParams,"transformer/attach requires sessionId");if(!n.transformers)throw le(z.InternalError,"transformer manager not configured");let i=n.transformers.resolveChain([e])[0];if(!i)throw le(z.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return sn(n.manager,r).addTransformer(i),{ok:!0}}async function Cx(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw le(z.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw le(z.InvalidParams,"hydra-acp/attention/set requires string reason");return sn(n.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function Rx(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw le(z.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw le(z.InvalidParams,"hydra-acp/attention/clear requires string reason");return sn(n.manager,r).clearAttentionFlag(e,i),{ok:!0}}function Tx(t){let e={sessionId:t.hydraSessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:t.interactive,updatedAt:t.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},n={currentMode:t.currentMode,agentArgs:t.agentArgs,availableCommands:t.agentCommands,availableModes:t.agentModes,availableModels:t.agentModels};return{[Tt]:Za(e,n)}}function Mu(t,e,n={}){let s=t.liveListEntry(e),r={clientId:n.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(),...n.resurrected===!0?{resurrected:!0}:{}};return Fo(e.agentMeta,Za(s,r))}function Ex(){return{protocolVersion:1,agentInfo:{name:"hydra",version:fe},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:Fo(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Px(t,e){if(!(!e.transformers||!e.manager))for(let n of e.manager.defaultTransformers){let s=e.transformers.resolveChain([n])[0];s&&t.addTransformer(s)}}function qd(t,e,n,s,r){return{clientId:r??`cli_${_u(8)}`,connection:t,clientInfo:s}}var Wd=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let n,s,r=new Promise((o,a)=>{n=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,n(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,n){let{complete:s}=this.reserve(e);s(n)}lookup(e){return this.byToken.get(e)}addDisposer(e,n){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(n)}async unbind(e){let n=this.byToken.get(e);if(n!==void 0){this.byToken.delete(e);for(let s of n.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as Mx}from"crypto";import{McpServer as _x}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as $x}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Pt}from"zod";function*$u(t){for(let e=0;e<t.length;e++){let n=t[e];if(!n)continue;let s=n;if(s.method!=="session/update")continue;let i=s.params?.update;!i||typeof i.sessionUpdate!="string"||(yield{entryId:e,entry:s,kind:i.sessionUpdate,update:i})}}function rn(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var Ig="Bearer ";function Hi(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(Ig))return;let n=e.slice(Ig.length).trim();return n.length>0?n:void 0}function Fx(t){let e=new _x({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:Pt.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return rn(s)}),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:Pt.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return rn(s)}),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:Pt.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:Pt.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Pt.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:n,max_bytes:s,wait_ms:r})=>{let i=await t.streamRead(n,s,r);return rn(i)}),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:Pt.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Pt.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:n,timeout_ms:s})=>{let r=await t.streamWaitFor(n,s),i=t.streamInfo();return rn({outcome:r,writeCursor:i.writeCursor,closed:i.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:Pt.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Pt.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Pt.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Pt.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Pt.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Pt.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Pt.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Pt.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Pt.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 n=>{let s={pattern:n.pattern};n.regex!==void 0&&(s.regex=n.regex),n.case_insensitive!==void 0&&(s.caseInsensitive=n.case_insensitive),n.invert!==void 0&&(s.invert=n.invert),n.max_matches!==void 0&&(s.maxMatches=n.max_matches),n.max_bytes!==void 0&&(s.maxBytes=n.max_bytes),n.context_before!==void 0&&(s.contextBefore=n.context_before),n.context_after!==void 0&&(s.contextAfter=n.context_after),n.cursor!==void 0&&(s.cursor=n.cursor);let r=t.streamGrep(s);return rn(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let n=t.streamInfo();return rn(n)}),e}var Ox=1e4;function xg(t,e){let n=new Map;async function s(o,a){let c=n.get(o);if(c!==void 0)return c.transport;let d=Fx(a),l=new $x({sessionIdGenerator:()=>Mx()});await d.connect(l);let u={server:d,transport:l};return n.set(o,u),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=Hi(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(d.session!==void 0)l=d.session;else{let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),Ox)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),h===void 0){a.code(503).send({error:"session not ready"});return}l=h}let u=await s(c,l);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}dd();import{randomUUID as Lx}from"crypto";import{McpServer as Bx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Nx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ks}from"zod";function Dx(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Hx(t,e){if(t.length<=148)return t;let r=Math.floor(148/2),i=e-r;i<0&&(i=0);let o=i+148;o>t.length&&(i=t.length-148,i<0&&(i=0));let a=t.slice(i,o);return i>0&&(a="\u2026"+a),o<t.length&&(a=a+"\u2026"),a}function Ux(t){let e=new Bx({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. 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:Ks.string().min(1).describe("Case-insensitive substring to search for."),limit:Ks.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Ks.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:n,limit:s=10,include_tool_calls:r=!0})=>{let i=await t();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return rn({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 o=await i.getHistorySnapshot(),a=[];for(let{entryId:d,entry:l,kind:u}of $u(o)){if(u==="tool_call"&&!r)continue;let f=Ai([l]),p=f.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let h=Dx(u),m=Hx(f,p),y=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(a.push({entryId:d,speaker:h,snippet:m,timestamp:y}),a.length>=s)break}let c=a.length>=s&&a.length<o.length;return rn({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:Ks.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Ks.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:n,to_entry:s})=>{let r=await t();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return rn({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(s<n)throw new Error(`range: to_entry (${s}) must be >= from_entry (${n})`);let i=s-n+1;if(i>50)throw new Error(`range: range size (${i}) exceeds maximum of 50 entries`);let o=await r.getHistorySnapshot(),a=Math.min(n,o.length-1),c=Math.min(s,o.length-1),d=a>n||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:d}};let l=o.slice(a,c+1),u=Ai(l);return{content:[{type:"text",text:u}],structuredContent:{text:u,entry_count:l.length,truncated:d}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:Ks.string().optional(),file_path:Ks.string().optional(),limit:Ks.number().int().min(1).max(100).optional()}},async({tool_name:n,file_path:s,limit:r=20})=>{let i=await t();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return rn({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 o=typeof n=="string"&&n.length>0,a=typeof s=="string"&&s.length>0;if(!o&&!a)throw new Error("tool_calls: at least one of tool_name or file_path must be provided");let c=await i.getHistorySnapshot(),d=[],l=new Map;for(let{entryId:p,entry:h,kind:m,update:y}of $u(c)){if(m!=="tool_call"&&m!=="tool_call_update")continue;let b=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:`__noid_${p}`,v=l.get(b);v||(v={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},l.set(b,v),d.push(b)),typeof y.name=="string"&&y.name.length>0?v.toolName=y.name:(v.toolName==="(unnamed)"||m==="tool_call")&&typeof y.title=="string"&&y.title.length>0&&(v.toolName=y.title);let S=y.rawInput;if(S&&typeof S=="object"&&!Array.isArray(S)&&Object.keys(S).length>0)for(let[k,T]of Object.entries(S))v.rawInput[k]=T;if(Array.isArray(y.locations))for(let k of y.locations){let T=k?.path;typeof T=="string"&&T.length>0&&!v.locations.includes(T)&&v.locations.push(T)}typeof y.status=="string"&&(v.status=y.status),h.recordedAt!==void 0&&v.timestamp===void 0&&(v.timestamp=String(h.recordedAt))}let u=[];for(let p of d){let h=l.get(p);if(n!==void 0&&h.toolName.toLowerCase()!==n.toLowerCase())continue;if(a){let y=s.toLowerCase(),b=["file_path","filePath","path"],v=!1;for(let S of b){let k=h.rawInput[S];if(typeof k=="string"&&k.toLowerCase().includes(y)){v=!0;break}}if(!v){for(let S of h.locations)if(S.toLowerCase().includes(y)){v=!0;break}}if(!v)continue}let m={};for(let[y,b]of Object.entries(h.rawInput))typeof b=="string"?m[y]=b.length>500?b.slice(0,497)+"\u2026":b:(typeof b=="number"||typeof b=="boolean")&&(m[y]=b);if(h.locations.length>0&&m.locations===void 0&&(m.locations=h.locations),u.push({entryId:h.entryId,tool:h.toolName,args:m,status:h.status,timestamp:h.timestamp}),u.length>=r)break}let f=u.length>=r;return rn({calls:u,truncated:f})}),e}var jx=1e4;function Ag(t,e){let n=new Map;async function s(o,a){let c=n.get(o);if(c!==void 0)return c.transport;let d=Ux(a),l=new Nx({sessionIdGenerator:()=>Lx()});await d.connect(l);let u={server:d,transport:l};return n.set(o,u),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=Hi(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown recall token"});return}let u=await s(c,async()=>{if(d.session!==void 0)return d.session;let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),jx)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),h===void 0)throw new Error("recall: session not ready");return h});a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)})}var zd=class{byName=new Map;changeHandlers=[];register(e,n,s,r){this.byName.set(e,{connection:n,instructions:s,tools:[...r]}),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 n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(e,n){for(let s of this.changeHandlers)try{s(e,n)}catch{}}};import{StreamableHTTPServerTransport as Qx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Gx}from"crypto";import{Server as qx}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Wx,ListToolsRequestSchema as zx}from"@modelcontextprotocol/sdk/types.js";function Cg(t,e,n){let s=typeof n=="function"?async()=>n():async()=>n,r=new qx({name:t,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=new Map(e.tools.map(o=>[o.name,o]));return r.setRequestHandler(zx,async()=>({tools:e.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema,...o.outputSchema!==void 0?{outputSchema:o.outputSchema}:{}}))})),r.setRequestHandler(Wx,async(o,a)=>{let c=o.params.name;if(!i.has(c))return Kd(`unknown tool: ${c}`);let d=a._meta?.progressToken??a.requestId,l=Jx(d,a.sendNotification);try{let u=await s(),f=await Yx(e.connection,t,c,o.params.arguments??{},u);return Vx(f,c)}catch(u){return Kd(u instanceof Error?u.message:String(u))}finally{l()}}),r}var Kx=15e3;function Jx(t,e,n=Kx){if(t===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:t,progress:s}}).catch(()=>{})},n);return r.unref?.(),()=>clearInterval(r)}async function Yx(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function Vx(t,e){if(t===null||typeof t!="object")return Kd(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:Kd(`extension ${e} omitted content array`)}function Kd(t){return{content:[{type:"text",text:t}],isError:!0}}var Xx=1e4;function Rg(t,e,n){let s=new Map;async function r(d){try{await d.transport.close()}catch{}try{await d.server.close()}catch{}}function i(d){for(let l of s.values()){let u=l.get(d);u!==void 0&&(l.delete(d),r(u))}}n.onChange(d=>{i(d)});async function o(d,l){let u=s.get(d);u===void 0&&(u=new Map,s.set(d,u),e.addDisposer(d,async()=>{let b=s.get(d);if(b!==void 0){s.delete(d);for(let v of b.values())await r(v)}}));let f=u.get(l);if(f!==void 0)return f.transport;let p=n.lookup(l);if(p===void 0)return;let m=Cg(l,p,async()=>{let b=e.lookup(d);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let v,S=new Promise(T=>{v=setTimeout(()=>T(void 0),Xx)}),k=await Promise.race([b.sessionReady.catch(()=>{}),S]);if(v!==void 0&&clearTimeout(v),k===void 0)throw new Error("session not ready");return k.sessionId}),y=new Qx({sessionIdGenerator:()=>Gx()});return await m.connect(y),u.set(l,{server:m,transport:y}),y}async function a(d,l){let u=Hi(d);if(u===void 0){l.code(401).send({error:"missing bearer token"});return}if(e.lookup(u)===void 0){l.code(404).send({error:"unknown mcp token"});return}let p=d.params.name,h=await o(u,p);if(h===void 0){l.code(404).send({error:`unknown mcp server: ${p}`});return}l.hijack(),await h.handleRequest(d.raw,l.raw,d.body)}let c={config:{skipAuth:!0}};t.post("/mcp/:name",c,async(d,l)=>{await a(d,l)}),t.get("/mcp/:name",c,async(d,l)=>{await a(d,l)}),t.delete("/mcp/:name",c,async(d,l)=>{await a(d,l)})}async function _g(t,e){rA(t);let n=t.daemon.tls?await Ui.readFile(et(t.daemon.tls.key)):void 0,s=t.daemon.tls?await Ui.readFile(et(t.daemon.tls.cert)):void 0;await Ui.mkdir(_.home(),{recursive:!0});let{stream:r,fileStream:i}=await nA(t.daemon.logLevel),o=Zx({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(eA,{options:{handleProtocols:zp}}),Il(Y=>{o.log.info(Y)}),Cl(Y=>{o.log.info(Y)});let a=await Td.load(),c=new $d,d=new _d,l=new Md([new Ed(e),new Pd(a),d]),u=Bm({validator:l});o.addHook("onRequest",async(Y,xe)=>{Y.routeOptions.config?.skipAuth||Y.url==="/acp"||Y.url?.startsWith("/acp?")||await u(Y,xe)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new Qa(t,{onFetched:()=>{Tm(h,v)}});yu(Y=>o.log.info(Y));let m={info:Y=>o.log.info(Y),warn:Y=>o.log.warn(Y)},y=Y=>Ds.spawn({...Y,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:m});Vp(t.compressToolContent);let b=new Cd,v=new vd(h,y,void 0,{idleTimeoutMs:t.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:t.defaultModels,synopsisAgent:t.synopsisAgent,synopsisModel:t.synopsisModel,compactionAgent:t.compaction?.agent,compactionModel:t.compaction?.model,defaultTransformers:t.defaultTransformers,sessionHistoryMaxEntries:t.daemon.sessionHistoryMaxEntries,logger:m,npmRegistry:t.npmRegistry,extensionCommands:b,defaultCwd:t.defaultCwd}),S=new xd(yp(t),void 0,{tokenRegistry:d}),k=new Ad(wp(t),void 0,{tokenRegistry:d});og(o,fe,qs(t));let T=new Wd,F=new zd,$,B=()=>{if($!==void 0)return $;let Y=o.server.address();return $=`http://127.0.0.1:${Y&&typeof Y=="object"?Y.port:t.daemon.port}`,$};rg(o,v,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port,compaction:t.compaction},{extensionMcp:F,mcpTokenRegistry:T,getDaemonOrigin:B}),ig(o,h,v,{npmRegistry:t.npmRegistry}),ag(o,S),dg(o,k),cg(o,{defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,defaultModels:{...t.defaultModels},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers]}),yg(o,{store:a,rateLimiter:c}),xg(o,T),Ag(o,T),Rg(o,T,F),kg(o,{validator:l,manager:v,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(Y,xe)=>S.reportVersion(Y,xe),onTransformerVersion:(Y,xe)=>k.reportVersion(Y,xe),transformers:k,extensionCommands:b,mcpTokenRegistry:T,extensionMcp:F,getDaemonOrigin:B,registry:h});let K=!!t.daemon.tls;await o.listen({host:K?"127.0.0.1":t.daemon.host,port:K?0:t.daemon.port});let U=o.server.address(),L=U&&typeof U=="object"?U.port:t.daemon.port,N,Z=t.daemon.host,G=L;if(K&&n&&s){N=sA({listenHost:t.daemon.host,listenPort:t.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:L,tlsOptions:{key:n,cert:s},logger:o.log});let Y=N.address();Y&&typeof Y=="object"&&(G=Y.port)}await Ui.mkdir(_.home(),{recursive:!0}),await Cp({pid:process.pid,host:Z,port:G,loopbackPort:L,startedAt:new Date().toISOString()});let Se={daemonUrl:`http://127.0.0.1:${L}`,daemonHost:"127.0.0.1",daemonPort:L,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${L}/acp`,hydraHome:_.home()};S.setContext(Se),k.setContext(Se),await S.start(),await k.start();try{await v.reconcilePermissionFlags()}catch(Y){o.log.warn(`permission flag reconcile failed: ${Y.message}`)}v.resurrectPendingQueues().catch(Y=>{o.log.warn(`queue replay scan failed: ${Y.message}`)}),v.resumePendingCompactions().catch(Y=>{o.log.warn(`compaction resume scan failed: ${Y.message}`)}),v.resumePendingAgentSwaps().catch(Y=>{o.log.warn(`agent-swap resume scan failed: ${Y.message}`)});let X=t.daemon.agentSyncIntervalMinutes*60*1e3,ce=X>0?Em({registry:h,manager:v,intervalMs:X,logger:m}):void 0,Je=t.daemon.sessionGcIntervalMinutes*60*1e3,sr=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,ks=Je>0?Pm({manager:v,intervalMs:Je,maxAgeMs:sr,logger:m}):void 0;return{app:o,manager:v,registry:h,extensions:S,transformers:k,mcpTokenRegistry:T,extensionMcp:F,processRegistry:d,shutdown:async()=>{ks&&ks(),ce&&ce(),clearInterval(f),clearInterval(p);let Y=async(xe,es)=>{try{await es()}catch(ve){o.log.warn(`shutdown step ${xe} failed: ${ve instanceof Error?ve.message:String(ve)}`)}};await Y("sessionTokenStore.flush",()=>a.flush()),await Y("extensions.stop",()=>S.stop()),await Y("transformers.stop",()=>k.stop()),await Y("manager.closeAll",()=>v.closeAll()),await Y("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await Y("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await Y("manager.flushMetaWrites",()=>v.flushMetaWrites()),await Y("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),Il(null),Cl(null),yu(null),N&&await Y("tlsTerminator.close",()=>new Promise(xe=>N.close(()=>xe()))),await Y("app.close",()=>o.close());try{Eg.unlinkSync(_.pidFile())}catch{}await Y("fileStream.flushSync",()=>i.flushSync())}}}async function nA(t){let e=await tA({file:_.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),n=Tg.destination(2);return{stream:Tg.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function sA(t){let e=Mg.createServer(t.tlsOptions,n=>{let s=Pg.connect({host:t.upstreamHost,port:t.upstreamPort}),r=!1,i=o=>{if(!r){r=!0,o&&t.logger.warn(`tls terminator forwarder error: ${o.message??String(o)}`);try{n.destroy()}catch{}try{s.destroy()}catch{}}};n.on("error",i),s.on("error",i),n.on("close",()=>i()),s.on("close",()=>i()),n.pipe(s),s.pipe(n)});return e.on("tlsClientError",n=>{t.logger.warn(`tls handshake error: ${n.message}`)}),e.listen({host:t.listenHost,port:t.listenPort}),e}function rA(t){let e=t.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!t.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}Or();nn();Xo();sa();async function Lg(t={}){let e=await be(),n=await Ro();if(await Jd(e)){let r=await Wi();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
318
- `);return}if(ci(t,"foreground")){process.title="hydra-daemon";let r=await _g(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
311
+ `);for(let u of l)t.push(`> _${$r(u)}_`);t.push("");break}case"tool-call":{if(c(),a(),s.has(d.toolCallId))break;s.add(d.toolCallId);let l=n.get(d.toolCallId)??{title:d.title,status:d.status??"pending"};t.push(`- ${GI(l.status)} ${QI(l)}`),t.push("");break}case"tool-call-update":break;case"plan":{c(),a(),t.push("**Plan:**"),t.push("");for(let l of d.entries){let u=l.status==="completed"?"[x]":"[ ]";t.push(`- ${u} ${$r(l.content)}`)}t.push("");break}case"mode-changed":c(),a(),t.push(`_mode: ${$r(d.mode)}_`),t.push("");break;case"model-changed":c(),a(),t.push(`_model: ${$r(d.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function YI(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function QI(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${$r(t.title)}${n}`}function GI(t){switch(t){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function $r(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function xu(t){return t.toLocaleString("en-US")}Et();nn();Po();Ws();function XI(t){let e=t.trim();if(e.length===0)return{operator:"OR",terms:[]};let n=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=n.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,c=[];for(let l of s){let u=l.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>ZI(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function ZI(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:Gm(e[1]),term:e[2]};let n=/^"([^"]*)"$/.exec(t);if(n)return{scope:"all",term:n[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(t);return s?{scope:Gm(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function Gm(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function ex(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var tx=5,nx=200,Xm=30;async function tg(t,e,n={}){let s=XI(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??tx,i=n.maxSessions??nx,o=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),c=o?a.filter(u=>o.has(u.sessionId)):a,d=[],l=!1;for(let u of c){if(d.length>=i){l=!0;break}let f=await t.loadHistory(u.sessionId).catch(()=>[]),p=sx(f,s,r);if(p.snippets.length===0)continue;let h={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(h.title=u.title),d.push(h)}return{query:e,truncated:l,results:d}}function sx(t,e,n){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=rx(t,o,i,n-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function rx(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=ix(a).filter(d=>ex(n,d.kind));for(let d of c){let l=d.text.toLowerCase(),u=l.indexOf(r);if(u===-1)continue;let f=0;for(;u!==-1;)f++,u=l.indexOf(r,u+r.length);if(i+=f,o.length<s){let p=l.indexOf(r),h={kind:d.kind,text:lx(d.text,p,r.length),recordedAt:a.recordedAt};d.toolName!==void 0&&(h.toolName=d.toolName),o.push(h)}}}return{totalMatches:i,snippets:o}}function ix(t){if(t.method!=="session/update")return[];let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return[];let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=Nd(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?lt(s.text):Nd(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(dx(s))return[];let i=Nd(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=cx(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return ox(s);default:return[]}}function ox(t){let e=Zm(t,"name"),n=Zm(t,"title"),s=[];if(n!==void 0){let a=Ee(n);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==n){let a=Ee(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=eg(r);if(a.length>0){let c={kind:"tool-input",text:Ee(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=eg(i);if(a.length>0){let c={kind:"tool-input",text:Ee(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=ax(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function ax(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=s.content;if(!i||typeof i!="object")continue;let o=i;if(o.type==="text"&&typeof o.text=="string"){let a=Ee(o.text);if(a.length>0)return a}}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"){let r=Ee(s);if(r.length>0)return r}}return null}function dx(t){let e=t._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e["hydra-acp"];return!n||typeof n!="object"||Array.isArray(n)?!1:n.compatFor==="prompt_received"}function Nd(t){if(typeof t=="string")return lt(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?lt(e.text):""}function cx(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=Nd(n);s.length>0&&e.push(s)}return e.join("")}function Zm(t,e){let n=t[e];return typeof n=="string"?n:void 0}function eg(t){try{return JSON.stringify(t)}catch{return""}}function lx(t,e,n){let s=t.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=t.slice(e,e+n).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-Xm),c=Math.min(s.length,o+i.length+Xm),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as sg}from"crypto";function ng(t){let e=sg(32).toString("hex");return t.tokenRegistry.reserve(e).complete(t.session),t.session.onClose(()=>{t.tokenRegistry.unbind(e)}),{name:t.name,type:"http",url:`${t.getOrigin()}/mcp/${t.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function Au(t){if(t.deps.mcpTokenRegistry===void 0||t.deps.getDaemonOrigin===void 0)return;let e=t.deps.mcpTokenRegistry,n=t.deps.getDaemonOrigin;return async s=>{let r=[...t.baselineMcpServers??[]];t.stdinEnabled&&r.push(ng({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push(ng({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=Ni(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function Ni(t){if(t.extensionMcp===void 0||t.mcpTokenRegistry===void 0||t.getDaemonOrigin===void 0)return;let e=t.extensionMcp.list();if(e.length===0)return;let n=sg(32).toString("hex"),s=t.mcpTokenRegistry.reserve(n),r=t.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${n}`}]})),o=t.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(n)})},abandon:a=>s.abandon(a)}}var Dd=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function rg(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!kr(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function og(t,e,n,s={}){t.get("/v1/sessions",async d=>{let l=d.query,u=l?.includeNonInteractive==="1"||l?.includeNonInteractive==="true";return{sessions:await e.list({cwd:l?.cwd,includeNonInteractive:u})}}),t.get("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.getOne(f);return p||(l.code(404).send({error:"session not found"}),l)}),t.post("/v1/sessions/search",async(d,l)=>{let u=d.body??{},f=typeof u.q=="string"?u.q:"";if(f.trim().length===0)return l.code(400).send({error:"q is required"}),l;let p=Array.isArray(u.sessionIds)?u.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await tg(e,f,{sessionIds:p})}),t.post("/v1/sessions",async(d,l)=>{let u=d.body??{},f=et(u.cwd??n.cwd),p=u.agentId??n.agentId,h=Ni(s),m=h!==void 0?[...u.mcpServers??[],...h.descriptors]:u.mcpServers;try{let y=await e.create({cwd:f,agentId:p,mcpServers:m});h!==void 0&&h.bindToSession(y),l.code(201).send({sessionId:y.sessionId,agentId:y.agentId,cwd:y.cwd})}catch(y){h!==void 0&&h.abandon(y instanceof Error?y:void 0),l.code(500).send({error:y.message})}}),t.post("/v1/sessions/collect",async(d,l)=>{let u=d.body??{},f=typeof u.maxAgeDays=="number"&&u.maxAgeDays>0?u.maxAgeDays*24*60*60*1e3:0,p=typeof u.limit=="number"&&u.limit>0?u.limit:1e3,h=u.selection==="explicit"||u.selection==="unpromoted"?u.selection:"unpromoted";try{let m=await bu({manager:e,maxAgeMs:f,maxDeletions:p,selection:h,verbose:!1});l.code(200).send(m)}catch(m){l.code(500).send({error:m.message})}}),t.post("/v1/sessions/:id/kill",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){p.close({deleteRecord:!1}).catch(()=>{}),l.code(202).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.post("/v1/sessions/:id/stdin/open",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m={};(h.mode==="memory"||h.mode==="file")&&(m.mode=h.mode),typeof h.capacityBytes=="number"&&(m.capacityBytes=h.capacityBytes),typeof h.fileCapBytes=="number"&&(m.fileCapBytes=h.fileCapBytes),(m.mode??"memory")==="file"&&(m.filePathFor=y=>ig.join(na.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return p.openStream(m)}catch(y){return l.code(409).send({error:y.message}),l}}),t.post("/v1/sessions/:id/stdin",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m=typeof h.chunk=="string"?h.chunk:"",y=h.eof===!0;try{return p.streamWrite(m,y)}catch(b){return l.code(409).send({error:b.message}),l}}),t.patch("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.body??{};if(p.priority!==void 0){let m=p.priority,y;if(m===null||m===0)y=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)y=m;else{l.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(f,y)){l.code(404).send({error:"session not found"});return}l.code(204).send();return}if(p.regen===!0){if(!(e.get(f)!==void 0||await e.hasRecord(f))){l.code(404).send({error:"session not found"});return}e.scheduleSynopsis(f),l.code(202).send();return}if(typeof p.title!="string"||p.title.trim().length===0){l.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(f,p.title)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.delete("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){await p.close({deleteRecord:!0}),await e.waitForDeletion(f),await e.hasRecord(f)&&await e.deleteRecord(f),l.code(204).send();return}if(!await e.deleteRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.get("/v1/sessions/:id/export",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.query?.tools,h=p==="references"?"references":mm(p),m=await e.exportBundle(f,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=Ko({record:m.record,history:h==="summary"?gm(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:fe,machine:na.hostname(),hydraHost:rg(n)}),b=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${f}-${b}.hydra"`),l.code(200).send(y)}),t.get("/v1/sessions/:id/diff",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let h=d.query??{},m=h.fold==="true"||h.fold==="1",y=typeof h.paths=="string"&&h.paths.length>0?new Set(h.paths.split(",").map(v=>v.trim()).filter(v=>v.length>0)):void 0,b=Li(p.history);y&&(b=b.filter(v=>y.has(v.path))),m&&(b=b.map(v=>({...v,hunks:Bi(v.hunks)}))),l.code(200).send(b)}),t.get("/v1/sessions/:id/tools/:hash",async(d,l)=>{let u=d.params,f=await e.resolveCanonicalId(u.id)??u.id,p=await e.loadToolBlob(f,u.hash);if(p===null){l.code(404).send({error:"tool blob not found"});return}l.header("Content-Type","text/plain; charset=utf-8"),l.code(200).send(p)}),t.get("/v1/sessions/:id/transcript",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let h=Ko({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:fe,machine:na.hostname(),hydraHost:rg(n)});l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(Bd(h))}),t.post("/v1/sessions/:id/fork",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.body??{},h={};if(p.forkAt!==void 0){if(typeof p.forkAt!="string"||p.forkAt.length===0){l.code(400).send({error:"forkAt must be a non-empty string"});return}h.forkAt=p.forkAt}if(p.cwd!==void 0){if(typeof p.cwd!="string"||p.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}h.cwd=et(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){l.code(400).send({error:"agentId must be a non-empty string"});return}h.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){l.code(400).send({error:"title must be a string"});return}h.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){l.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}h.mode=p.mode}if(p.model!==void 0){if(typeof p.model!="string"||p.model.length===0){l.code(400).send({error:"model must be a non-empty string"});return}h.model=p.model}try{let m=await e.forkSession(f,h);l.code(201).send(m)}catch(m){let y=m;if(y.code===z.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===z.InvalidParams||y.code===z.AgentNotInstalled){l.code(400).send({error:y.message});return}l.code(500).send({error:y.message})}}),t.post("/v1/sessions/import",async(d,l)=>{let u=d.body??{};if(u.bundle===void 0){l.code(400).send({error:"missing bundle"});return}let f;if(u.cwd!==void 0){if(typeof u.cwd!="string"||u.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}f=u.cwd}let p;try{p=_n(u.bundle)}catch(h){l.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(p,{replace:u.replace===!0,...f!==void 0?{cwd:f}:{}});l.code(201).send(h)}catch(h){let m=h;if(m.code===z.BundleAlreadyImported){l.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}l.code(500).send({error:m.message})}}),t.get("/v1/sessions/:id/compact/status",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f),h;if(p?h=p.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(f),h===void 0&&!await e.hasRecord(f))return l.code(404).send({error:"session not found"}),l;let m=await e.getCompactionState(f),y=await e.getRollbackBreadcrumb(f),b=!1,v,k=await e.getHistory(f).catch(()=>[])??[];if(k.length>0&&n.compaction){let T=h??0,O=k.length,B=k.slice(T).reduce((N,Z)=>N+JSON.stringify(Z.params).length,0);v=Su(B);let K=p?.currentModel,U=k.at(-1).recordedAt,L=p?.currentUsage;b=Um({summarizedThroughEntry:T,totalEntries:O,unsummarizedChars:B,compactionInFlight:e.getCompactionInFlight(),currentModel:K,lastActivityMs:U,nowMs:Date.now(),config:n.compaction,...typeof L?.used=="number"?{agentReportedUsed:L.used}:{},...typeof L?.size=="number"?{agentReportedSize:L.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:b,...v!=null?{approxTokens:v}:{},...m!=null?{compactionState:m}:{},...y!=null?{rollbackBreadcrumb:y}:{}}}),t.post("/v1/sessions/:id/compact",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(e.get(f)){e.scheduleCompaction(f),l.code(202).send({scheduled:!0});return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}e.scheduleCompaction(f),l.code(202).send({scheduled:!0})}),t.post("/v1/sessions/:id/compact/rollback",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}try{await e.performUncompact(f),l.code(202).send({rolledBack:!0})}catch(p){let h=p instanceof Error?p.message:String(p);l.code(409).send({error:h})}}),t.get("/v1/sessions/:id/history",async(d,l)=>{let u=d.params.id,f=d.query,p=f?.follow==="1"||f?.follow==="true",h=await e.resolveCanonicalId(u)??u,m=e.get(h),y,b,v=!1,S=1e4,k=[];if(m){p&&(b=m.onBroadcast(O=>{l.raw.writableEnded||(v?l.raw.write(JSON.stringify(O)+`
312
+ `):(k.push(O),k.length>S&&k.shift()))})),d.raw.on("close",()=>{b?.(),l.raw.writableEnded||l.raw.end()});try{y=await m.getHistorySnapshot()}catch(O){throw b?.(),O}}else{let O=await e.getHistory(h);if(O===void 0)return l.code(404).send({error:"session not found"}),l;y=O}l.raw.setHeader("Content-Type","application/x-ndjson"),l.raw.setHeader("Cache-Control","no-cache"),l.raw.statusCode=200;let T=new Set;for(let O of y??[]){l.raw.write(JSON.stringify(O)+`
313
+ `);let $=O;typeof $.recordedAt=="number"&&T.add(String($.recordedAt))}for(;k.length>0;){let O=k.splice(0,k.length);for(let $ of O){let B=$,K=typeof B.recordedAt=="number"?String(B.recordedAt):"";K&&T.has(K)||l.raw.write(JSON.stringify($)+`
314
+ `)}}return v=!0,b||l.raw.end(),l});function r(d,l,u){let f=typeof d=="string"?d.trim():"";if(f.length===0)return null;let p;try{p=JSON.parse(f)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!p||typeof p!="object"||Array.isArray(p))return console.debug("events endpoint: skipping non-object JSONL line"),null;let h=p;if(typeof h.recordedAt!="number"||u!==void 0&&h.recordedAt<u||typeof h.params!="object"||h.params===null||Array.isArray(h.params))return null;let m=h.params;if(typeof m.update!="object"||m.update===null||Array.isArray(m.update))return null;let b=m.update.sessionUpdate;return typeof b!="string"||!l.has(b)?null:{recordedAt:h.recordedAt,entry:p}}function i(d,l,u){let p=l.params.update,h={sessionId:d,ts:new Date(l.recordedAt).toISOString(),kind:u,update:p};return p.messageId!==void 0&&p.messageId!==null&&(h.messageId=p.messageId),h}async function*o(d,l,u,f){for await(let p of l){let h=r(p,u,f);if(h){let m=h.entry.params.update.sessionUpdate;yield{ts:h.recordedAt,row:i(d,h.entry,m)}}}}async function a(d,l,u,f){let p=Ru.createInterface({input:Cu.createReadStream(l),crlfDelay:1/0}),h=o(d,p,u,f),m=await h.next(),y=m.done?null:m.value;return{sessionId:d,rl:p,gen:h,current:y,exhausted:y===null}}async function c(d){let l=await d.gen.next();l.done?(d.exhausted=!0,d.current=null):d.current=l.value}t.get("/v1/sessions/events",async(d,l)=>{let u=d.query,f=u.kinds;if(!f||f.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let p=f.split(",").map(S=>S.trim());if(p.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let S of p)if(!Dd.has(S))return l.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...Dd].join(", ")}`}),l;let h=new Set(p),m;if(u.since!==void 0&&u.since.trim().length>0){let S=new Date(u.since);if(isNaN(S.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;m=S.getTime()}let y=await e.list({includeNonInteractive:!0}),b=m!==void 0?y.filter(S=>new Date(S.updatedAt).getTime()>=m):y;l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;let v=[];for(let S of b)try{let k=_.historyFile(S.sessionId),T=await a(S.sessionId,k,h,m);T.exhausted||v.push(T)}catch(k){if(k.code==="ENOENT")continue;throw k}d.raw.on("close",()=>{for(let S of v)try{S.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;v.length>0;){let S=-1,k=1/0;for(let O=0;O<v.length;O++){let $=v[O];$.current!==null&&$.current.ts<k&&(k=$.current.ts,S=O)}if(S===-1)break;let T=v[S];if(l.raw.write(JSON.stringify(T.current.row)+`
315
+ `),await c(T),T.exhausted){try{T.rl.close()}catch{}v.splice(S,1)}}}catch(S){for(let k of v)try{k.rl.close()}catch{}throw S}return l.raw.end(),l}),t.get("/v1/sessions/:id/events",async(d,l)=>{let u=d.params.id,f=d.query,p=await e.resolveCanonicalId(u)??u;if(!e.get(p)&&!await e.hasRecord(p))return l.code(404).send({error:"session not found"}),l;let m=f.kinds;if(!m||m.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let y=m.split(",").map(O=>O.trim());if(y.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let O of y)if(!Dd.has(O))return l.code(400).send({error:`kind "${O}" is not queryable; allowed kinds: ${[...Dd].join(", ")}`}),l;let b=new Set(y),v;if(f.since!==void 0&&f.since.trim().length>0){let O=new Date(f.since);if(isNaN(O.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;v=O.getTime()}let S=_.historyFile(p),k=Cu.createReadStream(S),T=Ru.createInterface({input:k,crlfDelay:1/0});l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;try{for await(let O of T){let $=typeof O=="string"?O.trim():"";if($.length===0)continue;let B;try{B=JSON.parse($)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",S);continue}if(!B||typeof B!="object"||Array.isArray(B)){console.debug("events endpoint: skipping non-object JSONL line in %s",S);continue}let K=B;if(typeof K.recordedAt!="number"||typeof K.params!="object"||K.params===null||Array.isArray(K.params))continue;let U=K.params;if(typeof U.update!="object"||U.update===null||Array.isArray(U.update))continue;let L=U.update,N=L.sessionUpdate;if(typeof N!="string"||!b.has(N)||v!==void 0&&K.recordedAt<v)continue;let Z={ts:new Date(K.recordedAt).toISOString(),kind:N,update:L};L.messageId!==void 0&&L.messageId!==null&&(Z.messageId=L.messageId),l.raw.write(JSON.stringify(Z)+`
316
+ `)}}catch(O){if(O.code==="ENOENT")return l.raw.end(),l;throw O}return l.raw.end(),l}),t.get("/v1/sessions/:id/attention",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);return!p&&!await e.hasRecord(f)?(l.code(404).send({error:"session not found"}),l):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(f))?.attentionFlags??[]}}),t.get("/v1/sessions/attention",async(d,l)=>{let u=d.query;if(!u.source||u.source.trim().length===0)return l.code(400).send({error:"source query parameter is required"}),l;let f=await e.list({includeNonInteractive:!0}),p=[];for(let h of f){let m=e.get(h.sessionId),y;m?y=m.listAttentionFlags():y=(await e.store.read(h.sessionId))?.attentionFlags??[];for(let b of y)b.source===u.source&&p.push({...b,sessionId:h.sessionId})}return{flags:p}}),t.post("/v1/sessions/:id/attention/clear",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,h=d.body??{},m=typeof h.source=="string"?h.source:"",y=typeof h.reason=="string"?h.reason:"";if((m.length>0||y.length>0)&&!(m.length>0&&y.length>0)){l.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}m.length===0&&y.length;let b=e.get(f);if(b){if(m.length>0&&y.length>0)b.clearAttentionFlag(m,y);else{let O=Array.from(b.listAttentionFlags()).map($=>`${$.source}::${$.reason}`);for(let $ of O)b.clearAttentionFlag($.split("::")[0],$.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}let v=e.store,S=await v.read(f);if(!S){l.code(404).send({error:"session not found"});return}let k=S.attentionFlags??[],T;if(m.length>0&&y.length>0){let O=`${m}::${y}`;T=k.filter($=>`${$.source}::${$.reason}`!==O)}else T=[];if(T.length===k.length&&T.every((O,$)=>O.source===k[$].source&&O.reason===k[$].reason)){l.code(204).send();return}await v.write({...S,attentionFlags:T}),l.code(204).send()})}Et();function ag(t,e,n,s={}){t.get("/v1/agents",async()=>bi(e)),t.get("/v1/registry",async()=>e.load()),t.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),t.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.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 c=await wn(a,[],{npmRegistry:s.npmRegistry}),d=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:c.version,distribution:d,installed:!0,command:c.command})}catch(c){i.code(500).send({error:c.message})}}),t.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:c}=await n.syncFromAgent(o);return{synced:a.map(d=>({sessionId:d.sessionId,upstreamSessionId:d.upstreamSessionId,agentId:d.agentId,cwd:d.cwd,title:d.title,updatedAt:d.updatedAt})),skipped:c}}catch(a){let c=a;if(c.code===z.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function dg(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var ux=/^[A-Za-z0-9._-]+$/;function Hd(t,e,n){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;t.get(r,async()=>({[s]:n.list()})),t.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,c=n.get(a);if(!c){o.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),t.post(r,async(i,o)=>{let a=i.body??{},c=fx(a);if("error"in c){o.code(400).send({error:c.error});return}try{let d=n.register(c.config);o.code(201).send(d)}catch(d){sa(o,d)}}),t.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await n.unregister(a),o.code(204).send()}catch(c){sa(o,c)}}),t.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let c=await n.startByName(a);o.code(200).send(c)}catch(c){sa(o,c)}}),t.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let c=await n.stopByName(a);o.code(200).send(c)}catch(c){sa(o,c)}}),t.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let c=await n.restartByName(a);o.code(200).send(c)}catch(c){sa(o,c)}})}function sa(t,e){let n=e.code,s=e.message??"unknown error";if(n==="NOT_FOUND"){t.code(404).send({error:s});return}if(n==="CONFLICT"){t.code(409).send({error:s});return}t.code(500).send({error:s})}function fx(t){let e=t.name;if(typeof e!="string"||!ux.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let n=t.command;if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=t.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=t.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=t.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:n??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function cg(t,e){Hd(t,"extension",e)}function lg(t,e){Hd(t,"transformer",e)}function ug(t,e){t.get("/v1/config",async()=>e)}import{z as Di}from"zod";he();import*as zs from"fs/promises";import*as mg from"path";import{randomBytes as px,scrypt as hx,timingSafeEqual as mx}from"crypto";import{promisify as gx}from"util";var gg=gx(hx);function Tu(){return mg.join(_.home(),"password-hash")}var fg=32768,pg=8,hg=1,yx=64,wx=16,yg=128*1024*1024;async function wg(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=px(wx),n=await gg(t,e,yx,{N:fg,r:pg,p:hg,maxmem:yg}),s=`scrypt$${fg}$${pg}$${hg}$${e.toString("hex")}$${n.toString("hex")}
317
+ `;await zs.mkdir(_.home(),{recursive:!0}),await zs.writeFile(Tu(),s,{encoding:"utf8",mode:384})}async function Ud(){try{return(await zs.readFile(Tu(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jd(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await zs.readFile(Tu(),"utf8")).trim()}catch(d){if(d.code==="ENOENT")return!1;throw d}let n=e.split("$");if(n.length!==6||n[0]!=="scrypt")return!1;let s=parseInt(n[1],10),r=parseInt(n[2],10),i=parseInt(n[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(n[4],"hex"),a=Buffer.from(n[5],"hex");if(o.length===0||a.length===0)return!1;let c=await gg(t,o,a.length,{N:s,r,p:i,maxmem:yg});return c.length!==a.length?!1:mx(c,a)}var bx=Di.object({password:Di.string().min(1),label:Di.string().min(1).max(256).optional(),ttlSec:Di.number().int().positive().optional()}),vx=Di.object({id:Di.string().optional()}).optional();function bg(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=Sx(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=bx.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Ud())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await jd(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),t.post("/v1/auth/logout",async(n,s)=>{let r;try{r=vx.parse(n.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??n.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),t.get("/v1/auth/verify",async(n,s)=>s.code(200).send({ok:!0})),t.get("/v1/auth/sessions",async(n,s)=>s.code(200).send({sessions:e.store.list()})),t.delete("/v1/auth/sessions/:id",async(n,s)=>{let r=n.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function Sx(t){return t.ip||"unknown"}Tr();Hi();import{nanoid as $u}from"nanoid";ad();Et();nn();import{randomBytes as Sg}from"crypto";import*as kg from"os";import*as Ig from"path";function le(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function Cx(t){if(!t||typeof t!="object")return 512;let s=t.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let c=a;if(typeof c.text=="string"&&(r+=c.text.length),c.content&&typeof c.content=="object"){let d=c.content;typeof d.text=="string"&&(r+=d.text.length)}}return r}function sn(t,e,n){let s=t.get(e);if(!s)throw le(z.SessionNotFound,n??`session ${e} not found`);return s}async function Eu(t,e){let n=Ni(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=Sg(32).toString("hex"),r=t.mcpTokenRegistry.reserve(s),i={name:"hydra-acp-recall",type:"http",url:`${t.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...n?.descriptors??[],...i!==void 0?[i]:[]],c=Au({baselineMcpServers:void 0,stdinEnabled:!1,deps:t}),d;try{d=await t.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(l){throw n!==void 0&&n.abandon(l instanceof Error?l:void 0),r!==void 0&&r.abandon(l instanceof Error?l:void 0),l}if(n!==void 0&&n.bindToSession(d),s!==void 0&&r!==void 0&&t.mcpTokenRegistry!==void 0){let l=s,u=t.mcpTokenRegistry;r.complete(d),d.onClose(()=>{u.unbind(l)})}return Ox(d,t),d}function xg(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=Hm({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){n.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=Jn(n),a=new zt(o),c={clientId:`hydra_client_${$u(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of c.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);c.attached.clear()});let d=(u,f)=>{if(c.attached.get(u)?.readonly)throw le(z.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=uh.parse(u??{});f.clientInfo?.name&&(c.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let p=f.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),$x()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},h=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let y=m;if(typeof y.verb!="string")return;let b={verb:y.verb};return typeof y.argsHint=="string"&&(b.argsHint=y.argsHint),typeof y.description=="string"&&(b.description=y.description),b}).filter(m=>m!==void 0):[];return u.register(i.name,a,h),{ok:!0,registered:h.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async f=>{let p=f??{},h=typeof p.instructions=="string"?p.instructions:void 0,m=Array.isArray(p.tools)?p.tools.map(y=>{if(!y||typeof y!="object")return;let b=y;if(typeof b.name!="string"||b.name.length===0||typeof b.description!="string"||b.inputSchema===null||typeof b.inputSchema!="object")return;let v={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(v.outputSchema=b.outputSchema),v}).filter(y=>y!==void 0):[];if(m.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,h,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let f=u??{},p=Array.isArray(f.intercepts)?f.intercepts.filter(h=>typeof h=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let h=e.transformers.resolveChain([i.name])[0];if(h)for(let m of e.manager.liveSessions())m.addTransformer(h)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0,h=typeof f.method=="string"?f.method:void 0,m=f.envelope,y=f.route;if(!p)throw le(-32602,"emit_message requires sessionId");if(!h&&y!=="client_broadcast")throw le(-32602,"emit_message requires method");let b=sn(e.manager,p),v=typeof f.respondsTo=="string"?f.respondsTo:void 0;if(v)return b.dischargeClaim(v,m),{ok:!0};if(y==="chain")return{ok:!0,response:await b.emitToChain(i.name,h,m)};if(y==="queue"){if(h!=="session/prompt")throw le(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await b.emitToQueue(i.name,m)}}if(y==="daemon")return{ok:!0,response:await b.emitToChain(i.name,h,m)};if(y==="client_broadcast"){if(!m||typeof m!="object")throw le(-32602,"client_broadcast requires an envelope object");return b.broadcastClientUpdate(m),{ok:!0}}throw le(-32602,`unsupported route: ${JSON.stringify(y)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw le(-32602,"hydra-acp/session/request_permission requires sessionId");return sn(e.manager,p).requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async u=>Ex(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let f=u??{},p=typeof f.agentId=="string"?f.agentId:e.defaultAgent,h=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.parentSessionId=="string"?f.parentSessionId:void 0,y=f._meta&&typeof f._meta=="object"?f._meta:void 0,b=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,v=b&&typeof b.title=="string"?b.title:void 0,S=b&&typeof b.model=="string"?b.model:void 0;if(!h&&m){let O=e.manager.get(m);O&&(h=O.cwd)}if(!h)throw le(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let k=typeof f.interactive=="boolean"?f.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:h,parentSessionId:m,interactive:k,transformChain:[],title:v,model:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw le(z.InvalidParams,"fork_session requires sessionId");let p=typeof f.forkAt=="string"?f.forkAt:void 0,h=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.agentId=="string"?f.agentId:void 0,y=typeof f.mode=="string"&&(f.mode==="verbatim"||f.mode==="synthesis")?f.mode:void 0,b=typeof f.model=="string"&&f.model.length>0?f.model:void 0;return await e.manager.forkSession(f.sessionId,{...p!==void 0?{forkAt:p}:{},...h!==void 0?{cwd:h}:{},...m!==void 0?{agentId:m}:{},...y!==void 0?{mode:y}:{},...b!==void 0?{model:b}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw le(z.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,h=e.manager.get(p);if(h)return await h.close({deleteRecord:!0}),await e.manager.waitForDeletion(p),await e.manager.hasRecord(p)&&await e.manager.deleteRecord(p),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw le(z.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0,h=f.until==="idle"?"idle":"turn_complete",m=typeof f.timeoutMs=="number"?Math.min(f.timeoutMs,18e5):3e5;if(!p)throw le(-32602,"await_child requires childSessionId");let y=sn(e.manager,p,`child session ${p} not found`);return new Promise(b=>{let k=[],T=[],O=0,$=!1,B,K,U=!1,L=()=>{U||(U=!0,clearTimeout(N),B?.(),K?.(),b($?{entries:k,truncated:!0}:{entries:k}))};B=y.onBroadcast(Z=>{let G=Cx(Z);for(k.push(Z),T.push(G),O+=G;k.length>0&&(k.length>1e3||O>1048576);)k.shift(),O-=T.shift()??0,$=!0;h==="turn_complete"&&Z.params?.update?.sessionUpdate==="turn_complete"&&L()});let N=setTimeout(L,m);typeof N.unref=="function"&&N.unref(),K=y.onClose(()=>L())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0;if(!p)throw le(-32602,"close_child_session requires childSessionId");let h=e.manager.get(p);return h&&await h.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async u=>Px(u,i.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>Mx(u,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let f=u??{},p=typeof f.token=="string"?f.token:void 0,h=typeof f.sessionId=="string"?f.sessionId:void 0,m=typeof f.estimatedRemainingMs=="number"?f.estimatedRemainingMs:void 0;return p&&h&&e.manager.get(h)?.keepAliveClaim(p,m),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let f=u??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw le(z.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,h=await e.manager.loadToolBlob(p,f.hash);if(h===null)throw le(z.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async u=>Rx(u,e)),a.onRequest("session/new",async u=>{let f=fh.parse(u),p=en(u?._meta),h=Array.isArray(p.transformers)&&p.transformers.every(N=>typeof N=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(h)??[],y,b,v=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=Sg(32).toString("hex"),b=e.mcpTokenRegistry.reserve(y);let Z={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};v=[...f.mcpServers??[],Z]}let S,k,T=Ni(e);T!==void 0&&(v=[...v??[],...T.descriptors]);let O=Au({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),$;try{$=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:v,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:vg(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...O?{mintMcpServersForSwap:O}:{}})}catch(N){throw b!==void 0&&b.abandon(N instanceof Error?N:void 0),k!==void 0&&k.abandon(N instanceof Error?N:void 0),T!==void 0&&T.abandon(N instanceof Error?N:void 0),N}if(y!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let N=y,Z=e.mcpTokenRegistry;b.complete($),$.onClose(()=>{Z.unbind(N)})}if(S!==void 0&&k!==void 0&&e.mcpTokenRegistry!==void 0){let N=S,Z=e.mcpTokenRegistry;k.complete($),$.onClose(()=>{Z.unbind(N)})}T!==void 0&&T.bindToSession($);let B,K;try{B=qd(a,$,c),{entries:K}=await $.attach(B,"full")}catch(N){throw await $.close({deleteRecord:!1}).catch(()=>{}),N}c.attached.set($.sessionId,{sessionId:$.sessionId,clientId:B.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let N of K){if(a.isClosed())break;await a.notify(N.method,N.params).catch(()=>{})}})()});let U=Pu($),L=Mu($);return{sessionId:$.sessionId,...U?{modes:U}:{},...L?{models:L}:{},configOptions:$.buildConfigOptions(),_meta:_u(e.manager,$,{clientId:B.clientId})}}),a.onRequest("session/attach",async u=>{let f=hh.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=en(f._meta),m=h.resume,y=h.readonly===!0,b=h.env;t.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${y}`);let v=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,S=e.manager.get(v);if(!S&&y){let L=await e.manager.loadFromDisk(v);if(!L)throw le(z.SessionNotFound,`session ${f.sessionId} not found`);let N=await e.manager.loadHistory(v),Z=f.clientId??`cli_${$u(8)}`;c.attached.set(L.hydraSessionId,{sessionId:L.hydraSessionId,clientId:Z,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${L.hydraSessionId} clientId=${Z} attachedCount=${c.attached.size} replayed=${N.length}`);for(let G of N)await a.notify(G.method,G.params).catch(()=>{});return{sessionId:L.hydraSessionId,clientId:Z,connectedClients:[Z],historyPolicy:"full",replayed:N.length,_meta:_x(L)}}let k=!S;if(!S){let L=await e.manager.loadFromDisk(v),N=L;if(m&&(N={...L,hydraSessionId:f.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!N)throw le(z.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(N.agentId,N.upstreamSessionId))throw le(z.SessionNotFound,`session ${f.sessionId} was deleted`);let Z=N.originatingClient?N:{...N,originatingClient:c.clientInfo},G=b!==void 0?{...Z,forwardedEnv:b}:Z;S=await Eu(e,{...G,onInstallProgress:vg(a)})}let T=qd(a,S,c,f.clientInfo,f.clientId),O=h.replayMode==="drip",{entries:$,appliedPolicy:B}=await S.attach(T,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:O,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:T.clientId,readonly:y}),b!==void 0&&await e.manager.setForwardedEnv(S.sessionId,b).catch(()=>{}),t.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${T.clientId} attachedCount=${c.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${B} replayed=${$.length} readonly=${y}${O?" replayMode=drip":""}`),O){let L=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,N=750;(async()=>{let Z=null;for(let G of $){let Se=typeof G.recordedAt=="number"?G.recordedAt:null;if(Z!==null&&Se!==null){let X=Math.min(N,Math.max(0,(Se-Z)/L));X>0&&await new Promise(ce=>setTimeout(ce,X))}Se!==null&&(Z=Se);try{await a.notify(G.method,G.params)}catch{return}}})()}else for(let L=0;L<$.length&&!a.isClosed();L++){let N=$[L],Z=a.notify(N.method,N.params).catch(()=>{});(L+1)%200===0&&await Z}S.replayPendingPermissions(T);let K=Pu(S),U=Mu(S);return{sessionId:S.sessionId,clientId:T.clientId,connectedClients:S.connectedClients(T.clientId),historyPolicy:B,replayed:$.length,...K?{modes:K}:{},...U?{models:U}:{},configOptions:S.buildConfigOptions(),_meta:_u(e.manager,S,{resurrected:k})}}),a.onRequest("session/detach",async u=>{let f=mh.parse(u),p=c.attached.get(f.sessionId);if(!p)throw le(z.SessionNotFound,"client not attached to that session");let h=e.manager.get(f.sessionId);return h?.detach(p.clientId),c.attached.delete(f.sessionId),h&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[Tt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=gh.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==Er).map(yh)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw le(z.InternalError,"agent registry unavailable");return bi(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async u=>{let f=u??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw le(z.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(f.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async u=>{let f=wh.parse(u);d(f.sessionId,"session/prompt");let p=c.attached.get(f.sessionId);if(!p)throw t.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),le(z.SessionNotFound,"not attached to session");let h=e.manager.get(f.sessionId);if(!h){let m=await e.manager.loadFromDisk(f.sessionId);if(!m)throw le(z.SessionNotFound,`session ${f.sessionId} not found`);t.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),h=await Eu(e,m);let y=qd(a,h,c,void 0,p.clientId);await h.attach(y,"none")}return h.prompt(p.clientId,f)});let l=u=>{let f;try{f=nd.parse(u)}catch(m){t.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=c.attached.get(f.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let h=e.manager.get(f.sessionId);h&&h.cancel(p.clientId).catch(m=>{t.log.warn(`session/cancel for ${f.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async u=>{let f=nd.parse(u);return d(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=vh.parse(u);return d(f.sessionId,"hydra-acp/prompt/cancel"),sn(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=nd.parse(u);return d(f.sessionId,"hydra-acp/session/force_cancel"),sn(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=Sh.parse(u);return d(f.sessionId,"hydra-acp/prompt/update"),sn(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=kh.parse(u);d(f.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(f.sessionId);if(!p)throw le(z.SessionNotFound,"not attached to session");return sn(e.manager,f.sessionId).amendPrompt(p.clientId,f)}),a.onRequest("session/load",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw le(z.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let k=await e.manager.loadFromDisk(h);if(!k)throw le(z.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Eu(e,k)}let y=qd(a,m,c),{entries:b}=await m.attach(y,"pending_only");c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1});for(let k of b){if(a.isClosed())break;await a.notify(k.method,k.params).catch(()=>{})}m.replayPendingPermissions(y);let v=Pu(m),S=Mu(m);return{sessionId:m.sessionId,...v?{modes:v}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:_u(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/set_model",async u=>{let f=u?.sessionId;typeof f=="string"&&d(f,"session/set_model");let p=Tx(u,e.manager);if(p.kind==="error")throw t.log.warn(p.logMessage),le(p.code,p.message);if(p.kind==="no_op")return t.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;t.log.info(p.logMessage);let{modelId:h}=p,m=await p.session.forwardRequest("session/set_model",{...u,modelId:h});return p.session.applyModelChange(h),m}),a.onRequest("session/set_mode",async u=>{let f=u,p=f?.sessionId;if(typeof p=="string"&&d(p,"session/set_mode"),!f||typeof f.sessionId!="string")throw le(z.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw le(z.InvalidParams,"session/set_mode requires string modeId");let h=sn(e.manager,f.sessionId),m=await h.forwardRequest("session/set_mode",u);return h.applyModeChange(f.modeId),m}),a.onRequest("session/set_config_option",async u=>{let f=u,p=b=>le(z.InvalidParams,b),h=f?.sessionId;if(typeof h=="string"&&d(h,"session/set_config_option"),!f||typeof f.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw p("session/set_config_option requires string configId");if(typeof f.value!="string")throw p("session/set_config_option requires string value");let m=sn(e.manager,f.sessionId),y=m.buildConfigOptions().find(b=>b.id===f.configId);if(!y)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!y.options.some(b=>b.value===f.value))throw p(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{f.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:f.sessionId,modelId:f.value}),m.applyModelChange(f.value);break}case"mode":{f.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),m.applyModeChange(f.value);break}case"agent":{f.value!==m.agentId&&await m.setAgent(f.value);break}default:throw p(`configId ${JSON.stringify(f.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(u,f)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),h=f.startsWith("session/"),m=f.startsWith("hydra-acp/");if(!h&&!m||u===null||typeof u!="object"||p.has(f))throw le(z.MethodNotFound,`Method not found: ${f}`);let y=u.sessionId;if(typeof y!="string")throw le(z.MethodNotFound,`Method not found: ${f}`);return d(y,f),sn(e.manager,y).forwardRequest(f,u)})})}async function Rx(t,e){let n=t??{};if(typeof n.methodId!="string"||n.methodId.length===0)throw le(z.InvalidParams,"authenticate requires a non-empty methodId string");let s=n.methodId,r=n._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let p=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let c=a.authMethods??[],d=c.find(p=>p.id===s);if(!d){let p=c.map(h=>h.id);throw le(z.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${p.map(h=>JSON.stringify(h)).join(", ")}]`)}let l=d._meta?.type,u=(()=>{let p=d._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((d.type??(l==="agent"||l==="terminal"?l:u!==void 0?"terminal":"agent"))==="terminal"){let p=(S,k)=>{if(!Array.isArray(S))throw le(z.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be a string[]; got ${S===null?"null":typeof S}`);for(let T of S)if(typeof T!="string")throw le(z.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${k} must be string[]; got non-string entry ${JSON.stringify(T)}`);return S},h=await e.manager.planSpawnForAgent(a.agentId),m,y;if(u?.args!==void 0){let S=typeof u.command=="string"?u.command:void 0;m=S!==void 0&&Ig.isAbsolute(S)?S:h.command,y=p(u.args,'_meta["terminal-auth"].args')}else{let S=d.args!==void 0?{raw:d.args,label:"args"}:d._meta?.args!==void 0?{raw:d._meta.args,label:"_meta.args"}:void 0,k=S!==void 0?p(S.raw,S.label):[];m=h.command,y=[...h.args,...k]}let b={};for(let[S,k]of Object.entries(process.env))typeof k=="string"&&(b[S]=k);Object.assign(b,h.env);let v=kg.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:y,env:b,cwd:v}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw Us(p,a)}}function vg(t){return e=>{let n={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(n.receivedBytes=e.receivedBytes),"totalBytes"in e&&(n.totalBytes=e.totalBytes),"packageSpec"in e&&(n.packageSpec=e.packageSpec),t.notify(sd,n).catch(()=>{})}}function Pu(t){let e=t.availableModes();if(e.length===0)return;let n=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:t.currentMode??e[0].id,availableModes:n}}function Mu(t){let e=t.availableModels();if(e.length===0)return;let n=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:t.currentModel??e[0].modelId,availableModels:n}}function Tx(t,e){if(!t||typeof t!="object")return{kind:"error",code:z.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let n=t;if(typeof n.sessionId!="string")return{kind:"error",code:z.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof n.modelId!="string")return{kind:"error",code:z.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${n.sessionId}`};let s=e.get(n.sessionId);if(!s)return{kind:"error",code:z.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),i=Ai(n.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model accepted sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(c=>c.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:n.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:z.InvalidParams,message:`model "${n.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function Ex(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw le(z.InvalidParams,"transformer/attach requires sessionId");if(!n.transformers)throw le(z.InternalError,"transformer manager not configured");let i=n.transformers.resolveChain([e])[0];if(!i)throw le(z.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return sn(n.manager,r).addTransformer(i),{ok:!0}}async function Px(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw le(z.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw le(z.InvalidParams,"hydra-acp/attention/set requires string reason");return sn(n.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function Mx(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw le(z.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw le(z.InvalidParams,"hydra-acp/attention/clear requires string reason");return sn(n.manager,r).clearAttentionFlag(e,i),{ok:!0}}function _x(t){let e={sessionId:t.hydraSessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:t.interactive,updatedAt:t.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},n={currentMode:t.currentMode,agentArgs:t.agentArgs,availableCommands:t.agentCommands,availableModes:t.agentModes,availableModels:t.agentModels};return{[Tt]:ed(e,n)}}function _u(t,e,n={}){let s=t.liveListEntry(e),r={clientId:n.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(),...n.resurrected===!0?{resurrected:!0}:{}};return Fo(e.agentMeta,ed(s,r))}function $x(){return{protocolVersion:1,agentInfo:{name:"hydra",version:fe},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:Fo(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Ox(t,e){if(!(!e.transformers||!e.manager))for(let n of e.manager.defaultTransformers){let s=e.transformers.resolveChain([n])[0];s&&t.addTransformer(s)}}function qd(t,e,n,s,r){return{clientId:r??`cli_${$u(8)}`,connection:t,clientInfo:s}}var Wd=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let n,s,r=new Promise((o,a)=>{n=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,n(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,n){let{complete:s}=this.reserve(e);s(n)}lookup(e){return this.byToken.get(e)}addDisposer(e,n){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(n)}async unbind(e){let n=this.byToken.get(e);if(n!==void 0){this.byToken.delete(e);for(let s of n.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as Fx}from"crypto";import{McpServer as Lx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Bx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Pt}from"zod";function*Ou(t){for(let e=0;e<t.length;e++){let n=t[e];if(!n)continue;let s=n;if(s.method!=="session/update")continue;let i=s.params?.update;!i||typeof i.sessionUpdate!="string"||(yield{entryId:e,entry:s,kind:i.sessionUpdate,update:i})}}function rn(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var Ag="Bearer ";function Ui(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(Ag))return;let n=e.slice(Ag.length).trim();return n.length>0?n:void 0}function Nx(t){let e=new Lx({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:Pt.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return rn(s)}),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:Pt.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return rn(s)}),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:Pt.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:Pt.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Pt.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:n,max_bytes:s,wait_ms:r})=>{let i=await t.streamRead(n,s,r);return rn(i)}),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:Pt.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Pt.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:n,timeout_ms:s})=>{let r=await t.streamWaitFor(n,s),i=t.streamInfo();return rn({outcome:r,writeCursor:i.writeCursor,closed:i.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:Pt.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Pt.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Pt.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Pt.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Pt.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Pt.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Pt.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Pt.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Pt.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 n=>{let s={pattern:n.pattern};n.regex!==void 0&&(s.regex=n.regex),n.case_insensitive!==void 0&&(s.caseInsensitive=n.case_insensitive),n.invert!==void 0&&(s.invert=n.invert),n.max_matches!==void 0&&(s.maxMatches=n.max_matches),n.max_bytes!==void 0&&(s.maxBytes=n.max_bytes),n.context_before!==void 0&&(s.contextBefore=n.context_before),n.context_after!==void 0&&(s.contextAfter=n.context_after),n.cursor!==void 0&&(s.cursor=n.cursor);let r=t.streamGrep(s);return rn(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let n=t.streamInfo();return rn(n)}),e}var Dx=1e4;function Cg(t,e){let n=new Map;async function s(o,a){let c=n.get(o);if(c!==void 0)return c.transport;let d=Nx(a),l=new Bx({sessionIdGenerator:()=>Fx()});await d.connect(l);let u={server:d,transport:l};return n.set(o,u),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=Ui(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(d.session!==void 0)l=d.session;else{let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),Dx)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),h===void 0){a.code(503).send({error:"session not ready"});return}l=h}let u=await s(c,l);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}dd();import{randomUUID as Hx}from"crypto";import{McpServer as Ux}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as jx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ks}from"zod";function qx(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Wx(t,e){if(t.length<=148)return t;let r=Math.floor(148/2),i=e-r;i<0&&(i=0);let o=i+148;o>t.length&&(i=t.length-148,i<0&&(i=0));let a=t.slice(i,o);return i>0&&(a="\u2026"+a),o<t.length&&(a=a+"\u2026"),a}function zx(t){let e=new Ux({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. 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:Ks.string().min(1).describe("Case-insensitive substring to search for."),limit:Ks.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Ks.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:n,limit:s=10,include_tool_calls:r=!0})=>{let i=await t();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return rn({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 o=await i.getHistorySnapshot(),a=[];for(let{entryId:d,entry:l,kind:u}of Ou(o)){if(u==="tool_call"&&!r)continue;let f=Ci([l]),p=f.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let h=qx(u),m=Wx(f,p),y=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(a.push({entryId:d,speaker:h,snippet:m,timestamp:y}),a.length>=s)break}let c=a.length>=s&&a.length<o.length;return rn({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:Ks.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Ks.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:n,to_entry:s})=>{let r=await t();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return rn({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(s<n)throw new Error(`range: to_entry (${s}) must be >= from_entry (${n})`);let i=s-n+1;if(i>50)throw new Error(`range: range size (${i}) exceeds maximum of 50 entries`);let o=await r.getHistorySnapshot(),a=Math.min(n,o.length-1),c=Math.min(s,o.length-1),d=a>n||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:d}};let l=o.slice(a,c+1),u=Ci(l);return{content:[{type:"text",text:u}],structuredContent:{text:u,entry_count:l.length,truncated:d}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:Ks.string().optional(),file_path:Ks.string().optional(),limit:Ks.number().int().min(1).max(100).optional()}},async({tool_name:n,file_path:s,limit:r=20})=>{let i=await t();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return rn({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 o=typeof n=="string"&&n.length>0,a=typeof s=="string"&&s.length>0;if(!o&&!a)throw new Error("tool_calls: at least one of tool_name or file_path must be provided");let c=await i.getHistorySnapshot(),d=[],l=new Map;for(let{entryId:p,entry:h,kind:m,update:y}of Ou(c)){if(m!=="tool_call"&&m!=="tool_call_update")continue;let b=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:`__noid_${p}`,v=l.get(b);v||(v={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},l.set(b,v),d.push(b)),typeof y.name=="string"&&y.name.length>0?v.toolName=y.name:(v.toolName==="(unnamed)"||m==="tool_call")&&typeof y.title=="string"&&y.title.length>0&&(v.toolName=y.title);let S=y.rawInput;if(S&&typeof S=="object"&&!Array.isArray(S)&&Object.keys(S).length>0)for(let[k,T]of Object.entries(S))v.rawInput[k]=T;if(Array.isArray(y.locations))for(let k of y.locations){let T=k?.path;typeof T=="string"&&T.length>0&&!v.locations.includes(T)&&v.locations.push(T)}typeof y.status=="string"&&(v.status=y.status),h.recordedAt!==void 0&&v.timestamp===void 0&&(v.timestamp=String(h.recordedAt))}let u=[];for(let p of d){let h=l.get(p);if(n!==void 0&&h.toolName.toLowerCase()!==n.toLowerCase())continue;if(a){let y=s.toLowerCase(),b=["file_path","filePath","path"],v=!1;for(let S of b){let k=h.rawInput[S];if(typeof k=="string"&&k.toLowerCase().includes(y)){v=!0;break}}if(!v){for(let S of h.locations)if(S.toLowerCase().includes(y)){v=!0;break}}if(!v)continue}let m={};for(let[y,b]of Object.entries(h.rawInput))typeof b=="string"?m[y]=b.length>500?b.slice(0,497)+"\u2026":b:(typeof b=="number"||typeof b=="boolean")&&(m[y]=b);if(h.locations.length>0&&m.locations===void 0&&(m.locations=h.locations),u.push({entryId:h.entryId,tool:h.toolName,args:m,status:h.status,timestamp:h.timestamp}),u.length>=r)break}let f=u.length>=r;return rn({calls:u,truncated:f})}),e}var Kx=1e4;function Rg(t,e){let n=new Map;async function s(o,a){let c=n.get(o);if(c!==void 0)return c.transport;let d=zx(a),l=new jx({sessionIdGenerator:()=>Hx()});await d.connect(l);let u={server:d,transport:l};return n.set(o,u),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=Ui(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown recall token"});return}let u=await s(c,async()=>{if(d.session!==void 0)return d.session;let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),Kx)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),h===void 0)throw new Error("recall: session not ready");return h});a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)})}var zd=class{byName=new Map;changeHandlers=[];register(e,n,s,r){this.byName.set(e,{connection:n,instructions:s,tools:[...r]}),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 n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(e,n){for(let s of this.changeHandlers)try{s(e,n)}catch{}}};import{StreamableHTTPServerTransport as eA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as tA}from"crypto";import{Server as Jx}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Vx,ListToolsRequestSchema as Yx}from"@modelcontextprotocol/sdk/types.js";function Tg(t,e,n){let s=typeof n=="function"?async()=>n():async()=>n,r=new Jx({name:t,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=new Map(e.tools.map(o=>[o.name,o]));return r.setRequestHandler(Yx,async()=>({tools:e.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema,...o.outputSchema!==void 0?{outputSchema:o.outputSchema}:{}}))})),r.setRequestHandler(Vx,async(o,a)=>{let c=o.params.name;if(!i.has(c))return Kd(`unknown tool: ${c}`);let d=a._meta?.progressToken??a.requestId,l=Gx(d,a.sendNotification);try{let u=await s(),f=await Xx(e.connection,t,c,o.params.arguments??{},u);return Zx(f,c)}catch(u){return Kd(u instanceof Error?u.message:String(u))}finally{l()}}),r}var Qx=15e3;function Gx(t,e,n=Qx){if(t===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:t,progress:s}}).catch(()=>{})},n);return r.unref?.(),()=>clearInterval(r)}async function Xx(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function Zx(t,e){if(t===null||typeof t!="object")return Kd(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:Kd(`extension ${e} omitted content array`)}function Kd(t){return{content:[{type:"text",text:t}],isError:!0}}var nA=1e4;function Eg(t,e,n){let s=new Map;async function r(d){try{await d.transport.close()}catch{}try{await d.server.close()}catch{}}function i(d){for(let l of s.values()){let u=l.get(d);u!==void 0&&(l.delete(d),r(u))}}n.onChange(d=>{i(d)});async function o(d,l){let u=s.get(d);u===void 0&&(u=new Map,s.set(d,u),e.addDisposer(d,async()=>{let b=s.get(d);if(b!==void 0){s.delete(d);for(let v of b.values())await r(v)}}));let f=u.get(l);if(f!==void 0)return f.transport;let p=n.lookup(l);if(p===void 0)return;let m=Tg(l,p,async()=>{let b=e.lookup(d);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let v,S=new Promise(T=>{v=setTimeout(()=>T(void 0),nA)}),k=await Promise.race([b.sessionReady.catch(()=>{}),S]);if(v!==void 0&&clearTimeout(v),k===void 0)throw new Error("session not ready");return k.sessionId}),y=new eA({sessionIdGenerator:()=>tA()});return await m.connect(y),u.set(l,{server:m,transport:y}),y}async function a(d,l){let u=Ui(d);if(u===void 0){l.code(401).send({error:"missing bearer token"});return}if(e.lookup(u)===void 0){l.code(404).send({error:"unknown mcp token"});return}let p=d.params.name,h=await o(u,p);if(h===void 0){l.code(404).send({error:`unknown mcp server: ${p}`});return}l.hijack(),await h.handleRequest(d.raw,l.raw,d.body)}let c={config:{skipAuth:!0}};t.post("/mcp/:name",c,async(d,l)=>{await a(d,l)}),t.get("/mcp/:name",c,async(d,l)=>{await a(d,l)}),t.delete("/mcp/:name",c,async(d,l)=>{await a(d,l)})}async function Og(t,e){dA(t);let n=t.daemon.tls?await ji.readFile(et(t.daemon.tls.key)):void 0,s=t.daemon.tls?await ji.readFile(et(t.daemon.tls.cert)):void 0;await ji.mkdir(_.home(),{recursive:!0});let{stream:r,fileStream:i}=await oA(t.daemon.logLevel),o=sA({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(rA,{options:{handleProtocols:Kp}}),xl(V=>{o.log.info(V)}),Rl(V=>{o.log.info(V)});let a=await Td.load(),c=new $d,d=new _d,l=new Md([new Ed(e),new Pd(a),d]),u=Dm({validator:l});o.addHook("onRequest",async(V,xe)=>{V.routeOptions.config?.skipAuth||V.url==="/acp"||V.url?.startsWith("/acp?")||await u(V,xe)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new Ga(t,{onFetched:()=>{Pm(h,v)}});wu(V=>o.log.info(V));let m={info:V=>o.log.info(V),warn:V=>o.log.warn(V)},y=V=>Ds.spawn({...V,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:m});Qp(t.compressToolContent);let b=new Cd,v=new vd(h,y,void 0,{idleTimeoutMs:t.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:t.defaultModels,synopsisAgent:t.synopsisAgent,synopsisModel:t.synopsisModel,compactionAgent:t.compaction?.agent,compactionModel:t.compaction?.model,defaultTransformers:t.defaultTransformers,sessionHistoryMaxEntries:t.daemon.sessionHistoryMaxEntries,logger:m,npmRegistry:t.npmRegistry,extensionCommands:b,defaultCwd:t.defaultCwd}),S=new xd(wp(t),void 0,{tokenRegistry:d}),k=new Ad(bp(t),void 0,{tokenRegistry:d});dg(o,fe,qs(t));let T=new Wd,O=new zd,$,B=()=>{if($!==void 0)return $;let V=o.server.address();return $=`http://127.0.0.1:${V&&typeof V=="object"?V.port:t.daemon.port}`,$};og(o,v,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port,compaction:t.compaction},{extensionMcp:O,mcpTokenRegistry:T,getDaemonOrigin:B}),ag(o,h,v,{npmRegistry:t.npmRegistry}),cg(o,S),lg(o,k),ug(o,{defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,defaultModels:{...t.defaultModels},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers]}),bg(o,{store:a,rateLimiter:c}),Cg(o,T),Rg(o,T),Eg(o,T,O),xg(o,{validator:l,manager:v,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(V,xe)=>S.reportVersion(V,xe),onTransformerVersion:(V,xe)=>k.reportVersion(V,xe),transformers:k,extensionCommands:b,mcpTokenRegistry:T,extensionMcp:O,getDaemonOrigin:B,registry:h});let K=!!t.daemon.tls;await o.listen({host:K?"127.0.0.1":t.daemon.host,port:K?0:t.daemon.port});let U=o.server.address(),L=U&&typeof U=="object"?U.port:t.daemon.port,N,Z=t.daemon.host,G=L;if(K&&n&&s){N=aA({listenHost:t.daemon.host,listenPort:t.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:L,tlsOptions:{key:n,cert:s},logger:o.log});let V=N.address();V&&typeof V=="object"&&(G=V.port)}await ji.mkdir(_.home(),{recursive:!0}),await Rp({pid:process.pid,host:Z,port:G,loopbackPort:L,startedAt:new Date().toISOString()});let Se={daemonUrl:`http://127.0.0.1:${L}`,daemonHost:"127.0.0.1",daemonPort:L,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${L}/acp`,hydraHome:_.home()};S.setContext(Se),k.setContext(Se),await S.start(),await k.start();try{await v.reconcilePermissionFlags()}catch(V){o.log.warn(`permission flag reconcile failed: ${V.message}`)}v.resurrectPendingQueues().catch(V=>{o.log.warn(`queue replay scan failed: ${V.message}`)}),v.resumePendingCompactions().catch(V=>{o.log.warn(`compaction resume scan failed: ${V.message}`)}),v.resumePendingAgentSwaps().catch(V=>{o.log.warn(`agent-swap resume scan failed: ${V.message}`)});let X=t.daemon.agentSyncIntervalMinutes*60*1e3,ce=X>0?Mm({registry:h,manager:v,intervalMs:X,logger:m}):void 0,Ye=t.daemon.sessionGcIntervalMinutes*60*1e3,sr=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,ks=Ye>0?_m({manager:v,intervalMs:Ye,maxAgeMs:sr,logger:m}):void 0;return{app:o,manager:v,registry:h,extensions:S,transformers:k,mcpTokenRegistry:T,extensionMcp:O,processRegistry:d,shutdown:async()=>{ks&&ks(),ce&&ce(),clearInterval(f),clearInterval(p);let V=async(xe,ts)=>{try{await ts()}catch(ve){o.log.warn(`shutdown step ${xe} failed: ${ve instanceof Error?ve.message:String(ve)}`)}};await V("sessionTokenStore.flush",()=>a.flush()),await V("extensions.stop",()=>S.stop()),await V("transformers.stop",()=>k.stop()),await V("manager.closeAll",()=>v.closeAll()),await V("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await V("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await V("manager.flushMetaWrites",()=>v.flushMetaWrites()),await V("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),xl(null),Rl(null),wu(null),N&&await V("tlsTerminator.close",()=>new Promise(xe=>N.close(()=>xe()))),await V("app.close",()=>o.close());try{Mg.unlinkSync(_.pidFile())}catch{}await V("fileStream.flushSync",()=>i.flushSync())}}}async function oA(t){let e=await iA({file:_.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),n=Pg.destination(2);return{stream:Pg.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function aA(t){let e=$g.createServer(t.tlsOptions,n=>{let s=_g.connect({host:t.upstreamHost,port:t.upstreamPort}),r=!1,i=o=>{if(!r){r=!0,o&&t.logger.warn(`tls terminator forwarder error: ${o.message??String(o)}`);try{n.destroy()}catch{}try{s.destroy()}catch{}}};n.on("error",i),s.on("error",i),n.on("close",()=>i()),s.on("close",()=>i()),n.pipe(s),s.pipe(n)});return e.on("tlsClientError",n=>{t.logger.warn(`tls handshake error: ${n.message}`)}),e.listen({host:t.listenHost,port:t.listenPort}),e}function dA(t){let e=t.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!t.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}Fr();nn();Zo();ra();async function Ng(t={}){let e=await be(),n=await To();if(await Jd(e)){let r=await zi();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
318
+ `);return}if(ci(t,"foreground")){process.title="hydra-daemon";let r=await Og(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
319
319
  `);let i=1e4,o=!1,a=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
320
320
  `),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
321
321
  `);let c=setTimeout(()=>{process.stderr.write(`Graceful shutdown did not complete within ${i}ms; forcing exit.
322
322
  `),process.exit(1)},i);c.unref();try{await r.shutdown()}catch(d){process.stderr.write(`shutdown failed: ${d instanceof Error?d.message:String(d)}
323
- `)}clearTimeout(c),process.exit(0)};process.on("SIGINT",()=>{a()}),process.on("SIGTERM",()=>{a()}),process.on("SIGHUP",()=>{});return}Yd(),await Vd(e);let s=await Wi();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
324
- `)}async function Bg(){let t=await Wi();if(!t){process.stdout.write(`No running daemon found.
323
+ `)}clearTimeout(c),process.exit(0)};process.on("SIGINT",()=>{a()}),process.on("SIGTERM",()=>{a()}),process.on("SIGHUP",()=>{});return}Vd(),await Yd(e);let s=await zi();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
324
+ `)}async function Dg(){let t=await zi();if(!t){process.stdout.write(`No running daemon found.
325
325
  `);return}try{process.kill(t.pid,"SIGTERM"),process.stdout.write(`Sent SIGTERM to daemon pid ${t.pid}
326
326
  `)}catch(e){process.stderr.write(`Failed to signal daemon: ${e.message}
327
- `)}}async function Ng(){let t=await be();await Ro();let e=await Wi();if(e&&Mn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
327
+ `)}}async function Hg(){let t=await be();await To();let e=await zi();if(e&&Mn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
328
328
  `);try{process.kill(e.pid,"SIGTERM")}catch(n){process.stderr.write(`Failed to signal daemon: ${n.message}
329
- `),process.exit(1)}await uA(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
329
+ `),process.exit(1)}await mA(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
330
330
  `),process.exit(1))}else process.stdout.write(`No running daemon found; starting a fresh one.
331
- `);if(Yd(),await Vd(t),await Jd(t)){let n=await Wi();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
332
- `)}}async function uA(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!Mn(t))return!0;await lA(50)}return!1}async function Dg(t){await qi(_.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function Hg(){let t=await Wi();if(!t){process.stdout.write(`Daemon: not running
331
+ `);if(Vd(),await Yd(t),await Jd(t)){let n=await zi();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
332
+ `)}}async function mA(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!Mn(t))return!0;await hA(50)}return!1}async function Ug(t){await Wi(_.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function jg(){let t=await zi();if(!t){process.stdout.write(`Daemon: not running
333
333
  `),process.stdout.write(`CLI version: ${fe}
334
334
  `);return}let e=Mn(t.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${t.pid} host=${t.host} port=${t.port} started=${t.startedAt}
335
- `);let n,s;if(e)try{let o=await be();n=await Fr(o),s=qs(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${fe}
335
+ `);let n,s;if(e)try{let o=await be();n=await Or(o),s=qs(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${fe}
336
336
  `),e&&process.stdout.write(`Daemon version: unknown (health endpoint unreachable)
337
337
  `);return}let r=n.version===fe,i=n.configDigest!==void 0&&s!==void 0&&n.configDigest===s;if(r&&i){process.stdout.write(`Version: ${fe}
338
338
  `);return}process.stdout.write(`CLI version: ${fe}
339
339
  `),process.stdout.write(`Daemon version: ${n.version}
340
- `),r||process.stdout.write(Og.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(Og.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function Wi(){return hs()}Ve();fs();Ys();Ar();Eo();qn();ia();Mr();import*as vn from"fs/promises";import*as Zg from"os";import*as Sn from"path";rc();async function ey(t={}){let e=await be(),n=t.includeNonInteractive||t.all?"?includeNonInteractive=true":"",r=(await Fe(`/v1/sessions${n}`,{expectStatus:200})).body,i=r.sessions,o=t.host??"local",a=o==="all"?i:o==="local"?i.filter(y=>!y.importedFromMachine||!!y.upstreamSessionId):i.filter(y=>y.importedFromMachine===o&&!y.upstreamSessionId);if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
340
+ `),r||process.stdout.write(Bg.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(Bg.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function zi(){return ms()}Ge();ps();Vs();Ar();Po();qn();oa();Mr();import*as vn from"fs/promises";import*as ty from"os";import*as Sn from"path";rc();async function ny(t={}){let e=await be(),n=t.includeNonInteractive||t.all?"?includeNonInteractive=true":"",r=(await Oe(`/v1/sessions${n}`,{expectStatus:200})).body,i=r.sessions,o=t.host??"local",a=o==="all"?i:o==="local"?i.filter(y=>!y.importedFromMachine||!!y.upstreamSessionId):i.filter(y=>y.importedFromMachine===o&&!y.upstreamSessionId);if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
341
341
  `);return}if(a.length===0){if(o==="local"&&r.sessions.length>0){process.stdout.write(`No local sessions. Use --host=all to include imported sessions.
342
342
  `);return}if(o!=="local"&&o!=="all"){process.stdout.write(`No sessions from ${o}.
343
343
  `);return}process.stdout.write(`No active sessions.
344
- `);return}let c=a.slice().sort((y,b)=>{let v=(b.status==="warm"?1:0)-(y.status==="warm"?1:0);return v!==0?v:String(b.updatedAt||"").localeCompare(String(y.updatedAt||""))}),d=c,l=0;if(!t.all){let y=c.filter(k=>k.status!=="cold").length,b=e.sessionListColdLimit,v=c.slice(y,y+b),S=c.length-y-v.length;d=[...c.slice(0,y),...v],l=S}let u=Date.now(),f=d.map(y=>Qi(y,u)),p={columns:t.columns??e.tui.sessionColumns??Yi,cwdMaxWidth:e.tui.cwdColumnMaxWidth},h=Gi(f,p),m=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Vs(Vi,h,m,p)+`
345
- `);for(let y of f)process.stdout.write(Vs(y,h,m,p)+`
344
+ `);return}let c=a.slice().sort((y,b)=>{let v=(b.status==="warm"?1:0)-(y.status==="warm"?1:0);return v!==0?v:String(b.updatedAt||"").localeCompare(String(y.updatedAt||""))}),d=c,l=0;if(!t.all){let y=c.filter(k=>k.status!=="cold").length,b=e.sessionListColdLimit,v=c.slice(y,y+b),S=c.length-y-v.length;d=[...c.slice(0,y),...v],l=S}let u=Date.now(),f=d.map(y=>Gi(y,u)),p={columns:t.columns??e.tui.sessionColumns??Yi,cwdMaxWidth:e.tui.cwdColumnMaxWidth},h=Xi(f,p),m=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Ys(Qi,h,m,p)+`
345
+ `);for(let y of f)process.stdout.write(Ys(y,h,m,p)+`
346
346
  `);l>0&&process.stdout.write(`
347
347
  ... ${l} more cold session${l===1?"":"s"} hidden. Use --all to show.
348
- `)}async function ty(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
349
- `),process.exit(2));let e=await Fe(`/v1/sessions/${t}/kill`,{method:"POST"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
348
+ `)}async function sy(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
349
+ `),process.exit(2));let e=await Oe(`/v1/sessions/${t}/kill`,{method:"POST"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
350
350
  `),process.exit(1)),process.stdout.write(`Killed ${t}
351
- `)}async function ny(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
352
- `),process.exit(2));let e=await Fe(`/v1/sessions/${t}`,{method:"DELETE"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
351
+ `)}async function ry(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
352
+ `),process.exit(2));let e=await Oe(`/v1/sessions/${t}`,{method:"DELETE"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
353
353
  `),process.exit(1)),process.stdout.write(`Removed ${t}
354
- `)}async function sy(t){let e=t.maxAgeDays!==void 0?t.maxAgeDays:0,n={maxAgeDays:e};t.limit!==void 0&&(n.limit=t.limit),n.selection=t.keepUndecided?"explicit":"unpromoted";let r=(await Fe("/v1/sessions/collect",{method:"POST",body:n,expectStatus:200})).body;if(t.json){process.stdout.write(`${JSON.stringify(r,null,2)}
354
+ `)}async function iy(t){let e=t.maxAgeDays!==void 0?t.maxAgeDays:0,n={maxAgeDays:e};t.limit!==void 0&&(n.limit=t.limit),n.selection=t.keepUndecided?"explicit":"unpromoted";let r=(await Oe("/v1/sessions/collect",{method:"POST",body:n,expectStatus:200})).body;if(t.json){process.stdout.write(`${JSON.stringify(r,null,2)}
355
355
  `);return}let i=t.keepUndecided?"non-interactive":"unpromoted (cat one-shots + editor ghosts)";if(r.considered===0){let a=e>0?` older than ${e}d`:"";process.stdout.write(`No ${i} sessions${a} found.
356
- `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${Ki(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
356
+ `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${Ji(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
357
357
  `),r.failed>0&&process.stdout.write(` ${r.failed} failed (see daemon log).
358
358
  `),r.deferred>0&&process.stdout.write(` ${r.deferred} deferred \u2014 re-run \`hydra sessions collect\` to drain.
359
- `)}async function ry(t,e,n){t||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
360
- `),process.exit(2));let s=await vr(),r=await zi(),i=n==="summary"?"?tools=summary":"",o=await fetch(`${r}/v1/sessions/${encodeURIComponent(t)}/export${i}`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){let d=await o.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${o.status}: ${d}
359
+ `)}async function oy(t,e,n){t||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
360
+ `),process.exit(2));let s=await vr(),r=await Ki(),i=n==="summary"?"?tools=summary":"",o=await fetch(`${r}/v1/sessions/${encodeURIComponent(t)}/export${i}`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){let d=await o.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${o.status}: ${d}
361
361
  `),process.exit(1)}let a=await o.text();if(!e){process.stdout.write(a),a.endsWith(`
362
362
  `)||process.stdout.write(`
363
- `);return}let c=e==="."?EA(o,t):e;await vn.mkdir(Sn.dirname(Sn.resolve(c)),{recursive:!0}),await vn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
364
- `)}async function iy(t,e){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.]
365
- `),process.exit(2));let n,s,r=await xA(t);if(r!==null){let o=AA(r.raw);n=Bd(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${Sn.basename(t,Sn.extname(t))}-${a}.md`}else{let o=await vr(),a=await zi(),c=await fetch(`${a}/v1/sessions/${encodeURIComponent(t)}/transcript`,{headers:{Authorization:`Bearer ${o}`}});if(!c.ok){let l=await c.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${c.status}: ${l}
363
+ `);return}let c=e==="."?$A(o,t):e;await vn.mkdir(Sn.dirname(Sn.resolve(c)),{recursive:!0}),await vn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
364
+ `)}async function ay(t,e){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.]
365
+ `),process.exit(2));let n,s,r=await TA(t);if(r!==null){let o=EA(r.raw);n=Bd(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${Sn.basename(t,Sn.extname(t))}-${a}.md`}else{let o=await vr(),a=await Ki(),c=await fetch(`${a}/v1/sessions/${encodeURIComponent(t)}/transcript`,{headers:{Authorization:`Bearer ${o}`}});if(!c.ok){let l=await c.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${c.status}: ${l}
366
366
  `),process.exit(1)}n=await c.text();let d=new Date().toISOString().replace(/[:.]/g,"-");s=`hydra-${t}-${d}.md`}if(!e){process.stdout.write(n),n.endsWith(`
367
367
  `)||process.stdout.write(`
368
368
  `);return}let i=e==="."?s:e;await vn.mkdir(Sn.dirname(Sn.resolve(i)),{recursive:!0}),await vn.writeFile(i,n,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${i}
369
- `)}async function xA(t){try{if(!(await vn.stat(t)).isFile())return null}catch{return null}let e=await vn.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
370
- `),process.exit(1)}}function AA(t){try{return _n(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
371
- `),process.exit(1)}}async function oy(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
369
+ `)}async function TA(t){try{if(!(await vn.stat(t)).isFile())return null}catch{return null}let e=await vn.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
370
+ `),process.exit(1)}}function EA(t){try{return _n(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
371
+ `),process.exit(1)}}async function dy(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
372
372
  `),process.exit(2));let n;if(e.cwd!==void 0){let a=Sn.resolve(e.cwd);try{(await vn.stat(a)).isDirectory()||(process.stderr.write(`--cwd ${a} is not a directory
373
373
  `),process.exit(1))}catch{process.stderr.write(`--cwd ${a} does not exist
374
- `),process.exit(1)}n=a}let s;t==="-"?s=await TA():s=await vn.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
375
- `),process.exit(1)}if(e.info===!0){let a=await be();RA(r,a.tui.cwdColumnMaxWidth);return}let i=await Fe("/v1/sessions/import",{method:"POST",body:{bundle:r,replace:e.replace===!0,...n!==void 0?{cwd:n}:{}}});if(i.status===409){let a=i.body??{};process.stderr.write(`Bundle already imported as ${a.existingSessionId??"unknown"}. Use --replace to overwrite.
374
+ `),process.exit(1)}n=a}let s;t==="-"?s=await _A():s=await vn.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
375
+ `),process.exit(1)}if(e.info===!0){let a=await be();MA(r,a.tui.cwdColumnMaxWidth);return}let i=await Oe("/v1/sessions/import",{method:"POST",body:{bundle:r,replace:e.replace===!0,...n!==void 0?{cwd:n}:{}}});if(i.status===409){let a=i.body??{};process.stderr.write(`Bundle already imported as ${a.existingSessionId??"unknown"}. Use --replace to overwrite.
376
376
  `),process.exit(1)}i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
377
377
  `),process.exit(1));let o=i.body;process.stdout.write(o.replaced?`Replaced ${o.sessionId} (from ${o.importedFromSessionId})
378
378
  `:`Imported as ${o.sessionId} (from ${o.importedFromSessionId})
379
- `)}function CA(t){return{sessionId:t.session.sessionId,cwd:t.session.cwd,agentId:t.session.agentId,currentUsage:t.session.currentUsage,title:t.session.title,importedFromMachine:t.exportedFrom.machine,attachedClients:0,updatedAt:t.session.updatedAt,status:"cold",compactionState:t.session.compactionState}}function RA(t,e){let n;try{n=_n(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
380
- `),process.exit(1)}let s=CA(n),r=Qi(s),i={columns:sc,cwdMaxWidth:e},o=Gi([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Vs(Vi,o,a,i)+`
381
- `),process.stdout.write(Vs(r,o,a,i)+`
379
+ `)}function PA(t){return{sessionId:t.session.sessionId,cwd:t.session.cwd,agentId:t.session.agentId,currentUsage:t.session.currentUsage,title:t.session.title,importedFromMachine:t.exportedFrom.machine,attachedClients:0,updatedAt:t.session.updatedAt,status:"cold",compactionState:t.session.compactionState}}function MA(t,e){let n;try{n=_n(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
380
+ `),process.exit(1)}let s=PA(n),r=Gi(s),i={columns:sc,cwdMaxWidth:e},o=Xi([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Ys(Qi,o,a,i)+`
381
+ `),process.stdout.write(Ys(r,o,a,i)+`
382
382
  `);let c=n.session.upstreamSessionId??"-";process.stdout.write(`
383
383
  lineage: ${n.session.lineageId}
384
384
  exported: ${n.exportedAt} from ${n.exportedFrom.machine} (hydra ${n.exportedFrom.hydraVersion})
@@ -386,75 +386,75 @@ origin session: ${n.session.sessionId}
386
386
  origin upstream: ${c}
387
387
  history entries: ${n.history.length}`+(n.promptHistory?`, prompt history: ${n.promptHistory.length}
388
388
  `:`
389
- `))}async function TA(){let t=[];for await(let e of process.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}function EA(t,e){let n=t.headers.get("content-disposition");if(n){let r=n.match(/filename="([^"]+)"/);if(r)return r[1]}let s=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${s}.hydra`}async function ay(t,e={}){let n=await be(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await Ft(n),l=e.cwd?Sn.resolve(e.cwd):process.cwd(),u=await Yn(d,{cwd:l,all:!0}),f=tc(u,l);f||(process.stderr.write(`No sessions found for ${l}.
390
- `),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=PA(e.host,n),a=rt(s),c=Ip({host:r,port:i,sessionId:a});process.stdout.write(c+`
389
+ `))}async function _A(){let t=[];for await(let e of process.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}function $A(t,e){let n=t.headers.get("content-disposition");if(n){let r=n.match(/filename="([^"]+)"/);if(r)return r[1]}let s=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${s}.hydra`}async function cy(t,e={}){let n=await be(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await Ot(n),l=e.cwd?Sn.resolve(e.cwd):process.cwd(),u=await Vn(d,{cwd:l,all:!0}),f=tc(u,l);f||(process.stderr.write(`No sessions found for ${l}.
390
+ `),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=OA(e.host,n),a=rt(s),c=xp({host:r,port:i,sessionId:a});process.stdout.write(c+`
391
391
  `),o&&process.stderr.write(`Note: this URL points at loopback (127.0.0.1) and only works from the same machine. Set daemon.publicHost in config.json or pass --host <name> to advertise an externally-reachable hostname.
392
- `)}function PA(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=Xg(t,Pn);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=Xg(e.daemon.publicHost,Pn);return{host:n,port:s,isFallback:!1}}return MA(e.daemon.host)?{host:_A(),port:e.daemon.port,isFallback:!1}:kr(e.daemon.host)?{host:"127.0.0.1",port:e.daemon.port,isFallback:!0}:{host:e.daemon.host,port:e.daemon.port,isFallback:!1}}function MA(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function _A(){let t=Zg.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function Xg(t,e){if(t.startsWith("[")){let s=t.indexOf("]");if(s>0){let r=t.slice(1,s),i=t.slice(s+1);if(i.startsWith(":")){let o=Number(i.slice(1));return{host:r,port:Number.isInteger(o)&&o>0?o:e}}return{host:r,port:e}}}let n=t.lastIndexOf(":");if(n>0&&t.indexOf(":")===n){let s=t.slice(0,n),r=Number(t.slice(n+1));if(Number.isInteger(r)&&r>0)return{host:s,port:r}}return{host:t,port:e}}Xu();rc();Yu();Ve();he();sa();Ys();var hC={extension:{singular:"extension",plural:"extensions",logFile:t=>_.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>_.transformerLogFile(t)}};function lc(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function to(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function uc(t){let e=hC[t],n=`/v1/${e.plural}`;async function s(){let u=(await Fe(n,{expectStatus:200})).body[e.plural]??[];if(u.length===0){process.stdout.write(`No ${e.plural} configured.
393
- `);return}let f=u.map(y=>({name:y.name,status:y.status.toUpperCase(),version:y.version??"-",pid:y.pid!=null?String(y.pid):"-",restarts:String(y.restartCount),started:y.startedAt?Ki(y.startedAt):"-",log:y.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},h={name:to(p.name,f.map(y=>y.name)),status:to(p.status,f.map(y=>y.status)),version:to(p.version,f.map(y=>y.version)),pid:to(p.pid,f.map(y=>y.pid)),restarts:to(p.restarts,f.map(y=>y.restarts)),started:to(p.started,f.map(y=>y.started))},m=y=>[y.name.padEnd(h.name),y.status.padEnd(h.status),y.version.padEnd(h.version),y.pid.padStart(h.pid),y.restarts.padStart(h.restarts),y.started.padEnd(h.started),y.log].join(" ");process.stdout.write(m(p)+`
392
+ `)}function OA(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=ey(t,Pn);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=ey(e.daemon.publicHost,Pn);return{host:n,port:s,isFallback:!1}}return FA(e.daemon.host)?{host:LA(),port:e.daemon.port,isFallback:!1}:kr(e.daemon.host)?{host:"127.0.0.1",port:e.daemon.port,isFallback:!0}:{host:e.daemon.host,port:e.daemon.port,isFallback:!1}}function FA(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function LA(){let t=ty.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function ey(t,e){if(t.startsWith("[")){let s=t.indexOf("]");if(s>0){let r=t.slice(1,s),i=t.slice(s+1);if(i.startsWith(":")){let o=Number(i.slice(1));return{host:r,port:Number.isInteger(o)&&o>0?o:e}}return{host:r,port:e}}}let n=t.lastIndexOf(":");if(n>0&&t.indexOf(":")===n){let s=t.slice(0,n),r=Number(t.slice(n+1));if(Number.isInteger(r)&&r>0)return{host:s,port:r}}return{host:t,port:e}}Zu();rc();Yu();Ge();he();ra();Vs();var bC={extension:{singular:"extension",plural:"extensions",logFile:t=>_.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>_.transformerLogFile(t)}};function lc(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function no(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function uc(t){let e=bC[t],n=`/v1/${e.plural}`;async function s(){let u=(await Oe(n,{expectStatus:200})).body[e.plural]??[];if(u.length===0){process.stdout.write(`No ${e.plural} configured.
393
+ `);return}let f=u.map(y=>({name:y.name,status:y.status.toUpperCase(),version:y.version??"-",pid:y.pid!=null?String(y.pid):"-",restarts:String(y.restartCount),started:y.startedAt?Ji(y.startedAt):"-",log:y.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},h={name:no(p.name,f.map(y=>y.name)),status:no(p.status,f.map(y=>y.status)),version:no(p.version,f.map(y=>y.version)),pid:no(p.pid,f.map(y=>y.pid)),restarts:no(p.restarts,f.map(y=>y.restarts)),started:no(p.started,f.map(y=>y.started))},m=y=>[y.name.padEnd(h.name),y.status.padEnd(h.status),y.version.padEnd(h.version),y.pid.padStart(h.pid),y.restarts.padStart(h.restarts),y.started.padEnd(h.started),y.log].join(" ");process.stdout.write(m(p)+`
394
394
  `);for(let y of f)process.stdout.write(m(y)+`
395
395
  `);for(let y of u)y.failureReason&&process.stdout.write(` \u21B3 ${y.name}: ${y.failureReason}
396
396
  `)}async function r(d,l){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} add <name> [--command CMD] [--args A,B,C] [--env K=V]... [--disabled]
397
397
  `),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(d)){process.stderr.write(`Invalid ${e.singular} name '${d}': must match [A-Za-z0-9._-]+
398
- `),process.exit(2);return}await be();let u=await Ji(),f=u;(!f[e.plural]||typeof f[e.plural]!="object")&&(f[e.plural]={});let p=f[e.plural];if(p[d]){process.stderr.write(`${Iy(e.singular)} '${d}' already exists in config.
399
- `),process.exit(1);return}let h=Xd(l,e.singular),m=h.command,y={};m.length>0&&(y.command=m),h.args.length>0&&(y.args=h.args),Object.keys(h.env).length>0&&(y.env=h.env),h.enabled||(y.enabled=!1),p[d]=y,await Ou(u),process.stdout.write(`Added ${e.singular} '${d}' to ${_.config()}
400
- `);let b={name:d,...y};try{let v=await Fe(n,{method:"POST",body:b,rethrowNetworkError:!0});if(v.ok){let S=v.body,k=S.pid!=null?` pid=${S.pid}`:"";process.stdout.write(`${d}: ${S.status}${k}
398
+ `),process.exit(2);return}await be();let u=await Vi(),f=u;(!f[e.plural]||typeof f[e.plural]!="object")&&(f[e.plural]={});let p=f[e.plural];if(p[d]){process.stderr.write(`${Ay(e.singular)} '${d}' already exists in config.
399
+ `),process.exit(1);return}let h=Xd(l,e.singular),m=h.command,y={};m.length>0&&(y.command=m),h.args.length>0&&(y.args=h.args),Object.keys(h.env).length>0&&(y.env=h.env),h.enabled||(y.enabled=!1),p[d]=y,await Lu(u),process.stdout.write(`Added ${e.singular} '${d}' to ${_.config()}
400
+ `);let b={name:d,...y};try{let v=await Oe(n,{method:"POST",body:b,rethrowNetworkError:!0});if(v.ok){let S=v.body,k=S.pid!=null?` pid=${S.pid}`:"";process.stdout.write(`${d}: ${S.status}${k}
401
401
  `);return}process.stderr.write(`Daemon refused to register ${d} (HTTP ${v.status}${lc(v.body)}). Restart the daemon to apply.
402
402
  `)}catch{}}async function i(d){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} remove <name>
403
- `),process.exit(2);return}await be();let l=await Ji(),u=l,f=u[e.plural]??{};if(!f[d]){process.stderr.write(`${Iy(e.singular)} '${d}' not found in config.
404
- `),process.exit(1);return}delete f[d],u[e.plural]=f,await Ou(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${_.config()}
405
- `);try{let p=await Fe(`${n}/${encodeURIComponent(d)}`,{method:"DELETE",rethrowNetworkError:!0});if(p.status===204||p.status===404){process.stdout.write(`${d}: stopped
403
+ `),process.exit(2);return}await be();let l=await Vi(),u=l,f=u[e.plural]??{};if(!f[d]){process.stderr.write(`${Ay(e.singular)} '${d}' not found in config.
404
+ `),process.exit(1);return}delete f[d],u[e.plural]=f,await Lu(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${_.config()}
405
+ `);try{let p=await Oe(`${n}/${encodeURIComponent(d)}`,{method:"DELETE",rethrowNetworkError:!0});if(p.status===204||p.status===404){process.stdout.write(`${d}: stopped
406
406
  `);return}process.stderr.write(`Daemon refused to unregister ${d} (HTTP ${p.status}${lc(p.body)}).
407
407
  `)}catch(p){process.stderr.write(`Daemon not reachable (${p.message}). Config saved.
408
408
  `)}}async function o(d,l){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} ${l} <name|all>
409
- `),process.exit(2);return}if(d==="all"){await a(l);return}let u=await Fe(`${n}/${encodeURIComponent(d)}/${l}`,{method:"POST"});if(!u.ok){process.stderr.write(`HTTP ${u.status}${lc(u.body)}
409
+ `),process.exit(2);return}if(d==="all"){await a(l);return}let u=await Oe(`${n}/${encodeURIComponent(d)}/${l}`,{method:"POST"});if(!u.ok){process.stderr.write(`HTTP ${u.status}${lc(u.body)}
410
410
  `),process.exit(1);return}let f=u.body,p=f.pid!=null?` pid=${f.pid}`:"";process.stdout.write(`${d}: ${f.status}${p}
411
- `)}async function a(d){let p=((await Fe(n,{expectStatus:200})).body[e.plural]??[]).filter(m=>d==="start"?m.enabled&&m.status!=="running":m.status==="running");if(p.length===0){let m=d==="start"?`no enabled ${e.plural} are stopped`:`no ${e.plural} are running`;process.stdout.write(`Nothing to ${d}: ${m}.
412
- `);return}let h=0;for(let m of p)try{let y=await Fe(`${n}/${encodeURIComponent(m.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!y.ok){process.stdout.write(`${m.name}: ERROR HTTP ${y.status}${lc(y.body)}
411
+ `)}async function a(d){let p=((await Oe(n,{expectStatus:200})).body[e.plural]??[]).filter(m=>d==="start"?m.enabled&&m.status!=="running":m.status==="running");if(p.length===0){let m=d==="start"?`no enabled ${e.plural} are stopped`:`no ${e.plural} are running`;process.stdout.write(`Nothing to ${d}: ${m}.
412
+ `);return}let h=0;for(let m of p)try{let y=await Oe(`${n}/${encodeURIComponent(m.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!y.ok){process.stdout.write(`${m.name}: ERROR HTTP ${y.status}${lc(y.body)}
413
413
  `),h+=1;continue}let b=y.body,v=b.pid!=null?` pid=${b.pid}`:"";process.stdout.write(`${m.name}: ${b.status}${v}
414
414
  `)}catch(y){process.stdout.write(`${m.name}: ERROR ${y.message}
415
415
  `),h+=1}h>0&&process.exit(1)}async function c(d){let{name:l,rest:u}=Qd(d);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
416
- `),process.exit(2);return}let f=e.logFile(l);await qi(f,u,`No log file (${e.singular} never ran?)`)}return{list:s,add:r,remove:i,start:d=>o(d,"start"),stop:d=>o(d,"stop"),restart:d=>o(d,"restart"),logs:c}}function Iy(t){return t.charAt(0).toUpperCase()+t.slice(1)}var Br=uc("extension"),xy=Br.list,Ay=Br.add,Cy=Br.remove,Ry=Br.start,Ty=Br.stop,Ey=Br.restart,Py=Br.logs;var Nr=uc("transformer"),My=Nr.list,_y=Nr.add,$y=Nr.remove,Fy=Nr.start,Oy=Nr.stop,Ly=Nr.restart,By=Nr.logs;lf();ra();Di();Tr();Ve();Ar();Or();Et();nn();Xa();hf();import MC from"os";import{spawn as _C}from"child_process";async function $C({conn:t,agentId:e,authMethods:n,method:s,spawn:r}){let i;try{let c=await t.request("hydra-acp/agents/auth_methods",{agentId:e});i=Array.isArray(c?.authMethods)?c.authMethods:[]}catch{i=void 0}let o=c=>new Promise(d=>{let l=r(c.command,c.args,{stdio:"inherit",env:c.env,cwd:c.cwd});l.on("exit",u=>{d({exitCode:u})}),l.on("error",()=>{d({exitCode:-1})})}),a=async(c,d)=>{let l=await FC(c,s),u=await pf(l,{authenticate:f=>t.request("authenticate",{methodId:f,_meta:{"hydra-acp":{agentId:d}}}),runTerminalAuth:o});return u.kind==="terminal-completed"?{exitCode:0}:u.kind==="retry"?(process.stderr.write(`auth method completed without terminal step; you may need to retry session/new
416
+ `),process.exit(2);return}let f=e.logFile(l);await Wi(f,u,`No log file (${e.singular} never ran?)`)}return{list:s,add:r,remove:i,start:d=>o(d,"start"),stop:d=>o(d,"stop"),restart:d=>o(d,"restart"),logs:c}}function Ay(t){return t.charAt(0).toUpperCase()+t.slice(1)}var Br=uc("extension"),Cy=Br.list,Ry=Br.add,Ty=Br.remove,Ey=Br.start,Py=Br.stop,My=Br.restart,_y=Br.logs;var Nr=uc("transformer"),$y=Nr.list,Oy=Nr.add,Fy=Nr.remove,Ly=Nr.start,By=Nr.stop,Ny=Nr.restart,Dy=Nr.logs;uf();ia();Hi();Tr();Ge();Ar();Fr();Et();nn();Za();mf();import LC from"os";import{spawn as BC}from"child_process";async function NC({conn:t,agentId:e,authMethods:n,method:s,spawn:r}){let i;try{let c=await t.request("hydra-acp/agents/auth_methods",{agentId:e});i=Array.isArray(c?.authMethods)?c.authMethods:[]}catch{i=void 0}let o=c=>new Promise(d=>{let l=r(c.command,c.args,{stdio:"inherit",env:c.env,cwd:c.cwd});l.on("exit",u=>{d({exitCode:u})}),l.on("error",()=>{d({exitCode:-1})})}),a=async(c,d)=>{let l=await DC(c,s),u=await hf(l,{authenticate:f=>t.request("authenticate",{methodId:f,_meta:{"hydra-acp":{agentId:d}}}),runTerminalAuth:o});return u.kind==="terminal-completed"?{exitCode:0}:u.kind==="retry"?(process.stderr.write(`auth method completed without terminal step; you may need to retry session/new
417
417
  `),{exitCode:0}):u.kind==="error"?(process.stderr.write(`${u.message}
418
418
  `),{exitCode:1}):(process.stderr.write(`auth process exited with code ${u.exitCode}
419
- `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await t.request("session/new",{cwd:MC.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
420
- `),{exitCode:0}}catch(c){if(c instanceof Error&&"code"in c&&c.code===z.AuthRequired){let d=c.data,l=d?._meta?.["hydra-acp"]?.authMethods??n,u=d?._meta?.["hydra-acp"]?.agentId??e;return a(l,u)}throw c}}async function FC(t,e){if(e!==void 0){let s=t.find(i=>i.id===e);if(s)return s;let r=t.map(i=>i.id).join(", ");process.stderr.write(`unknown auth method "${e}" \u2014 valid ids: ${r}
419
+ `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await t.request("session/new",{cwd:LC.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
420
+ `),{exitCode:0}}catch(c){if(c instanceof Error&&"code"in c&&c.code===z.AuthRequired){let d=c.data,l=d?._meta?.["hydra-acp"]?.authMethods??n,u=d?._meta?.["hydra-acp"]?.agentId??e;return a(l,u)}throw c}}async function DC(t,e){if(e!==void 0){let s=t.find(i=>i.id===e);if(s)return s;let r=t.map(i=>i.id).join(", ");process.stderr.write(`unknown auth method "${e}" \u2014 valid ids: ${r}
421
421
  `),process.exit(2)}if(t.length===1)return t[0];if(process.stdin.isTTY===!0){let s=t.map((c,d)=>`${d+1}) ${c.id} \u2014 ${c.name??c.description??""}`);process.stdout.write(`multiple auth methods available. choose one:
422
422
  ${s.join(`
423
423
  `)}
424
424
  `);let{createInterface:r}=await import("readline/promises"),i=r({input:process.stdin,output:process.stdout}),o=await i.question("method> ");i.close();let a=parseInt(o.trim(),10);return(Number.isNaN(a)||a<1||a>t.length)&&(process.stderr.write(`invalid selection "${o}" \u2014 enter a number between 1 and ${t.length}
425
425
  `),process.exit(2)),t[a-1]}let n=t.map(s=>s.id).join(", ");process.stderr.write(`multiple auth methods available; pass --method <id> (one of: ${n})
426
- `),process.exit(2)}async function iw(t,e){(t===void 0||t.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
427
- `),process.exit(2));let{resolveAgentIdOrExit:n}=await Promise.resolve().then(()=>(lf(),Uy)),s=await n(t,"hydra agent auth"),r=await be(),i=await Ft(r);await Js(r);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await Lr(i.wsUrl,o),c=Jn(a),d=new zt(c);try{await d.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:fe}})}catch{}let l;try{l=await $C({conn:d,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:_C})}finally{a.close()}process.exit(l.exitCode)}sa();cl();Ys();async function ow(t){let e=ci(t,"force");if(await Ud()&&!e){let r=await hi("Current password: ");await jd(r)||(process.stderr.write(`Wrong password.
426
+ `),process.exit(2)}async function aw(t,e){(t===void 0||t.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
427
+ `),process.exit(2));let{resolveAgentIdOrExit:n}=await Promise.resolve().then(()=>(uf(),qy)),s=await n(t,"hydra agent auth"),r=await be(),i=await Ot(r);await Js(r);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await Lr(i.wsUrl,o),c=Jn(a),d=new zt(c);try{await d.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:fe}})}catch{}let l;try{l=await NC({conn:d,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:BC})}finally{a.close()}process.exit(l.exitCode)}ra();ll();Vs();async function dw(t){let e=ci(t,"force");if(await Ud()&&!e){let r=await hi("Current password: ");await jd(r)||(process.stderr.write(`Wrong password.
428
428
  `),process.exit(1))}let n=await hi("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
429
429
  `),process.exit(2));let s=await hi("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
430
- `),process.exit(1)),await gg(n),process.stdout.write(`Password set.
431
- `)}async function aw(){let e=(await Fe("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
430
+ `),process.exit(1)),await wg(n),process.stdout.write(`Password set.
431
+ `)}async function cw(){let e=(await Oe("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
432
432
  `);return}let n={id:"ID",label:"LABEL",createdAt:"CREATED",expiresAt:"EXPIRES",lastUsedAt:"LAST USED"},s=e.sessions.map(o=>({id:o.id,label:o.label??"-",createdAt:o.createdAt,expiresAt:o.expiresAt,lastUsedAt:o.lastUsedAt})),r={id:vc(n.id,s.map(o=>o.id)),label:vc(n.label,s.map(o=>o.label)),createdAt:vc(n.createdAt,s.map(o=>o.createdAt)),expiresAt:vc(n.expiresAt,s.map(o=>o.expiresAt))},i=o=>[o.id.padEnd(r.id),o.label.padEnd(r.label),o.createdAt.padEnd(r.createdAt),o.expiresAt.padEnd(r.expiresAt),o.lastUsedAt].join(" ");process.stdout.write(i(n)+`
433
433
  `);for(let o of s)process.stdout.write(i(o)+`
434
- `)}async function dw(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
435
- `),process.exit(2));let e=await Fe(`/v1/auth/sessions/${t}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${t}
434
+ `)}async function lw(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
435
+ `),process.exit(2));let e=await Oe(`/v1/auth/sessions/${t}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${t}
436
436
  `);return}e.status===404&&(process.stderr.write(`No session token with id ${t}
437
437
  `),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${e.status}
438
- `),process.exit(1)}function vc(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as Xs from"fs";Ve();Ar();Or();mf();Et();var Sc=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(yf(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(gf(e)){if(e.method==="session/new"){let n=e.params??{},s=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"new",data:{cwd:s}});return}if(e.method==="session/attach"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"";this.pending.set(e.id,{kind:"attach",data:{sessionId:s}});return}if(e.method==="session/load"||e.method==="session/resume"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"",r=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"load",data:{sessionId:s,cwd:r}})}}}observeFromServer(e){if(!gf(e)&&!yf(e)&&"method"in e){if(e.method==="session/update"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0,p=typeof u.update?.messageId=="string"?u.update.messageId:void 0;f&&p&&this.lastMessageIds.set(f,p)}return}if(gf(e)){if(e.method==="session/request_permission"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0;if(f){let p=u.toolCall,h=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,m={requestId:e.id,sessionId:f,toolCallId:h,params:u};if(this.pendingPermissions.set(e.id,m),h){let y=this.pendingPermissionsByToolCall.get(h);y?y.push(e.id):this.pendingPermissionsByToolCall.set(h,[e.id])}}}return}if(!yf(e)||e.id===null)return;if(e.error){this.pending.delete(e.id);return}let n=this.pending.get(e.id);if(!n)return;this.pending.delete(e.id);let s=e.result??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)return;let i=s._meta,o=en(i),a=o.upstreamSessionId,c=o.agentId,d="";(n.kind==="new"||n.kind==="load")&&(d=n.data.cwd);let l=o.cwd??d;!a||!c||!l||this.contexts.set(r,{sessionId:r,upstreamSessionId:a,agentId:c,cwd:l,title:o.title,agentArgs:o.agentArgs})}list(){return[...this.contexts.values()]}forget(e){this.contexts.delete(e),this.lastMessageIds.delete(e)}lastMessageId(e){return this.lastMessageIds.get(e)}clearPending(){this.pending.clear()}takePendingPermissions(){let e=[...this.pendingPermissions.values()];return this.pendingPermissions.clear(),this.pendingPermissionsByToolCall.clear(),e}takePendingPermission(e){let n=this.pendingPermissions.get(e);return n&&this.deletePendingPermission(n),n}takePendingPermissionByToolCall(e){let n=this.pendingPermissionsByToolCall.get(e);if(!n||n.length===0)return;let s=n[0],r=this.pendingPermissions.get(s);return r&&this.deletePendingPermission(r),r}deletePendingPermission(e){if(this.pendingPermissions.delete(e.requestId),e.toolCallId){let n=this.pendingPermissionsByToolCall.get(e.toolCallId);if(n){let s=n.indexOf(e.requestId);s>=0&&n.splice(s,1),n.length===0&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}}}};function gf(t){return"method"in t&&"id"in t&&t.id!==void 0}function yf(t){return!("method"in t)&&"id"in t}Ic();nn();he();Po();import{writeFileSync as HC}from"fs";var UC=t=>{HC("/proc/self/comm",t)};function co(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??UC;try{s(e.commName??Dn())}catch{}}function lo(t,e=Dn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function Ac(t){co(lo(process.argv.slice(2)),{commName:"hydra-shim"});let e=await be(),n=t.target??await Ft(e);n.isLocal&&!t.target&&await Js(e);let s=new Sc,r=sd(process.stdin,process.stdout),i=n.isLocal?async()=>(await Ft(await be())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new ao({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await JC(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
439
- `);for(let l of d)await YC(a,l,s.lastMessageId(l.sessionId))}}});jC({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
440
- `),r.close(),process.exit(c?1:0)}),r.onClose(()=>{(async()=>(await Promise.race([a.close().catch(()=>{}),new Promise(d=>setTimeout(d,1e3))]),process.exit(0)))()}),await a.start()}function jC({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(mw("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&XC(i)){e.send({jsonrpc:"2.0",id:i.id,result:Wr(i.params)});return}qC(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(mw("client\u2192daemon",i),s.observeFromClient(i),QC(i)){e.send(GC(i));return}if(VC(i)){if(t.sessionId){e.send(ZC(i,t.sessionId));return}let o=i;t.agentId&&(o=xc(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=xc(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=xc(o,{title:r.name}),r.used=!0),t.model&&(o=xc(o,{model:t.model})),e.send(o);return}e.send(i)})}function qC(t,e,n){let s=WC(t);if(!s)return;let r=typeof s.toolCallId=="string"?s.toolCallId:void 0;if(!r)return;let i=e.takePendingPermissionByToolCall(r);if(!i)return;let o=KC(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function WC(t){if(!zC(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function zC(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function KC(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function JC(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
441
- `);for(let s of n){let r=typeof s.params.sessionId=="string"?s.params.sessionId:void 0;if(!r)continue;let i={sessionUpdate:"permission_resolved",outcome:{kind:"cancelled",reason:"daemon-disconnected"},resolvedBy:{clientId:"hydra-acp"}};s.toolCallId&&(i.toolCallId=s.toolCallId),await e.send({jsonrpc:"2.0",method:"session/update",params:{sessionId:r,update:i}}).catch(()=>{})}}}async function YC(t,e,n){let s={upstreamSessionId:e.upstreamSessionId,agentId:e.agentId,cwd:e.cwd};e.title!==void 0&&(s.title=e.title),e.agentArgs&&e.agentArgs.length>0&&(s.agentArgs=e.agentArgs);let r={sessionId:e.sessionId,_meta:{"hydra-acp":{resume:s}}};n?(r.historyPolicy="after_message",r.afterMessageId=n):r.historyPolicy="pending_only";let i={jsonrpc:"2.0",id:`resume-${e.sessionId}-${Date.now()}`,method:"session/attach",params:r};try{let o=await t.request(i);o.error&&process.stderr.write(`hydra-acp: replay attach for ${e.sessionId} failed: ${o.error.message}
438
+ `),process.exit(1)}function vc(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as Xs from"fs";Ge();Ar();Fr();gf();Et();var Sc=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(wf(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(yf(e)){if(e.method==="session/new"){let n=e.params??{},s=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"new",data:{cwd:s}});return}if(e.method==="session/attach"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"";this.pending.set(e.id,{kind:"attach",data:{sessionId:s}});return}if(e.method==="session/load"||e.method==="session/resume"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"",r=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"load",data:{sessionId:s,cwd:r}})}}}observeFromServer(e){if(!yf(e)&&!wf(e)&&"method"in e){if(e.method==="session/update"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0,p=typeof u.update?.messageId=="string"?u.update.messageId:void 0;f&&p&&this.lastMessageIds.set(f,p)}return}if(yf(e)){if(e.method==="session/request_permission"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0;if(f){let p=u.toolCall,h=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,m={requestId:e.id,sessionId:f,toolCallId:h,params:u};if(this.pendingPermissions.set(e.id,m),h){let y=this.pendingPermissionsByToolCall.get(h);y?y.push(e.id):this.pendingPermissionsByToolCall.set(h,[e.id])}}}return}if(!wf(e)||e.id===null)return;if(e.error){this.pending.delete(e.id);return}let n=this.pending.get(e.id);if(!n)return;this.pending.delete(e.id);let s=e.result??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)return;let i=s._meta,o=en(i),a=o.upstreamSessionId,c=o.agentId,d="";(n.kind==="new"||n.kind==="load")&&(d=n.data.cwd);let l=o.cwd??d;!a||!c||!l||this.contexts.set(r,{sessionId:r,upstreamSessionId:a,agentId:c,cwd:l,title:o.title,agentArgs:o.agentArgs})}list(){return[...this.contexts.values()]}forget(e){this.contexts.delete(e),this.lastMessageIds.delete(e)}lastMessageId(e){return this.lastMessageIds.get(e)}clearPending(){this.pending.clear()}takePendingPermissions(){let e=[...this.pendingPermissions.values()];return this.pendingPermissions.clear(),this.pendingPermissionsByToolCall.clear(),e}takePendingPermission(e){let n=this.pendingPermissions.get(e);return n&&this.deletePendingPermission(n),n}takePendingPermissionByToolCall(e){let n=this.pendingPermissionsByToolCall.get(e);if(!n||n.length===0)return;let s=n[0],r=this.pendingPermissions.get(s);return r&&this.deletePendingPermission(r),r}deletePendingPermission(e){if(this.pendingPermissions.delete(e.requestId),e.toolCallId){let n=this.pendingPermissionsByToolCall.get(e.toolCallId);if(n){let s=n.indexOf(e.requestId);s>=0&&n.splice(s,1),n.length===0&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}}}};function yf(t){return"method"in t&&"id"in t&&t.id!==void 0}function wf(t){return!("method"in t)&&"id"in t}Ic();nn();he();Mo();import{writeFileSync as zC}from"fs";var KC=t=>{zC("/proc/self/comm",t)};function lo(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??KC;try{s(e.commName??Dn())}catch{}}function uo(t,e=Dn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function Ac(t){lo(uo(process.argv.slice(2)),{commName:"hydra-shim"});let e=await be(),n=t.target??await Ot(e);n.isLocal&&!t.target&&await Js(e);let s=new Sc,r=rd(process.stdin,process.stdout),i=n.isLocal?async()=>(await Ot(await be())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new co({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await XC(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
439
+ `);for(let l of d)await ZC(a,l,s.lastMessageId(l.sessionId))}}});JC({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
440
+ `),r.close(),process.exit(c?1:0)}),r.onClose(()=>{(async()=>(await Promise.race([a.close().catch(()=>{}),new Promise(d=>setTimeout(d,1e3))]),process.exit(0)))()}),await a.start()}function JC({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(yw("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&sR(i)){e.send({jsonrpc:"2.0",id:i.id,result:Wr(i.params)});return}VC(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(yw("client\u2192daemon",i),s.observeFromClient(i),tR(i)){e.send(nR(i));return}if(eR(i)){if(t.sessionId){e.send(rR(i,t.sessionId));return}let o=i;t.agentId&&(o=xc(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=xc(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=xc(o,{title:r.name}),r.used=!0),t.model&&(o=xc(o,{model:t.model})),e.send(o);return}e.send(i)})}function VC(t,e,n){let s=YC(t);if(!s)return;let r=typeof s.toolCallId=="string"?s.toolCallId:void 0;if(!r)return;let i=e.takePendingPermissionByToolCall(r);if(!i)return;let o=GC(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function YC(t){if(!QC(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function QC(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function GC(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function XC(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
441
+ `);for(let s of n){let r=typeof s.params.sessionId=="string"?s.params.sessionId:void 0;if(!r)continue;let i={sessionUpdate:"permission_resolved",outcome:{kind:"cancelled",reason:"daemon-disconnected"},resolvedBy:{clientId:"hydra-acp"}};s.toolCallId&&(i.toolCallId=s.toolCallId),await e.send({jsonrpc:"2.0",method:"session/update",params:{sessionId:r,update:i}}).catch(()=>{})}}}async function ZC(t,e,n){let s={upstreamSessionId:e.upstreamSessionId,agentId:e.agentId,cwd:e.cwd};e.title!==void 0&&(s.title=e.title),e.agentArgs&&e.agentArgs.length>0&&(s.agentArgs=e.agentArgs);let r={sessionId:e.sessionId,_meta:{"hydra-acp":{resume:s}}};n?(r.historyPolicy="after_message",r.afterMessageId=n):r.historyPolicy="pending_only";let i={jsonrpc:"2.0",id:`resume-${e.sessionId}-${Date.now()}`,method:"session/attach",params:r};try{let o=await t.request(i);o.error&&process.stderr.write(`hydra-acp: replay attach for ${e.sessionId} failed: ${o.error.message}
442
442
  `)}catch(o){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${o.message}
443
- `)}}function VC(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function QC(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function GC(t){let e=t.params??{},n=e.clientInfo,s=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?t:{...t,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:fe}}}}function XC(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function ZC(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var eR=25*1024*1024,hw=!1,zr=null;function mw(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!hw){hw=!0;try{zr=_.shimWireLogFile(),Xs.mkdirSync(_.home(),{recursive:!0});let n=Xs.statSync(zr,{throwIfNoEntry:!1});n&&n.size>eR&&Xs.renameSync(zr,`${zr}.1`)}catch{zr=null}}if(zr)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
444
- `;Xs.appendFile(zr,n,()=>{})}catch{}}}function xc(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}Tr();Di();ra();Ve();Ar();Or();Ws();Et();nn();Ic();import{mkdtempSync as uR,rmSync as fR}from"fs";import{tmpdir as pR}from"os";import{join as hR}from"path";function gw(t){let e="",n=!1,s=!1,r=!1,i=()=>{if(e.length===0)return;let a=e;e="",t.onChunk(a)},o=()=>{s||(s=!0,n=!1,t.scheduleFlushCheck(()=>{if(s=!1,n){o();return}i()}))};return{feed(a){r||a.length===0||(e+=a,s?n=!0:o())},eof(){r||(r=!0,i())}}}eo();import tR from"chalk";import nR from"strip-ansi";var Cc=new tR.Instance({level:3});function yw(t,e){if(t.length===0)return"";let n=Gs(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(sR(i,e));let r=s.join(`
443
+ `)}}function eR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function tR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function nR(t){let e=t.params??{},n=e.clientInfo,s=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?t:{...t,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:fe}}}}function sR(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function rR(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var iR=25*1024*1024,gw=!1,zr=null;function yw(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!gw){gw=!0;try{zr=_.shimWireLogFile(),Xs.mkdirSync(_.home(),{recursive:!0});let n=Xs.statSync(zr,{throwIfNoEntry:!1});n&&n.size>iR&&Xs.renameSync(zr,`${zr}.1`)}catch{zr=null}}if(zr)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
444
+ `;Xs.appendFile(zr,n,()=>{})}catch{}}}function xc(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}Tr();Hi();ia();Ge();Ar();Fr();Ws();Et();nn();Ic();import{mkdtempSync as gR,rmSync as yR}from"fs";import{tmpdir as wR}from"os";import{join as bR}from"path";function ww(t){let e="",n=!1,s=!1,r=!1,i=()=>{if(e.length===0)return;let a=e;e="",t.onChunk(a)},o=()=>{s||(s=!0,n=!1,t.scheduleFlushCheck(()=>{if(s=!1,n){o();return}i()}))};return{feed(a){r||a.length===0||(e+=a,s?n=!0:o())},eof(){r||(r=!0,i())}}}to();import oR from"chalk";import aR from"strip-ansi";var Cc=new oR.Instance({level:3});function bw(t,e){if(t.length===0)return"";let n=Gs(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(dR(i,e));let r=s.join(`
445
445
  `);return r.endsWith(`
446
446
  `)||(r+=`
447
- `),r}function sR(t,e){let n=cR(t.body,e);return e==="ansi"?n=lR(n,t.bodyStyle):n=nR(n),n}var rR="\x1B[1m",iR="\x1B[96m",oR="\x1B[93m",aR="\x1B[0m",dR="\0";function cR(t,e){let n=t.replace(/\^\^/g,dR);return e==="ansi"&&(n=n.replace(/\^\+/g,rR).replace(/\^C/g,iR).replace(/\^Y/g,oR).replace(/\^:/g,aR)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function lR(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return Cc.bold.yellowBright(t);case"heading-2":return Cc.bold.cyanBright(t);case"heading-3":return Cc.bold(t);case"dim":return Cc.dim(t);default:return t}}var mR=1*1024*1024,ww="mcp__hydra-acp-stdin__";function bw(t,e){return{sessionId:t,prompt:e,_meta:{[Tt]:{ancillary:!0}}}}function gR(t){if(t)for(let e of t.split(/\r?\n/)){let n=e.trim();if(n)return n.length>80?`${n.slice(0,80)}\u2026`:n}}function yR(t){if(!t||typeof t!="object")return!1;let e=t.toolCall;if(!e||typeof e!="object")return!1;let n=e.title;if(typeof n=="string"&&n.startsWith(ww))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(ww))}async function vw(t){if(co(lo(process.argv.slice(2))),process.stdin.isTTY&&!t.prompt&&!t.sessionId){process.stderr.write(`hydra-acp cat: nothing to send. Pipe input on stdin, pass -p <text>, or attach to an existing session with --session.
448
- `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let c=uR(hR(pR(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{fR(c,{recursive:!0,force:!0})}catch{}})}let e=await be(),n=t.target??await Ft(e);n.isLocal&&!t.target&&await Js(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await Lr(n.wsUrl,s),i=Jn(r),o=new zt(i),a=await bR({conn:o,opts:t,stdin:process.stdin,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0,stdout:c=>process.stdout.write(c),stderr:c=>{process.stderr.write(c)},streamClient:wR(n.baseUrl,n.token)});process.exit(a.exitCode)}function wR(t,e){let n={"Content-Type":"application/json",Authorization:`Bearer ${e}`},s=(r,i)=>`${t}/v1/sessions/${encodeURIComponent(r)}/stdin${i}`;return{async open(r,i){let o=await fetch(s(r,"/open"),{method:"POST",headers:n,body:JSON.stringify(i)});if(!o.ok)throw new Error(`stdin/open HTTP ${o.status}`);return await o.json()},async write(r,i,o){let a=await fetch(s(r,""),{method:"POST",headers:n,body:JSON.stringify({chunk:i,eof:o})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function bR(t){let{conn:e,opts:n,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=t,c=i?"ansi":"plain",d=n.raw===!0,l=!r&&n.sessionId===void 0&&n.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async X=>n.dangerouslySkipPermissions?Wr(X):yR(X)?Wr(X):uw(X));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:Er,version:fe}})}catch{}let u=await kR(e,n,l),f=!1,p=!0,h="",m=0,y=X=>{X.length!==0&&(o(X),p=X.charCodeAt(X.length-1)===10,f=!0)},b=()=>{if(d||h.length===0)return;let X=yw(h,c);if(h="",X.length===0)return;let ce=m>0?`
447
+ `),r}function dR(t,e){let n=hR(t.body,e);return e==="ansi"?n=mR(n,t.bodyStyle):n=aR(n),n}var cR="\x1B[1m",lR="\x1B[96m",uR="\x1B[93m",fR="\x1B[0m",pR="\0";function hR(t,e){let n=t.replace(/\^\^/g,pR);return e==="ansi"&&(n=n.replace(/\^\+/g,cR).replace(/\^C/g,lR).replace(/\^Y/g,uR).replace(/\^:/g,fR)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function mR(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return Cc.bold.yellowBright(t);case"heading-2":return Cc.bold.cyanBright(t);case"heading-3":return Cc.bold(t);case"dim":return Cc.dim(t);default:return t}}var vR=1*1024*1024,vw="mcp__hydra-acp-stdin__";function Sw(t,e){return{sessionId:t,prompt:e,_meta:{[Tt]:{ancillary:!0}}}}function SR(t){if(t)for(let e of t.split(/\r?\n/)){let n=e.trim();if(n)return n.length>80?`${n.slice(0,80)}\u2026`:n}}function kR(t){if(!t||typeof t!="object")return!1;let e=t.toolCall;if(!e||typeof e!="object")return!1;let n=e.title;if(typeof n=="string"&&n.startsWith(vw))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(vw))}async function kw(t){if(lo(uo(process.argv.slice(2))),process.stdin.isTTY&&!t.prompt&&!t.sessionId){process.stderr.write(`hydra-acp cat: nothing to send. Pipe input on stdin, pass -p <text>, or attach to an existing session with --session.
448
+ `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let c=gR(bR(wR(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{yR(c,{recursive:!0,force:!0})}catch{}})}let e=await be(),n=t.target??await Ot(e);n.isLocal&&!t.target&&await Js(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await Lr(n.wsUrl,s),i=Jn(r),o=new zt(i),a=await xR({conn:o,opts:t,stdin:process.stdin,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0,stdout:c=>process.stdout.write(c),stderr:c=>{process.stderr.write(c)},streamClient:IR(n.baseUrl,n.token)});process.exit(a.exitCode)}function IR(t,e){let n={"Content-Type":"application/json",Authorization:`Bearer ${e}`},s=(r,i)=>`${t}/v1/sessions/${encodeURIComponent(r)}/stdin${i}`;return{async open(r,i){let o=await fetch(s(r,"/open"),{method:"POST",headers:n,body:JSON.stringify(i)});if(!o.ok)throw new Error(`stdin/open HTTP ${o.status}`);return await o.json()},async write(r,i,o){let a=await fetch(s(r,""),{method:"POST",headers:n,body:JSON.stringify({chunk:i,eof:o})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function xR(t){let{conn:e,opts:n,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=t,c=i?"ansi":"plain",d=n.raw===!0,l=!r&&n.sessionId===void 0&&n.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async X=>n.dangerouslySkipPermissions?Wr(X):kR(X)?Wr(X):pw(X));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:Er,version:fe}})}catch{}let u=await RR(e,n,l),f=!1,p=!0,h="",m=0,y=X=>{X.length!==0&&(o(X),p=X.charCodeAt(X.length-1)===10,f=!0)},b=()=>{if(d||h.length===0)return;let X=bw(h,c);if(h="",X.length===0)return;let ce=m>0?`
449
449
  `:"";y(ce+X),m+=1},v=()=>{b(),f&&!p&&y(`
450
- `),f=!1};e.onNotification("session/update",X=>{let ce=X?.update,Je=Kn(ce,{cwd:n.cwd});if(Je){if(Je.kind==="agent-text"){d?y(Je.text):h+=Je.text;return}if(Je.kind==="turn-complete"){v();return}switch(Je.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":b();return;default:return}}});let S=!1,k=async X=>{let ce=[];if(n.prompt&&!S&&ce.push({type:"text",text:n.prompt}),X.length>0&&ce.push({type:"text",text:X}),ce.length!==0){try{await e.request("session/prompt",bw(u,ce)),S=!0}catch(Je){a(`hydra-acp cat: prompt failed: ${Je.message}
451
- `);return}v()}},T=0,F,$=new Promise(X=>{F=X}),B=!1,K=async X=>{B||(B=!0,v(),n.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:u}))().catch(()=>{}),new Promise(Je=>setTimeout(Je,500))]),await e.close().catch(()=>{}),F({exitCode:X}))};e.onClose(X=>{X&&(a(`hydra-acp cat: ${X.message}
452
- `),T=1),B||(B=!0,v(),F({exitCode:T}))});let U=[],L=!1,N=!1,Z=async()=>{if(!L){L=!0;try{for(;U.length>0;){let X=U.shift();if(X===void 0)break;await k(X)}}finally{L=!1,N&&U.length===0&&await K(T)}}};if(r&&!n.sessionId)return n.prompt&&await k(""),await K(0),$;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),vR({conn:e,streamClient:t.streamClient,sessionId:u,opts:n,stdin:s,stderr:a,sendInline:k,onEof:()=>{N=!0,!L&&U.length===0&&K(T)},onError:X=>{a(`hydra-acp cat: stdin error: ${X.message}
450
+ `),f=!1};e.onNotification("session/update",X=>{let ce=X?.update,Ye=Kn(ce,{cwd:n.cwd});if(Ye){if(Ye.kind==="agent-text"){d?y(Ye.text):h+=Ye.text;return}if(Ye.kind==="turn-complete"){v();return}switch(Ye.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":b();return;default:return}}});let S=!1,k=async X=>{let ce=[];if(n.prompt&&!S&&ce.push({type:"text",text:n.prompt}),X.length>0&&ce.push({type:"text",text:X}),ce.length!==0){try{await e.request("session/prompt",Sw(u,ce)),S=!0}catch(Ye){a(`hydra-acp cat: prompt failed: ${Ye.message}
451
+ `);return}v()}},T=0,O,$=new Promise(X=>{O=X}),B=!1,K=async X=>{B||(B=!0,v(),n.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:u}))().catch(()=>{}),new Promise(Ye=>setTimeout(Ye,500))]),await e.close().catch(()=>{}),O({exitCode:X}))};e.onClose(X=>{X&&(a(`hydra-acp cat: ${X.message}
452
+ `),T=1),B||(B=!0,v(),O({exitCode:T}))});let U=[],L=!1,N=!1,Z=async()=>{if(!L){L=!0;try{for(;U.length>0;){let X=U.shift();if(X===void 0)break;await k(X)}}finally{L=!1,N&&U.length===0&&await K(T)}}};if(r&&!n.sessionId)return n.prompt&&await k(""),await K(0),$;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),AR({conn:e,streamClient:t.streamClient,sessionId:u,opts:n,stdin:s,stderr:a,sendInline:k,onEof:()=>{N=!0,!L&&U.length===0&&K(T)},onError:X=>{a(`hydra-acp cat: stdin error: ${X.message}
453
453
  `),T=1,N=!0,!L&&U.length===0&&K(T)},onPromptFailed:X=>{a(`hydra-acp cat: ${X.message}
454
- `),T=1,N=!0,!L&&U.length===0&&K(T)}}),$;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let X=gw({scheduleFlushCheck:ce=>{let Je=setImmediate(ce);return()=>clearImmediate(Je)},onChunk:ce=>{U.push(ce),Z()}});return s.on("data",ce=>{X.feed(typeof ce=="string"?ce:ce.toString("utf8"))}),s.on("end",()=>{X.eof(),N=!0,!L&&U.length===0&&K(T)}),s.on("error",ce=>{a(`hydra-acp cat: stdin error: ${ce.message}
454
+ `),T=1,N=!0,!L&&U.length===0&&K(T)}}),$;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let X=ww({scheduleFlushCheck:ce=>{let Ye=setImmediate(ce);return()=>clearImmediate(Ye)},onChunk:ce=>{U.push(ce),Z()}});return s.on("data",ce=>{X.feed(typeof ce=="string"?ce:ce.toString("utf8"))}),s.on("end",()=>{X.eof(),N=!0,!L&&U.length===0&&K(T)}),s.on("error",ce=>{a(`hydra-acp cat: stdin error: ${ce.message}
455
455
  `),T=1,N=!0,!L&&U.length===0&&K(T)}),$}let Se="";return s.on("data",X=>{Se+=typeof X=="string"?X:X.toString("utf8")}),s.on("end",()=>{N=!0,Se.length>0&&U.push(Se),Z()}),s.on("error",X=>{a(`hydra-acp cat: stdin error: ${X.message}
456
- `),T=1,N=!0,!L&&U.length===0&&K(T)}),$}function vR(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??mR,d="undecided",l=!1,u=[],f=0,p=!1,h=Promise.resolve(),m=(v,S)=>{let k=v.toString("base64");h=h.then(()=>n.write(s,k,S)).catch(T=>{o(`hydra-acp cat: stdin write failed: ${T.message}
457
- `)})},y=async()=>{d="inline";let v=Buffer.concat(u,f).toString("utf8");u=[],f=0;try{await a(v)}catch(S){t.onPromptFailed(S);return}t.onEof()},b=async()=>{d="pivoting";let v;try{let T={mode:"memory"};r.streamBufferBytes!==void 0&&(T.capacityBytes=r.streamBufferBytes),v=await n.open(s,T)}catch(T){t.onPromptFailed(new Error(`stdin/open failed: ${T.message}`));return}f>0&&(m(Buffer.concat(u,f),!1),u=[],f=0),d="file",l&&(l=!1,m(Buffer.alloc(0),!0)),await h.catch(()=>{});let S=SR(r.prompt,v.capacityBytes);e.request("session/prompt",bw(s,[{type:"text",text:S}])).catch(T=>{t.onPromptFailed(new Error(`prompt failed: ${T.message}`))}).then(()=>{p||m(Buffer.alloc(0),!0),t.onEof()})};i.on("data",v=>{let S=typeof v=="string"?Buffer.from(v,"utf8"):v;if(d==="undecided"){u.push(S),f+=S.length,f>c&&b();return}if(d==="pivoting"){u.push(S),f+=S.length;return}if(d==="file"){m(S,!1);return}u.push(S),f+=S.length}),i.on("end",()=>{if(p=!0,d==="undecided"){y();return}if(d==="pivoting"){l=!0;return}d==="file"&&m(Buffer.alloc(0),!0)}),i.on("error",t.onError)}function SR(t,e){let s=`The user has piped data into this session. The bytes are NOT in your prompt; they live in the \`hydra-acp-stdin\` MCP server and you read them via its tools:
456
+ `),T=1,N=!0,!L&&U.length===0&&K(T)}),$}function AR(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??vR,d="undecided",l=!1,u=[],f=0,p=!1,h=Promise.resolve(),m=(v,S)=>{let k=v.toString("base64");h=h.then(()=>n.write(s,k,S)).catch(T=>{o(`hydra-acp cat: stdin write failed: ${T.message}
457
+ `)})},y=async()=>{d="inline";let v=Buffer.concat(u,f).toString("utf8");u=[],f=0;try{await a(v)}catch(S){t.onPromptFailed(S);return}t.onEof()},b=async()=>{d="pivoting";let v;try{let T={mode:"memory"};r.streamBufferBytes!==void 0&&(T.capacityBytes=r.streamBufferBytes),v=await n.open(s,T)}catch(T){t.onPromptFailed(new Error(`stdin/open failed: ${T.message}`));return}f>0&&(m(Buffer.concat(u,f),!1),u=[],f=0),d="file",l&&(l=!1,m(Buffer.alloc(0),!0)),await h.catch(()=>{});let S=CR(r.prompt,v.capacityBytes);e.request("session/prompt",Sw(s,[{type:"text",text:S}])).catch(T=>{t.onPromptFailed(new Error(`prompt failed: ${T.message}`))}).then(()=>{p||m(Buffer.alloc(0),!0),t.onEof()})};i.on("data",v=>{let S=typeof v=="string"?Buffer.from(v,"utf8"):v;if(d==="undecided"){u.push(S),f+=S.length,f>c&&b();return}if(d==="pivoting"){u.push(S),f+=S.length;return}if(d==="file"){m(S,!1);return}u.push(S),f+=S.length}),i.on("end",()=>{if(p=!0,d==="undecided"){y();return}if(d==="pivoting"){l=!0;return}d==="file"&&m(Buffer.alloc(0),!0)}),i.on("error",t.onError)}function CR(t,e){let s=`The user has piped data into this session. The bytes are NOT in your prompt; they live in the \`hydra-acp-stdin\` MCP server and you read them via its tools:
458
458
  - \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
459
459
  - \`grep({pattern, regex?, case_insensitive?, context_before?, context_after?, cursor?})\` \u2014 server-side line filter; returns matching lines as decoded strings (not base64). Prefer this for "find lines that mention X" questions on multi-MB inputs.
460
460
  - \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
@@ -469,50 +469,50 @@ Use those tools NOW to answer the user's question \u2014 do not ask whether to c
469
469
  User's question:
470
470
  ${t}`:`${s}
471
471
 
472
- Use those tools to inspect the piped input and report what's there. Start with \`info()\` to see the size, then \`head\` and/or \`tail\` to look at the bytes.`}async function kR(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:Er,version:fe}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=gR(e.prompt);a&&(s.title=a)}e.model&&(s.model=e.model),n&&(s.mcpStdin=!0);let i={cwd:e.cwd??process.cwd()};e.agentId&&(s.agentId=e.agentId),Object.keys(s).length>0&&(i._meta={[Tt]:s});let o=await t.request("session/new",i);return en(o._meta),o.sessionId}Ve();he();function Rc(t){let e=t.split(".").filter(n=>n.length>0);if(e.length===0)throw new Error("config key must be a non-empty dotted path");return e}function Sw(t,e){let n=t;for(let s of e){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[s]}return n}function IR(t){try{return JSON.parse(t)}catch{return t}}function kw(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function Iw(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
473
- `),process.exit(2));let e=Rc(t),n=await be(),s=Sw(n,e);s===void 0&&(process.stderr.write(`config: key '${t}' is unset
474
- `),process.exit(1)),process.stdout.write(`${kw(s)}
475
- `)}async function xw(t,e){(!t||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
476
- `),process.exit(2));let n=Rc(t),s=IR(e);try{await ps(r=>{let i=r;for(let o=0;o<n.length-1;o++){let a=n[o],c=i[a];if(c==null){let d={};i[a]=d,i=d;continue}if(typeof c!="object"||Array.isArray(c))throw new Error(`config: cannot descend into '${n.slice(0,o+1).join(".")}' (not an object)`);i=c}i[n[n.length-1]]=s})}catch(r){process.stderr.write(`${r.message}
477
- `),process.exit(1)}process.stdout.write(`set ${t} = ${kw(s)}
478
- `)}async function Aw(t){t||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
479
- `),process.exit(2));let e=Rc(t);try{await ps(n=>{let s=n;for(let r=0;r<e.length-1;r++){let i=e[r],o=s[i];if(o==null||typeof o!="object"||Array.isArray(o))return;s=o}delete s[e[e.length-1]]})}catch(n){process.stderr.write(`${n.message}
472
+ Use those tools to inspect the piped input and report what's there. Start with \`info()\` to see the size, then \`head\` and/or \`tail\` to look at the bytes.`}async function RR(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:Er,version:fe}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=SR(e.prompt);a&&(s.title=a)}e.model&&(s.model=e.model),n&&(s.mcpStdin=!0);let i={cwd:e.cwd??process.cwd()};e.agentId&&(s.agentId=e.agentId),Object.keys(s).length>0&&(i._meta={[Tt]:s});let o=await t.request("session/new",i);return en(o._meta),o.sessionId}Ge();he();function Rc(t){let e=t.split(".").filter(n=>n.length>0);if(e.length===0)throw new Error("config key must be a non-empty dotted path");return e}function Iw(t,e){let n=t;for(let s of e){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[s]}return n}function TR(t){try{return JSON.parse(t)}catch{return t}}function xw(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function Aw(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
473
+ `),process.exit(2));let e=Rc(t),n=await be(),s=Iw(n,e);s===void 0&&(process.stderr.write(`config: key '${t}' is unset
474
+ `),process.exit(1)),process.stdout.write(`${xw(s)}
475
+ `)}async function Cw(t,e){(!t||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
476
+ `),process.exit(2));let n=Rc(t),s=TR(e);try{await hs(r=>{let i=r;for(let o=0;o<n.length-1;o++){let a=n[o],c=i[a];if(c==null){let d={};i[a]=d,i=d;continue}if(typeof c!="object"||Array.isArray(c))throw new Error(`config: cannot descend into '${n.slice(0,o+1).join(".")}' (not an object)`);i=c}i[n[n.length-1]]=s})}catch(r){process.stderr.write(`${r.message}
477
+ `),process.exit(1)}process.stdout.write(`set ${t} = ${xw(s)}
478
+ `)}async function Rw(t){t||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
479
+ `),process.exit(2));let e=Rc(t);try{await hs(n=>{let s=n;for(let r=0;r<e.length-1;r++){let i=e[r],o=s[i];if(o==null||typeof o!="object"||Array.isArray(o))return;s=o}delete s[e[e.length-1]]})}catch(n){process.stderr.write(`${n.message}
480
480
  `),process.exit(1)}process.stdout.write(`unset ${t}
481
- `)}async function Cw(t){let e=await be(),n=t?Sw(e,Rc(t)):e;n===void 0&&(process.stderr.write(`config: key '${t}' is unset
481
+ `)}async function Tw(t){let e=await be(),n=t?Iw(e,Rc(t)):e;n===void 0&&(process.stderr.write(`config: key '${t}' is unset
482
482
  `),process.exit(1)),process.stdout.write(`${JSON.stringify(n,null,2)}
483
- `)}function Rw(){process.stdout.write(`${_.config()}
484
- `)}Ve();fs();Or();nn();Ys();async function Pw(t={}){let{report:e,configLoaded:n}=await xR();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
483
+ `)}function Ew(){process.stdout.write(`${_.config()}
484
+ `)}Ge();ps();Fr();nn();Vs();async function _w(t={}){let{report:e,configLoaded:n}=await ER();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
485
485
  `);return}process.stdout.write(`CLI: ${e.cli}
486
486
  `),n&&(process.stdout.write(`Daemon: ${e.daemon??(e.daemonReachable?"unknown":"not running")}
487
- `),e.daemonReachable&&(Tw("Extensions",e.extensions),Tw("Transformers",e.transformers)))}function Tw(t,e){if(process.stdout.write(`
487
+ `),e.daemonReachable&&(Pw("Extensions",e.extensions),Pw("Transformers",e.transformers)))}function Pw(t,e){if(process.stdout.write(`
488
488
  ${t}:
489
489
  `),e.length===0){process.stdout.write(` (none)
490
490
  `);return}let n=Math.max(...e.map(r=>r.name.length)),s=Math.max(...e.map(r=>(r.version??"-").length),7);for(let r of e){let i=r.version??"-";process.stdout.write(` ${r.name.padEnd(n)} ${i.padEnd(s)} ${r.status}
491
- `)}}async function xR(){let t={cli:fe,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await be()}catch{return{report:t,configLoaded:!1}}let n=await Fr(e);if(n!==void 0&&(t.daemonReachable=!0,t.daemon=n.version??null),!t.daemonReachable)return{report:t,configLoaded:!0};let s;try{s=await vr()}catch{return{report:t,configLoaded:!0}}let r=await zi(),i={Authorization:`Bearer ${s}`};return t.extensions=await Ew(`${r}/v1/extensions`,i,"extensions"),t.transformers=await Ew(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function Ew(t,e,n){try{let s=await fetch(t,{headers:e});if(!s.ok)return[];let i=(await s.json())[n];return Array.isArray(i)?i.map(o=>({name:o.name,version:o.version??null,status:o.status})):[]}catch{return[]}}import{spawnSync as AR}from"child_process";import{accessSync as CR,constants as RR,statSync as TR}from"fs";import{delimiter as ER,join as PR}from"path";var MR=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function _R(t){return MR.has(t)}function $R(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function FR(t){let e=[],n=!1;for(let s of t){if(!n&&s!==void 0&&!s.startsWith("-")){n=!0;continue}s!==void 0&&e.push(s)}return e}function OR(t){try{if(!TR(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return CR(t,RR.X_OK),!0}catch{return!1}}function LR(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(ER).filter(o=>o.length>0),r=`hydra-acp-${t}`,i=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""];for(let o of s)for(let a of i){let c=PR(o,r+a);if(OR(c))return c}}function BR(t,e){let n=AR(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
492
- `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function Mw(t){let e=$R(t);if(e===void 0||_R(e))return!1;let n=LR(e);if(n===void 0)return!1;BR(n,FR(t))}wf();var nr=!1,Qb=!1;function Gb(t){!t||Qb||(Qb=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
493
- `))}async function AT(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>($o(),_p));t();let e=process.argv.slice(2),n=e.indexOf("launch");if(n!==-1){let b=e.slice(0,n),v=e.slice(n+1),S=v[0],k=v.slice(1),{flags:T}=el(b);if(Zb(T),T.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
494
- `),process.exit(2);return}let F=S??yt(T,"agent");if(!F){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
495
- `),process.exit(2);return}let $=await ev(yl(T),{allowPrompt:!1}),B=yt(T,"name"),K=yt(T,"model");nr=!0;let U=T["dangerously-skip-permissions"]===!0;Gb(U);let L={agentId:F,agentArgs:k,name:B,model:K,dangerouslySkipPermissions:U};$?.sessionId!==void 0&&(L.sessionId=$.sessionId),$?.target!==void 0&&$.fromUrl&&(L.target=$.target),await Ac(L);return}Zf(e)===void 0&&!e.some(b=>b==="--prompt"||b.startsWith("--prompt="))&&Mw(e);let{positional:s,flags:r}=el(e);if(Zb(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${CT()}
496
- `);return}if(r.help===!0){sp(s[0]);return}let i=Zf(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=yt(r,"name"),d=yt(r,"agent"),l=yt(r,"model"),u=r["dangerously-skip-permissions"]===!0;Gb(u);let f=yl(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await ev(f,{allowPrompt:p});h!==void 0&&h.sessionId!==void 0&&r.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
497
- `),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){nr=!0,await Xb(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return}nr=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(b.sessionId=m),y!==void 0&&(b.target=y),await Ac(b);return}switch(a){case"shim":{nr=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(b.sessionId=m),y!==void 0&&(b.target=y),await Ac(b);return}case"cat":{let b=Zf(e),v=typeof r.prompt=="string"?r.prompt:void 0,S=b??v,k=yt(r,"cwd"),T={prompt:S,sessionId:m,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:u};k!==void 0&&(T.cwd=k),y!==void 0&&(T.target=y);let F=np(r,"stream-threshold");F!==void 0&&(T.streamThreshold=F);let $=np(r,"stream-bytes");$!==void 0&&(T.streamBufferBytes=$),d!==void 0&&await fc(d),nr=!0,await vw(T);return}case"version":{nr=!0,await Pw({json:r.json===!0});return}case"init":await qp(r);return;case"daemon":{let b=e.indexOf("daemon"),v=e.slice(b+1),S=v[0];if(S===void 0||S==="status"){await Hg();return}if(S==="start"){await Lg(r);return}if(S==="stop"){await Bg();return}if(S==="restart"){await Ng();return}if(S==="log"||S==="logs"){await Dg(v.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
498
- `),process.exit(2);return}case"session":case"sessions":{let b=s[1];if(b===void 0||b==="list"){let v=yt(r,"columns"),S;if(v!==void 0)try{S=Gg(v)}catch(k){process.stderr.write(`${k.message}
499
- `),process.exit(2);return}await ey({all:r.all===!0,json:r.json===!0,host:typeof r.host=="string"?r.host:void 0,includeNonInteractive:r["include-non-interactive"]===!0,columns:S});return}if(b==="info"){await ky(s[2],{verbose:r.verbose===!0,json:r.json===!0,diff:r.diff===!0,fold:r.fold===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0});return}if(b==="diff"){await Sy(s[2],{json:r.json===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0,fold:r.fold===!0});return}if(b==="kill"){await ty(s[2]);return}if(b==="remove"){await ny(s[2]);return}if(b==="collect"){let v=yt(r,"max-age-days"),S=yt(r,"limit"),k={json:r.json===!0,keepUndecided:r["keep-undecided"]===!0};if(v!==void 0){let T=Number(v);if(!Number.isFinite(T)||T<0){process.stderr.write(`--max-age-days must be a non-negative number
491
+ `)}}async function ER(){let t={cli:fe,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await be()}catch{return{report:t,configLoaded:!1}}let n=await Or(e);if(n!==void 0&&(t.daemonReachable=!0,t.daemon=n.version??null),!t.daemonReachable)return{report:t,configLoaded:!0};let s;try{s=await vr()}catch{return{report:t,configLoaded:!0}}let r=await Ki(),i={Authorization:`Bearer ${s}`};return t.extensions=await Mw(`${r}/v1/extensions`,i,"extensions"),t.transformers=await Mw(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function Mw(t,e,n){try{let s=await fetch(t,{headers:e});if(!s.ok)return[];let i=(await s.json())[n];return Array.isArray(i)?i.map(o=>({name:o.name,version:o.version??null,status:o.status})):[]}catch{return[]}}import{spawnSync as PR}from"child_process";import{accessSync as MR,constants as _R,statSync as $R}from"fs";import{delimiter as OR,join as FR}from"path";var LR=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function BR(t){return LR.has(t)}function NR(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function DR(t){let e=[],n=!1;for(let s of t){if(!n&&s!==void 0&&!s.startsWith("-")){n=!0;continue}s!==void 0&&e.push(s)}return e}function HR(t){try{if(!$R(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return MR(t,_R.X_OK),!0}catch{return!1}}function UR(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(OR).filter(o=>o.length>0),r=`hydra-acp-${t}`,i=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""];for(let o of s)for(let a of i){let c=FR(o,r+a);if(HR(c))return c}}function jR(t,e){let n=PR(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
492
+ `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function $w(t){let e=NR(t);if(e===void 0||BR(e))return!1;let n=UR(e);if(n===void 0)return!1;jR(n,DR(t))}bf();var nr=!1,Zb=!1;function ev(t){!t||Zb||(Zb=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
493
+ `))}async function MT(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>(Oo(),$p));t();let e=process.argv.slice(2),n=e.indexOf("launch");if(n!==-1){let b=e.slice(0,n),v=e.slice(n+1),S=v[0],k=v.slice(1),{flags:T}=tl(b);if(nv(T),T.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
494
+ `),process.exit(2);return}let O=S??yt(T,"agent");if(!O){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
495
+ `),process.exit(2);return}let $=await sv(wl(T),{allowPrompt:!1}),B=yt(T,"name"),K=yt(T,"model");nr=!0;let U=T["dangerously-skip-permissions"]===!0;ev(U);let L={agentId:O,agentArgs:k,name:B,model:K,dangerouslySkipPermissions:U};$?.sessionId!==void 0&&(L.sessionId=$.sessionId),$?.target!==void 0&&$.fromUrl&&(L.target=$.target),await Ac(L);return}ep(e)===void 0&&!e.some(b=>b==="--prompt"||b.startsWith("--prompt="))&&$w(e);let{positional:s,flags:r}=tl(e);if(nv(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${_T()}
496
+ `);return}if(r.help===!0){rp(s[0]);return}let i=ep(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=yt(r,"name"),d=yt(r,"agent"),l=yt(r,"model"),u=r["dangerously-skip-permissions"]===!0;ev(u);let f=wl(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await sv(f,{allowPrompt:p});h!==void 0&&h.sessionId!==void 0&&r.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
497
+ `),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){nr=!0,await tv(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return}nr=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(b.sessionId=m),y!==void 0&&(b.target=y),await Ac(b);return}switch(a){case"shim":{nr=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(b.sessionId=m),y!==void 0&&(b.target=y),await Ac(b);return}case"cat":{let b=ep(e),v=typeof r.prompt=="string"?r.prompt:void 0,S=b??v,k=yt(r,"cwd"),T={prompt:S,sessionId:m,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:u};k!==void 0&&(T.cwd=k),y!==void 0&&(T.target=y);let O=sp(r,"stream-threshold");O!==void 0&&(T.streamThreshold=O);let $=sp(r,"stream-bytes");$!==void 0&&(T.streamBufferBytes=$),d!==void 0&&await fc(d),nr=!0,await kw(T);return}case"version":{nr=!0,await _w({json:r.json===!0});return}case"init":await Wp(r);return;case"daemon":{let b=e.indexOf("daemon"),v=e.slice(b+1),S=v[0];if(S===void 0||S==="status"){await jg();return}if(S==="start"){await Ng(r);return}if(S==="stop"){await Dg();return}if(S==="restart"){await Hg();return}if(S==="log"||S==="logs"){await Ug(v.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
498
+ `),process.exit(2);return}case"session":case"sessions":{let b=s[1];if(b===void 0||b==="list"){let v=yt(r,"columns"),S;if(v!==void 0)try{S=Zg(v)}catch(k){process.stderr.write(`${k.message}
499
+ `),process.exit(2);return}await ny({all:r.all===!0,json:r.json===!0,host:typeof r.host=="string"?r.host:void 0,includeNonInteractive:r["include-non-interactive"]===!0,columns:S});return}if(b==="info"){await xy(s[2],{verbose:r.verbose===!0,json:r.json===!0,diff:r.diff===!0,fold:r.fold===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0});return}if(b==="diff"){await Iy(s[2],{json:r.json===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0,fold:r.fold===!0});return}if(b==="kill"){await sy(s[2]);return}if(b==="remove"){await ry(s[2]);return}if(b==="collect"){let v=yt(r,"max-age-days"),S=yt(r,"limit"),k={json:r.json===!0,keepUndecided:r["keep-undecided"]===!0};if(v!==void 0){let T=Number(v);if(!Number.isFinite(T)||T<0){process.stderr.write(`--max-age-days must be a non-negative number
500
500
  `),process.exit(2);return}k.maxAgeDays=T}if(S!==void 0){let T=Number(S);if(!Number.isFinite(T)||T<=0){process.stderr.write(`--limit must be a positive number
501
- `),process.exit(2);return}k.limit=T}await sy(k);return}if(b==="export"){let v=yt(r,"out"),S=yt(r,"tools");await ry(s[2],v,S);return}if(b==="transcript"){let v=yt(r,"out");await iy(s[2],v);return}if(b==="import"){let v=yt(r,"cwd");await oy(s[2],{replace:r.replace===!0,info:r.info===!0,...v!==void 0?{cwd:v}:{}});return}if(b==="share"){let v=yt(r,"host"),S=yt(r,"cwd");await ay(s[2],{...v!==void 0?{host:v}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${b}
502
- `),process.exit(2);return}case"extension":case"extensions":{let b=e.indexOf(a),v=e.slice(b+1),S=v[0],k=v[1],T=v.slice(2);if(S===void 0||S==="list"){await xy();return}if(S==="add"){await Ay(k,T);return}if(S==="remove"){await Cy(k);return}if(S==="start"){await Ry(k);return}if(S==="stop"){await Ty(k);return}if(S==="restart"){await Ey(k);return}if(S==="log"||S==="logs"){await Py(v.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
503
- `),process.exit(2);return}case"transformer":case"transformers":{let b=e.indexOf(a),v=e.slice(b+1),S=v[0],k=v[1],T=v.slice(2);if(S===void 0||S==="list"){await My();return}if(S==="add"){await _y(k,T);return}if(S==="remove"){await $y(k);return}if(S==="start"){await Fy(k);return}if(S==="stop"){await Oy(k);return}if(S==="restart"){await Ly(k);return}if(S==="log"||S==="logs"){await By(v.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
504
- `),process.exit(2);return}case"agent":case"agents":{let b=s[1];if(b===void 0||b==="list"){await ef();return}if(b==="refresh"){await pc();return}if(b==="install"){await nf(s[2]);return}if(b==="sync"){await sf(s[2]);return}if(b==="set"){await of(s[2],s[3]);return}if(b==="pin"){await af(s[2],s[3]);return}if(b==="add"){let v=e.indexOf(a),S=e.slice(v+1);await df(S[1],S.slice(2));return}if(b==="remove"){await cf(s[2]);return}if(b==="log"||b==="logs"){let v=e.indexOf(a),S=e.slice(v+2),{name:k,rest:T}=Qd(S);await rf(k,T);return}if(b==="auth"){await iw(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${b}
501
+ `),process.exit(2);return}k.limit=T}await iy(k);return}if(b==="export"){let v=yt(r,"out"),S=yt(r,"tools");await oy(s[2],v,S);return}if(b==="transcript"){let v=yt(r,"out");await ay(s[2],v);return}if(b==="import"){let v=yt(r,"cwd");await dy(s[2],{replace:r.replace===!0,info:r.info===!0,...v!==void 0?{cwd:v}:{}});return}if(b==="share"){let v=yt(r,"host"),S=yt(r,"cwd");await cy(s[2],{...v!==void 0?{host:v}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${b}
502
+ `),process.exit(2);return}case"extension":case"extensions":{let b=e.indexOf(a),v=e.slice(b+1),S=v[0],k=v[1],T=v.slice(2);if(S===void 0||S==="list"){await Cy();return}if(S==="add"){await Ry(k,T);return}if(S==="remove"){await Ty(k);return}if(S==="start"){await Ey(k);return}if(S==="stop"){await Py(k);return}if(S==="restart"){await My(k);return}if(S==="log"||S==="logs"){await _y(v.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
503
+ `),process.exit(2);return}case"transformer":case"transformers":{let b=e.indexOf(a),v=e.slice(b+1),S=v[0],k=v[1],T=v.slice(2);if(S===void 0||S==="list"){await $y();return}if(S==="add"){await Oy(k,T);return}if(S==="remove"){await Fy(k);return}if(S==="start"){await Ly(k);return}if(S==="stop"){await By(k);return}if(S==="restart"){await Ny(k);return}if(S==="log"||S==="logs"){await Dy(v.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
504
+ `),process.exit(2);return}case"agent":case"agents":{let b=s[1];if(b===void 0||b==="list"){await tf();return}if(b==="refresh"){await pc();return}if(b==="install"){await sf(s[2]);return}if(b==="sync"){await rf(s[2]);return}if(b==="set"){await af(s[2],s[3]);return}if(b==="pin"){await df(s[2],s[3]);return}if(b==="add"){let v=e.indexOf(a),S=e.slice(v+1);await cf(S[1],S.slice(2));return}if(b==="remove"){await lf(s[2]);return}if(b==="log"||b==="logs"){let v=e.indexOf(a),S=e.slice(v+2),{name:k,rest:T}=Qd(S);await of(k,T);return}if(b==="auth"){await aw(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${b}
505
505
  `),process.exit(2);return}case"registry":{let b=s[1];if(b==="refresh"){await pc();return}if(b==="pin"){await hc(!0);return}if(b==="unpin"){await hc(!1);return}process.stderr.write(`Unknown registry subcommand: ${b}
506
- `),process.exit(2);return}case"auth":{let b=s[1];if(b==="password"){let v=s[2];if(v===void 0||v==="set"){await ow(r);return}process.stderr.write(`Unknown auth password action: ${v}
507
- `),process.exit(2);return}if(b===void 0||b==="list"){await aw();return}if(b==="revoke"){await dw(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${b}
508
- `),process.exit(2);return}case"config":{let b=s[1];if(b===void 0||b==="list"){await Cw(s[2]);return}if(b==="get"){await Iw(s[2]);return}if(b==="set"){await xw(s[2],s[3]);return}if(b==="unset"){await Aw(s[2]);return}if(b==="path"){Rw();return}process.stderr.write(`Unknown config subcommand: ${b}
509
- `),process.exit(2);return}case"tui":nr=!0,await Xb(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
510
- `),sp(),process.exit(2)}}async function Xb(t,e){let n=yt(t,"cwd"),s=t.reattach===!0,r=t.new===!0,i=t.readonly===!0;i&&e.sessionId===void 0&&(process.stderr.write("hydra-acp: --readonly requires a session id. Pass --session <id-or-url> --readonly, or open the picker and press `v` on a session.\n"),process.exit(2)),e.agentId!==void 0&&await fc(e.agentId),co(lo(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Vb(),Yb)),a={resume:s,forceNew:r,readonly:i};if(e.sessionId!==void 0&&(a.sessionId=e.sessionId),e.agentId!==void 0&&(a.agentId=e.agentId),n!==void 0&&(a.cwd=n),e.name!==void 0&&(a.name=e.name),e.model!==void 0&&(a.model=e.model),e.target!==void 0&&(a.target=e.target),e.dangerouslySkipPermissions===!0&&(a.dangerouslySkipPermissions=!0),t.drip===!0){e.sessionId===void 0&&(process.stderr.write(`hydra-acp: --drip requires a session id. Pass --session <id-or-url> --drip.
511
- `),process.exit(2)),a.drip=!0;let c=np(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function np(t,e){let n=t[e];if(n!==void 0){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let s=Number(n);if(Number.isFinite(s))return s}}}function Zb(t){let e=fp(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
506
+ `),process.exit(2);return}case"auth":{let b=s[1];if(b==="password"){let v=s[2];if(v===void 0||v==="set"){await dw(r);return}process.stderr.write(`Unknown auth password action: ${v}
507
+ `),process.exit(2);return}if(b===void 0||b==="list"){await cw();return}if(b==="revoke"){await lw(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${b}
508
+ `),process.exit(2);return}case"config":{let b=s[1];if(b===void 0||b==="list"){await Tw(s[2]);return}if(b==="get"){await Aw(s[2]);return}if(b==="set"){await Cw(s[2],s[3]);return}if(b==="unset"){await Rw(s[2]);return}if(b==="path"){Ew();return}process.stderr.write(`Unknown config subcommand: ${b}
509
+ `),process.exit(2);return}case"tui":nr=!0,await tv(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
510
+ `),rp(),process.exit(2)}}async function tv(t,e){let n=yt(t,"cwd"),s=t.reattach===!0,r=t.new===!0,i=t.readonly===!0;i&&e.sessionId===void 0&&(process.stderr.write("hydra-acp: --readonly requires a session id. Pass --session <id-or-url> --readonly, or open the picker and press `v` on a session.\n"),process.exit(2)),e.agentId!==void 0&&await fc(e.agentId),lo(uo(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Xb(),Gb)),a={resume:s,forceNew:r,readonly:i};if(e.sessionId!==void 0&&(a.sessionId=e.sessionId),e.agentId!==void 0&&(a.agentId=e.agentId),n!==void 0&&(a.cwd=n),e.name!==void 0&&(a.name=e.name),e.model!==void 0&&(a.model=e.model),e.target!==void 0&&(a.target=e.target),e.dangerouslySkipPermissions===!0&&(a.dangerouslySkipPermissions=!0),t.drip===!0){e.sessionId===void 0&&(process.stderr.write(`hydra-acp: --drip requires a session id. Pass --session <id-or-url> --drip.
511
+ `),process.exit(2)),a.drip=!0;let c=sp(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function sp(t,e){let n=t[e];if(n!==void 0){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let s=Number(n);if(Number.isFinite(s))return s}}}function nv(t){let e=pp(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
512
512
 
513
- `),sp(),process.exit(2))}function Zf(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n!==void 0){if(n==="-p")return t[e+1];if(n.startsWith("-p")&&!n.startsWith("--"))return n.slice(2)}}}async function ev(t,e){try{return await Dp(t,e)}catch(n){se({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n)}),process.stderr.write(`${n.message}
514
- `),process.exit(1)}}function CT(){try{let t=IT(kT(import.meta.url));return JSON.parse(ST(xT(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}var ep=["tui"],RT=["shim"],bt=["cat"],qc=["launch"],TT=["init"],Wc=["daemon"],ET=["version"],it=["session","sessions"],xa=["extension","extensions"],Aa=["transformer","transformers"],Zn=["agent","agents"],PT=["registry"],Ca=["config"],tp=["auth"];function sp(t){let e=["hydra-acp \u2014 multi-client ACP session daemon","","Usage:",{globalOnly:" hydra-acp [--session <id-or-url>] [--reattach] [opts]"},{globalOnly:" Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."},{globalOnly:" With -p / --prompt and no subcommand, auto-dispatch to cat."},[ep," hydra-acp tui [same flags] Force TUI explicitly."],[RT," hydra-acp shim [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."],[bt," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"],[bt," Pipe-friendly headless mode. Reads stdin and sends it"],[bt," as a prompt to a fresh session, streams the agent's"],[bt," response to stdout, exits when stdin closes. A bounded"],[bt,' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'],[bt," as one turn; a streaming input (e.g. `tail -f`) is"],[bt," chunked by the natural pauses in the writer. -p is an"],[bt," optional standing instruction prepended to every chunk;"],[bt," if stdin already contains the question, -p is not needed."],[bt," By default, agent markdown is post-processed: ANSI-styled"],[bt," on a TTY, stripped to plain text on a pipe, tables laid"],[bt," out in both modes. Tool calls / thoughts split paragraphs"],[bt," but otherwise stay hidden. --raw bypasses the renderer"],[bt," and emits chunks immediately, the way cat used to behave."],[bt," With --session, attach to an existing session instead"],[bt," of creating a new one. With --detach, the session"],[bt," survives in the daemon for slack/browser/notifier"],[bt," extensions."],[qc," hydra-acp launch <agent> [agent-args...]"],[qc," Shim mode, force daemon to spawn <agent>"],[qc," from the registry. Args after <agent>"],[qc," are forwarded to the agent's command."],"",...(()=>{let s=["tui","shim","cat","launch"];return[[s,"Session selection (any entry point):"],[s," --session <id> Attach to a local session by id."],[s," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"],[s," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"],[s," falling back to a password prompt \u2014 but only on the TUI path)."],[s," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."],[s," --reattach Pick the most-recent session for the current cwd."],[s," --new Force a fresh session."],[s," --readonly Open a session as a transcript viewer (requires --session)."],[s," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."],[s," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."]]})(),[TT," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"],[Wc," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"],[Wc," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"],[Wc," hydra-acp daemon stop|restart"],[Wc," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"],[ET," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"],[it," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"],[it," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."],[it," --host filters by origin machine: 'local' (default) shows only sessions created here, 'all' shows everything, or pass a hostname (e.g. machine-b) to show only imports from that peer."],[it," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."],[it," --columns picks which columns show and their order, e.g. --columns=session,state,title,cost (valid: session,upstream,host,state,agent,model,age,cwd,title,cost). UPSTREAM/HOST/MODEL hidden by default; COST is the trailing column; overrides config.tui.sessionColumns."],[it," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"],[it," Aggregate one session: turn count, tool histogram, files touched, cost/duration, synopsis. --diff appends the session diff under the summary and pages the whole thing on a TTY (inherits --fold)."],[it," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"],[it," Print a git-diff-shaped view of every file the session edited, reconstructed from history (no git). Pages through $HYDRA_ACP_PAGER / $PAGER / less on a TTY (LESS=FRX default); --no-pager bypasses. --fold collapses sequential hunks that rewrite the same region into one net-effect hunk."],[it," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"],[it," hydra-acp session remove <id> Remove a session entirely (live or cold)"],[it," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"],[it," Delete cold sessions that were never promoted to a real conversation \u2014 `hydra cat` one-shots (interactive=false) AND editor-spawned panels that never had a turn (interactive=undefined). With no --max-age-days, collects every matching cold row regardless of age (you typed `collect`, so collect it all). Pass --max-age-days N to scope to anything older than N days; 0 is the same as omitting it. --keep-undecided narrows to only explicit interactive=false rows (matches what the background timer does). --limit caps deletions per call (default 1000); re-run to drain a larger backlog. The daemon also runs this on a timer using config.daemon.sessionGcMaxAgeDays (with the conservative explicit-only policy) \u2014 this is the manual trigger."],[it," hydra-acp session export <id> [--out <file>|.]"],[it," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"],[it," hydra-acp session transcript <id>|<file> [--out <file>|.]"],[it," Render a session as a markdown transcript. Accepts a session id (renders via the daemon) or a local .hydra bundle file (rendered in-process). Writes to <file>, to a default-named file when --out=., or to stdout"],[it," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"],[it," Import a bundle from <file> or stdin (-); --replace overwrites a lineage match (kills it if live); --cwd overrides the bundle's recorded working directory; --info prints the bundle's meta without importing"],[it," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"],[it," Print a hydra:// URL the recipient can paste into `--session`. With no id, picks the most-recent session for cwd. Host precedence: --host > config.daemon.publicHost > config.daemon.host > 127.0.0.1 (with a stderr warning that the URL is loopback-only)."],[xa," hydra-acp extension list List configured extensions and live state"],[xa," hydra-acp extension add <name> [opts] Add an extension to config"],[xa," hydra-acp extension remove <name> Remove an extension from config"],[xa," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"],[xa," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"],[Aa," hydra-acp transformer list List configured transformers and live state"],[Aa," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"],[Aa," hydra-acp transformer remove <name> Remove a transformer from config"],[Aa," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"],[Aa," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"],[Zn," hydra-acp agent [list] List agents in the cached registry"],[Zn," hydra-acp agent refresh Force a registry re-fetch"],[Zn," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"],[Zn," hydra-acp agent set [<id>] [model] With no args, report the daemon's current default agent and its default model. With <id>, set <id> as the default agent (config.defaultAgent). With <id> and [model], set the per-agent default model (config.defaultModels[<id>])."],[Zn," hydra-acp agent pin <id> [packageSpec] Pin a registry agent to a specific npm version (e.g. opencode-ai@0.5.12). Omit packageSpec to clear. Sidesteps a broken upstream publish."],[Zn," hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]... Define a local agent that bypasses the registry (e.g. your system `opencode`). --command defaults to <id> (resolved off PATH)."],[Zn," hydra-acp agent remove <id> Remove a local agent."],[PT," hydra-acp registry pin | unpin Freeze the daemon on its cached registry (pin) so a bad push isn't picked up, or resume normal TTL fetching (unpin). `agent refresh` still forces a fetch."],[Zn," hydra-acp agent sync <id> Spawn <id> just long enough to ACP session/list it, then persist any sessions it remembers (across every cwd) as cold rows in `session list`"],[Zn," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"],[Zn," hydra-acp agent auth <id> Run the auth flow for <id>"],[Ca," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"],[Ca," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"],[Ca," hydra-acp config set <dotted.key> <value> Persist a value; <value> is parsed as JSON when possible, else stored as a string. Validated against the schema before write."],[Ca," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"],[Ca," hydra-acp config path Print the config file path"],[tp," hydra-acp auth password [--force] Set the daemon's master password"],[tp," hydra-acp auth [list] List active session tokens"],[tp," hydra-acp auth revoke <id> Revoke a session token"],[ep," hydra-acp tui [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"],[ep," Interactive terminal UI. Smart default (no flags): shows a picker when sessions exist, else new."],{globalOnly:" hydra-acp --version Print version"},{globalOnly:" hydra-acp --help Show this help"},{globalOnly:""},{globalOnly:"External subcommands:"},{globalOnly:" Any `hydra-acp <name>` whose <name> is not built-in is exec'd as"},{globalOnly:" `hydra-acp-<name>` from PATH (git-style). Ecosystem packages like"},{globalOnly:" @hydra-acp/planner expose themselves through this mechanism."},{globalOnly:""},{globalOnly:"Config knob flags accept env-var equivalents (flag wins):"},{globalOnly:" --agent HYDRA_ACP_AGENT"},{globalOnly:" --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"},{globalOnly:" --session HYDRA_ACP_SESSION (session id or hydra:// URL)"},{globalOnly:" --name HYDRA_ACP_NAME"},""],n=[];for(let s of e){if(typeof s=="string"){n.push(s);continue}if("globalOnly"in s){t===void 0&&n.push(s.globalOnly);continue}let[r,i]=s;(t===void 0||r.includes(t))&&n.push(i)}process.stdout.write(n.join(`
513
+ `),rp(),process.exit(2))}function ep(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n!==void 0){if(n==="-p")return t[e+1];if(n.startsWith("-p")&&!n.startsWith("--"))return n.slice(2)}}}async function sv(t,e){try{return await Hp(t,e)}catch(n){se({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n)}),process.stderr.write(`${n.message}
514
+ `),process.exit(1)}}function _T(){try{let t=ET(TT(import.meta.url));return JSON.parse(RT(PT(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}var tp=["tui"],$T=["shim"],bt=["cat"],Wc=["launch"],OT=["init"],zc=["daemon"],FT=["version"],it=["session","sessions"],Aa=["extension","extensions"],Ca=["transformer","transformers"],es=["agent","agents"],LT=["registry"],Ra=["config"],np=["auth"];function rp(t){let e=["hydra-acp \u2014 multi-client ACP session daemon","","Usage:",{globalOnly:" hydra-acp [--session <id-or-url>] [--reattach] [opts]"},{globalOnly:" Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."},{globalOnly:" With -p / --prompt and no subcommand, auto-dispatch to cat."},[tp," hydra-acp tui [same flags] Force TUI explicitly."],[$T," hydra-acp shim [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."],[bt," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"],[bt," Pipe-friendly headless mode. Reads stdin and sends it"],[bt," as a prompt to a fresh session, streams the agent's"],[bt," response to stdout, exits when stdin closes. A bounded"],[bt,' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'],[bt," as one turn; a streaming input (e.g. `tail -f`) is"],[bt," chunked by the natural pauses in the writer. -p is an"],[bt," optional standing instruction prepended to every chunk;"],[bt," if stdin already contains the question, -p is not needed."],[bt," By default, agent markdown is post-processed: ANSI-styled"],[bt," on a TTY, stripped to plain text on a pipe, tables laid"],[bt," out in both modes. Tool calls / thoughts split paragraphs"],[bt," but otherwise stay hidden. --raw bypasses the renderer"],[bt," and emits chunks immediately, the way cat used to behave."],[bt," With --session, attach to an existing session instead"],[bt," of creating a new one. With --detach, the session"],[bt," survives in the daemon for slack/browser/notifier"],[bt," extensions."],[Wc," hydra-acp launch <agent> [agent-args...]"],[Wc," Shim mode, force daemon to spawn <agent>"],[Wc," from the registry. Args after <agent>"],[Wc," are forwarded to the agent's command."],"",...(()=>{let s=["tui","shim","cat","launch"];return[[s,"Session selection (any entry point):"],[s," --session <id> Attach to a local session by id."],[s," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"],[s," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"],[s," falling back to a password prompt \u2014 but only on the TUI path)."],[s," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."],[s," --reattach Pick the most-recent session for the current cwd."],[s," --new Force a fresh session."],[s," --readonly Open a session as a transcript viewer (requires --session)."],[s," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."],[s," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."]]})(),[OT," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"],[zc," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"],[zc," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"],[zc," hydra-acp daemon stop|restart"],[zc," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"],[FT," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"],[it," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"],[it," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."],[it," --host filters by origin machine: 'local' (default) shows only sessions created here, 'all' shows everything, or pass a hostname (e.g. machine-b) to show only imports from that peer."],[it," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."],[it," --columns picks which columns show and their order, e.g. --columns=session,state,title,cost (valid: session,upstream,host,state,agent,model,age,cwd,title,cost). UPSTREAM/HOST/MODEL hidden by default; COST is the trailing column; overrides config.tui.sessionColumns."],[it," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"],[it," Aggregate one session: turn count, tool histogram, files touched, cost/duration, synopsis. --diff appends the session diff under the summary and pages the whole thing on a TTY (inherits --fold)."],[it," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"],[it," Print a git-diff-shaped view of every file the session edited, reconstructed from history (no git). Pages through $HYDRA_ACP_PAGER / $PAGER / less on a TTY (LESS=FRX default); --no-pager bypasses. --fold collapses sequential hunks that rewrite the same region into one net-effect hunk."],[it," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"],[it," hydra-acp session remove <id> Remove a session entirely (live or cold)"],[it," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"],[it," Delete cold sessions that were never promoted to a real conversation \u2014 `hydra cat` one-shots (interactive=false) AND editor-spawned panels that never had a turn (interactive=undefined). With no --max-age-days, collects every matching cold row regardless of age (you typed `collect`, so collect it all). Pass --max-age-days N to scope to anything older than N days; 0 is the same as omitting it. --keep-undecided narrows to only explicit interactive=false rows (matches what the background timer does). --limit caps deletions per call (default 1000); re-run to drain a larger backlog. The daemon also runs this on a timer using config.daemon.sessionGcMaxAgeDays (with the conservative explicit-only policy) \u2014 this is the manual trigger."],[it," hydra-acp session export <id> [--out <file>|.]"],[it," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"],[it," hydra-acp session transcript <id>|<file> [--out <file>|.]"],[it," Render a session as a markdown transcript. Accepts a session id (renders via the daemon) or a local .hydra bundle file (rendered in-process). Writes to <file>, to a default-named file when --out=., or to stdout"],[it," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"],[it," Import a bundle from <file> or stdin (-); --replace overwrites a lineage match (kills it if live); --cwd overrides the bundle's recorded working directory; --info prints the bundle's meta without importing"],[it," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"],[it," Print a hydra:// URL the recipient can paste into `--session`. With no id, picks the most-recent session for cwd. Host precedence: --host > config.daemon.publicHost > config.daemon.host > 127.0.0.1 (with a stderr warning that the URL is loopback-only)."],[Aa," hydra-acp extension list List configured extensions and live state"],[Aa," hydra-acp extension add <name> [opts] Add an extension to config"],[Aa," hydra-acp extension remove <name> Remove an extension from config"],[Aa," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"],[Aa," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"],[Ca," hydra-acp transformer list List configured transformers and live state"],[Ca," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"],[Ca," hydra-acp transformer remove <name> Remove a transformer from config"],[Ca," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"],[Ca," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"],[es," hydra-acp agent [list] List agents in the cached registry"],[es," hydra-acp agent refresh Force a registry re-fetch"],[es," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"],[es," hydra-acp agent set [<id>] [model] With no args, report the daemon's current default agent and its default model. With <id>, set <id> as the default agent (config.defaultAgent). With <id> and [model], set the per-agent default model (config.defaultModels[<id>])."],[es," hydra-acp agent pin <id> [packageSpec] Pin a registry agent to a specific npm version (e.g. opencode-ai@0.5.12). Omit packageSpec to clear. Sidesteps a broken upstream publish."],[es," hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]... Define a local agent that bypasses the registry (e.g. your system `opencode`). --command defaults to <id> (resolved off PATH)."],[es," hydra-acp agent remove <id> Remove a local agent."],[LT," hydra-acp registry pin | unpin Freeze the daemon on its cached registry (pin) so a bad push isn't picked up, or resume normal TTL fetching (unpin). `agent refresh` still forces a fetch."],[es," hydra-acp agent sync <id> Spawn <id> just long enough to ACP session/list it, then persist any sessions it remembers (across every cwd) as cold rows in `session list`"],[es," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"],[es," hydra-acp agent auth <id> Run the auth flow for <id>"],[Ra," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"],[Ra," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"],[Ra," hydra-acp config set <dotted.key> <value> Persist a value; <value> is parsed as JSON when possible, else stored as a string. Validated against the schema before write."],[Ra," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"],[Ra," hydra-acp config path Print the config file path"],[np," hydra-acp auth password [--force] Set the daemon's master password"],[np," hydra-acp auth [list] List active session tokens"],[np," hydra-acp auth revoke <id> Revoke a session token"],[tp," hydra-acp tui [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"],[tp," Interactive terminal UI. Smart default (no flags): shows a picker when sessions exist, else new."],{globalOnly:" hydra-acp --version Print version"},{globalOnly:" hydra-acp --help Show this help"},{globalOnly:""},{globalOnly:"External subcommands:"},{globalOnly:" Any `hydra-acp <name>` whose <name> is not built-in is exec'd as"},{globalOnly:" `hydra-acp-<name>` from PATH (git-style). Ecosystem packages like"},{globalOnly:" @hydra-acp/planner expose themselves through this mechanism."},{globalOnly:""},{globalOnly:"Config knob flags accept env-var equivalents (flag wins):"},{globalOnly:" --agent HYDRA_ACP_AGENT"},{globalOnly:" --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"},{globalOnly:" --session HYDRA_ACP_SESSION (session id or hydra:// URL)"},{globalOnly:" --name HYDRA_ACP_NAME"},""],n=[];for(let s of e){if(typeof s=="string"){n.push(s);continue}if("globalOnly"in s){t===void 0&&n.push(s.globalOnly);continue}let[r,i]=s;(t===void 0||r.includes(t))&&n.push(i)}process.stdout.write(n.join(`
515
515
  `)+`
516
- `)}async function tv(){if(!nr)try{let t=await ha();t&&process.stderr.write(`\u2728 ${ma(t)}
517
- `)}catch{}}AT().then(tv).catch(async t=>{se({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`hydra-acp: ${t.message}
518
- `),await tv(),process.exit(1)});
516
+ `)}async function rv(){if(!nr)try{let t=await ma();t&&process.stderr.write(`\u2728 ${ga(t)}
517
+ `)}catch{}}MT().then(rv).catch(async t=>{se({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`hydra-acp: ${t.message}
518
+ `),await rv(),process.exit(1)});